chill-bundles/src/Bundle/ChillMainBundle/Templating/Entity/ChillEntityRenderExtension.php
2022-02-22 12:12:53 +01:00

97 lines
2.1 KiB
PHP

<?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Chill\MainBundle\Templating\Entity;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;
/**
* Class ChillEntityRenderExtension.
*/
class ChillEntityRenderExtension extends AbstractExtension
{
/**
* @var ChillEntityRender
*/
protected $defaultRender;
/**
* @var iterable|ChillEntityRenderInterface[]
*/
protected $renders = [];
/**
* ChillEntityRenderExtension constructor.
*/
public function __construct(iterable $renders)
{
$this->defaultRender = new ChillEntityRender();
$this->renders = $renders;
}
/**
* @return array|TwigFilter[]
*/
public function getFilters()
{
return [
new TwigFilter('chill_entity_render_string', [$this, 'renderString'], [
'is_safe' => ['html'],
]),
new TwigFilter('chill_entity_render_box', [$this, 'renderBox'], [
'is_safe' => ['html'],
]),
];
}
/**
* @param $entity
*/
public function renderBox($entity, array $options = []): string
{
if (null === $entity) {
return '';
}
return $this->getRender($entity, $options)
->renderBox($entity, $options);
}
/**
* @param $entity
*/
public function renderString($entity, array $options = []): string
{
if (null === $entity) {
return '';
}
return $this->getRender($entity, $options)
->renderString($entity, $options);
}
/**
* @param $entity
* @param $options
*/
protected function getRender($entity, $options): ?ChillEntityRenderInterface
{
foreach ($this->renders as $render) {
if ($render->supports($entity, $options)) {
return $render;
}
}
return $this->defaultRender;
}
}