1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Silverback\ApiComponentBundle\Validator\Constraints; |
4
|
|
|
|
5
|
|
|
use Doctrine\Common\Collections\ArrayCollection; |
6
|
|
|
use Silverback\ApiComponentBundle\Entity\ValidComponentInterface; |
7
|
|
|
use Silverback\ApiComponentBundle\Validator\ClassNameValidator; |
8
|
|
|
use Silverback\ApiComponentBundle\Entity\Content\ComponentLocation as ComponentLocationEntity; |
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
|
3 |
|
public function validate($entity, Constraint $constraint): void |
20
|
|
|
{ |
21
|
3 |
|
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
|
2 |
|
$content = $entity->getContent(); |
27
|
2 |
|
if ($content instanceof ValidComponentInterface) { |
28
|
|
|
/** @var ArrayCollection|string[] $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
|
2 |
|
} |
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) |
47
|
|
|
{ |
48
|
2 |
|
$componentIsValid = false; |
49
|
2 |
|
if ($validComponents->count()) { |
50
|
2 |
|
$component = $entity->getComponent(); |
51
|
2 |
|
foreach ($validComponents as $validComponent) { |
52
|
2 |
|
if (ClassNameValidator::isClassSame($validComponent, $component)) { |
53
|
1 |
|
$componentIsValid = true; |
54
|
2 |
|
break; |
55
|
|
|
} |
56
|
|
|
} |
57
|
|
|
} |
58
|
2 |
|
return $componentIsValid; |
59
|
|
|
} |
60
|
|
|
} |
61
|
|
|
|