Completed
Push — master ( be2280...4a4169 )
by Andrii
01:43
created

FieldFactory::createByModelAttributes()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 19
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
dl 0
loc 19
ccs 0
cts 17
cp 0
rs 9.2
c 0
b 0
f 0
cc 4
eloc 12
nc 4
nop 3
crap 20
1
<?php
2
/**
3
 * HiAPI Yii2 base project for building API
4
 *
5
 * @link      https://github.com/hiqdev/hiapi
6
 * @package   hiapi
7
 * @license   BSD-3-Clause
8
 * @copyright Copyright (c) 2017, HiQDev (http://hiqdev.com/)
9
 */
10
11
namespace hiapi\query;
12
13
use hiqdev\billing\hiapi\models\ModelInterface;
14
15
class FieldFactory implements FieldFactoryInterface
16
{
17
    /**
18
     * @param ModelInterface $model
19
     * @param $map
20
     * @param string[] parent attribute names
21
     * @return Field[]
22
     */
23
    public function createByModelAttributes($model, $map, array $parents = [])
24
    {
25
        $result = [];
26
27
        foreach ($map as $attributeName => $definition) {
28
            if (!is_array($definition)) {
29
                $result[] = is_object($definition) ? $definition : $this->buildField($model, $attributeName, $definition, $parents);
30
            } else {
31
                $relationClass = $model->getRelation($attributeName);
32
                $result = array_merge($result, $this->createByModelAttributes(
33
                    new $relationClass(),
34
                    $definition,
35
                    array_merge($parents, [$attributeName])
36
                ));
37
            }
38
        }
39
40
        return $result;
41
    }
42
43
    protected function buildField($model, $attributeName, $sql, array $parents)
44
    {
45
        array_push($parents, $attributeName);
46
        $name = implode($this->getHierarchySeparator(), $parents);
47
48
        return new Field($name, $sql, $model->getAttribute($attributeName));
49
    }
50
51
    public function getHierarchySeparator()
52
    {
53
        return '-';
54
    }
55
}
56