Hex::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Mbright\Validation\Rule\Sanitize;
4
5
class Hex
6
{
7
    /** @var int|null */
8
    protected $max;
9
10
    /**
11
     * @param int|null $max
12
     */
13 3
    public function __construct(int $max = null)
14
    {
15 3
        $this->max = $max;
16 3
    }
17
18
    /**
19
     * @param $subject
20
     * @param $field
21
     *
22
     * @return bool
23
     */
24 3
    public function __invoke($subject, string $field): bool
25
    {
26 3
        $value = $subject->$field;
27
28 3
        if (!is_scalar($value)) {
29
            return false;
30
        }
31
32 3
        $value = preg_replace('/[^0-9a-f]/i', '', $value);
33 3
        if ($value === '') {
34
            return false;
35
        }
36
37 3
        if ($this->max && strlen($value) > $this->max) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->max of type integer|null is loosely compared to true; this is ambiguous if the integer can be 0. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
38
            $value = substr($value, 0, $this->max);
39
        }
40
41 3
        $subject->$field = $value;
42
43 3
        return true;
44
    }
45
}
46