Completed
Push — master ( 8aa7dc...60303f )
by Marcus
02:14
created

BitValue::__construct()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 3.1406

Importance

Changes 0
Metric Value
cc 3
eloc 3
nc 2
nop 1
dl 0
loc 7
ccs 3
cts 4
cp 0.75
crap 3.1406
rs 10
c 0
b 0
f 0
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
    /**
18
     * @param int $size number of bits to allow
19
     */
20 9
    public function __construct(int $size)
21
    {
22 9
        if ($size < 1 || $size > 64) {
23
            throw new \InvalidArgumentException('Mysql Bit columns can only accept a size between 1 and 64');
24
        }
25
26 9
        $this->size = $size;
27 9
    }
28
29
    /**
30
     * Validates that the given field has an integer value that can be expressed in the appropriate number of bits.
31
     *
32
     * @param object $subject
33
     * @param string $field
34
     *
35
     * @return bool
36
     */
37 9
    public function __invoke($subject, string $field): bool
38
    {
39 9
        $value = $subject->$field;
40 9
        $isInteger = $this->isInteger($value);
41 9
        $size = (int)(log($value) / log(2)) + 1;
42
43 9
        return $isInteger && $size <= $this->size;
44
    }
45
}
46