Passed
Push — master ( a023d2...6d474d )
by Daniel
06:11
created

ComponentLocationValidator   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
dl 0
loc 46
ccs 22
cts 22
cp 1
rs 10
c 0
b 0
f 0
wmc 8

2 Methods

Rating   Name   Duplication   Size   Complexity  
A validate() 0 17 4
A validateValidComponentInterface() 0 12 4
1
<?php
2
3
namespace Silverback\ApiComponentBundle\Validator\Constraints;
4
5
use Doctrine\Common\Collections\ArrayCollection;
6
use Silverback\ApiComponentBundle\Entity\Content\Component\ComponentLocation as ComponentLocationEntity;
7
use Silverback\ApiComponentBundle\Entity\ValidComponentInterface;
8
use Silverback\ApiComponentBundle\Validator\ClassNameValidator;
9
use Symfony\Component\Validator\Constraint;
10
use Symfony\Component\Validator\ConstraintValidator;
11
12
class ComponentLocationValidator extends ConstraintValidator
13
{
14
    /**
15
     * @param mixed $entity
16
     * @param Constraint $constraint
17
     * @throws \ReflectionException
18
     */
19 4
    public function validate($entity, Constraint $constraint): void
20
    {
21 4
        if (!$entity instanceof ComponentLocationEntity) {
22 1
            throw new \InvalidArgumentException(
23 1
                sprintf('The ComponentLocationValidator should only be used with %s', ComponentLocationEntity::class)
24
            );
25
        }
26 3
        $content = $entity->getContent();
27 3
        if ($content instanceof ValidComponentInterface) {
28
            /** @var ArrayCollection $validComponents */
29 2
            $validComponents = $content->getValidComponents();
30 2
            $componentIsValid = $this->validateValidComponentInterface($entity, $validComponents);
31 2
            if (!$componentIsValid) {
32 1
                $this->context->buildViolation($constraint->message)
33 1
                    ->atPath('component')
34 1
                    ->setParameter('{{ string }}', implode(', ', $validComponents->toArray()))
35 1
                    ->addViolation();
36
            }
37
        }
38 3
    }
39
40
    /**
41
     * @param ComponentLocationEntity $entity
42
     * @param ArrayCollection $validComponents
43
     * @return bool
44
     * @throws \ReflectionException
45
     */
46 2
    private function validateValidComponentInterface(ComponentLocationEntity $entity, ArrayCollection $validComponents): bool
47
    {
48 2
        $componentIsValid = false;
49 2
        if ($validComponents->count()) {
50 2
            $component = $entity->getComponent();
51 2
            foreach ($validComponents as $validComponent) {
52 2
                if ($componentIsValid = ClassNameValidator::isClassSame($validComponent, $component)) {
53 2
                    break;
54
                }
55
            }
56
        }
57 2
        return $componentIsValid;
58
    }
59
}
60