<?php
declare(strict_types=1);
namespace Hitso\Bundle\CommonBundle\Helper\Templating;
use Hitso\Bundle\CommonBundle\Controller\Controller;
use ReflectionClass;
use Symfony\Bundle\FrameworkBundle\Templating\EngineInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Bundle\BundleInterface;
use Symfony\Component\HttpKernel\KernelInterface;
use Twig\Environment;
class TemplatingHelper implements TemplatingHelperInterface
{
/**
* @var EngineInterface
*/
protected $engine;
/**
* @var KernelInterface
*/
protected $kernel;
/**
* @var Environment
*/
protected $environment;
public function __construct(EngineInterface $engine, Environment $environment, KernelInterface $kernel)
{
$this->engine = $engine;
$this->environment = $environment;
$this->kernel = $kernel;
}
public function render(string $name, array $parameters = []): string
{
return $this->engine->render($name, $parameters);
}
public function renderFromString(string $content, array $parameters = []): string
{
$template = $this->environment->createTemplate($content);
return $template->render($parameters);
}
public function renderControllerResponse(Controller $controller, string $templateName, array $parameters = []): Response
{
$template = $this->resolveControllerTemplate($controller, $templateName);
return $this->engine->renderResponse($template, $parameters);
}
public function resolveControllerTemplate(Controller $controller, string $templateName): string
{
$reflectionClass = new ReflectionClass($controller);
$controllerName = $this->getControllerLogicalName($reflectionClass);
$bundleName = $this->getBundleName($reflectionClass);
return sprintf('%s:%s:%s.html.twig', $bundleName, $controllerName, $templateName);
}
protected function getControllerLogicalName(ReflectionClass $reflectionClass): string
{
$className = $reflectionClass->getName();
preg_match('/Controller\\\(.+)Controller$/', $className, $matchController);
return $matchController[1];
}
protected function getBundleName(ReflectionClass $reflectionClass): string
{
$currentBundle = $this->getBundleForClass($reflectionClass);
return $currentBundle->getName();
}
protected function getBundleForClass(ReflectionClass $reflectionClass): BundleInterface
{
$bundles = $this->kernel->getBundles();
do {
$namespace = $reflectionClass->getNamespaceName();
foreach ($bundles as $bundle) {
if (0 === strpos($namespace, $bundle->getNamespace())) {
return $bundle;
}
}
$reflectionClass = $reflectionClass->getParentClass();
} while ($reflectionClass);
}
}