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

Query::initSelect()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 0
cts 4
cp 0
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
crap 2
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 yii\base\InvalidConfigException;
14
15
abstract class Query extends \yii\db\Query
16
{
17
    /**
18
     * @var FieldFactoryInterface
19
     */
20
    protected $fieldFactory;
21
22
    /**
23
     * @var string
24
     */
25
    protected $modelClass;
26
27
    public function __construct(FieldFactoryInterface $filterFactory, array $config = [])
28
    {
29
        parent::__construct($config);
30
31
        $this->fieldFactory = $filterFactory;
32
33
        if (!isset($this->modelClass)) {
34
            throw new InvalidConfigException('Property "modelClass" must be set');
35
        }
36
    }
37
38
    /**
39
     * @return Field[]
40
     */
41
    public function getFields()
42
    {
43
        return $this->fieldFactory->createByModelAttributes(new $this->modelClass(), $this->attributesMap());
44
    }
45
46
    /**
47
     * @param Field[] $fields
48
     * @return $this
49
     */
50
    protected function selectByFields($fields)
51
    {
52
        foreach ($fields as $field) {
53
            if ($field->canBeSelected()) {
54
                $statement = $field->getSql();
55
                if (is_object($statement)) {
56
                    $this->addSelect($statement);
57
                } else {
58
                    $this->addSelect($statement . ' as ' . $field->getName());
59
                }
60
            }
61
        }
62
63
        return $this;
64
    }
65
66
    public function restoreHierarchy($row)
67
    {
68
        $separator = $this->fieldFactory->getHierarchySeparator();
69
70
        foreach ($row as $key => $value) {
71
            if (strpos($key, $separator) === false) {
72
                continue;
73
            }
74
75
            $parts = explode($separator, $key);
76
            while (!empty($parts)) {
77
                $value = [array_pop($parts) => $value];
78
            }
79
            $row = array_merge_recursive($row, $value);
80
        }
81
82
        return $row;
83
    }
84
85
    public function initSelect()
86
    {
87
        return $this->initFrom()->selectByFields($this->getFields());
88
    }
89
90
    /**
91
     * @return $this
92
     */
93
    abstract protected function initFrom();
94
95
    /**
96
     * @return mixed
97
     */
98
    abstract protected function attributesMap();
99
}
100