FormatValidator::validate()   A
last analyzed

Complexity

Conditions 6
Paths 4

Size

Total Lines 18
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 11
nc 4
nop 2
dl 0
loc 18
rs 9.2222
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Damax\Media\Bridge\Symfony\Validator\Constraints;
6
7
use Damax\Media\Type\Types;
8
use Symfony\Component\Validator\Constraint;
9
use Symfony\Component\Validator\ConstraintValidator;
10
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
11
12
final class FormatValidator extends ConstraintValidator
13
{
14
    private $types;
15
16
    public function __construct(Types $types)
17
    {
18
        $this->types = $types;
19
    }
20
21
    public function validate($value, Constraint $constraint)
22
    {
23
        if (!$constraint instanceof Format) {
24
            throw new UnexpectedTypeException($constraint, Format::class);
25
        }
26
27
        if (!$value || !$value->type || !$this->types->hasDefinition($value->type)) {
28
            return;
29
        }
30
31
        $mimeTypes = $this->types->definition($value->type)->mimeTypes();
32
33
        if (!in_array($value->mimeType, $mimeTypes)) {
34
            $this->context
35
                ->buildViolation($constraint->message)
36
                ->atPath($constraint->propertyPath)
37
                ->setInvalidValue($value->mimeType)
38
                ->addViolation()
39
            ;
40
        }
41
    }
42
}
43