BitNormalizer::getNormalized()   D
last analyzed

Complexity

Conditions 10
Paths 9

Size

Total Lines 35
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 11.3498

Importance

Changes 0
Metric Value
dl 0
loc 35
c 0
b 0
f 0
ccs 16
cts 21
cp 0.7619
rs 4.8196
cc 10
eloc 21
nc 9
nop 1
crap 11.3498

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/**
4
 * @author KonstantinKuklin <[email protected]>
5
 */
6
7
namespace KonstantinKuklin\DoctrineCompressedFields;
8
9
use KonstantinKuklin\DoctrineCompressedFields\Exception\WrongBitMappingRule;
10
11
class BitNormalizer
12
{
13
    /**
14
     * @param string[] $bitList
15
     *
16
     * @return int[]
17
     * @throws \Exception
18
     */
19 8
    public static function getNormalized(array $bitList)
20
    {
21 8
        $bitListNormalized = [];
22 8
        foreach ($bitList as $bitRow) {
23 8
            $matches = [];
24 8
            preg_match('/^(?<first>[\d]+)(-(?<second>[\d]+))?$/', (string)$bitRow, $matches);
25 8
            if (empty($matches)) {
26
                throw new WrongBitMappingRule("Incorrect Bit syntax: '{$bitRow}'");
27
            }
28
29 8
            if (!isset($matches['second'])) {
30 8
                if (isset($bitListNormalized[$matches['first']])) {
31
                    throw new WrongBitMappingRule('You can`t add "-" after number.');
32
                }
33 8
                $bitListNormalized[$matches['first']] = (int)$matches['first'];
34 8
                continue;
35
            }
36
37 1
            if ($matches['first'] > $matches['second']) {
38
                throw new WrongBitMappingRule("Start bit zone should be greater than end. But got: {$matches['first']} - {$matches['second']}");
39
            }
40 1
            if (!is_numeric($matches['first']) || !is_numeric($matches['second'])) {
41
                throw new WrongBitMappingRule("Start and end of zone should be numbers, but got: {$matches['first']} - {$matches['second']}");
42
            }
43
44 1
            for ($i = (int)$matches['first'], $end = $matches['second']; $i <= $end; $i++) {
45 1
                if (isset($bitListNormalized[$i])) {
46
                    throw new WrongBitMappingRule("Bit {$bitListNormalized[$i]} used more than once");
47
                }
48 1
                $bitListNormalized[$i] = $i; // Bits started from 1, but in array we start working with 0
49
            }
50
        }
51
52 8
        return array_values($bitListNormalized);
53
    }
54
}
55