Completed
Pull Request — master (#2680)
by
unknown
06:45
created

IsExtensionAllowedValidator::validate()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
dl 0
loc 16
ccs 0
cts 14
cp 0
rs 9.7333
c 0
b 0
f 0
cc 4
nc 4
nop 2
crap 20
1
<?php
2
3
namespace Kunstmaan\MediaBundle\Validator\Constraints;
4
5
use Kunstmaan\MediaBundle\Helper\MediaManager;
6
use Symfony\Component\Form\Exception\UnexpectedTypeException;
7
use Symfony\Component\HttpFoundation\File\UploadedFile;
8
use Symfony\Component\Translation\TranslatorInterface;
9
use Symfony\Component\Validator\Constraint;
10
use Symfony\Component\Validator\ConstraintValidator;
11
12
class IsExtensionAllowedValidator extends ConstraintValidator
13
{
14
    /** @var MediaManager */
15
    private $mediaManager;
16
17
    /** @var TranslatorInterface */
18
    private $translator;
19
20
    public function __construct(MediaManager $mediaManager, TranslatorInterface $translator)
21
    {
22
        $this->mediaManager = $mediaManager;
23
        $this->translator = $translator;
24
    }
25
26
    public function validate($value, Constraint $constraint)
27
    {
28
        if (!$constraint instanceof IsExtensionAllowed) {
29
            throw new UnexpectedTypeException($constraint, IsExtensionAllowed::class);
30
        }
31
32
        if (!$value instanceof UploadedFile) {
33
            return;
34
        }
35
36
        if (!$this->mediaManager->isExtensionAllowed($value)) {
37
            $this->context->buildViolation($this->translator->trans($constraint->notAllowedMessage))
38
                ->setCode(IsExtensionAllowed::NOT_ALLOWED)
39
                ->addViolation();
40
        }
41
    }
42
}
43