Issues (5)

src/Constraint/MimeTypeConstraint.php (1 issue)

Labels
Severity
1
<?php
2
3
namespace Slince\Upload\Constraint;
4
5
use Symfony\Component\HttpFoundation\File\UploadedFile;
6
7
class MimeTypeConstraint implements ConstraintInterface
8
{
9
    /**
10
     * @var string
11
     */
12
    protected $errorMessageTemplate = 'File type {type} is invalid';
13
14
    /**
15
     * @var array
16
     */
17
    protected $allowedMimeTypes;
18
19
    public function __construct(array $allowedMimeTypes)
20
    {
21
        $this->allowedMimeTypes = $allowedMimeTypes;
22
    }
23
24
    /**
25
     * {@inheritdoc]
26
     */
27
    public function validate(UploadedFile $file): bool
28
    {
29
        foreach ($this->allowedMimeTypes as $mimeType) {
30
            if ($mimeType === $file->getClientMimeType()
31
                || (strpos($mimeType, '/*') !== false
32
                    && explode('/', $mimeType)[0] === explode('/', $file->getMimeType())[0])
0 ignored issues
show
It seems like $file->getMimeType() can also be of type null; however, parameter $string of explode() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

32
                    && explode('/', $mimeType)[0] === explode('/', /** @scrutinizer ignore-type */ $file->getMimeType())[0])
Loading history...
33
            ) {
34
                return true;
35
            }
36
        }
37
        return false;
38
    }
39
40
    /**
41
     * {@inheritdoc}
42
     */
43
    public function getErrorMessage(UploadedFile $file): string
44
    {
45
        return str_replace('{type}', $file->getClientMimeType(), $this->errorMessageTemplate);
46
    }
47
48
    /**
49
     * {@inheritdoc}
50
     */
51
    public function setErrorMessage(string $messageTemplate): void
52
    {
53
        $this->errorMessageTemplate = $messageTemplate;
54
    }
55
}
56