1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/* |
4
|
|
|
* This file is part of Respect/Validation. |
5
|
|
|
* |
6
|
|
|
* (c) Alexandre Gomes Gaigalas <[email protected]> |
7
|
|
|
* |
8
|
|
|
* For the full copyright and license information, please view the "LICENSE.md" |
9
|
|
|
* file that was distributed with this source code. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
declare(strict_types=1); |
13
|
|
|
|
14
|
|
|
namespace Respect\Validation\Rules; |
15
|
|
|
|
16
|
|
|
use function in_array; |
17
|
|
|
use function is_array; |
18
|
|
|
use function mb_detect_encoding; |
19
|
|
|
use function mb_stripos; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* Validates if the input contains at least one of provided values. |
23
|
|
|
* |
24
|
|
|
* @author Alexandre Gomes Gaigalas <[email protected]> |
25
|
|
|
* @author Kirill Dlussky <[email protected]> |
26
|
|
|
*/ |
27
|
|
|
final class ContainsAny extends AbstractRule |
28
|
|
|
{ |
29
|
|
|
/** |
30
|
|
|
* @var array |
31
|
|
|
*/ |
32
|
|
|
private $needles; |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* @var bool |
36
|
|
|
*/ |
37
|
|
|
private $strictCompareArray; |
38
|
|
|
|
39
|
|
|
/** |
40
|
|
|
* Initializes the ContainsAny rule. |
41
|
|
|
* |
42
|
|
|
* @param array $needles At least one of the values provided must be found in input string or array |
43
|
|
|
* @param bool $strictCompareArray Defines whether the value should be compared strictly, when validating array |
44
|
|
|
*/ |
45
|
|
|
public function __construct(array $needles, bool $strictCompareArray = false) |
46
|
|
|
{ |
47
|
|
|
$this->needles = $needles; |
48
|
|
|
$this->strictCompareArray = $strictCompareArray; |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
/** |
52
|
|
|
* {@inheritdoc} |
53
|
|
|
*/ |
54
|
|
|
public function validate($input): bool |
55
|
|
|
{ |
56
|
|
|
if (is_array($input)) { |
57
|
|
|
return $this->validateArray($input); |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
return $this->validateString((string) $input); |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
private function validateString(string $inputString): bool |
64
|
|
|
{ |
65
|
|
|
foreach ($this->needles as &$needle) { |
66
|
|
|
if (false !== mb_stripos($inputString, (string) $needle, 0, mb_detect_encoding($inputString))) { |
67
|
|
|
return true; |
68
|
|
|
} |
69
|
|
|
} unset ($needle); |
70
|
|
|
|
71
|
|
|
return false; |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
private function validateArray(array $inputArray): bool |
75
|
|
|
{ |
76
|
|
|
foreach ($this->needles as &$needle) { |
77
|
|
|
if (in_array($needle, $inputArray, $this->strictCompareArray)) { |
78
|
|
|
return true; |
79
|
|
|
} |
80
|
|
|
} unset ($needle); |
81
|
|
|
|
82
|
|
|
return false; |
83
|
|
|
} |
84
|
|
|
} |
85
|
|
|
|