summaryrefslogtreecommitdiff
path: root/app/Rules/MimeTypeRule.php
blob: 3a054303632b4d460bfa95e90201b164cb71d6d7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<?php

namespace App\Rules;

use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Http\UploadedFile;

class MimeTypeRule implements ValidationRule
{
    protected array $allowedMimes;

    public function __construct(array $allowedMimes)
    {
        $this->allowedMimes = $allowedMimes;
    }

    public function validate(string $attribute, mixed $value, Closure $fail): void
    {
        if (!$value instanceof UploadedFile) {
            $fail('The :attribute must be a valid file.');
            return;
        }

        // Use finfo to detect actual MIME type (not just extension)
        $finfo = finfo_open(FILEINFO_MIME_TYPE);
        $mimeType = finfo_file($finfo, $value->getRealPath());
        finfo_close($finfo);

        if (!in_array($mimeType, $this->allowedMimes)) {
            $fail("The :attribute has an unsupported file type ({$mimeType}).");
        }
    }
}