I'm trying to find a way to get a list of all magento 1.9 blocks with their names programmatically.
I.e:
$blocks= [
'core/text_tag_css_admin' => 'Mage_Core_Block_Text_Tag_Css_Admin',
'core/text_list_item' => 'Mage_Core_Block_Text_List_Item',
'core/text_list_link' => 'Mage_Core_Block_Text_List_Link',
]
I searched but I haven't found anything on how to approach this problem.
Here's the code I have so far in case it will help someone else.
public function toOptionArray()
{
/**
* @var $blocks Mage_Core_Model_Config_Element
*/
$blocks = Mage::getConfig()->getNode('global/blocks')->asArray();
$classes = [];
$options = [];
$realClasses = [];
foreach ($blocks as $key => $value) {
$classes[$key] = $value['class'];
}
foreach ($classes as $key => $class) {
$classKeys = explode('_', $class);
$moduleDir = Mage::getModuleDir('', $classKeys[0] . '_' . $classKeys[1]);
$moduleDir = $moduleDir . DS . $classKeys[2];
if (empty($moduleDir))
continue;
$files = [];
$files = $this->listFIles($moduleDir);
$relativeClasses = $this->getRelativeClasses($files, $moduleDir);
foreach ($relativeClasses as $relativeClass) {
$realClass = $class . $relativeClass;
$realClasses[] = $realClass;
}
}
$result = [];
sort($realClasses);
//TODO: Eliminate abstract classes
foreach ($realClasses as $realClass) {
try {
//throws fatal error so can't be caught
$r = new ReflectionClass($realClass);
} catch (Exception $e) {
}
if (isset($r) && !$r->isAbstract())
$result[] = array('value' => $realClass, 'label' => $realClass);
}
return $result;
}
protected function getRelativeClasses($files, $moduleDir)
{
if (empty($files) || !file_exists($moduleDir))
return [];
$classes = [];
foreach ($files as $file) {
$filePath = $file->getPathname();
$relativeClassPath = str_replace($moduleDir, '', $filePath);
$relativeClassPath = str_replace('.php', '', $relativeClassPath);
$relativeClassPath = str_replace(DS, '_', $relativeClassPath);
$classes[] = $relativeClassPath;
}
return $classes;
}
protected function listFIles($dir)
{
if (!file_exists($dir))
return [];
$files = [];
$di = new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS);
$it = new RecursiveIteratorIterator($di);
foreach ($it as $file) {
if (pathinfo($file, PATHINFO_EXTENSION) == "php") {
$files[] = $file;
}
}
return $files;
}