Completed
Push — master ( 119f8d...4ad486 )
by Paweł
10:35
created

__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 5
rs 9.4285
cc 1
eloc 3
nc 1
nop 2
1
<?php
2
3
/*
4
 * This file is part of the Sylius package.
5
 *
6
 * (c) Paweł Jędrzejewski
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 Sylius\Bundle\CoreBundle\Validator\Constraints;
13
14
use Sylius\Component\Attribute\AttributeType\AttributeTypeInterface;
15
use Sylius\Component\Attribute\Model\AttributeValueInterface;
16
use Sylius\Component\Registry\ServiceRegistryInterface;
17
use Sylius\Component\Resource\Exception\UnexpectedTypeException;
18
use Sylius\Component\Resource\Translation\Provider\TranslationLocaleProviderInterface;
19
use Symfony\Component\Validator\Constraint;
20
use Symfony\Component\Validator\ConstraintValidator;
21
22
/**
23
 * @author Anna Walasek <[email protected]>
24
 */
25
final class LocalesAwareValidAttributeValueValidator extends ConstraintValidator
26
{
27
    /**
28
     * @var ServiceRegistryInterface
29
     */
30
    private $attributeTypeRegistry;
31
32
    /**
33
     * @var TranslationLocaleProviderInterface
34
     */
35
    private $localeProvider;
36
37
    /**
38
     * @param ServiceRegistryInterface $attributeTypeRegistry
39
     */
40
    public function __construct(ServiceRegistryInterface $attributeTypeRegistry, TranslationLocaleProviderInterface $localeProvider)
41
    {
42
        $this->attributeTypeRegistry = $attributeTypeRegistry;
43
        $this->localeProvider = $localeProvider;
44
    }
45
46
    /**
47
     * {@inheritdoc}
48
     */
49
    public function validate($value, Constraint $constraint)
50
    {
51
        if (!$value instanceof AttributeValueInterface) {
52
            throw new UnexpectedTypeException(get_class($value), AttributeValueInterface::class);
53
        }
54
55
        $defaultLocale = $this->localeProvider->getDefaultLocaleCode();
56
        $configuration = $value->getAttribute()->getConfiguration();
57
58
        if ($defaultLocale === $value->getLocaleCode()) {
59
            $configuration = array_merge($configuration, ['required' => true]);
60
        }
61
62
        /** @var AttributeTypeInterface $attributeType */
63
        $attributeType = $this->attributeTypeRegistry->get($value->getType());
64
65
        $attributeType->validate($value, $this->context, $configuration);
66
    }
67
}
68