Integer::__invoke()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 39
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 4

Importance

Changes 0
Metric Value
cc 4
eloc 15
nc 4
nop 2
dl 0
loc 39
ccs 16
cts 16
cp 1
crap 4
rs 9.7666
c 0
b 0
f 0
1
<?php
2
3
namespace Mbright\Validation\Rule\Sanitize;
4
5
class Integer implements SanitizeRuleInterface
6
{
7
    /**
8
     * Converts the field to an integer.
9
     *
10
     * @param $subject
11
     * @param string $field
12
     *
13
     * @return bool
14
     */
15 15
    public function __invoke($subject, string $field): bool
16
    {
17 15
        $value = $subject->$field;
18
19 15
        if (is_numeric($value)) {
20
            // we double-cast here to honor scientific notation.
21
            // (int) 1E5 == 15, but (int) (float) 1E5 == 100000
22 3
            $value = (float) $value;
23 3
            $subject->$field = (int) $value;
24
25 3
            return true;
26
        }
27
28 12
        if (!is_string($value)) {
29
            // cannot sanitize a non-string
30 3
            return false;
31
        }
32
33
        // it's a non-numeric string, attempt to extract an integer from it.
34
35
        // remove all chars except digit and minus. this removes all + signs; any - sign takes precedence because
36
        //     0 + -1 = -1
37
        //     0 - +1 = -1
38
        // ... at least it seems that way to me now.
39 9
        $value = preg_replace('/[^0-9-]/', '', $value);
40
41
        // remove all trailing minuses
42 9
        $value = rtrim($value, '-');
43
44
        // remove all minuses not at the front
45 9
        $isNegative = preg_match('/^-/', $value);
46 9
        $value = str_replace('-', '', $value);
47 9
        if ($isNegative) {
48 3
            $value = '-' . $value;
49
        }
50
51 9
        $subject->$field = (int) $value;
52
53 9
        return true;
54
    }
55
}
56