Blame view

common/components/artboxtree/ArtboxTreeBehavior.php 13.3 KB
a8370482   Alexander Karnovsky   init project
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
  <?php
  
  namespace common\components\artboxtree;
  
  use common\modules\rubrication\models\TaxOption;
  use Yii;
  use yii\base\Behavior;
  use yii\base\Exception;
  use yii\base\NotSupportedException;
  use yii\db\ActiveRecord;
  use yii\db\Expression;
  
  class ArtboxTreeBehavior extends Behavior {
  
      /** @var  ActiveRecord $owner */
      public $owner;
  
      public $keyNameId;
      public $keyNameParentId = 'parent_id';
      public $keyNameGroup = 'group';
      public $keyNamePath = 'path_int';
      public $keyNameDepth = 'depth'; // @todo -> $keyNameDepth;
b519af22   Karnovsky A   Base-product func...
23
      public $primaryKeyMode = true;
a8370482   Alexander Karnovsky   init project
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
  
      /**
       * @var string
       */
      public $delimiter = '|';
  
      /**
       * @var ActiveRecord|self|null
       */
      protected $entity;
  
      /**
       * @param ActiveRecord $owner
       * @throws Exception
       */
      public function attach($owner)
      {
          parent::attach($owner);
          if ($this->keyNameId === null) {
              $primaryKey = $owner->primaryKey();
              if (!isset($primaryKey[0])) {
                  throw new Exception('"' . $owner->className() . '" must have a primary key.');
              }
              $this->keyNameId = $primaryKey[0];
          }
      }
  
      public function events()
      {
          return [
              // @todo Use beforeSave for automatic set MP-params
              ActiveRecord::EVENT_BEFORE_UPDATE   => 'beforeUpdate',
              ActiveRecord::EVENT_AFTER_INSERT   => 'afterInsert',
          ];
      }
  
      /*
       * Main methods
       */
  
      /*
       * get one parent
       * use AL-method
       */
      public function getParent() {
          return $this->getParentAL();
      }
  
      /*
       * get all parents
       * use MP-method
       */
      public function getParents() {
          return $this->getParentsMP();
      }
  
      /*
       * get one-level children items
       * use AL-method
       */
      public function getChildren() {
          return $this->getChildrenAL();
      }
  
      /*
       * get all-level children items
       * use MP-method
       */
b519af22   Karnovsky A   Base-product func...
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
      public function getAllChildren($depth = null, $where = []) {
          return $this->getAllChildrenMP($depth)->where($where);
      }
  
      /*
       * get all-level children items
       * use MP-method
       */
      public function getAllChildrenTree($depth = null, $where = []) {
          return $this->buildTree($this->getAllChildrenMP($depth, $where)->all(), $this->owner->getAttribute($this->keyNameId));
      }
  
      protected function buildTree(array $data, $parentId = 0) {
          $result = [];
          foreach ($data as $key => $element) {
              if ($element->getAttribute($this->keyNameParentId) == $parentId) {
                  unset($data[$key]);
                  $children = $this->buildTree($data, $element->getAttribute($this->keyNameId));
                  $result[] = [
                      'item' => $element,
                      'children' => $children
                  ];
              }
          }
          return $result;
a8370482   Alexander Karnovsky   init project
117
118
119
120
121
122
123
124
125
126
127
128
129
      }
  
  
      /*
       * ================================
       * MP-methods
       * ================================
       */
  
      /*
       * Full-path (use MP-method)
       */
      public function getParentsMP($depth = null) {
b519af22   Karnovsky A   Base-product func...
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
          $tableName = $this->owner->tableName();
          $path  = $this->owner->getAttribute($this->keyNamePath);
          $query = $this->owner->find()
              ->andWhere(['<@', "{$tableName}.[[{$this->keyNamePath}]]", $path]);
          if ($depth > 0) {
              $query->andWhere(['>=', "{$tableName}.[[{$this->keyNameDepth}]]", $this->owner->getAttribute($this->keyNameDepth) - $depth]);
          }
          $query->andWhere(['<', "{$tableName}.[[{$this->keyNameDepth}]]", $this->owner->getAttribute($this->keyNameDepth)]);
  
          $orderBy = [];
          $orderBy["{$tableName}.[[{$this->keyNameDepth}]]"] = SORT_ASC;
          $orderBy["{$tableName}.[[{$this->keyNameId}]]"]  = SORT_ASC;
  
          $query
              ->andWhere($this->groupWhere())
              ->addOrderBy($orderBy);
          $query->multiple = true;
  
          return $query;
      }
      /*public function getParentsMP($depth = null) {
a8370482   Alexander Karnovsky   init project
151
152
          $path  = $this->getParentPath();
          if ($path !== null) {
b519af22   Karnovsky A   Base-product func...
153
              $paths = explode(',', trim($path, '{}'));
a8370482   Alexander Karnovsky   init project
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
              if (!$this->primaryKeyMode) {
                  $path  = null;
                  $paths = array_map(
                      function ($value) use (&$path) {
                          return $path = ($path !== null ? $path . ',' : '') . $value;
                      },
                      $paths
                  );
              }
              if ($depth !== null) {
                  $paths = array_slice($paths, -$depth);
              }
          } else {
              $paths = [];
          }
  
          $tableName = $this->owner->tableName();
a8370482   Alexander Karnovsky   init project
171
172
173
174
175
176
177
178
          if ($this->primaryKeyMode) {
              $condition[] = ["{$tableName}.[[{$this->keyNameId}]]" => $paths];
          } else {
              $condition[] = ["{$tableName}.[[{$this->keyNamePath}]]" => $paths];
          }
  
          $query = $this->owner->find()
              ->andWhere($condition)
b519af22   Karnovsky A   Base-product func...
179
              ->andWhere($this->groupWhere())
a8370482   Alexander Karnovsky   init project
180
181
182
183
              ->addOrderBy(["{$tableName}.[[{$this->keyNamePath}]]" => SORT_ASC]);
          $query->multiple = true;
  
          return $query;
b519af22   Karnovsky A   Base-product func...
184
      }*/
a8370482   Alexander Karnovsky   init project
185
186
187
188
189
190
191
192
193
  
      /**
       * @param bool $asArray = false
       * @return null|string|array
       */
      public function getParentPath($asArray = false)
      {
          return static::getParentPathInternal($this->owner->getAttribute($this->keyNamePath), $asArray);
      }
b519af22   Karnovsky A   Base-product func...
194
195
196
197
198
199
200
201
202
203
204
205
206
      /**
       * @return array
       */
      protected function groupWhere()
      {
          $tableName = $this->owner->tableName();
          if ($this->keyNameGroup === null) {
              return [];
          } else {
              return ["{$tableName}.[[{$this->keyNameGroup}]]" => $this->owner->getAttribute($this->keyNameGroup)];
          }
      }
      
a8370482   Alexander Karnovsky   init project
207
208
209
210
211
212
  
      public function getAllChildrenMP($depth = null)
      {
          $tableName = $this->owner->tableName();
          $path = $this->owner->getAttribute($this->keyNamePath);
          $query = $this->owner->find()
b519af22   Karnovsky A   Base-product func...
213
              ->andWhere(['@>', "{$tableName}.[[{$this->keyNamePath}]]", $path]);
a8370482   Alexander Karnovsky   init project
214
215
216
217
218
219
220
221
222
223
  
          if ($depth > 0) {
              $query->andWhere(['<=', "{$tableName}.[[{$this->keyNameDepth}]]", $this->owner->getAttribute($this->keyNameDepth) + $depth]);
          }
  
          $orderBy = [];
          $orderBy["{$tableName}.[[{$this->keyNameDepth}]]"] = SORT_ASC;
          $orderBy["{$tableName}.[[{$this->keyNameId}]]"]  = SORT_ASC;
  
          $query
b519af22   Karnovsky A   Base-product func...
224
              ->andWhere($this->groupWhere())
a8370482   Alexander Karnovsky   init project
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
              ->addOrderBy($orderBy);
          $query->multiple = true;
  
          return $query;
      }
  
      /*
       * ================================
       * AL methods
       * ================================
       */
  
      /*
      * Parent entity (use AL-method)
      * @return \yii\db\ActiveRecord
      */
      public function getParentAL() {
          $parent_id = $this->owner->getAttribute($this->keyNameParentId);
          if (empty($parent_id))
              return null;
b519af22   Karnovsky A   Base-product func...
245
246
247
248
249
250
251
  
          $where = [$this->keyNameId => $parent_id];
          if ($this->keyNameGroup) {
              $where[$this->keyNameGroup] = $this->owner->getAttribute($this->keyNameGroup);
          }
  
          return $this->owner->find()->where($where)->one();
a8370482   Alexander Karnovsky   init project
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
      }
  
      /*
       * Get parents by AL-method
       * @return array
       */
      public function getParentsAL() {
          $parent_id = $this->owner->getAttribute($this->keyNameParentId);
          if ($parent_id == 0) {
              return [];
          }
  
          $parent = $this->owner;
          $parents = [];
          while(true) {
              $parent = $parent->getParentAL();
              if (is_null($parent))
                  break;
              $parents[] = $parent;
          }
  
          return array_reverse($parents);
      }
  
      /*
      * Children entities (one-step) (use AL-method)
      * @return ActiveQuery
      */
      public function getChildrenAL() {
b519af22   Karnovsky A   Base-product func...
281
282
283
284
285
          $where = [$this->keyNameParentId => $this->owner->getAttribute($this->keyNameId)];
          if ($this->keyNameGroup) {
              $where[$this->keyNameGroup] = $this->owner->getAttribute($this->keyNameGroup);
          }
          return $this->owner->find()->where($where);
a8370482   Alexander Karnovsky   init project
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
      }
  
      // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  
      /**
       * @param array $changedAttributes
       * @throws Exception
       */
      protected function _rebuildChildren($changedAttributes)
      {
          $path = isset($changedAttributes[$this->keyNamePath]) ? $changedAttributes[$this->keyNamePath] : $this->owner->getAttribute($this->keyNamePath);
          $update = [];
          $condition = [
              'and',
              ['@>', "[[{$this->keyNamePath}]]", $path, false],
          ];
          if ($this->keyNameGroup !== null) {
              $group = isset($changedAttributes[$this->keyNameGroup]) ? $changedAttributes[$this->keyNameGroup] : $this->owner->getAttribute($this->keyNameGroup);
              $condition[] = [$this->keyNameGroup => $group];
          }
          $params = [];
  
          if (isset($changedAttributes[$this->keyNamePath])) {
              $substringExpr = $this->substringExpression(
                  "[[{$this->keyNamePath}]]",
                  'array_length(:pathOld) + 1',
                  "array_length([[{$this->keyNamePath}]]) - array_length(:pathOld)"
              );
              $update[$this->keyNamePath] = new Expression($this->concatExpression([':pathNew', $substringExpr]));
              $params[':pathOld'] = $path;
              $params[':pathNew'] = $this->owner->getAttribute($this->keyNamePath);
          }
  
          if ($this->keyNameGroup !== null && isset($changedAttributes[$this->keyNameGroup])) {
              $update[$this->keyNameGroup] = $this->owner->getAttribute($this->keyNameGroup);
          }
  
          if ($this->keyNameDepth !== null && isset($changedAttributes[$this->keyNameDepth])) {
              $delta = $this->owner->getAttribute($this->keyNameDepth) - $changedAttributes[$this->keyNameDepth];
              $update[$this->keyNameDepth] = new Expression("[[{$this->keyNameDepth}]]" . sprintf('%+d', $delta));
          }
          if (!empty($update)) {
              $this->owner->updateAll($update, $condition, $params);
          }
      }
  
      /**
       * @param string $path
       * @param string $delimiter
       * @param bool $asArray = false
       * @return null|string|array
       */
      protected static function getParentPathInternal($path, $asArray = false)
      {
b519af22   Karnovsky A   Base-product func...
340
          $path = explode(',', trim($path, '{}'));
a8370482   Alexander Karnovsky   init project
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
          array_pop($path);
          if ($asArray) {
              return $path;
          }
          return count($path) > 0 ? implode(',', $path) : null;
      }
  
      protected function toLike($path) {
          return strtr($path . ',', ['%' => '\%', '_' => '\_', '\\' => '\\\\']) . '%';
      }
  
      protected function concatExpression($items)
      {
          if ($this->owner->getDb()->driverName === 'sqlite' || $this->owner->getDb()->driverName === 'pgsql') {
              return implode(' || ', $items);
          }
          return 'CONCAT(' . implode(',', $items) . ')';
      }
  
      protected function substringExpression($string, $from, $length)
      {
          if ($this->owner->getDb()->driverName === 'sqlite') {
              return "SUBSTR({$string}, {$from}, {$length})";
          }
          return "SUBSTRING({$string}, {$from}, {$length})";
      }
  
      // =======================================================
      public function afterInsert() {
          $this->withSave();
          $this->owner->updateAttributes([$this->keyNamePath => $this->owner->getAttribute($this->keyNamePath), $this->keyNameDepth => $this->owner->getAttribute($this->keyNameDepth)]);
      }
  
      public function beforeUpdate()
      {
          if ($this->owner->getIsNewRecord()) {
              throw new NotSupportedException('Method "' . $this->owner->className() . '::insert" is not supported for inserting new entitys.');
          }
          $this->withSave();
      }
  
      protected function withSave() {
          $id = $this->owner->getAttribute($this->keyNameId);
          $parent_id = $this->owner->getAttribute($this->keyNameParentId);
  
          if (is_null($parent_id)) {
              $parent_id = 0;
          }
  
          // check parent_id value is changed!
          /*if ($this->owner->getOldAttribute($this->keyNameParentId) == $parent_id) {
              return;
          }*/
  
          // rebuild parents entities
          if ($parent_id == 0) {
              $depth = 0;
              $path = [intval($id)];
          } else {
              $parents = $this->getParentsAL();
              $path = [];
              $depth = 0;
              foreach ($parents as $entity) {
                  $path[] = $entity->getAttribute($this->keyNameId);
                  $depth++;
              }
              $path[] = intval($id);
          }
  
          $path = '{'. implode(',', $path) .'}';
  
          // rebuild children entities (recurcive)
  //        $this->_rebuildChildren([
  //            $this->keyNamePath => $path
  //        ]);
  
b519af22   Karnovsky A   Base-product func...
417
          $this->owner->setAttribute($this->keyNamePath, $path);
a8370482   Alexander Karnovsky   init project
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
  //        $this->owner->setAttribute($this->keyNamePath, $path);
          $this->owner->setAttribute($this->keyNameDepth, $depth);
      }
  
      public function _recursiveRebuildChildren() {
          $children = $this->getChildrenAL()->all();
          $root_path = explode(',', $this->owner->getAttribute($this->keyNamePath));
          $root_depth = $this->owner->getAttribute($this->keyNameDepth);
  
          /** @var $child ActiveRecord */
          foreach ($children as $child) {
              $path = $root_path;
              $path[] = $child->getAttribute($this->keyNameId);
              $depth = $root_depth + 1;
  
              $child->_recursiveRebuildChildren();
          }
      }
  }