<?php
namespace App\Component\ViewLayer\ViewHandlers;
use App\Component\ViewLayer\AbstractView;
use App\Component\ViewLayer\AbstractViewHandler;
use App\Component\ViewLayer\Views\AbstractWebView;
use Cms\FrontendBundle\Service\FrontendBuilder;
use Cms\Widgets\Html\Html;
use Twig\Environment;
/**
*
*/
final class WebViewHandler extends AbstractViewHandler
{
// DI
protected Environment $twig;
protected FrontendBuilder $builder;
/**
* @param Environment $twig
* @param FrontendBuilder $builder
*/
public function __construct(
Environment $twig,
FrontendBuilder $builder
)
{
$this->twig = $twig;
$this->builder = $builder;
}
/**
* {@inheritDoc}
*/
public function supports(AbstractView $view): bool
{
return ($view instanceof AbstractWebView);
}
/**
* {@inheritDoc}
* @param AbstractWebView $view
*/
public function prepare(AbstractView $view): void
{
// see if we don't have a template given; if not generate a default one
if (empty($view->getTemplate())) {
// get the routing information
$route = $view->getRequest()->attributes->get('_route');
// get the parts that make up the route; currently ignoring the first two
// TODO: need to make this a bit more flexible as the naming convention might not be consistent?
$paths = array_slice(explode('.', $route), 3, -1);
// set the template path
$view->setTemplate(sprintf(
'@package$/controllers/%s.html.twig',
implode('/', $paths)
));
}
}
/**
* {@inheritDoc}
* @param AbstractWebView $view
*/
public function handle(AbstractView $view): string
{
// render the main content area and set it into the dom
$content = $this->twig->render(
$view->getTemplate(),
array_merge(
$view->getParameters(),
[]
)
);
// render the full page
return $this->builder->renderCustom(
$view->getRenderContext()->toFrontendGlobals(),
[(new Html())->setContent($content)]
);
}
}