![]() Server : Apache System : Linux server2.corals.io 4.18.0-348.2.1.el8_5.x86_64 #1 SMP Mon Nov 15 09:17:08 EST 2021 x86_64 User : corals ( 1002) PHP Version : 7.4.33 Disable Function : exec,passthru,shell_exec,system Directory : /home/corals/old/app/code/Cnc/Catalog/Model/Config/Source/ |
<?php /** * Copyright (c) 2021 Kaliop Digital Commerce (https://digitalcommerce.kaliop.com) All Rights Reserved. * https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) * Krzysztof Majkowski <[email protected]> */ declare(strict_types=1); namespace Cnc\Catalog\Model\Config\Source; use Magento\Catalog\Model\ResourceModel\Category\CollectionFactory; use Magento\Framework\Exception\LocalizedException; use Magento\Framework\Option\ArrayInterface; class Category implements ArrayInterface { const SYSTEM_CATEGORY_ID = 1; const ROOT_LEVEL = 1; /** * @var CollectionFactory */ private $collectionFactory; /** * Category constructor. * @param CollectionFactory $collectionFactory */ public function __construct(CollectionFactory $collectionFactory) { $this->collectionFactory = $collectionFactory; } /** * @return array * @throws LocalizedException */ public function toOptionArray(): array { $optionArray = []; $arr = $this->toArray(); foreach ($arr as $value => $label) { $optionArray[] = [ 'value' => $value, 'label' => $label ]; } return $optionArray; } /** * @return array * @throws LocalizedException */ public function toArray(): array { $options = []; $options = array_replace( $options, $this->getChildren(self::SYSTEM_CATEGORY_ID, self::ROOT_LEVEL) ); return $options; } /** * @param $parentCategoryId * @param $level * @return array * @throws LocalizedException */ private function getChildren($parentCategoryId, $level): array { $options = []; $collection = $this->collectionFactory->create(); $collection ->setStoreId(0) ->addAttributeToSelect('name') ->addAttributeToFilter('level', $level) ->addAttributeToFilter('parent_id', $parentCategoryId) ->setOrder('position', 'asc'); foreach ($collection as $category) { $options[$category->getId()] = str_repeat(". ", max(0, ($category->getLevel() - 1) * 3)) . $category->getName(); if ($category->hasChildren()) { $options = array_replace($options, $this->getChildren($category->getId(), $category->getLevel() + 1)); } } return $options; } }