![]() 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/vendor/extmag/shiplab/Model/Source/ |
<?php /** * Copyright © Extmag. All rights reserved. */ namespace Extmag\Shiplab\Model\Source; use Magento\Catalog\Model\CategoryFactory; use Magento\Catalog\Model\ResourceModel\Category\CollectionFactory; use Magento\Framework\Data\OptionSourceInterface; class ProductCategories implements OptionSourceInterface { protected $categoryFactory; protected $categoryCollectionFactory; public function __construct( CategoryFactory $categoryFactory, CollectionFactory $categoryCollectionFactory ) { $this->categoryFactory = $categoryFactory; $this->categoryCollectionFactory = $categoryCollectionFactory; } public function toOptionArray() { $arr = $this->_toArray(); $ret = []; foreach ($arr as $key => $value) { $ret[] = [ 'value' => $key, 'label' => $value, ]; } return $ret; } protected function _toArray() { $categories = $this->getCategoryCollection(false, false, false, false); $categoryList = []; foreach ($categories as $category) { $categoryList[$category->getEntityId()] = __( $this->_getParentName($category->getPath()) . $category->getName() ); } return $categoryList; } public function getCategoryCollection($isActive = true, $level = false, $sortBy = false, $pageSize = false) { $collection = $this->categoryCollectionFactory->create(); $collection->addAttributeToSelect('*'); // select only active categories if ($isActive) { $collection->addIsActiveFilter(); } // select categories of certain level if ($level) { $collection->addLevelFilter($level); } // sort categories by some value if ($sortBy) { $collection->addOrderField($sortBy); } // select certain number of categories if ($pageSize) { $collection->setPageSize($pageSize); } return $collection; } protected function _getParentName($path = '') { $parentName = ''; $rootCats = [1, 2]; $catTree = explode("/", $path); // Deleting category itself array_pop($catTree); if ($catTree && (count($catTree) > count($rootCats))) { foreach ($catTree as $catId) { if (!in_array($catId, $rootCats)) { $category = $this->categoryFactory->create()->load($catId); $categoryName = $category->getName(); $parentName .= $categoryName . ' -> '; } } } return $parentName; } }