Skip to content

Instantly share code, notes, and snippets.

@yceruto
Last active August 10, 2023 12:19
Show Gist options
  • Save yceruto/fc5594963df6a642c34111eea1a82b17 to your computer and use it in GitHub Desktop.
Save yceruto/fc5594963df6a642c34111eea1a82b17 to your computer and use it in GitHub Desktop.
controller render block
<?php
protected function renderView(string $view, array $parameters = []): string
{
if (!$this->container->has('twig')) {
throw new \LogicException('You cannot use the "renderView" method if the Twig Bundle is not available. Try running "composer require symfony/twig-bundle".');
}
return $this->container->get('twig')->render($view, $this->normalizeViewParameters($parameters));
}
protected function renderViewBlock(string $view, string $block, array $parameters = []): string
{
if (!$this->container->has('twig')) {
throw new \LogicException('You cannot use the "renderViewBlock" method if the Twig Bundle is not available. Try running "composer require symfony/twig-bundle".');
}
return $this->container->get('twig')->load($view)->renderBlock($block, $this->normalizeViewParameters($parameters));
}
protected function render(string $view, array $parameters = [], Response $response = null): Response
{
$content = $this->renderView($view, $parameters);
return $this->prepareResponse($response ?? new Response(), $parameters, $content);
}
protected function renderBlock(string $view, string $block, array $parameters = [], Response $response = null): Response
{
$content = $this->renderViewBlock($view, $block, $parameters);
return $this->prepareResponse($response ?? new Response(), $parameters, $content);
}
private function normalizeViewParameters(array $parameters): array
{
foreach ($parameters as $k => $v) {
if ($v instanceof FormInterface) {
$parameters[$k] = $v->createView();
}
}
return $parameters;
}
private function prepareResponse(Response $response, array $parameters, string $content): Response
{
if (200 === $response->getStatusCode()) {
foreach ($parameters as $v) {
if ($v instanceof FormInterface && $v->isSubmitted() && !$v->isValid()) {
$response->setStatusCode(422);
break;
}
}
}
$response->setContent($content);
return $response;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment