1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* @copyright Bluz PHP Team |
4
|
|
|
* @link https://github.com/bluzphp/skeleton |
5
|
|
|
*/ |
6
|
|
|
|
7
|
|
|
declare(strict_types=1); |
8
|
|
|
|
9
|
|
|
namespace Application\Categories; |
10
|
|
|
|
11
|
|
|
use Bluz\Proxy\Db; |
12
|
|
|
|
13
|
|
|
/** |
14
|
|
|
* Class Table |
15
|
|
|
* |
16
|
|
|
* @package Application\Categories |
17
|
|
|
* |
18
|
|
|
* @method static Row findRow($primaryKey) |
19
|
|
|
* @method static Row findRowWhere($whereList) |
20
|
|
|
*/ |
21
|
|
|
class Table extends \Bluz\Db\Table |
22
|
|
|
{ |
23
|
|
|
/** |
24
|
|
|
* Table |
25
|
|
|
* |
26
|
|
|
* @var string |
27
|
|
|
*/ |
28
|
|
|
protected $name = 'categories'; |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* Primary key(s) |
32
|
|
|
* @var array |
33
|
|
|
*/ |
34
|
|
|
protected $primary = ['id']; |
35
|
|
|
|
36
|
|
|
/** |
37
|
|
|
* Get root categories |
38
|
|
|
* @return Row[] |
39
|
|
|
*/ |
40
|
|
|
public function getRootCategories(): array |
41
|
|
|
{ |
42
|
|
|
return self::select()->where('parentId IS NULL')->orderBy('name')->execute(); |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
/** |
46
|
|
|
* Build tree by root id |
47
|
|
|
* @param int $id |
48
|
|
|
* @return Row |
49
|
|
|
*/ |
50
|
|
|
public function buildTree($id = null): Row |
51
|
|
|
{ |
52
|
|
|
$tree = $this->generateTree($id); |
53
|
|
|
return $tree[$id]; |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
/** |
57
|
|
|
* Build tree by root alias |
58
|
|
|
* |
59
|
|
|
* @param string $alias |
60
|
|
|
* |
61
|
|
|
* @return Row |
62
|
|
|
* @throws \Bluz\Db\Exception\DbException |
63
|
|
|
* @throws \Bluz\Db\Exception\InvalidPrimaryKeyException |
64
|
|
|
*/ |
65
|
|
|
public function buildTreeByAlias($alias): Row |
66
|
|
|
{ |
67
|
|
|
$current = self::findRow(['alias' => $alias]); |
68
|
|
|
|
69
|
|
|
return $this->buildTree($current['id']); |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
/** |
73
|
|
|
* Get all categories in tree by rootId |
74
|
|
|
* @param integer $rootId |
75
|
|
|
* @return Row[] |
76
|
|
|
*/ |
77
|
|
|
protected function generateTree($rootId): array |
78
|
|
|
{ |
79
|
|
|
/** @var Row[] $categories */ |
80
|
|
|
$categories = Db::fetchGroup( |
81
|
|
|
'SELECT id, categories.* FROM categories WHERE rootId = :id or id = :id ORDER BY `name`', |
82
|
|
|
['id' => $rootId], |
83
|
|
|
$this->rowClass |
84
|
|
|
); |
85
|
|
|
$categories = array_map('reset', $categories); |
86
|
|
|
|
87
|
|
|
foreach ($categories as $category) { |
88
|
|
|
if ($category->parentId && $category->id !== $category->parentId) { |
89
|
|
|
$categories[$category->parentId]->addChild($category); |
90
|
|
|
} |
91
|
|
|
} |
92
|
|
|
return $categories; |
93
|
|
|
} |
94
|
|
|
} |
95
|
|
|
|