This repository has been archived on 2023-08-20. You can view files and clone it, but cannot push or open issues or pull requests.
symfony/src/Symfony/Component/Templating/DelegatingEngine.php

112 lines
2.9 KiB
PHP
Raw Normal View History

<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Templating;
/**
* DelegatingEngine selects an engine for a given template.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class DelegatingEngine implements EngineInterface
{
protected $engines;
/**
* Constructor.
*
* @param array $engines An array of EngineInterface instances to add
*/
public function __construct(array $engines = array())
{
$this->engines = array();
foreach ($engines as $engine) {
$this->addEngine($engine);
}
}
/**
* Renders a template.
*
2011-02-10 17:20:44 +00:00
* @param mixed $name A template name or a TemplateReferenceInterface instance
* @param array $parameters An array of parameters to pass to the template
*
* @return string The evaluated template as a string
*
* @throws \InvalidArgumentException if the template does not exist
* @throws \RuntimeException if the template cannot be rendered
*/
public function render($name, array $parameters = array())
{
return $this->getEngine($name)->render($name, $parameters);
}
/**
* Returns true if the template exists.
*
2011-02-10 17:20:44 +00:00
* @param mixed $name A template name or a TemplateReferenceInterface instance
*
* @return Boolean true if the template exists, false otherwise
*/
public function exists($name)
{
return $this->getEngine($name)->exists($name);
}
/**
* Adds an engine.
*
* @param EngineInterface $engine An EngineInterface instance
*/
public function addEngine(EngineInterface $engine)
{
$this->engines[] = $engine;
}
/**
* Returns true if this class is able to render the given template.
*
2011-02-10 17:20:44 +00:00
* @param mixed $name A template name or a TemplateReferenceInterface instance
*
2011-02-10 17:20:44 +00:00
* @return Boolean true if this class supports the given template, false otherwise
*/
public function supports($name)
{
2011-02-10 17:20:44 +00:00
try {
$this->getEngine($name);
} catch (\RuntimeException $e) {
return false;
}
2011-02-10 17:20:44 +00:00
return true;
}
2011-02-07 13:11:46 +00:00
/**
* Get an engine able to render the given template.
*
2011-02-10 17:20:44 +00:00
* @param mixed $name A template name or a TemplateReferenceInterface instance
2011-02-07 13:11:46 +00:00
*
* @return EngineInterface The engine
*
* @throws \RuntimeException if no engine able to work with the template is found
*/
protected function getEngine($name)
{
foreach ($this->engines as $engine) {
if ($engine->supports($name)) {
return $engine;
}
}
throw new \RuntimeException(sprintf('No engine is able to work with the %s template.', json_encode($name)));
}
}