Beautiful Open-Source Form Builder
Fix file type case sensitive validation
Julien Nahum2ac9b9628492
diff --git a/app/Rules/StorageFile.php b/app/Rules/StorageFile.phpindex 2a0a382ee..4af3fe031 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 Ruleif (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.phpnew file mode 100644index 000000000..ad11084bd--- /dev/null+++ b/tests/Unit/Rules/StorageFileTest.php@@ -0,0 +1,42 @@+<?php++use Illuminate\Support\Facades\Storage;+use Illuminate\Support\Str;++it('can validate file types', function () {+ Storage::shouldReceive('exists')+ ->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'));+});