|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace BatteryIncludedSdk\Shop; |
| 6 | + |
| 7 | +class FacetCategoryDto extends FacetDto |
| 8 | +{ |
| 9 | + private mixed $categories; |
| 10 | + |
| 11 | + public function __construct(array $data, protected array $appliedFilterValues = []) |
| 12 | + { |
| 13 | + parent::__construct($data, $appliedFilterValues); |
| 14 | + |
| 15 | + $this->categories = $this->buildCategoryTree($data['counts'] ?? []); |
| 16 | + } |
| 17 | + |
| 18 | + private function buildCategoryTree(array $items, $separator = '>') |
| 19 | + { |
| 20 | + $tree = []; |
| 21 | + foreach ($this->appliedFilterValues[$this->fieldName] ?? [] as $filter) { |
| 22 | + $appliedFilter = array_map('trim', explode($separator, $filter)); |
| 23 | + $filterPrefix = ''; |
| 24 | + foreach ($appliedFilter as $filterPart) { |
| 25 | + foreach ($items as $key => $item) { |
| 26 | + if ($item['value'] === $filterPrefix . $filterPart) { |
| 27 | + $items[$key]['checked'] = true; |
| 28 | + $filterPrefix .= $filterPart . ' ' . $separator . ' '; |
| 29 | + } |
| 30 | + } |
| 31 | + } |
| 32 | + } |
| 33 | + |
| 34 | + foreach ($items as $item) { |
| 35 | + $parts = array_map('trim', explode($separator, $item['value'])); |
| 36 | + $count = $item['count']; |
| 37 | + $checked = $item['checked'] ?? false; |
| 38 | + |
| 39 | + $current = &$tree; |
| 40 | + foreach ($parts as $part) { |
| 41 | + /* @phpstan-ignore isset.offset */ |
| 42 | + if (!isset($current['childs'][$part])) { |
| 43 | + $current['childs'][$part] = []; |
| 44 | + } |
| 45 | + $current = &$current['childs'][$part]; |
| 46 | + } |
| 47 | + |
| 48 | + $current['count'] = $count; |
| 49 | + $current['checked'] = $checked; |
| 50 | + } |
| 51 | + |
| 52 | + /* @phpstan-ignore nullCoalesce.offset */ |
| 53 | + return $tree['childs'] ?? []; |
| 54 | + } |
| 55 | + |
| 56 | + public function getCategories(): array |
| 57 | + { |
| 58 | + return $this->categories; |
| 59 | + } |
| 60 | +} |
0 commit comments