lean/src/Response/FileDownloadResponse.php
Dave Mc Nicoll f482c19df5 - Splitted cronard definitions
- Added TMP_PATH env var
- Added support for Events from attributes
- Added Negundo client support
2023-03-29 13:59:59 +00:00

87 lines
2.8 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 FileDownloadResponse 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 $filepath 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($filepath, int $status = 200, array $headers = [])
{
$body = $this->createBody($filepath);
if (class_exists(\Mimey\MimeTypes::class)) {
$mime = (new \Mimey\MimeTypes())->getMimeType(pathinfo($filepath, PATHINFO_EXTENSION));
}
else {
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $filepath);
finfo_close($finfo);
}
parent::__construct(
$body,
$status,
$this->injectContentType($mime, $headers)
);
}
/**
* Create the message body.
*
* @param string|StreamInterface $filepath
* @throws Exception\InvalidArgumentException if $filepath is neither a string or stream.
*/
private function createBody($filepath) : StreamInterface
{
if ($filepath instanceof StreamInterface) {
return $filepath;
}
if (! is_string($filepath)) {
throw new Exception\InvalidArgumentException(sprintf(
'Invalid content (%s) provided to %s',
(is_object($filepath) ? get_class($filepath) : gettype($filepath)),
__CLASS__
));
}
if ( ! file_exists($filepath) ) {
throw new Exception\InvalidArgumentException("Given file (%s) do not look like a valid file path.", $filepath);
}
if ( ! is_readable($filepath) ) {
throw new Exception\InvalidArgumentException("Given file (%s) do not seem to be readable. This could indicate a permission problem", $filepath);
}
return new Stream(fopen($filepath, "r"), 'r');
}
}