44 lines
1.2 KiB
PHP
44 lines
1.2 KiB
PHP
<?php
|
|
|
|
namespace App\Rules;
|
|
|
|
use Closure;
|
|
use Illuminate\Contracts\Validation\ValidationRule;
|
|
|
|
class FileType implements ValidationRule
|
|
{
|
|
protected array $disallowedExtensions;
|
|
|
|
/**
|
|
* Constructor to initialize disallowed file extensions.
|
|
*
|
|
* @param array $disallowedExtensions
|
|
*/
|
|
public function __construct(array $disallowedExtensions)
|
|
{
|
|
$this->disallowedExtensions = $disallowedExtensions;
|
|
}
|
|
|
|
/**
|
|
* Run the validation rule.
|
|
*
|
|
* @param string $attribute
|
|
* @param mixed $value
|
|
* @param \Closure(string, ?string=): \Illuminate\Translation\PotentiallyTranslatedString $fail
|
|
*/
|
|
public function validate(string $attribute, mixed $value, Closure $fail): void
|
|
{
|
|
if ($value && $value->isValid()) {
|
|
// Get the file extension
|
|
$extension = strtolower($value->getClientOriginalExtension());
|
|
|
|
// Check if the extension is in the disallowed list
|
|
if (in_array($extension, $this->disallowedExtensions)) {
|
|
$fail("The file type '{$extension}' is not allowed.");
|
|
}
|
|
} else {
|
|
$fail("The uploaded file for '{$attribute}' is invalid.");
|
|
}
|
|
}
|
|
}
|