Completed
Pull Request — master (#1646)
by Grégoire
15:02
created

FormatValidator::validate()   A

Complexity

Conditions 5
Paths 4

Size

Total Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 17
rs 9.3888
c 0
b 0
f 0
cc 5
nc 4
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the Sonata Project package.
7
 *
8
 * (c) Thomas Rabaix <[email protected]>
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace Sonata\MediaBundle\Validator;
15
16
use Sonata\MediaBundle\Model\GalleryInterface;
17
use Sonata\MediaBundle\Provider\MediaProviderInterface;
18
use Sonata\MediaBundle\Provider\Pool;
19
use Symfony\Component\Validator\Constraint;
20
use Symfony\Component\Validator\ConstraintValidator;
21
22
/**
23
 * @final since sonata-project/media-bundle 3.21.0
24
 */
25
class FormatValidator extends ConstraintValidator
26
{
27
    /**
28
     * @var Pool
29
     */
30
    protected $pool;
31
32
    public function __construct(Pool $pool)
33
    {
34
        $this->pool = $pool;
35
    }
36
37
    /**
38
     * {@inheritdoc}
39
     */
40
    public function validate($value, Constraint $constraint): void
41
    {
42
        $formats = $this->pool->getFormatNamesByContext($value->getContext());
43
44
        if (!$value instanceof GalleryInterface) {
45
            $this->context->buildViolation('Invalid instance, expected GalleryInterface')
46
               ->atPath('defaultFormat')
47
               ->addViolation();
48
        }
49
50
        $galleryDefaultFormat = $value->getDefaultFormat();
51
52
        if (MediaProviderInterface::FORMAT_REFERENCE !== $galleryDefaultFormat
53
            && !($formats && \array_key_exists($galleryDefaultFormat, $formats))) {
54
            $this->context->addViolation('invalid format');
55
        }
56
    }
57
}
58