Strlen::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

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