From c76b61e806f1d35871aaf8765f7d61ffcb8187ec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mat=C4=9Bj=20Hump=C3=A1l?= Date: Mon, 4 Nov 2024 14:08:43 +0100 Subject: [PATCH] FileUpload: Initialize properties (#235)(#195) --- src/Http/FileUpload.php | 16 ++++++++-------- tests/Http/FileUpload.basic.phpt | 13 +++++++++++++ 2 files changed, 21 insertions(+), 8 deletions(-) diff --git a/src/Http/FileUpload.php b/src/Http/FileUpload.php index 5599639d..acd30f52 100644 --- a/src/Http/FileUpload.php +++ b/src/Http/FileUpload.php @@ -34,7 +34,7 @@ final class FileUpload public const IMAGE_MIME_TYPES = ['image/gif', 'image/png', 'image/jpeg', 'image/webp']; private readonly string $name; - private readonly string|null $fullPath; + private readonly ?string $fullPath; private string|false|null $type = null; private string|false|null $extension = null; private readonly int $size; @@ -46,16 +46,16 @@ public function __construct(?array $value) { foreach (['name', 'size', 'tmp_name', 'error'] as $key) { if (!isset($value[$key]) || !is_scalar($value[$key])) { - $this->error = UPLOAD_ERR_NO_FILE; - return; // or throw exception? + $value = []; + break; } } - $this->name = $value['name']; + $this->name = $value['name'] ?? ''; $this->fullPath = $value['full_path'] ?? null; - $this->size = $value['size']; - $this->tmpName = $value['tmp_name']; - $this->error = $value['error']; + $this->size = $value['size'] ?? 0; + $this->tmpName = $value['tmp_name'] ?? ''; + $this->error = $value['error'] ?? UPLOAD_ERR_NO_FILE; } @@ -174,7 +174,7 @@ public function __toString(): string /** - * Returns the error code. It is be one of UPLOAD_ERR_XXX constants. + * Returns the error code. It has to be one of UPLOAD_ERR_XXX constants. * @see http://php.net/manual/en/features.file-upload.errors.php */ public function getError(): int diff --git a/tests/Http/FileUpload.basic.phpt b/tests/Http/FileUpload.basic.phpt index 505774dc..fc01ab61 100644 --- a/tests/Http/FileUpload.basic.phpt +++ b/tests/Http/FileUpload.basic.phpt @@ -71,4 +71,17 @@ test('', function () { Assert::null($upload->getContentType()); Assert::false($upload->isImage()); Assert::null($upload->getSuggestedExtension()); + Assert::same('', (string) $upload); +}); + + +test('', function () { + $upload = new FileUpload([]); + + Assert::false($upload->isOk()); + Assert::false($upload->hasFile()); + Assert::null($upload->getContentType()); + Assert::false($upload->isImage()); + Assert::null($upload->getSuggestedExtension()); + Assert::same('', (string) $upload); });