1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* InArray |
4
|
|
|
* |
5
|
|
|
* @category StrokerForm\Renderer\JqueryValidate\Rule |
6
|
|
|
* @package StrokerForm\Renderer\JqueryValidate\Rule |
7
|
|
|
* @copyright 2013 ACSI Holding bv (http://www.acsi.eu) |
8
|
|
|
* @version SVN: $Id$ |
9
|
|
|
*/ |
10
|
|
|
|
11
|
|
|
namespace StrokerForm\Renderer\JqueryValidate\Rule; |
12
|
|
|
|
13
|
|
|
use Zend\Form\ElementInterface; |
14
|
|
|
use Zend\Validator\ValidatorInterface; |
15
|
|
|
use Zend\Validator\InArray as InArrayValidator; |
16
|
|
|
|
17
|
|
|
class InArray extends AbstractRule |
18
|
|
|
{ |
19
|
|
|
/** |
20
|
|
|
* Get the validation rules |
21
|
|
|
* |
22
|
|
|
* @param \Zend\Validator\ValidatorInterface $validator |
23
|
|
|
* @param \Zend\Form\ElementInterface $element |
24
|
|
|
* |
25
|
|
|
* @return array |
26
|
|
|
*/ |
27
|
|
|
public function getRules(ValidatorInterface $validator, ElementInterface $element = null) |
28
|
|
|
{ |
29
|
|
|
// Javascript doesn't support associative arrays. Therefore, check if the array is associative, |
30
|
|
|
// and if so, transform it to a non-associative one. |
31
|
|
|
if (array_keys($validator->getHaystack()) !== range(0, count($validator->getHaystack()) - 1)) { |
|
|
|
|
32
|
|
|
return ['in_array' => array_values($validator->getHaystack())]; |
|
|
|
|
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
return ['in_array' => (array)$validator->getHaystack()]; |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
/** |
39
|
|
|
* Get the validation message |
40
|
|
|
* |
41
|
|
|
* @param \Zend\Validator\ValidatorInterface $validator |
42
|
|
|
* |
43
|
|
|
* @return string |
44
|
|
|
*/ |
45
|
|
|
public function getMessages(ValidatorInterface $validator) |
46
|
|
|
{ |
47
|
|
|
return [ |
48
|
|
|
'in_array' => |
49
|
|
|
$this->translateMessage('The input is not a valid option') |
50
|
|
|
]; |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
/** |
54
|
|
|
* Whether this rule supports certain validators |
55
|
|
|
* |
56
|
|
|
* @param ValidatorInterface $validator |
57
|
|
|
* @return mixed |
58
|
|
|
*/ |
59
|
|
|
public function canHandle(ValidatorInterface $validator) |
60
|
|
|
{ |
61
|
|
|
return $validator instanceof InArrayValidator; |
62
|
|
|
} |
63
|
|
|
} |
64
|
|
|
|
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: