1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace FOA\CronBundle\Validator\Constraints; |
4
|
|
|
|
5
|
|
|
use Symfony\Component\Validator\Constraint; |
6
|
|
|
use Symfony\Component\Validator\ConstraintValidator; |
7
|
|
|
|
8
|
|
|
/** |
9
|
|
|
* @author JM Leroux <[email protected]> |
10
|
|
|
*/ |
11
|
|
|
abstract class AbstractCronTimeFormatValidator extends ConstraintValidator |
12
|
|
|
{ |
13
|
|
|
/** |
14
|
|
|
* @param string|int $value |
15
|
|
|
* @param Constraint $constraint |
16
|
|
|
*/ |
17
|
|
|
public function validate($value, Constraint $constraint) |
18
|
|
|
{ |
19
|
|
|
if (false !== strpos($value, ',')) { |
20
|
|
|
$isValid = $this->validateList(explode(',', $value)); |
21
|
|
|
} else { |
22
|
|
|
$isValid = $this->validateItem($value); |
23
|
|
|
} |
24
|
|
|
|
25
|
|
|
if (!$isValid) { |
26
|
|
|
$this->context->buildViolation($constraint->message) |
|
|
|
|
27
|
|
|
->setParameter('%string%', $value) |
28
|
|
|
->addViolation(); |
29
|
|
|
} |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* @param array $list |
34
|
|
|
* |
35
|
|
|
* @return bool |
36
|
|
|
*/ |
37
|
|
|
private function validateList($list) |
38
|
|
|
{ |
39
|
|
|
foreach ($list as $item) { |
40
|
|
|
if (!$this->validateItem($item)) { |
41
|
|
|
return false; |
42
|
|
|
} |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
return true; |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
/** |
49
|
|
|
* @param int|string $item |
50
|
|
|
* |
51
|
|
|
* @return bool |
52
|
|
|
*/ |
53
|
|
|
private function validateItem($item) |
54
|
|
|
{ |
55
|
|
|
if (false !== strpos($item, '-')) { |
56
|
|
|
return $this->validateRange($item); |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
return $this->validateTimeEntry($item); |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
/** |
63
|
|
|
* @param int|string $range |
64
|
|
|
* |
65
|
|
|
* @return bool |
66
|
|
|
*/ |
67
|
|
|
private function validateRange($range) |
68
|
|
|
{ |
69
|
|
|
$items = explode('-', $range); |
70
|
|
|
|
71
|
|
|
if (count($items) !== 2) { |
72
|
|
|
return false; |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
foreach ($items as $item) { |
76
|
|
|
if (!$this->validateTimeEntry($item)) { |
77
|
|
|
return false; |
78
|
|
|
} |
79
|
|
|
} |
80
|
|
|
|
81
|
|
|
return true; |
82
|
|
|
} |
83
|
|
|
|
84
|
|
|
/** |
85
|
|
|
* @param int|string $item |
86
|
|
|
* |
87
|
|
|
* @return bool |
88
|
|
|
*/ |
89
|
|
|
abstract protected function validateTimeEntry($item); |
90
|
|
|
} |
91
|
|
|
|
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 implementation 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 interface: