-
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathCategoryRepository.php
More file actions
91 lines (82 loc) · 2.92 KB
/
CategoryRepository.php
File metadata and controls
91 lines (82 loc) · 2.92 KB
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
<?php
declare(strict_types=1);
namespace Extcode\CartEvents\Domain\Repository;
/*
* This file is part of the package extcode/cart-events.
*
* For the full copyright and license information, please read the
* LICENSE file that was distributed with this source code.
*/
use Extcode\CartEvents\Domain\Model\Category;
use TYPO3\CMS\Extbase\Persistence\Repository;
class CategoryRepository extends Repository
{
public function findAllAsRecursiveTreeArray(?Category $selectedCategory = null): array
{
$categoriesArray = $this->findAllAsArray($selectedCategory);
return $this->buildSubcategories($categoriesArray, null);
}
public function findAllAsArray(?Category $selectedCategory = null): array
{
$localCategories = $this->findAll();
$categories = [];
// Transform categories to array
foreach ($localCategories as $localCategory) {
$newCategory = [
'uid' => $localCategory->getUid(),
'title' => $localCategory->getTitle(),
'parent' => $localCategory->getParent() ? $localCategory->getParent()->getUid() : null,
'subcategories' => null,
'isSelected' => $selectedCategory == $localCategory,
];
$categories[] = $newCategory;
}
return $categories;
}
public function findSubcategoriesRecursiveAsArray(Category $parentCategory): array
{
$categories = [];
$localCategories = $this->findAllAsArray();
foreach ($localCategories as $category) {
if (!$parentCategory
|| ($parentCategory && $category['uid'] === $parentCategory->getUid())
) {
$this->getSubcategoriesIds(
$localCategories,
$category,
$categories
);
}
}
return $categories;
}
protected function getSubcategoriesIds(
array $categoriesArray,
array $parentCategory,
array &$subcategoriesArray
): void {
$subcategoriesArray[] = $parentCategory['uid'];
foreach ($categoriesArray as $category) {
if ($category['parent'] === $parentCategory['uid']) {
$this->getSubcategoriesIds(
$categoriesArray,
$category,
$subcategoriesArray
);
}
}
}
protected function buildSubcategories(array $categoriesArray, array $parentCategory): array
{
$categories = null;
foreach ($categoriesArray as $category) {
if ($category['parent'] === $parentCategory['uid']) {
$newCategory = $category;
$newCategory['subcategories']
= $this->buildSubcategories($categoriesArray, $category);
$categories[] = $newCategory;
}
}
return $categories;
}
}