menu-bundle/Service/Generator.php

140 lines
3.7 KiB
PHP

<?php
namespace Catalyst\MenuBundle\Service;
use Symfony\Component\Routing\Exception\RouteNotFoundException;
use Symfony\Component\Yaml\Parser as YamlParser;
use Symfony\Component\Config\ConfigCache;
use Symfony\Component\Config\Resource\FileResource;
use Symfony\Component\Routing\RouterInterface;
use Catalyst\MenuBundle\Menu\Collection;
use Catalyst\MenuBundle\Menu\Item;
class Generator
{
protected $index;
protected $menu;
protected $menu_data;
public function __construct($menu_data)
{
$this->index = new Collection();
$this->menu = new Collection();
$this->menu_data = $this->processConfigs($menu_data);
}
public function getMenu($menu_key)
{
if (!isset($this->menu_data[$menu_key]))
return null;
return $this->menu_data[$menu_key];
}
public function setSelected($menu_key, $id)
{
if (!isset($this->menu_data[$menu_key]))
return false;
$sel = $this->menu_data[$menu_key]['index']->get($id);
if ($sel != null)
$sel->setSelected();
return true;
}
protected function processConfigs($data)
{
$pdata = [];
// TODO: cache this
// error_log(print_r($data, true));
// 1st layer are the groups and the parents
// NOTE: extension already merged and sorted the groups for us
foreach ($data as $group => $group_data)
{
// store orphans here in case their parents have not yet been defined
$orphans = [];
// initialize group data
if (!isset($pdata[$group]))
{
$pdata[$group] = [
'menu' => new Collection(),
'index' => new Collection(),
];
}
$index = $pdata[$group]['index'];
$menu = $pdata[$group]['menu'];
// 2nd layer is group data
foreach ($group_data as $mi_data)
{
// check params
if (!isset($mi_data['icon']))
$mi_data['icon'] = null;
// instantiate
$mi = $this->newItem($index, $mi_data['id'], $mi_data['label'], $mi_data['icon']);
// acl
if (isset($mi_data['acl']))
$mi->setACLKey($mi_data['acl']);
// check for orphans
if (isset($orphans[$mi_data['id']]))
{
foreach ($orphans[$mi_data['id']] as $orphan)
{
$mi->addChild($orphan);
}
}
// check parent
if (isset($mi_data['parent']) && $mi_data['parent'] != null)
{
$parent = $index->get($mi_data['parent']);
// if parent has not been set, add to orphans
if ($parent == null)
{
if (!isset($orphans[$mi_data['parent']]))
$orphans[$mi_data['parent']] = [];
$orphans[$mi_data['parent']][] = $mi;
continue;
}
$parent->addChild($mi);
}
else
$menu->add($mi);
}
}
// error_log(print_r($pdata, true));
return $pdata;
}
protected function newItem($index, $id, $label, $icon = null)
{
$mi = new Item();
$mi->setID($id)
->setLabel($label)
->setRoute($id);
if ($icon != null)
$mi->setIcon($icon);
$index->add($mi);
return $mi;
}
}