MimeTypeConstraint   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 47
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 8
eloc 12
c 2
b 0
f 0
dl 0
loc 47
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A validate() 0 11 5
A __construct() 0 3 1
A getErrorMessage() 0 3 1
A setErrorMessage() 0 3 1
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
Bug introduced by
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