Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
2 / 2
CRAP
100.00% covered (success)
100.00%
1 / 1
StringInputLength
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
2 / 2
7
100.00% covered (success)
100.00%
1 / 1
 validate
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
4
 isDateTime
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
3
1<?php
2
3declare(strict_types=1);
4
5namespace Engelsystem\Http\Validation\Rules;
6
7use DateTime;
8use Exception;
9use Illuminate\Support\Str;
10
11trait 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}