|
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 is_scalar; |
|
19
|
|
|
use function mb_detect_encoding; |
|
20
|
|
|
use function mb_stripos; |
|
21
|
|
|
use function mb_strpos; |
|
22
|
|
|
|
|
23
|
|
|
/** |
|
24
|
|
|
* Validates if the input contains some value. |
|
25
|
|
|
* |
|
26
|
|
|
* @author Alexandre Gomes Gaigalas <[email protected]> |
|
27
|
|
|
* @author Henrique Moody <[email protected]> |
|
28
|
|
|
* @author Marcelo Araujo <[email protected]> |
|
29
|
|
|
* @author William Espindola <[email protected]> |
|
30
|
|
|
*/ |
|
31
|
|
|
final class Contains extends AbstractRule |
|
32
|
|
|
{ |
|
33
|
|
|
/** |
|
34
|
|
|
* @var mixed |
|
35
|
|
|
*/ |
|
36
|
|
|
private $containsValue; |
|
37
|
|
|
|
|
38
|
|
|
/** |
|
39
|
|
|
* @var bool |
|
40
|
|
|
*/ |
|
41
|
|
|
private $identical; |
|
42
|
|
|
|
|
43
|
|
|
/** |
|
44
|
|
|
* Initializes the Contains rule. |
|
45
|
|
|
* |
|
46
|
|
|
* @param mixed $containsValue Value that will be sought |
|
47
|
|
|
* @param bool $identical Defines whether the value is identical, default is false |
|
48
|
|
|
*/ |
|
49
|
2 |
|
public function __construct($containsValue, bool $identical = false) |
|
50
|
|
|
{ |
|
51
|
2 |
|
$this->containsValue = $containsValue; |
|
52
|
2 |
|
$this->identical = $identical; |
|
53
|
2 |
|
} |
|
54
|
|
|
|
|
55
|
|
|
/** |
|
56
|
|
|
* {@inheritdoc} |
|
57
|
|
|
*/ |
|
58
|
25 |
|
public function validate($input): bool |
|
59
|
|
|
{ |
|
60
|
25 |
|
if (is_array($input)) { |
|
61
|
13 |
|
return in_array($this->containsValue, $input, $this->identical); |
|
62
|
|
|
} |
|
63
|
|
|
|
|
64
|
14 |
|
if (!is_scalar($input) || !is_scalar($this->containsValue)) { |
|
65
|
|
|
return false; |
|
66
|
|
|
} |
|
67
|
|
|
|
|
68
|
14 |
|
return $this->validateString((string) $input, (string) $this->containsValue); |
|
69
|
|
|
} |
|
70
|
|
|
|
|
71
|
14 |
|
private function validateString(string $haystack, string $needle): bool |
|
72
|
|
|
{ |
|
73
|
14 |
|
if ('' === $needle) { |
|
74
|
|
|
return false; |
|
75
|
|
|
} |
|
76
|
|
|
|
|
77
|
14 |
|
$encoding = mb_detect_encoding($haystack); |
|
78
|
14 |
|
if ($this->identical) { |
|
79
|
4 |
|
return false !== mb_strpos($haystack, $needle, 0, $encoding); |
|
80
|
|
|
} |
|
81
|
|
|
|
|
82
|
10 |
|
return false !== mb_stripos($haystack, $needle, 0, $encoding); |
|
83
|
|
|
} |
|
84
|
|
|
} |
|
85
|
|
|
|