PartialTreeDataAction::init()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 9
rs 9.6666
c 0
b 0
f 0
cc 3
eloc 5
nc 3
nop 0
1
<?php
2
3
namespace devgroup\JsTreeWidget\actions\AdjacencyList;
4
5
use DevGroup\TagDependencyHelper\NamingHelper;
6
use Yii;
7
use yii\base\Action;
8
use yii\base\InvalidConfigException;
9
use yii\caching\TagDependency;
10
use yii\helpers\ArrayHelper;
11
use yii\web\Response;
12
13
/**
14
 * Helper action for retrieving tree data for jstree by ajax.
15
 * Example use in controller:
16
 *
17
 * ``` php
18
 * public function actions()
19
 * {
20
 *     return [
21
 *         'getTree' => [
22
 *             'class' => PartialTreeDataAction::class,
23
 *             'className' => Category::class,
24
 *             'modelLabelAttribute' => 'defaultTranslation.name',
25
 *
26
 *         ],
27
 *     ...
28
 *     ];
29
 * }
30
 * ```
31
 */
32
class PartialTreeDataAction extends Action
33
{
34
35
    public $className;
36
37
    public $modelIdAttribute = 'id';
38
39
    public $modelLabelAttribute = 'name';
40
41
    public $modelParentAttribute = 'parent_id';
42
43
    public $varyByTypeAttribute;
44
45
    public $queryParentAttribute = 'id';
46
47
    public $querySortOrder = 'sort_order';
48
49
    public $querySelectedAttribute = 'selected_id';
50
    /**
51
     * Additional conditions for retrieving tree(ie. don't display nodes marked as deleted)
52
     * @var array|\Closure
53
     */
54
    public $whereCondition = [];
55
56
    /**
57
     * Cache key prefix. Should be unique if you have multiple actions with different $whereCondition
58
     * @var string|\Closure
59
     */
60
    public $cacheKey = 'PartialTree';
61
62
    /**
63
     * Cache lifetime for the full tree
64
     * @var int
65
     */
66
    public $cacheLifeTime = 86400;
67
68
    public function init()
69
    {
70
        if ($this->className === null) {
71
            throw new InvalidConfigException('Model name should be set in controller actions');
72
        }
73
        if (!class_exists($this->className)) {
74
            throw new InvalidConfigException('Model class does not exists');
75
        }
76
    }
77
78
    public function run()
79
    {
80
        Yii::$app->response->format = Response::FORMAT_JSON;
81
82
        /** @var \yii\db\ActiveRecord $class */
83
        $class = $this->className;
84
85 View Code Duplication
        if (null === $current_selected_id = Yii::$app->request->get($this->querySelectedAttribute)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
86
            $current_selected_id = Yii::$app->request->get($this->queryParentAttribute);
87
        }
88
89
        $parent_id = Yii::$app->request->get($this->queryParentAttribute, '#');
90
        if (!is_numeric($parent_id)) {
91
            $parent_id = 0;
92
        }
93
94
        $cacheKey = $this->cacheKey instanceof \Closure ? call_user_func($this->cacheKey) : $this->cacheKey;
95
96
        $cacheKey = "AdjacencyFullTreeData:$cacheKey:{$class}:{$this->querySortOrder}:$parent_id";
97
98
        if (false === $result = Yii::$app->cache->get($cacheKey)) {
99
            $query = $class::find()
100
                ->orderBy([$this->querySortOrder => SORT_ASC]);
101
102 View Code Duplication
            if ($this->whereCondition instanceof \Closure) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
103
                $query->where(call_user_func($this->whereCondition));
104
            } elseif (count($this->whereCondition) > 0) {
105
                $query->where($this->whereCondition);
106
            }
107
            $query->andWhere([$this->modelParentAttribute => $parent_id]);
108
109
            if (null === $rows = $query->asArray()->all()) {
110
                return [];
111
            }
112
113
            $result = [];
114
115 View Code Duplication
            foreach ($rows as $row) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
116
                $parent = ArrayHelper::getValue($row, $this->modelParentAttribute, 0);
117
                $item = [
118
                    'id' => ArrayHelper::getValue($row, $this->modelIdAttribute, 0),
119
                    'parent' => $parent ?: '#',
120
                    'text' => ArrayHelper::getValue($row, $this->modelLabelAttribute, 'item'),
121
                    'a_attr' => [
122
                        'data-id' => $row[$this->modelIdAttribute],
123
                        'data-parent_id' => $row[$this->modelParentAttribute]
124
                    ],
125
                    'children' => true,
126
                ];
127
128
                if (null !== $this->varyByTypeAttribute) {
129
                    $item['type'] = $row[$this->varyByTypeAttribute];
130
                }
131
132
                $result[$row[$this->modelIdAttribute]] = $item;
133
            }
134
135
            Yii::$app->cache->set(
136
                $cacheKey,
137
                $result,
138
                86400,
139
                new TagDependency([
140
                    'tags' => [
141
                        NamingHelper::getCommonTag($class),
142
                    ],
143
                ])
144
            );
145
        }
146
147 View Code Duplication
        if (array_key_exists($current_selected_id, $result)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
148
            $result[$current_selected_id] = array_merge(
149
                $result[$current_selected_id],
150
                ['state' => ['opened' => true, 'selected' => true]]
151
            );
152
        }
153
154
        return array_values($result);
155
    }
156
}
157