1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
|
3
|
|
|
namespace EdmondsCommerce\DoctrineStaticMeta\Entity\Validation\Constraints\FieldConstraints; |
4
|
|
|
|
5
|
|
|
use Symfony\Component\Validator\Constraint; |
6
|
|
|
use Symfony\Component\Validator\ConstraintValidator; |
7
|
|
|
|
8
|
|
|
/** |
9
|
|
|
* This is a template constraint validator. |
10
|
|
|
* |
11
|
|
|
* The Constraint Validator is in charge of actually doing the validation. |
12
|
|
|
* |
13
|
|
|
* See the comment on the constructor about brining in dependencies if required to perform the validation |
14
|
|
|
* |
15
|
|
|
* @see https://symfony.com/doc/2.6/cookbook/validation/custom_constraint.html |
16
|
|
|
* |
17
|
|
|
* Suggest using the `./bin/doctrine dsm:override:create` command to create a new |
18
|
|
|
* override straight after you generate the file. |
19
|
|
|
* |
20
|
|
|
* Then you can edit it and update your override as required using |
21
|
|
|
* `./bin/doctrine dsm:overrides:update -a fromProject` |
22
|
|
|
* |
23
|
|
|
* And then reapply after a new build using |
24
|
|
|
* `./bin/doctrine dsm:overrides:update -a toProject` |
25
|
|
|
* |
26
|
|
|
*/ |
27
|
|
|
class JsonDataValidator extends ConstraintValidator |
28
|
|
|
{ |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* If your validator requires dependencies to be injected, then simply declare them here. |
32
|
|
|
* |
33
|
|
|
* You also need to add this class to your list of Services in your DI container |
34
|
|
|
* |
35
|
|
|
* Finally you need to ensure that your container is configured to use the ContainerConstraintValidatorFactory |
36
|
|
|
* |
37
|
|
|
* @see \EdmondsCommerce\DoctrineStaticMeta\Container::configureValidationComponents |
38
|
|
|
*/ |
39
|
|
|
public function __construct() |
40
|
|
|
{ |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
/** |
44
|
|
|
* Checks if the passed value is valid. |
45
|
|
|
* |
46
|
|
|
* @param mixed $propertyValue The value that should be validated |
47
|
|
|
* @param Constraint $constraint The constraint for the validation |
48
|
|
|
*/ |
49
|
|
|
public function validate($propertyValue, Constraint $constraint) |
50
|
|
|
{ |
51
|
|
|
if ($propertyValue === null) { |
52
|
|
|
return; |
53
|
|
|
} |
54
|
|
|
json_decode($propertyValue); |
55
|
|
|
if (JSON_ERROR_NONE === json_last_error()) { |
56
|
|
|
return; |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
// Finally, if not valid, add the violation |
60
|
|
|
$this->context->buildViolation($constraint->payload) |
61
|
|
|
->setParameter('{{ string }}', $propertyValue) |
62
|
|
|
->setParameter('{{ error }}', json_last_error_msg()) |
63
|
|
|
->addViolation(); |
64
|
|
|
} |
65
|
|
|
} |