FullTreeDataAction::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\helpers\FileHelper;
12
use yii\web\Response;
13
14
/**
15
 * Helper action for retrieving tree data for jstree by ajax.
16
 * Example use in controller:
17
 *
18
 * ``` php
19
 * public function actions()
20
 * {
21
 *     return [
22
 *         'getTree' => [
23
 *             'class' => AdjacencyFullTreeDataAction::class,
24
 *             'className' => Category::class,
25
 *             'modelLabelAttribute' => 'defaultTranslation.name',
26
 *
27
 *         ],
28
 *     ...
29
 *     ];
30
 * }
31
 * ```
32
 */
33
class FullTreeDataAction extends Action
34
{
35
36
    public $className = null;
37
38
    public $modelIdAttribute = 'id';
39
40
    public $modelLabelAttribute = 'name';
41
42
    public $modelParentAttribute = 'parent_id';
43
44
    public $varyByTypeAttribute = null;
45
46
    public $queryParentAttribute = 'id';
47
48
    public $querySortOrder = 'sort_order';
49
50
    public $querySelectedAttribute = 'selected_id';
51
    /**
52
     * Additional conditions for retrieving tree(ie. don't display nodes marked as deleted)
53
     * @var array|\Closure
54
     */
55
    public $whereCondition = [];
56
57
    /**
58
     * Cache key prefix. Should be unique if you have multiple actions with different $whereCondition
59
     * @var string|\Closure
60
     */
61
    public $cacheKey = 'FullTree';
62
63
    /**
64
     * Cache lifetime for the full tree
65
     * @var int
66
     */
67
    public $cacheLifeTime = 86400;
68
69
    private $selectedNodes = [];
70
71
    public function init()
72
    {
73
        if (!isset($this->className)) {
74
            throw new InvalidConfigException("Model name should be set in controller actions");
75
        }
76
        if (!class_exists($this->className)) {
77
            throw new InvalidConfigException("Model class does not exists");
78
        }
79
    }
80
81
    public function run()
82
    {
83
        Yii::$app->response->format = Response::FORMAT_JSON;
84
85
        /** @var \yii\db\ActiveRecord $class */
86
        $class = $this->className;
87
88 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...
89
            $current_selected_id = Yii::$app->request->get($this->queryParentAttribute);
90
        }
91
        $cacheKey = $this->cacheKey instanceof \Closure ? call_user_func($this->cacheKey) : $this->cacheKey;
92
        $cacheKey = "AdjacencyFullTreeData:{$cacheKey}:{$class}:{$this->querySortOrder}";
93
94
        Yii::beginProfile('Get tree');
95
        if (false === $result = Yii::$app->cache->get($cacheKey)) {
96
            Yii::beginProfile('Build tree');
97
            $query = $class::find()
98
                ->orderBy([$this->querySortOrder => SORT_ASC]);
99
100 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...
101
                $query->where(call_user_func($this->whereCondition));
102
            } elseif (count($this->whereCondition) > 0) {
103
                $query->where($this->whereCondition);
104
            }
105
106
            if (null === $rows = $query->asArray()->all()) {
107
                return [];
108
            }
109
110
            $result = [];
111
112 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...
113
                $parent = ArrayHelper::getValue($row, $this->modelParentAttribute, 0);
114
                $item = [
115
                    'id' => ArrayHelper::getValue($row, $this->modelIdAttribute, 0),
116
                    'parent' => ($parent) ? $parent : '#',
117
                    'text' => ArrayHelper::getValue($row, $this->modelLabelAttribute, 'item'),
118
                    'a_attr' => [
119
                        'data-id' => $row[$this->modelIdAttribute],
120
                        'data-parent_id' => $row[$this->modelParentAttribute]
121
                    ],
122
                ];
123
124
                if (null !== $this->varyByTypeAttribute) {
125
                    $item['type'] = $row[$this->varyByTypeAttribute];
126
                }
127
128
                $result[$row[$this->modelIdAttribute]] = $item;
129
            }
130
131
            Yii::$app->cache->set(
132
                $cacheKey,
133
                $result,
134
                86400,
135
                new TagDependency([
136
                    'tags' => [
137
                        NamingHelper::getCommonTag($class),
138
                    ],
139
                ])
140
            );
141
142
            Yii::endProfile('Build tree');
143
        }
144
145 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...
146
            $result[$current_selected_id] = array_merge(
147
                $result[$current_selected_id],
148
                ['state' => ['opened' => true, 'selected' => true]]
149
            );
150
        }
151
        $this->selectedNodes = explode(',', Yii::$app->request->get('selected', ''));
152
        foreach ($this->selectedNodes as $node) {
153
            if ($node !== '') {
154
                if (array_key_exists($node, $result)) {
155
                    $result[$node]['state'] = [
156
                        'selected' => true,
157
                    ];
158
                }
159
            }
160
        }
161
        Yii::endProfile('Get tree');
162
163
        Yii::$app->response->format = Response::FORMAT_RAW;
164
        header('Content-Type: application/json');
165
        return json_encode(array_values($result));
166
    }
167
}
168