Fix file type case sensitive validation

This commit is contained in:
Julien Nahum 2024-02-29 10:48:19 +01:00
parent 8a067012e5
commit 2ac9b96284
2 changed files with 47 additions and 15 deletions

View File

@ -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;

View File

@ -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'));
});