deblan.tv/vendor/trinity/src/Trinity/Bundle/ContentManagerBundle/Twig/Extension/BlockExtension.php
2015-03-02 21:57:49 +01:00

99 lines
3 KiB
PHP

<?php
namespace Trinity\Bundle\ContentManagerBundle\Twig\Extension;
use Trinity\Bundle\ContentManagerBundle\Exception\BlockNotFoundException;
use Trinity\Bundle\ContentManagerBundle\Model\Page;
use Trinity\Bundle\ContentManagerBundle\Model\Block;
use \Trinity\Bundle\ContentManagerBundle\Block\BlockManager;
use \Symfony\Component\Routing\RouterInterface;
use \Trinity\Bundle\ContentManagerBundle\Page\PageManagerSelectorInterface;
class BlockExtension extends \Twig_Extension
{
private $environment;
private $code_render;
private $resources;
private $blockManager;
protected $pageSelector;
protected $router;
public function __construct(RouterInterface $router, PageManagerSelectorInterface $pageSelector, BlockManager $blockManager)
{
$this->router = $router;
$this->pageSelector = $pageSelector;
$this->blockManager = $blockManager;
}
public function initRuntime(\Twig_Environment $environment)
{
$this->environment = $environment;
$this->code_render = clone $this->environment;
$this->code_render->setLoader(new \Twig_Loader_String());
}
public function getName()
{
return 'block_extension';
}
public function getFunctions()
{
return array(
'render_block' => new \Twig_Function_Method($this, 'renderBlock', array('is_safe' => array('html'))),
'render_recursive_block' => new \Twig_Function_Method($this, 'renderRecursiveBlock', array('is_safe' => array('html'))),
'render_code_block' => new \Twig_Function_Method($this, 'renderCodeBlock', array('is_safe' => array('html'))),
);
}
public function renderBlock($block_name)
{
try {
$block = $this->blockManager->retrieve($block_name);
} catch (BlockNotFoundException $e) {
return null;
}
return $this->render($block->getTemplate(), array('block' => $block));
}
public function renderRecursiveBlock($block_name)
{
$cms = $this->pageSelector->retrieve();
if (!$cms) {
throw new \Twig_Error('No active page manager.');
}
try {
$block = $this->blockManager->recursiveRetrieve($block_name, $cms->getCurrentNode());
} catch (BlockNotFoundException $e) {
return null;
}
return $this->render($block->getTemplate(), array('block' => $block));
}
public function renderCodeBlock($block_name, $options)
{
try {
$block = $this->blockManager->retrieve($block_name);
} catch (BlockNotFoundException $e) {
return null;
}
return $this->code_render->render($block->getValue(), $options);
}
public function render($template, array $parameters = array())
{
if (!isset($this->resources[$template])) {
$this->resources[$template] = $this->environment->loadTemplate($template);
}
return $this->resources[$template]->render($parameters);
}
}