Issues (10)

src/Guards/Bases/StringBase.php (1 issue)

1
<?php
2
declare(strict_types=1);
3
4
namespace InputGuard\Guards\Bases;
5
6
trait StringBase
7
{
8
    use Strict;
9
10
    /**
11
     * @var int
12
     */
13
    private $minLen = 0;
14
15
    /**
16
     * @var int|null
17
     */
18
    private $maxLen;
19
20
    /**
21
     * @var string
22
     */
23
    private $regex = '';
24
25 9
    public function minLen(int $min): self
26
    {
27 9
        $this->minLen = $min;
28
29 9
        return $this;
30
    }
31
32 10
    public function maxLen(?int $max): self
33
    {
34 10
        $this->maxLen = $max;
35
36 10
        return $this;
37
    }
38
39 2
    public function betweenLen(int $min, ?int $max): self
40
    {
41 2
        $this->minLen = $min;
42 2
        $this->maxLen = $max;
43
44 2
        return $this;
45
    }
46
47 8
    public function regex(string $regex): self
48
    {
49 8
        $this->regex = $regex;
50
51 8
        return $this;
52
    }
53
54
    /**
55
     * A method to allow extra validation to be done for strings.
56
     *
57
     * @param mixed $input
58
     *
59
     * @return bool
60
     */
61
    abstract protected function validationShortCircuit($input): bool;
62
63 37
    protected function validation($input, &$value): bool
64
    {
65 37
        return $this->validationShortCircuit($input) && $this->validationComplete($input, $value);
66
    }
67
68 30
    private function validationComplete($input, &$value): bool
69
    {
70 30
        $inputString = (string)$input;
71
72 30
        if ($this->isBetweenLength($inputString) && $this->passesRegex($inputString)) {
73 25
            $value = is_scalar($input) ? $inputString : $input;
0 ignored issues
show
Inline IF statements are not allowed
Loading history...
74
75 25
            return true;
76
        }
77
78 5
        return false;
79
    }
80
81 30
    private function isBetweenLength(string $input): bool
82
    {
83 30
        $length = mb_strlen($input, mb_detect_encoding($input));
84
85 30
        return $this->isMoreThanMinLength($length) && $this->isLessThanMaxLength($length);
86
    }
87
88 30
    private function isMoreThanMinLength(int $length): bool
89
    {
90 30
        return $length >= $this->minLen;
91
    }
92
93 28
    private function isLessThanMaxLength(int $length): bool
94
    {
95 28
        return $this->maxLen === null || $length <= $this->maxLen;
96
    }
97
98 26
    private function passesRegex(string $input): bool
99
    {
100 26
        return $this->regex === '' || preg_match($this->regex, $input) === 1;
101
    }
102
}
103