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
|
|
|
* Throws an exception if the parameters don't fullfill the expected |
23
|
|
|
* parameter count. |
24
|
|
|
* |
25
|
|
|
* @param integer $parameterAmount |
26
|
|
|
* the amount of expected parameters |
27
|
|
|
*/ |
28
|
|
|
protected function validateParameterCount($parameterAmount) { |
29
|
|
|
if ($parameterAmount < 1) { |
30
|
|
|
throw new ValidationException('"contains" expects at least 1 parameter.'); |
31
|
|
|
} |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* Adjusts value and parameters to be case insensitive if the second |
36
|
|
|
* parameter says so or is not given. |
37
|
|
|
* |
38
|
|
|
* @param mixed $value |
39
|
|
|
* the value to validate |
40
|
|
|
* |
41
|
|
|
* @param array $parameters |
42
|
|
|
* the other parameters the validator need |
43
|
|
|
*/ |
44
|
|
|
protected function adjustCaseInsensitive(&$value, &$parameters) { |
45
|
|
|
$parameterAmount = count($parameters); |
46
|
|
|
if ($parameterAmount == 1 || $parameterAmount > 1 && $parameters[1]) { |
47
|
|
|
$parameters[0] = strtolower($parameters[0]); |
48
|
|
|
$value = strtolower($value); |
49
|
|
|
} |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
/** |
53
|
|
|
* {@inheritdoc} |
54
|
|
|
*/ |
55
|
|
|
public function isValid($value, array $parameters) { |
56
|
|
|
$parameterAmount = count($parameters); |
57
|
|
|
|
58
|
|
|
$this->validateParameterCount($parameterAmount); |
59
|
|
|
$this->adjustCaseInsensitive($value, $parameters); |
60
|
|
|
|
61
|
|
|
return in_array($value, array('', null), true) || strpos($value, $parameters[0]) !== false; |
62
|
|
|
} |
63
|
|
|
} |
64
|
|
|
|