Files
lean/src/Response/DownloadResponse.php
T

81 lines
2.6 KiB
PHP

<?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 Laminas\Diactoros\Exception,
Laminas\Diactoros\Response,
Laminas\Diactoros\Stream,
Laminas\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;
}
}