lean/src/Response/PdfResponse.php

71 lines
2.1 KiB
PHP

<?php declare(strict_types=1);
namespace Lean\Response;
use function get_class, gettype, is_object, is_string, sprintf;
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 PdfResponse 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 $content is neither a string or stream.
*/
public function __construct($content, int $status = 200, array $headers = [])
{
parent::__construct(
$this->createBody($content),
$status,
$this->injectContentType('application/pdf; charset=utf-8', $headers)
);
}
/**
* Create the message body.
*
* @param string|StreamInterface $content
* @throws Exception\InvalidArgumentException if $content is neither a string or stream.
*/
private function createBody($content) : StreamInterface
{
if ($content instanceof StreamInterface) {
return $content;
}
if (! is_string($content)) {
throw new Exception\InvalidArgumentException(sprintf(
'Invalid content (%s) provided to %s',
(is_object($content) ? get_class($content) : gettype($content)),
__CLASS__
));
}
$body = new Stream('php://temp', 'wb+');
$body->write($content);
$body->rewind();
return $body;
}
}