-
Notifications
You must be signed in to change notification settings - Fork 4
/
Category.php
604 lines (530 loc) · 16 KB
/
Category.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
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
281
282
283
284
285
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
340
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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Query\Builder;
class Category extends Model
{
public $table = 'categories';
protected $parentColumn = 'parent_id';
protected $pathColumn = 'path';
protected $newParent;
protected $fillable = ['name'];
protected $dateFormat = 'U';
/**
* Get the parent column name.
*
* @return string
*/
public function getParentColumnName()
{
return $this->parentColumn;
}
/**
* Get the parent column value.
*
* @return string
*/
public function getParentColumnValue()
{
return $this->{$this->getParentColumnName()};
}
/**
* Get the path column name.
*
* @return string
*/
public function getPathColumnName()
{
return $this->pathColumn;
}
/**
* Get the path column name.
*
* @param string $str
* @return string
*/
public function setPathColumn($newPath)
{
return $this->{$this->getPathColumnName()} = $newPath;
}
/**
* @param string $str
* @return string
*/
public function getPathColumnValue($str = '')
{
return \Illuminate\Support\Arr::get($this->attributes, $this->getPathColumnName(), '') . $str;
}
/**
* Parent relation (self-referential) 1-1.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function parent()
{
return $this->belongsTo(get_class($this), $this->getParentColumnName());
}
/**
* Children relation (self-referential) 1-N.
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function children()
{
return $this->hasMany(get_class($this), $this->getParentColumnName());
}
/**
* Move childs of this to other category
* @param $newParentId
*/
public function newParent($newParentId)
{
$this->newParent = $newParentId;
}
protected static function boot()
{
parent::boot();
static::created(function (Category $category) {
$category->saveChildOf($category->parent);
});
static::deleted(function (Category $category) {
$category->deleteNode();
});
if (property_exists('static', 'forceDeleting')) {
static::restored(function (Category $category) {
$category->restoreCateAndChild();
});
}
}
/**
* Create root category
*
* @return bool
* @throws \Exception
*/
public function saveRoot()
{
return $this->saveChildOf(null);
}
/**
* make this child of the destination category
* @param $category
* @return bool
* @throws \Exception
*/
public function saveChildOf($category)
{
if (is_null($category)) {
$newParentPath = '';
$newParentId = null;
} else {
if (is_numeric($category)) {
if ($this->getParentColumnValue() == $category) {
return $this->save();
}
$category = $this->newQuery()->find($category);
if (is_null($category)) {
throw new \Exception('New parent category not exists.');
}
}
/**
* @var Category $category
*/
$newParentPath = $category->getPathColumnValue();
$newParentId = $category->getKey();
}
if (!is_null($newParentId) && $this->isAncestorOf($category)) {
throw new \Exception('Destination category is children of this.');
}
$oldPath = $this->getPathColumnValue();
$newPath = sprintf('%s%s-', $newParentPath, $this->getKey());
$this->{$this->getParentColumnName()} = $newParentId;
$this->{$this->getPathColumnName()} = $newPath;
if ($this->save() && !empty($oldPath)) {
$this->newQuery()->where($this->getPathColumnName(), 'like', $oldPath . '%')->update([
$this->getPathColumnName() => \DB::raw(sprintf('REPLACE(%s,"%s","%s")', $this->getPathColumnName(), $oldPath, $newPath))
]);
}
return true;
}
/**
* Delete category and child or move child to new category
* @return bool|mixed
*/
public function deleteNode()
{
$childQuery = $this->newQuery();
if (!is_null($this->newParent)) {
$newParentQuery = $this->newQuery();
$pathColumn = $this->getPathColumnName();
$newParent = $newParentQuery->find($this->newParent, [$pathColumn, $this->getKeyName()]);
if (!$newParent) {
return false;
}
$childQuery->where($pathColumn, 'like', $this->getPathColumnValue('%'))->update([
$this->getPathColumnName() => \DB::raw(sprintf('REPLACE(%s,"%s","%s")', $pathColumn, $this->getPathColumnValue(), $newParent->getPathColumnValue())),
$this->getParentColumnName() => $newParent->getKey()
]);
}
return $childQuery->where($this->getPathColumnName(), 'like', $this->getPathColumnValue('%'))->delete();
}
/**
* restore category
*/
public function restoreCateAndChild()
{
$childQuery = $this->newQuery();
$childQuery->withTrashed()->where($this->getPathColumnName(), 'like', $this->getPathColumnValue('%'))->restore();
}
/**
* Check is root
* @return bool
*/
public function isRoot()
{
return is_null($this->getParentColumnValue());
}
/**
* Check isn't root
* @return bool
*/
public function isChild()
{
return !is_null($this->getParentColumnValue());
}
/**
* Check is leaf
*
* @return bool
*/
public function isLeaf()
{
if (!isset($this->relations['children'])) {
$this->load('children');
}
return $this->children->count() === 0;
}
/**
* Check this is child of destination category
* @param $category
* @return bool
*/
public function isChildOf($category)
{
if (($category instanceof $this) === false) {
$category = $this->newQuery()->find($category);
if (is_null($category)) {
return false;
}
}
return $this->getParentColumnValue() === $category->getKey();
}
/**
* Check this is descendant of destination category
* @param $category
* @param bool $orSelf
* @return bool
*/
public function isDescendantOf($category, $orSelf = false)
{
if (($category instanceof $this) === false) {
$category = $this->newQuery()->find($category);
}
if ($orSelf === true && $category->getKey() === $this->getKey()) {
return true;
}
return strpos($this->getPathColumnValue(), $category->getPathColumnValue()) === 0;
}
/**
* Check this is self or descendant of destination category
* @param $category
* @return bool
*/
public function isSelfOrDescendantOf($category)
{
return $this->isDescendantOf($category, true);
}
/**
* Check this is ancestor of destination category
* @param $category
* @param bool $orSelf
* @return bool
*/
public function isAncestorOf($category, $orSelf = false)
{
if (($category instanceof $this) === false) {
$category = $this->newQuery()->find($category);
}
if ($orSelf === true && $category->getKey() === $this->getKey()) {
return true;
}
if (empty($this->getPathColumnValue())) {
return false;
}
return strpos($category->getPathColumnValue(), $this->getPathColumnValue()) === 0;
}
/**
* Check this is self or ancestor of destination category
* @param $category
* @return bool
*/
public function isSelfOrAncestorOf($category)
{
return $this->isAncestorOf($category, true);
}
/**
* @param Builder $q
* @return Collection
*/
public function scopeRoots($q)
{
return $q->whereNull($this->getParentColumnName());
}
/**
* @param Builder $q
* @return Collection
*/
public function scopeAllLeaves($q)
{
return $q->whereNotIn($this->getKeyName(), function ($query) {
$parentColumn = $this->getParentColumnName();
return $query->from($this->getTable())->whereNotNull($parentColumn)->groupBy($parentColumn)->select($parentColumn);
});
}
/**
* @param Builder $q
* @return Collection
*/
public function scopeWithoutRoot($q)
{
return $q->whereNotNull($this->getParentColumnName());
}
/**
* Get level of current category
* @return int
*/
public function getLevel()
{
return substr_count($this->getPathColumnValue(), '-');
}
/**
* Query list ancestors
* @param bool $andSelf
* @return bool|\Illuminate\Database\Eloquent\Builder|static
*/
public function ancestors($andSelf = false)
{
if ($this->isRoot()) {
return false;
}
$path = $this->parsePath();
if (!$path) {
return false;
}
if (!$andSelf) {
array_pop($path);
}
$query = $this->newQuery();
$count = count($path);
for ($i = 1; $i <= $count; $i++) {
$query = $query->orWhere($this->getPathColumnName(), '=', implode('', array_slice($path, 0, $i)));
}
return $query;
}
public function ancestorsAndSelf()
{
return $this->ancestors(true);
}
public function siblings($andSelf = false)
{
$query = $this->newQuery();
if (!$andSelf) {
$query = $query->where($this->getKeyName(), '<>', $this->getKey());
}
return $query->where($this->getParentColumnName(), '=', $this->getParentColumnValue());
}
public function siblingsAndSelf()
{
return $this->siblings(true);
}
public function descendants($depth = false, $andSelf = false)
{
$query = $this->newQuery();
if ($andSelf === false) {
$query = $query->where($this->getKeyName(), '<>', $this->getKey());
}
$query = $query->where($this->getPathColumnName(), 'like', $this->getPathColumnValue('%'));
if ($depth !== false) {
$query = $query->limitDepth($depth);
}
return $query;
}
public function descendantsAndSelf($depth = false)
{
return $this->descendants($depth, true);
}
public function scopeLimitDepth($query, $depth)
{
return $query->where(
\DB::raw(
sprintf('(LENGTH(%s) - LENGTH(REPLACE(%s, "-", "")))', $this->getParentColumnName(), $this->getParentColumnName())
),
'>=',
$this->getLevel() + $depth
);
}
public function root()
{
if ($this->isRoot()) {
return false;
}
$query = $this->newQuery();
$path = $this->parsePath();
if ($path === false) {
return false;
}
return $query->where($this->getPathColumnName(), '=', $path[0]);
}
public function getRoot($attributes = ['*'])
{
return $this->root()->first($attributes);
}
public function getDescendantsAndSelf($depth = false, $attributes = ['*'])
{
return $this->descendantsAndSelf($depth)->get($attributes);
}
public function getDescendants($depth = false, $attributes = ['*'])
{
return $this->descendants($depth)->get($attributes);
}
public function getSiblingsAndSelf($attributes = ['*'])
{
return $this->siblingsAndSelf()->get($attributes);
}
public function getSiblings($attributes = ['*'])
{
return $this->siblings()->get($attributes);
}
public function getAncestorsAndSelf($attributes = ['*'])
{
return $this->ancestorsAndSelf()->get($attributes);
}
public function getAncestors($attributes = ['*'])
{
return $this->ancestors()->get($attributes);
}
public function scopeRebuild($query)
{
$parentIds = $query->groupBy($this->getParentColumnName())->lists($this->getParentColumnName());
foreach ($parentIds as $parentId) {
$parent = $this->find($parentId);
if ($parent) {
$parentPath = $parent->getPathColumnValue();
} else {
$parentPath = '';
}
$this->where($this->getParentColumnName(), $parentId)
->update([
$this->getPathColumnName() => \DB::raw(sprintf('CONCAT("%s", %s, "-")', $parentPath, $this->getKeyName()))
]);
}
return true;
}
public function allWithout($category, $withoutChildren = false)
{
if (is_numeric($category)) {
$category = $this->newQuery()->find($category);
if (!$category) {
return false;
}
}
if ($withoutChildren) {
return $this->newQuery()->where(
$category->getPathColumnName(),
'not like',
$category->getPathColumnValue($withoutChildren ? '%' : '')
);
}
return $this->newQuery()->where(
$category->getPathColumnName(),
'<>',
$category->getPathColumnValue()
);
}
public function allWithoutAndChildrend($category)
{
return $this->allWithout($category, true);
}
public function allWithoutSelf()
{
return $this->allWithout($this);
}
public function allWithoutSelfAndChildren()
{
return $this->allWithout($this, true);
}
public static function buildTree($data, $parent_id = null)
{
foreach ($data as $key => $category) {
$query = new static;
$query->name = $category['name'];
$query->slug = !isset($category['slug']) ? $query->generateSlug($category['name']) : $category['slug'];
$query->position = $key;
$query->{$query->getParentColumnName()} = $parent_id;
$query->save();
if (isset($category['children'])) {
$query->buildTree($category['children'], $query->getKey());
}
}
}
/**
* @param array $data
* @return int
*/
public function updateNestedMenu(array $data)
{
$ids = [];
$idWhereIn = [];
$updateData = [];
$position = [];
$sql = sprintf('UPDATE `%s` SET `%s` = CASE', $this->getTable(), $this->getParentColumnName());
foreach ($data as $key => $item) {
$updateData[] = $item['id'];
$updateData[] = $item['parent_id'];
$ids[] = $item['id'];
$position[] = $item['id'];
$position[] = $key;
$idWhereIn[] = '?';
}
$updateData = array_merge($updateData, $position, $ids);
$sql .= $this->updateColumnWithClause($data);
$sql .= ', `position` = CASE';
$sql .= $this->updateColumnWithClause($data);
$sql .= sprintf(' WHERE %s IN (%s)', $this->getKeyName(), implode(',', $idWhereIn));
return \DB::update(\DB::raw($sql), $updateData);
}
/**
* update multi record
* @param array $data
* @param string $field column
* @return string sql
*/
private function updateColumnWithClause($data)
{
$sql = '';
foreach ($data as $item)
$sql .= sprintf(' WHEN %s = ? THEN ?', $this->getKeyName());
$sql .= ' END';
return $sql;
}
protected function parsePath()
{
preg_match_all('/[0-9]+\-/', $this->getPathColumnValue(), $path);
$path = reset($path);
if (empty($path[0])) {
return false;
}
return $path;
}
}