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

RowsTrait::fromDbRows()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 8
c 1
b 0
f 0
dl 0
loc 13
ccs 8
cts 8
cp 1
rs 10
cc 3
nc 3
nop 2
crap 3
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