-
Notifications
You must be signed in to change notification settings - Fork 773
Expand file tree
/
Copy pathFilterVar.php
More file actions
66 lines (57 loc) · 1.89 KB
/
FilterVar.php
File metadata and controls
66 lines (57 loc) · 1.89 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
<?php
/*
* Copyright (c) Alexandre Gomes Gaigalas <alganet@gmail.com>
* SPDX-License-Identifier: MIT
*/
declare(strict_types=1);
namespace Respect\Validation\Validators;
use Attribute;
use Respect\Validation\Exceptions\InvalidRuleConstructorException;
use Respect\Validation\Message\Template;
use Respect\Validation\Result;
use Respect\Validation\Validator;
use function array_key_exists;
use function filter_var;
use const FILTER_VALIDATE_BOOLEAN;
use const FILTER_VALIDATE_DOMAIN;
use const FILTER_VALIDATE_EMAIL;
use const FILTER_VALIDATE_FLOAT;
use const FILTER_VALIDATE_INT;
use const FILTER_VALIDATE_IP;
use const FILTER_VALIDATE_REGEXP;
use const FILTER_VALIDATE_URL;
#[Attribute(Attribute::TARGET_PROPERTY | Attribute::IS_REPEATABLE)]
#[Template(
'{{subject}} must be valid',
'{{subject}} must not be valid',
)]
final readonly class FilterVar implements Validator
{
private const array ALLOWED_FILTERS = [
FILTER_VALIDATE_BOOLEAN => 'is_bool',
FILTER_VALIDATE_DOMAIN => 'is_string',
FILTER_VALIDATE_EMAIL => 'is_string',
FILTER_VALIDATE_FLOAT => 'is_float',
FILTER_VALIDATE_INT => 'is_int',
FILTER_VALIDATE_IP => 'is_string',
FILTER_VALIDATE_REGEXP => 'is_string',
FILTER_VALIDATE_URL => 'is_string',
];
public function __construct(private int $filter, private mixed $options = null)
{
if (!array_key_exists($filter, self::ALLOWED_FILTERS)) {
throw new InvalidRuleConstructorException('Cannot accept the given filter');
}
}
public function evaluate(mixed $input): Result
{
return Result::of(
(self::ALLOWED_FILTERS[$this->filter])(match ($this->options) {
null => filter_var($input, $this->filter),
default => filter_var($input, $this->filter, $this->options),
}),
$input,
$this,
);
}
}