Completed
Push — master ( b5c7fa...23b509 )
by Taosikai
13:59
created

MimeTypeConstraint::validate()   A

Complexity

Conditions 5
Paths 3

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 12
c 0
b 0
f 0
rs 9.5555
cc 5
nc 3
nop 1
1
<?php
2
3
/*
4
 * This file is part of the slince/upload package.
5
 *
6
 * (c) Slince <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Slince\Upload\Constraint;
13
14
use Slince\Upload\Exception\ConstraintException;
15
use Symfony\Component\HttpFoundation\File\UploadedFile;
16
17
class MimeTypeConstraint implements ConstraintInterface
18
{
19
    /**
20
     * @var array
21
     */
22
    protected $allowedMimeTypes;
23
24
    public function __construct(array $allowedMimeTypes)
25
    {
26
        $this->allowedMimeTypes = $allowedMimeTypes;
27
    }
28
29
    /**
30
     * {@inheritdoc]
31
     */
32
    public function validate(UploadedFile $file)
33
    {
34
        foreach ($this->allowedMimeTypes as $mimeType) {
35
            if ($mimeType === $file->getClientMimeType()
36
                || (strpos($mimeType, '/*') !== false
37
                    && explode('/', $mimeType)[0] == explode('/', $file->getMimeType())[0])
38
            ) {
39
                return true;
40
            }
41
        }
42
        return false;
43
    }
44
45
    /**
46
     * {@inheritdoc}
47
     */
48
    public function getErrorMessage(UploadedFile $file)
49
    {
50
        return sprintf('File type "%s" is invalid', $file->getClientMimeType());
51
    }
52
}