1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/* |
4
|
|
|
* This file is part of the Valdi package. |
5
|
|
|
* |
6
|
|
|
* (c) Philip Lehmann-Böhm <[email protected]> |
7
|
|
|
* |
8
|
|
|
* For the full copyright and license information, please view the LICENSE |
9
|
|
|
* file that was distributed with this source code. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
namespace Valdi\Validator; |
13
|
|
|
|
14
|
|
|
use Valdi\ValidationException; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* Validator for strings containing a substring. |
18
|
|
|
*/ |
19
|
|
|
class Contains implements ValidatorInterface |
20
|
|
|
{ |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* Throws an exception if the parameters don't fulfill the expected |
24
|
|
|
* parameter count. |
25
|
|
|
* |
26
|
|
|
* @param integer $parameterAmount the amount of expected parameters |
27
|
|
|
* |
28
|
|
|
* @throws ValidationException - thrown if less than one parameter is given |
29
|
|
|
*/ |
30
|
1 |
|
protected function validateParameterCount($parameterAmount) |
31
|
|
|
{ |
32
|
1 |
|
if ($parameterAmount < 1) { |
33
|
1 |
|
throw new ValidationException('"contains" expects at least 1 parameter.'); |
34
|
|
|
} |
35
|
1 |
|
} |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* Adjusts value and parameters to be case insensitive if the second |
39
|
|
|
* parameter says so or is not given. |
40
|
|
|
* |
41
|
|
|
* @param mixed $value the value to validate |
42
|
|
|
* |
43
|
|
|
* @param array $parameters - the other parameters the validator need |
44
|
|
|
*/ |
45
|
1 |
|
protected function adjustCaseInsensitive(&$value, &$parameters) |
46
|
|
|
{ |
47
|
1 |
|
$parameterAmount = count($parameters); |
48
|
1 |
|
if ($parameterAmount == 1 || $parameterAmount > 1 && $parameters[1]) { |
49
|
1 |
|
$parameters[0] = strtolower($parameters[0]); |
50
|
1 |
|
$value = strtolower($value); |
51
|
|
|
} |
52
|
1 |
|
} |
53
|
|
|
|
54
|
|
|
/** |
55
|
|
|
* {@inheritdoc} |
56
|
|
|
*/ |
57
|
1 |
|
public function isValid($value, array $parameters) |
58
|
|
|
{ |
59
|
1 |
|
$parameterAmount = count($parameters); |
60
|
|
|
|
61
|
1 |
|
$this->validateParameterCount($parameterAmount); |
62
|
1 |
|
$this->adjustCaseInsensitive($value, $parameters); |
63
|
|
|
|
64
|
1 |
|
return in_array($value, ['', null], true) || strpos($value, $parameters[0]) !== false; |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
/** |
68
|
|
|
* {@inheritdoc} |
69
|
|
|
*/ |
70
|
1 |
|
public function getInvalidDetails() |
71
|
|
|
{ |
72
|
1 |
|
return 'contains'; |
73
|
|
|
} |
74
|
|
|
} |
75
|
|
|
|