1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
|
3
|
|
|
namespace Overblog\GraphQLBundle\Validator\Constraints; |
4
|
|
|
|
5
|
|
|
use Overblog\GraphQLBundle\Validator\ValidationNode; |
6
|
|
|
use Symfony\Component\ExpressionLanguage\ExpressionLanguage; |
7
|
|
|
use Symfony\Component\Validator\Constraint; |
8
|
|
|
use Symfony\Component\Validator\Constraints\Expression; |
9
|
|
|
use Symfony\Component\Validator\Exception\LogicException; |
10
|
|
|
use Symfony\Component\Validator\Exception\UnexpectedTypeException; |
11
|
|
|
|
12
|
|
|
class ExpressionValidator extends \Symfony\Component\Validator\Constraints\ExpressionValidator |
13
|
|
|
{ |
14
|
|
|
private $expressionLanguage; |
15
|
|
|
|
16
|
|
|
public function __construct(ExpressionLanguage $expressionLanguage = null) |
17
|
|
|
{ |
18
|
|
|
$this->expressionLanguage = $expressionLanguage; |
19
|
|
|
} |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* {@inheritdoc} |
23
|
|
|
*/ |
24
|
|
|
public function validate($value, Constraint $constraint) |
25
|
|
|
{ |
26
|
|
|
if (!$constraint instanceof Expression) { |
27
|
|
|
throw new UnexpectedTypeException($constraint, __NAMESPACE__.'\Expression'); |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
$variables = $constraint->values; |
31
|
|
|
$variables['value'] = $value; |
32
|
|
|
|
33
|
|
|
$object = $this->context->getObject(); |
34
|
|
|
|
35
|
|
|
$variables['this'] = $object; |
36
|
|
|
|
37
|
|
|
if ($object instanceof ValidationNode) { |
38
|
|
|
$variables['prevValue'] = $object->getResolverArg('value'); |
39
|
|
|
$variables['context'] = $object->getResolverArg('context'); |
40
|
|
|
$variables['args'] = $object->getResolverArg('args'); |
41
|
|
|
$variables['info'] = $object->getResolverArg('info'); |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
if (!$this->getExpressionLanguage()->evaluate($constraint->expression, $variables)) { |
45
|
|
|
$this->context->buildViolation($constraint->message) |
46
|
|
|
->setParameter('{{ value }}', $this->formatValue($value, self::OBJECT_TO_STRING)) |
47
|
|
|
->setCode(Expression::EXPRESSION_FAILED_ERROR) |
48
|
|
|
->addViolation(); |
49
|
|
|
} |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
private function getExpressionLanguage() |
53
|
|
|
{ |
54
|
|
|
if (null === $this->expressionLanguage) { |
55
|
|
|
if (!class_exists('Symfony\Component\ExpressionLanguage\ExpressionLanguage')) { |
56
|
|
|
throw new LogicException('Unable to use expressions as the Symfony ExpressionLanguage component is not installed.'); |
57
|
|
|
} |
58
|
|
|
$this->expressionLanguage = new ExpressionLanguage(); |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
return $this->expressionLanguage; |
62
|
|
|
} |
63
|
|
|
} |
64
|
|
|
|