Completed
Push — master ( 929034...adc5e6 )
by Marcus
02:23
created

BitValue::__invoke()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 5
cts 5
cp 1
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 2
crap 2
1
<?php
2
3
namespace Mbright\Validation\Rule\Validate\MySql;
4
5
use Mbright\Validation\Rule\Validate\AbstractIntegerCase;
6
use Mbright\Validation\Rule\Validate\ValidateRuleInterface;
7
8
/**
9
 * Validates that data can be inserted into one of the following column types:
10
 * - BIT
11
 */
12
class BitValue extends AbstractIntegerCase implements ValidateRuleInterface
13
{
14
    /** @var int */
15
    protected $size;
16
17 9
    public function __construct(int $size)
18
    {
19 9
        if ($size < 1 || $size > 64) {
20
            throw new \InvalidArgumentException('Mysql Bit columns can only accept a size between 1 and 64');
21
        }
22
23 9
        $this->size = $size;
24 9
    }
25
26
    /**
27
     * Validates that the given field has an integer value that can be expressed in the appropriate number of bits.
28
     *
29
     * @param object $subject
30
     * @param string $field
31
     *
32
     * @return bool
33
     */
34 9
    public function __invoke($subject, string $field): bool
35
    {
36 9
        $value = $subject->$field;
37 9
        $isInteger = $this->isInteger($value);
38 9
        $size = (int)(log($value) / log(2)) + 1;
39
40 9
        return $isInteger && $size <= $this->size;
41
    }
42
}
43