- 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,77 @@
|
||||
<?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 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);
|
||||
|
||||
parent::__construct(
|
||||
$body,
|
||||
$status,
|
||||
$this->injectContentType( (new \Mimey\MimeTypes())->getMimeType( pathinfo($filepath, PATHINFO_EXTENSION) ), $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');
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user