diff --git a/app/Rules/StorageFile.php b/app/Rules/StorageFile.php index 2a0a382..4af3fe0 100644 --- a/app/Rules/StorageFile.php +++ b/app/Rules/StorageFile.php @@ -11,26 +11,15 @@ use Illuminate\Support\Str; class StorageFile implements Rule { - public int $maxSize; - public string $error = 'Invalid file.'; - /** @var string[] */ - public array $fileTypes; - - /** - * @param string[] $fileTypes - */ - public function __construct(int $maxSize, array $fileTypes = [], public ?Form $form = null) + public function __construct(public int $maxSize, public array $fileTypes = [], public ?Form $form = null) { - $this->maxSize = $maxSize; - - $this->fileTypes = $fileTypes; } /** * File can have 2 formats: - * - file_name-{uuid}.{ext} + * - file-name_{uuid}.{ext} * - {uuid} * * @param string $attribute @@ -69,8 +58,9 @@ class StorageFile implements Rule if (count($this->fileTypes) > 0) { $this->error = 'Incorrect file type. Allowed only: '.implode(',', $this->fileTypes); - - return in_array($fileNameParser->extension, $this->fileTypes); + return collect($this->fileTypes)->map(function ($type) { + return strtolower($type); + })->contains(strtolower($fileNameParser->extension)); } return true; diff --git a/tests/Unit/Rules/StorageFileTest.php b/tests/Unit/Rules/StorageFileTest.php new file mode 100644 index 0000000..ad11084 --- /dev/null +++ b/tests/Unit/Rules/StorageFileTest.php @@ -0,0 +1,42 @@ +andReturn(true); + Storage::shouldReceive('size') + ->andReturn(1000000); + + $validator = new \App\Rules\StorageFile(1000000, ['jpg', 'JPEG', 'png']); + collect([ + 'file_name_' . Str::uuid() . '.jpg', + 'file_name_' . Str::uuid() . '.png', + 'file_name_' . Str::uuid() . '.JPG', + 'file_name_' . Str::uuid() . '.JPEG' + ])->each(function ($file) use ($validator) { + $this->assertTrue($validator->passes('file', $file)); + }); + + $this->assertFalse($validator->passes('file', 'file_name_' . Str::uuid() . '.pdf')); +}); + +it('can validate file size', function () { + Storage::shouldReceive('exists') + ->andReturn(true); + Storage::shouldReceive('size') + ->andReturn(1000000); + + $validator = new \App\Rules\StorageFile(1000000); + $this->assertTrue($validator->passes('file', 'file_name_' . Str::uuid() . '.jpg')); + + Storage::clearResolvedInstances(); + Storage::shouldReceive('exists') + ->andReturn(true) + ->shouldReceive('size') + ->andReturn(2000000); + + // Fake pdf with 2 times the authorized size + $this->assertFalse($validator->passes('file', 'file_name_' . Str::uuid() . '.pdf')); +});