|
1
|
|
|
<?php |
|
2
|
|
|
/** |
|
3
|
|
|
* Copyright (c) 2020. |
|
4
|
|
|
* @author Paweł Antosiak <[email protected]> |
|
5
|
|
|
*/ |
|
6
|
|
|
|
|
7
|
|
|
declare(strict_types=1); |
|
8
|
|
|
|
|
9
|
|
|
namespace Gorynych\Adapter; |
|
10
|
|
|
|
|
11
|
|
|
use Cake\Collection\Collection; |
|
12
|
|
|
use Gorynych\Resource\Dto\EntityViolation; |
|
13
|
|
|
use Gorynych\Resource\Exception\InvalidEntityException; |
|
14
|
|
|
use Symfony\Component\Config\FileLocatorInterface; |
|
15
|
|
|
use Symfony\Component\Validator\ConstraintViolationInterface; |
|
16
|
|
|
use Symfony\Component\Validator\Validation; |
|
17
|
|
|
use Symfony\Component\Validator\Validator\ValidatorInterface; |
|
18
|
|
|
|
|
19
|
|
|
class ValidatorAdapter |
|
20
|
|
|
{ |
|
21
|
|
|
protected ValidatorInterface $validator; |
|
22
|
|
|
protected FileLocatorInterface $configLocator; |
|
23
|
|
|
|
|
24
|
|
|
public function __construct(FileLocatorInterface $configLocator) |
|
25
|
|
|
{ |
|
26
|
|
|
$this->configLocator = $configLocator; |
|
27
|
|
|
} |
|
28
|
|
|
|
|
29
|
|
|
/** |
|
30
|
|
|
* Validates provided entity object |
|
31
|
|
|
* |
|
32
|
|
|
* @param object $entity |
|
33
|
|
|
* @throws InvalidEntityException if entity is not valid |
|
34
|
|
|
*/ |
|
35
|
1 |
|
public function validate(object $entity): void |
|
36
|
|
|
{ |
|
37
|
1 |
|
$errors = $this->validator->validate($entity); |
|
38
|
|
|
|
|
39
|
1 |
|
if ($errors->count() > 0) { |
|
40
|
1 |
|
$violations = (new Collection($errors))->map( |
|
41
|
1 |
|
static function (ConstraintViolationInterface $violation): EntityViolation { |
|
42
|
1 |
|
return new EntityViolation($violation->getPropertyPath(), $violation->getMessage()); |
|
43
|
1 |
|
} |
|
44
|
|
|
); |
|
45
|
|
|
|
|
46
|
1 |
|
throw InvalidEntityException::fromViolations(...$violations->toList()); |
|
47
|
|
|
} |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
|
|
/** |
|
51
|
|
|
* Setups validator |
|
52
|
|
|
* |
|
53
|
|
|
* @param string $constraint Constraint name to validate against |
|
54
|
|
|
* @return self |
|
55
|
|
|
*/ |
|
56
|
|
|
public function setup(string $constraint): self |
|
57
|
|
|
{ |
|
58
|
|
|
$constraintPath = $this->configLocator->locate("validator/{$constraint}.yaml"); |
|
59
|
|
|
|
|
60
|
|
|
$this->validator = Validation::createValidatorBuilder() |
|
61
|
|
|
->addYamlMapping($constraintPath) |
|
|
|
|
|
|
62
|
|
|
->getValidator(); |
|
63
|
|
|
|
|
64
|
|
|
return $this; |
|
65
|
|
|
} |
|
66
|
|
|
} |
|
67
|
|
|
|