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

BitValue   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 32
Duplicated Lines 0 %

Test Coverage

Coverage 90%

Importance

Changes 0
Metric Value
eloc 9
dl 0
loc 32
ccs 9
cts 10
cp 0.9
rs 10
c 0
b 0
f 0
wmc 5

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 7 3
A __invoke() 0 7 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
    /**
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