| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253 |
- <?php
- namespace Webkul\BagistoApi\Resolver;
- use ApiPlatform\GraphQl\Resolver\QueryCollectionResolverInterface;
- use Webkul\BagistoApi\Models\FrontMenuItem;
- /**
- * Resolves the enabled front navigation menu as a hierarchical tree.
- */
- class FrontMenuTreeResolver implements QueryCollectionResolverInterface
- {
- public function __invoke(?iterable $collection, array $context): iterable
- {
- $items = FrontMenuItem::query()
- ->where('status', 1)
- ->orderBy('sort_order')
- ->orderBy('id')
- ->get();
- return $this->buildTree($items);
- }
- /**
- * Recursively build the menu tree from a flat collection.
- *
- * Only enabled (status = 1) items are kept at every level, so a disabled
- * item is excluded whether it is a root node or a nested child.
- */
- protected function buildTree($items, ?int $parentId = null): array
- {
- $tree = [];
- foreach ($items as $item) {
- // Exclude disabled items at every level.
- if (! $item->status) {
- continue;
- }
- $itemParentId = $item->parent_id === null ? null : (int) $item->parent_id;
- if ($itemParentId === $parentId) {
- $children = $this->buildTree($items, (int) $item->id);
- $item->setRelation('children', collect($children));
- $tree[] = $item;
- }
- }
- return $tree;
- }
- }
|