Completed
Push — 1.0 ( 2fbcac...32464f )
by Kamil
116:20 queued 93:29
created

ValidSelectAttributeConfigurationValidator   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 50
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

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

1 Method

Rating   Name   Duplication   Size   Complexity  
C validate() 0 44 12
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
declare(strict_types=1);
13
14
namespace Sylius\Bundle\AttributeBundle\Validator\Constraints;
15
16
use Sylius\Component\Attribute\AttributeType\SelectAttributeType;
17
use Sylius\Component\Attribute\Model\AttributeInterface;
18
use Symfony\Component\Validator\Constraint;
19
use Symfony\Component\Validator\ConstraintValidator;
20
use Webmozart\Assert\Assert;
21
22
final class ValidSelectAttributeConfigurationValidator extends ConstraintValidator
23
{
24
    /**
25
     * {@inheritdoc}
26
     */
27
    public function validate($attribute, Constraint $constraint): void
28
    {
29
        /** @var AttributeInterface $attribute */
30
        Assert::isInstanceOf($attribute, AttributeInterface::class);
31
        Assert::isInstanceOf($constraint, ValidSelectAttributeConfiguration::class);
32
33
        if (SelectAttributeType::TYPE !== $attribute->getType()) {
34
            return;
35
        }
36
37
        $configuration = $attribute->getConfiguration();
38
39
        $min = null;
40
        if (!empty($configuration['min'])) {
41
            $min = $configuration['min'];
42
        }
43
44
        $max = null;
45
        if (!empty($configuration['max'])) {
46
            $max = $configuration['max'];
47
        }
48
49
        if (null === $min && null === $max) {
50
            return;
51
        }
52
53
        $multiple = $attribute->getConfiguration()['multiple'];
54
        if (!$multiple) {
55
            $this->context->addViolation($constraint->messageMultiple);
56
57
            return;
58
        }
59
60
        if (null !== $min && null !== $max && $min > $max) {
61
            $this->context->addViolation($constraint->messageMaxEntries);
62
63
            return;
64
        }
65
66
        $numberOfChoices = count($attribute->getConfiguration()['choices']);
67
        if (null !== $min && $min > $numberOfChoices) {
68
            $this->context->addViolation($constraint->messageMinEntries);
69
        }
70
    }
71
}
72