From 366da7a65b8c99f5618aaf5b0ca8fb726a8c022b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joan=20Fabr=C3=A9gat?= Date: Fri, 14 Sep 2018 17:36:44 +0200 Subject: [PATCH] code improvement --- src/FileResponse.php | 26 +++++++++++++++++++++++--- src/LocalFileResponse.php | 16 +--------------- 2 files changed, 24 insertions(+), 18 deletions(-) diff --git a/src/FileResponse.php b/src/FileResponse.php index a37ef2c..1dc9268 100644 --- a/src/FileResponse.php +++ b/src/FileResponse.php @@ -22,6 +22,7 @@ declare(strict_types = 1); namespace CodeInc\Psr7Responses; use CodeInc\MediaTypes\MediaTypes; +use function GuzzleHttp\Psr7\stream_for; use Psr\Http\Message\StreamInterface; @@ -39,7 +40,7 @@ class FileResponse extends StreamResponse /** * FileResponse constructor. * - * @param StreamInterface $fileStream + * @param string|resource|StreamInterface $file * @param null|string $fileName * @param null|string $contentType * @param bool $asAttachment @@ -49,12 +50,31 @@ class FileResponse extends StreamResponse * @param null|string $reason * @throws \CodeInc\MediaTypes\Exceptions\MediaTypesException */ - public function __construct(StreamInterface $fileStream, string $fileName, ?string $contentType = null, + public function __construct($file, string $fileName, ?string $contentType = null, bool $asAttachment = true, int $status = 200, array $headers = [], string $version = '1.1', ?string $reason = null) { + if (is_string($file)) { + if (!is_file($file)) { + throw new ResponseException( + sprintf("The path \"%s\" is not a file or does not exist", $file), + $this + ); + } + if (($handler = fopen($file, "r")) === false) { + throw new ResponseException( + sprintf("Unable to open the file \"%s\" for reading", $file), + $this + ); + } + $stream = stream_for($handler); + } + else { + $stream = stream_for($file); + } + parent::__construct( - $fileStream, + $stream, $contentType ?? MediaTypes::getFilenameMediaType($fileName, self::DEFAULT_MIME_TYPE), null, $fileName, diff --git a/src/LocalFileResponse.php b/src/LocalFileResponse.php index 58443f1..465456d 100644 --- a/src/LocalFileResponse.php +++ b/src/LocalFileResponse.php @@ -22,7 +22,6 @@ declare(strict_types = 1); namespace CodeInc\Psr7Responses; use CodeInc\Psr7Responses\Tests\LocalFileResponseTest; -use function GuzzleHttp\Psr7\stream_for; /** @@ -52,21 +51,8 @@ public function __construct(string $filePath, ?string $fileName = null, ?string bool $asAttachment = true, int $status = 200, array $headers = [], string $version = '1.1', ?string $reason = null) { - if (!is_file($filePath)) { - throw new ResponseException( - sprintf("The path \"%s\" is not a file or does not exist", $filePath), - $this - ); - } - if (($f = fopen($filePath, "r")) === false) { - throw new ResponseException( - sprintf("Unable to open the file \"%s\" for reading", $filePath), - $this - ); - } - parent::__construct( - stream_for($f), + $filePath, $fileName ?? basename($filePath), $contentType, $asAttachment,