Hex::__invoke()   A
last analyzed

Complexity

Conditions 5
Paths 4

Size

Total Lines 18
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 5.025

Importance

Changes 0
Metric Value
cc 5
eloc 9
nc 4
nop 2
dl 0
loc 18
ccs 9
cts 10
cp 0.9
crap 5.025
rs 9.6111
c 0
b 0
f 0
1
<?php
2
3
namespace Mbright\Validation\Rule\Validate;
4
5
class Hex implements ValidateRuleInterface
6
{
7
    /** @var int */
8
    protected $max;
9
10
11
    /**
12
     * @param int|null $max Maximum "ceiling" value for the hex
13
     */
14 27
    public function __construct(int $max = null)
15
    {
16 27
        $this->max = $max;
17 27
    }
18
19
    /**
20
     * Sanitizes a value to a hex.
21
     *
22
     * @param $subject
23
     * @param $field
24
     *
25
     * @return bool
26
     */
27 27
    public function __invoke($subject, string $field): bool
28
    {
29 27
        $value = $subject->$field;
30
31 27
        if (!is_scalar($value)) {
32 3
            return false;
33
        }
34
35 24
        $hex = ctype_xdigit($value);
36 24
        if (!$hex) {
37 12
            return false;
38
        }
39
40 12
        if ($this->max && strlen($value) > $this->max) {
41
            return false;
42
        }
43
44 12
        return true;
45
    }
46
}
47