Passed
Push — master ( f7d6c6...2d02cb )
by Petr
02:57
created

RowsTrait::fillDataFromRow()   B

Complexity

Conditions 10
Paths 11

Size

Total Lines 22
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 17
CRAP Score 10

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 17
c 1
b 0
f 0
dl 0
loc 22
ccs 17
cts 17
cp 1
rs 7.6666
cc 10
nc 11
nop 1
crap 10

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
namespace kalanis\nested_tree\Support;
4
5
/**
6
 * Trait to work with rows - convert them to the node data
7
 * @property Node $nodeBase
8
 * @property TableSettings $settings
9
 */
10
trait RowsTrait
11
{
12
    /**
13
     * @param array<array<mixed>> $rows
14
     * @param bool $hasIdAsKey
15
     * @return array<int, Node>
16
     */
17 120
    protected function fromDbRows(array $rows, bool $hasIdAsKey = true) : array
18
    {
19 120
        $result = [];
20 120
        foreach ($rows as &$row) {
21 120
            $data = $this->fillDataFromRow($row);
22 120
            if ($hasIdAsKey) {
23 120
                $result[$data->id] = $data;
24
            } else {
25 16
                $result[] = $data;
26
            }
27
        }
28
29 120
        return $result;
30
    }
31
32
    /**
33
     * @param array<mixed> $row
34
     * @return Node
35
     */
36 120
    protected function fillDataFromRow(array $row) : Node
37
    {
38 120
        $data = clone $this->nodeBase;
39 120
        foreach ($row as $k => $v) {
40 120
            if ($this->settings->idColumnName === $k) {
41 120
                $data->id = max(0, intval($v));
42 120
            } elseif ($this->settings->parentIdColumnName === $k) {
43 120
                $data->parentId = is_null($v) && $this->settings->rootIsNull ? null : max(0, intval($v));
44 120
            } elseif ($this->settings->levelColumnName === $k) {
45 120
                $data->level = max(0, intval($v));
46 120
            } elseif ($this->settings->leftColumnName === $k) {
47 120
                $data->left = max(0, intval($v));
48 120
            } elseif ($this->settings->rightColumnName === $k) {
49 120
                $data->right = max(0, intval($v));
50 120
            } elseif ($this->settings->positionColumnName === $k) {
51 120
                $data->position = max(0, intval($v));
52
            } else {
53 120
                $data->{$k} = strval($v);
54
            }
55
        }
56
57 120
        return $data;
58
    }
59
}
60