1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace SLLH\IsoCodesValidator; |
4
|
|
|
|
5
|
|
|
use SLLH\IsoCodesValidator\Constraints\IsoCodesGeneric; |
6
|
|
|
use SLLH\IsoCodesValidator\Constraints\IsoCodesGenericValidator; |
7
|
|
|
use SLLH\IsoCodesValidator\Exception\ValidatorNotExistsException; |
8
|
|
|
use Symfony\Component\Validator\Constraint; |
9
|
|
|
use Symfony\Component\Validator\ConstraintValidator; |
10
|
|
|
use Symfony\Component\Validator\Context\ExecutionContext; |
11
|
|
|
use Symfony\Component\Validator\Context\ExecutionContextInterface; |
12
|
|
|
use Symfony\Component\Validator\Exception\UnexpectedTypeException; |
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* @author Sullivan Senechal <[email protected]> |
16
|
|
|
*/ |
17
|
|
|
abstract class AbstractIsoCodesConstraintValidator extends ConstraintValidator |
18
|
|
|
{ |
19
|
|
|
/** |
20
|
|
|
* Override PHP doc block to get IDE completion. |
21
|
|
|
* Can be removed when `buildViolation` would be added on ExecutionContextInterface. |
22
|
|
|
* Should probably done in Symfony 3.0. |
23
|
|
|
* |
24
|
|
|
* @var ExecutionContextInterface|ExecutionContext |
25
|
|
|
*/ |
26
|
|
|
protected $context; |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* {@inheritdoc} |
30
|
|
|
*/ |
31
|
|
|
public function validate($value, Constraint $constraint) |
32
|
|
|
{ |
33
|
|
|
$validatorClass = get_class($this); |
34
|
|
|
if (IsoCodesGenericValidator::class === $validatorClass |
35
|
|
|
&& !($constraint instanceof AbstractIsoCodesGenericConstraint || $constraint instanceof IsoCodesGeneric) |
36
|
|
|
) { |
37
|
|
|
throw new UnexpectedTypeException($constraint, AbstractIsoCodesGenericConstraint::class); |
38
|
|
|
} elseif (IsoCodesGenericValidator::class !== $validatorClass) { |
39
|
|
|
$constraintClass = preg_replace('/Validator$/', '', $validatorClass); |
40
|
|
|
|
41
|
|
|
if (!$constraint instanceof $constraintClass) { |
42
|
|
|
throw new UnexpectedTypeException($constraint, $constraintClass); |
43
|
|
|
} |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
if (!class_exists($constraint->getIsoCodesClass())) { |
|
|
|
|
47
|
|
|
throw new ValidatorNotExistsException($constraint); |
|
|
|
|
48
|
|
|
} |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
/** |
52
|
|
|
* Makes and adds a Constraint violation. |
53
|
|
|
* |
54
|
|
|
* @param string $message |
55
|
|
|
*/ |
56
|
|
|
protected function createViolation($message) |
57
|
|
|
{ |
58
|
|
|
$this->context->buildViolation($message) |
59
|
|
|
->addViolation(); |
60
|
|
|
} |
61
|
|
|
} |
62
|
|
|
|
Let’s take a look at an example:
In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.
Available Fixes
Change the type-hint for the parameter:
Add an additional type-check:
Add the method to the parent class: