forked from Respect/Validation
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathIn.php
More file actions
70 lines (56 loc) · 1.75 KB
/
In.php
File metadata and controls
70 lines (56 loc) · 1.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
<?php
/*
* Copyright (c) Alexandre Gomes Gaigalas <alganet@gmail.com>
* SPDX-License-Identifier: MIT
*/
declare(strict_types=1);
namespace Respect\Validation\Rules;
use Attribute;
use Respect\Validation\Message\Template;
use Respect\Validation\Result;
use Respect\Validation\Rule;
use function in_array;
use function is_array;
use function mb_stripos;
use function mb_strpos;
#[Attribute(Attribute::TARGET_PROPERTY | Attribute::IS_REPEATABLE)]
#[Template(
'{{subject}} must be in {{haystack}}',
'{{subject}} must not be in {{haystack}}',
)]
final readonly class In implements Rule
{
public function __construct(
private mixed $haystack,
private bool $compareIdentical = false,
) {
}
public function evaluate(mixed $input): Result
{
$parameters = ['haystack' => $this->haystack];
if ($this->compareIdentical) {
return Result::of($this->validateIdentical($input), $input, $this, $parameters);
}
return Result::of($this->validateEquals($input), $input, $this, $parameters);
}
private function validateEquals(mixed $input): bool
{
if (is_array($this->haystack)) {
return in_array($input, $this->haystack);
}
if ($input === null || $input === '') {
return $input == $this->haystack;
}
return mb_stripos($this->haystack, (string) $input) !== false;
}
private function validateIdentical(mixed $input): bool
{
if (is_array($this->haystack)) {
return in_array($input, $this->haystack, true);
}
if ($input === null || $input === '') {
return $input === $this->haystack;
}
return mb_strpos($this->haystack, (string) $input) !== false;
}
}