1 | <?php |
||
2 | |||
3 | namespace Mbright\Validation\Rule\Sanitize; |
||
4 | |||
5 | class Hex |
||
6 | { |
||
7 | /** @var int|null */ |
||
8 | protected $max; |
||
9 | |||
10 | /** |
||
11 | * @param int|null $max |
||
12 | */ |
||
13 | 3 | public function __construct(int $max = null) |
|
14 | { |
||
15 | 3 | $this->max = $max; |
|
16 | 3 | } |
|
17 | |||
18 | /** |
||
19 | * @param $subject |
||
20 | * @param $field |
||
21 | * |
||
22 | * @return bool |
||
23 | */ |
||
24 | 3 | public function __invoke($subject, string $field): bool |
|
25 | { |
||
26 | 3 | $value = $subject->$field; |
|
27 | |||
28 | 3 | if (!is_scalar($value)) { |
|
29 | return false; |
||
30 | } |
||
31 | |||
32 | 3 | $value = preg_replace('/[^0-9a-f]/i', '', $value); |
|
33 | 3 | if ($value === '') { |
|
34 | return false; |
||
35 | } |
||
36 | |||
37 | 3 | if ($this->max && strlen($value) > $this->max) { |
|
0 ignored issues
–
show
|
|||
38 | $value = substr($value, 0, $this->max); |
||
39 | } |
||
40 | |||
41 | 3 | $subject->$field = $value; |
|
42 | |||
43 | 3 | return true; |
|
44 | } |
||
45 | } |
||
46 |
In PHP, under loose comparison (like
==
, or!=
, orswitch
conditions), values of different types might be equal.For
integer
values, zero is a special case, in particular the following results might be unexpected: