FrontMenuItemRepository.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. namespace Longyi\FrontMenu\Repositories;
  3. use Illuminate\Support\Facades\Cache;
  4. use Longyi\FrontMenu\Models\FrontMenuItem;
  5. use Webkul\Core\Eloquent\Repository;
  6. class FrontMenuItemRepository extends Repository
  7. {
  8. public function model()
  9. {
  10. return FrontMenuItem::class;
  11. }
  12. /**
  13. * Build a hierarchical tree (up to three levels) of all menu items.
  14. */
  15. public function getMenuTree(bool $onlyEnabled = false)
  16. {
  17. $query = $this->model->newQuery();
  18. if ($onlyEnabled) {
  19. $query->where('status', 1);
  20. }
  21. $items = $query->orderBy('parent_id')
  22. ->orderBy('sort_order')
  23. ->orderBy('id')
  24. ->get();
  25. return collect($this->buildTree($items));
  26. }
  27. /**
  28. * Get the enabled front menu tree, cached for the frontend / GraphQL.
  29. */
  30. public function getEnabledMenuTree()
  31. {
  32. return Cache::remember('front_menu_tree', 3600, function () {
  33. return $this->getMenuTree(true);
  34. });
  35. }
  36. /**
  37. * Recursively build the menu tree.
  38. */
  39. protected function buildTree($items, ?int $parentId = null)
  40. {
  41. $tree = [];
  42. foreach ($items as $item) {
  43. $itemParentId = $item->parent_id === null ? null : (int) $item->parent_id;
  44. if ($itemParentId === $parentId) {
  45. $children = $this->buildTree($items, (int) $item->id);
  46. $item->setRelation('children', collect($children));
  47. $tree[] = $item;
  48. }
  49. }
  50. return $tree;
  51. }
  52. /**
  53. * Clear the front menu cache.
  54. */
  55. public function clearCache(): void
  56. {
  57. Cache::forget('front_menu_tree');
  58. Cache::forget('front_menu_items');
  59. }
  60. }