- Work done on the kinda-micro-framework to allow smoother deployment
This commit is contained in:
1 parent
f719246624
commit
aba9a65a3c
14 files changed
+357
-12
No files matched your search
@@ -0,0 +1,80 @@
|
||||
<?php declare(strict_types=1);
|
||||
|
||||
namespace Lean\Response;
|
||||
|
||||
use function get_class, gettype, is_object, is_string, sprintfm, pathinfo, PATHINFO_EXTENSION;
|
||||
|
||||
use Psr\Http\Message\StreamInterface;
|
||||
|
||||
use Zend\Diactoros\Exception,
|
||||
Zend\Diactoros\Response,
|
||||
Zend\Diactoros\Stream,
|
||||
Zend\Diactoros\Response\InjectContentTypeTrait;
|
||||
|
||||
/**
|
||||
* PDF Response
|
||||
*
|
||||
* Allows creating a response by passing a string to the constructor;
|
||||
* by default, sets a status code of 200 and sets the Content-Type header to
|
||||
* application/pdf.
|
||||
*/
|
||||
class DownloadResponse extends Response
|
||||
{
|
||||
use InjectContentTypeTrait;
|
||||
|
||||
/**
|
||||
* Create a PDF response
|
||||
*
|
||||
* Produces a pdf response with a Content-Type of application/json and a default
|
||||
* status of 200.
|
||||
*
|
||||
* @param string|StreamInterface $content String or stream for the message body.
|
||||
* @param int $status Integer status code for the response; 200 by default.
|
||||
* @param array $headers Array of headers to use at initialization.
|
||||
* @throws Exception\InvalidArgumentException if $filepath is neither a string or stream.
|
||||
*/
|
||||
public function __construct(string $content, string $filename, int $status = 200, array $headers = [])
|
||||
{
|
||||
parent::__construct(
|
||||
$this->createBody($content),
|
||||
$status,
|
||||
$this->injectFilename($filename, $this->injectContentType("application/octet-stream", $headers))
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Inject the provided Content-Type, if none is already present.
|
||||
*
|
||||
* @return array Headers with injected Content-Type
|
||||
*/
|
||||
private function injectFilename(string $filename, array $headers) : array
|
||||
{
|
||||
$hasContentType = array_reduce(array_keys($headers), function ($carry, $item) {
|
||||
return $carry ?: (strtolower($item) === 'content-disposition');
|
||||
}, false);
|
||||
|
||||
if (! $hasContentType) {
|
||||
$headers['content-disposition'] = ['Content-Disposition:attachment; filename="' . $filename . '"'];
|
||||
}
|
||||
|
||||
return $headers;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create the message body.
|
||||
*
|
||||
* @param string|StreamInterface $content
|
||||
* @throws Exception\InvalidArgumentException if $content is neither a string or stream.
|
||||
*/
|
||||
private function createBody(string $content) : StreamInterface
|
||||
{
|
||||
if ($content instanceof StreamInterface) {
|
||||
return $content;
|
||||
}
|
||||
|
||||
$body = new Stream('php://temp', 'wb+');
|
||||
$body->write($content);
|
||||
$body->rewind();
|
||||
return $body;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user