StrBetween::__invoke()   A
last analyzed

Complexity

Conditions 4
Paths 5

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 4

Importance

Changes 0
Metric Value
cc 4
eloc 8
nc 5
nop 2
dl 0
loc 14
ccs 9
cts 9
cp 1
crap 4
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Mbright\Validation\Rule\Sanitize;
4
5
use Mbright\Validation\Rule\AbstractStringCase;
6
7
class StrBetween extends AbstractStringCase implements SanitizeRuleInterface
8
{
9
    /** @var int */
10
    protected $min;
11
12
    /** @var int */
13
    protected $max;
14
15
    /** @var string */
16
    protected $padString;
17
18
    /** @var int */
19
    protected $padType;
20
21
    /**
22
     * @param int $min The minimum length.
23
     * @param int $max The maximum length.
24
     * @param string $pad_string Pad using this string.
25
     * @param int $pad_type A `STR_PAD_*` constant.
26
     *
27
     */
28 39
    public function __construct(int $min, int $max, string $padString = ' ', int $padType = STR_PAD_RIGHT)
29
    {
30 39
        $this->min = $min;
31 39
        $this->max = $max;
32 39
        $this->padString = $padString;
33 39
        $this->padType = $padType;
34 39
    }
35
36
    /**
37
     * Sanitizes a string to a length range by padding or chopping it.
38
     *
39
     * @param object $subject The subject to be filtered.
40
     * @param string $field The subject field name.
41
     *
42
     * @return bool True if the value was sanitized, false if not.
43
     */
44 39
    public function __invoke($subject, string $field): bool
45
    {
46 39
        $value = $subject->$field;
47 39
        if (!is_scalar($value)) {
48 3
            return false;
49
        }
50 36
        if ($this->strlen($value) < $this->min) {
51 6
            $subject->$field = $this->strpad($value, $this->min, $this->padString, $this->padType);
52
        }
53 36
        if ($this->strlen($value) > $this->max) {
54 12
            $subject->$field = $this->substr($value, 0, $this->max);
55
        }
56
57 36
        return true;
58
    }
59
}
60