Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
Total | |
100.00% |
12 / 12 |
|
100.00% |
2 / 2 |
CRAP | |
100.00% |
1 / 1 |
StringInputLength | |
100.00% |
12 / 12 |
|
100.00% |
2 / 2 |
7 | |
100.00% |
1 / 1 |
validate | |
100.00% |
5 / 5 |
|
100.00% |
1 / 1 |
4 | |||
isDateTime | |
100.00% |
7 / 7 |
|
100.00% |
1 / 1 |
3 |
1 | <?php |
2 | |
3 | declare(strict_types=1); |
4 | |
5 | namespace Engelsystem\Http\Validation\Rules; |
6 | |
7 | use DateTime; |
8 | use Exception; |
9 | use Illuminate\Support\Str; |
10 | |
11 | trait StringInputLength |
12 | { |
13 | /** |
14 | * Use the input length of a string |
15 | */ |
16 | public function validate(mixed $input): bool |
17 | { |
18 | if ( |
19 | is_string($input) |
20 | && !is_numeric($input) |
21 | && !$this->isDateTime($input) |
22 | ) { |
23 | $input = Str::length($input); |
24 | } |
25 | |
26 | return parent::validate($input); |
27 | } |
28 | |
29 | protected function isDateTime(mixed $input): bool |
30 | { |
31 | try { |
32 | $inputDateTime = new DateTime($input); |
33 | $now = new DateTime(); |
34 | |
35 | // Min 1s diff to exclude any not auto-detected dates / times like ... |
36 | return abs($inputDateTime->getTimestamp() - $now->getTimestamp()) > 1 |
37 | // Different timezone to prevent interpreting the value as a timezone which happens with H |
38 | && $inputDateTime->getTimezone()->getName() != $input; |
39 | } catch (Exception) { |
40 | // Ignore it |
41 | } |
42 | |
43 | return false; |
44 | } |
45 | } |