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

FormatValidator   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 33
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 0
Metric Value
wmc 6
lcom 1
cbo 4
dl 0
loc 33
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A validate() 0 17 5
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