Created
October 8, 2013 12:52
-
-
Save jzahedieh/6884204 to your computer and use it in GitHub Desktop.
Magento Find Category by Path for http://stackoverflow.com/questions/19248041/magento-get-category-by-path
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Functionality taken from Mage_ImportExport_Model_Import_Entity_Product | |
*/ | |
class Your_Module_Model_Category_Finder | |
{ | |
/** | |
* Categories text-path to ID hash. | |
* | |
* @var array | |
*/ | |
protected $_categories = array(); | |
/** | |
* Categories text-path to ID hash with roots checking. | |
* | |
* @var array | |
*/ | |
protected $_categoriesWithRoots = array(); | |
/** | |
* Populates the models properties with category information. | |
*/ | |
public function __construct() | |
{ | |
$this->_initCategories(); | |
} | |
/** | |
* Finds a subcategory id from a path string | |
* | |
* @param $string | |
* @return bool | |
*/ | |
public function getIdFromPath($string) | |
{ | |
if (in_array($string, array_keys($this->_categories))) { | |
return $this->_categories[$string]; | |
} | |
return false; | |
} | |
/** | |
* Returns all valid path strings | |
* | |
* @return array | |
*/ | |
public function getAllPaths() | |
{ | |
return array_keys($this->_categories); | |
} | |
/** | |
* Initialize categories text-path to ID hash. | |
* | |
* @return Mage_ImportExport_Model_Import_Entity_Product | |
*/ | |
protected function _initCategories() | |
{ | |
$collection = Mage::getResourceModel('catalog/category_collection')->addNameToResult(); | |
/* @var $collection Mage_Catalog_Model_Resource_Eav_Mysql4_Category_Collection */ | |
foreach ($collection as $category) { | |
$structure = explode('/', $category->getPath()); | |
$pathSize = count($structure); | |
if ($pathSize > 1) { | |
$path = array(); | |
for ($i = 1; $i < $pathSize; $i++) { | |
$path[] = $collection->getItemById($structure[$i])->getName(); | |
} | |
$rootCategoryName = array_shift($path); | |
if (!isset($this->_categoriesWithRoots[$rootCategoryName])) { | |
$this->_categoriesWithRoots[$rootCategoryName] = array(); | |
} | |
$index = implode('/', $path); | |
$this->_categoriesWithRoots[$rootCategoryName][$index] = $category->getId(); | |
if ($pathSize > 2) { | |
$this->_categories[$index] = $category->getId(); | |
} | |
} | |
} | |
return $this; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment