/** * Builds a category tree with all the categories and subcategories * * cost O(n) * * @return array */ public function buildCategoryTree() { $categories = $this->categoryRepository->getAllCategoriesSortedByParentAndPositionAsc(); $categoryTree = [0 => null, 'children' => []]; /** * @var CategoryInterface $category */ foreach ($categories as $category) { $parentCategoryId = 0; $categoryId = $category->getId(); if (!$category->isRoot()) { if ($category->getParent() instanceof CategoryInterface) { $parentCategoryId = $category->getParent()->getId(); } else { /** * If category is not root and has no parent, * don't insert it into the tree */ continue; } } if ($parentCategoryId && !isset($categoryTree[$parentCategoryId])) { $categoryTree[$parentCategoryId] = ['entity' => null, 'children' => []]; } if (!isset($categoryTree[$categoryId])) { $categoryTree[$categoryId] = ['entity' => null, 'children' => []]; } $categoryTree[$categoryId]['entity'] = $category; $categoryTree[$parentCategoryId]['children'][] =& $categoryTree[$categoryId]; } return $categoryTree[0]['children'] ?: []; }
/** * Build category tree from doctrine * * cost O(n) * * @return Array Category tree */ protected function buildCategoryTree() { $categories = $this->categoryRepository->getAllCategoriesSortedByParentAndPositionAsc($this->loadOnlyCategoriesWithProducts); $categoryTree = [0 => null, 'children' => []]; /** * @var CategoryInterface $category */ foreach ($categories as $category) { $parentCategoryId = 0; $categoryId = $category->getId(); if (!$category->isRoot()) { if ($category->getParent() instanceof CategoryInterface) { $parentCategoryId = $category->getParent()->getId(); } else { /** * If category is not root and has no parent, * don't insert it into the tree */ continue; } } if ($parentCategoryId && !isset($categoryTree[$parentCategoryId])) { $categoryTree[$parentCategoryId] = array('entity' => null, 'children' => array()); } if (!isset($categoryTree[$categoryId])) { $categoryTree[$categoryId] = array('entity' => null, 'children' => array()); } $categoryTree[$categoryId]['entity'] = array('id' => $category->getId(), 'name' => $category->getName(), 'slug' => $category->getSlug(), 'productsCount' => $this->loadOnlyCategoriesWithProducts ? count($category->getProducts()) : 0); $categoryTree[$parentCategoryId]['children'][] =& $categoryTree[$categoryId]; } return $categoryTree[0]['children'] ?: []; }