Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

[TwigBridge] Add #[Template()] to describe how to render arrays returned by controllers #46906

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 12, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions 34 src/Symfony/Bridge/Twig/Attribute/Template.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?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\Bridge\Twig\Attribute;

#[\Attribute(\Attribute::TARGET_CLASS | \Attribute::TARGET_METHOD | \Attribute::TARGET_FUNCTION)]
class Template
{
public function __construct(
/**
* The name of the template to render.
*/
public string $template,

/**
* The controller method arguments to pass to the template.
*/
public ?array $vars = null,
nicolas-grekas marked this conversation as resolved.
Show resolved Hide resolved

/**
* Enables streaming the template.
*/
public bool $stream = false,
nicolas-grekas marked this conversation as resolved.
Show resolved Hide resolved
) {
}
}
1 change: 1 addition & 0 deletions 1 src/Symfony/Bridge/Twig/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ CHANGELOG
---

* Add `form_label_content` and `form_help_content` block to form themes
* Add `#[Template()]` to describe how to render arrays returned by controllers

6.1
---
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
<?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\Bridge\Twig\EventListener;

use Symfony\Bridge\Twig\Attribute\Template;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Symfony\Component\HttpKernel\Event\ControllerArgumentsEvent;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Twig\Environment;

class TemplateAttributeListener implements EventSubscriberInterface
{
public function __construct(
private Environment $twig,
) {
}

public function onKernelView(ViewEvent $event)
{
$parameters = $event->getControllerResult();

if (!\is_array($parameters ?? [])) {
return;
}
$attribute = $event->getRequest()->attributes->get('_template');

if (!$attribute instanceof Template && !$attribute = $event->controllerArgumentsEvent?->getAttributes()[Template::class][0] ?? null) {
return;
}

$parameters ??= $this->resolveParameters($event->controllerArgumentsEvent, $attribute->vars);
nicolas-grekas marked this conversation as resolved.
Show resolved Hide resolved
$status = 200;

foreach ($parameters as $k => $v) {
if (!$v instanceof FormInterface) {
continue;
}
if ($v->isSubmitted() && !$v->isValid()) {
$status = 422;
}
$parameters[$k] = $v->createView();
}

$event->setResponse($attribute->stream
? new StreamedResponse(fn () => $this->twig->display($attribute->template, $parameters), $status)
: new Response($this->twig->render($attribute->template, $parameters), $status)
);
}

public static function getSubscribedEvents(): array
{
return [
KernelEvents::VIEW => ['onKernelView', -128],
];
}

private function resolveParameters(ControllerArgumentsEvent $event, ?array $vars): array
{
if ([] === $vars) {
nicolas-grekas marked this conversation as resolved.
Show resolved Hide resolved
return [];
}

$parameters = $event->getNamedArguments();

if (null !== $vars) {
$parameters = array_intersect_key($parameters, array_flip($vars));
}

return $parameters;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
<?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\Bridge\Twig\Tests\EventListener;

use PHPUnit\Framework\TestCase;
use Symfony\Bridge\Twig\EventListener\TemplateAttributeListener;
use Symfony\Bridge\Twig\Tests\Fixtures\TemplateAttributeController;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\ControllerArgumentsEvent;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Twig\Environment;

class TemplateAttributeListenerTest extends TestCase
{
public function testAttribute()
{
$twig = $this->createMock(Environment::class);
$twig->expects($this->exactly(2))
->method('render')
->withConsecutive(
['templates/foo.html.twig', ['foo' => 'bar']],
['templates/foo.html.twig', ['bar' => 'Bar', 'buz' => 'def']]
)
->willReturn('Bar');

$request = new Request();
$kernel = $this->createMock(HttpKernelInterface::class);
$controllerArgumentsEvent = new ControllerArgumentsEvent($kernel, [new TemplateAttributeController(), 'foo'], ['Bar'], $request, null);
nicolas-grekas marked this conversation as resolved.
Show resolved Hide resolved
$listener = new TemplateAttributeListener($twig);

$event = new ViewEvent($kernel, $request, HttpKernelInterface::MAIN_REQUEST, ['foo' => 'bar'], $controllerArgumentsEvent);
$listener->onKernelView($event);
$this->assertSame('Bar', $event->getResponse()->getContent());

$event = new ViewEvent($kernel, $request, HttpKernelInterface::MAIN_REQUEST, null, $controllerArgumentsEvent);
$listener->onKernelView($event);
$this->assertSame('Bar', $event->getResponse()->getContent());

$event = new ViewEvent($kernel, $request, HttpKernelInterface::MAIN_REQUEST, null);
$listener->onKernelView($event);
$this->assertNull($event->getResponse());
}

public function testForm()
{
$request = new Request();
$kernel = $this->createMock(HttpKernelInterface::class);
$controllerArgumentsEvent = new ControllerArgumentsEvent($kernel, [new TemplateAttributeController(), 'foo'], [], $request, null);
$listener = new TemplateAttributeListener($this->createMock(Environment::class));

$form = $this->createMock(FormInterface::class);
$form->expects($this->once())->method('createView');
$form->expects($this->once())->method('isSubmitted')->willReturn(true);
$form->expects($this->once())->method('isValid')->willReturn(false);

$event = new ViewEvent($kernel, $request, HttpKernelInterface::MAIN_REQUEST, ['bar' => $form], $controllerArgumentsEvent);
$listener->onKernelView($event);

$this->assertSame(422, $event->getResponse()->getStatusCode());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?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\Bridge\Twig\Tests\Fixtures;

use Symfony\Bridge\Twig\Attribute\Template;

class TemplateAttributeController
{
#[Template('templates/foo.html.twig', vars: ['bar', 'buz'])]
public function foo($bar, $baz = 'abc', $buz = 'def')
{
}
}
4 changes: 2 additions & 2 deletions 4 src/Symfony/Bridge/Twig/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
"symfony/form": "^6.1",
"symfony/html-sanitizer": "^6.1",
"symfony/http-foundation": "^5.4|^6.0",
"symfony/http-kernel": "^5.4|^6.0",
"symfony/http-kernel": "^6.2",
"symfony/intl": "^5.4|^6.0",
"symfony/mime": "^5.4|^6.0",
"symfony/polyfill-intl-icu": "~1.0",
Expand Down Expand Up @@ -58,7 +58,7 @@
"symfony/console": "<5.4",
"symfony/form": "<6.1",
"symfony/http-foundation": "<5.4",
"symfony/http-kernel": "<5.4",
"symfony/http-kernel": "<6.2",
"symfony/translation": "<5.4",
"symfony/workflow": "<5.4"
},
Expand Down
5 changes: 5 additions & 0 deletions 5 src/Symfony/Bundle/TwigBundle/Resources/config/twig.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use Symfony\Bridge\Twig\AppVariable;
use Symfony\Bridge\Twig\DataCollector\TwigDataCollector;
use Symfony\Bridge\Twig\ErrorRenderer\TwigErrorRenderer;
use Symfony\Bridge\Twig\EventListener\TemplateAttributeListener;
use Symfony\Bridge\Twig\Extension\AssetExtension;
use Symfony\Bridge\Twig\Extension\CodeExtension;
use Symfony\Bridge\Twig\Extension\ExpressionExtension;
Expand Down Expand Up @@ -169,5 +170,9 @@
->args([service('serializer')])

->set('twig.extension.serializer', SerializerExtension::class)

->set('controller.template_attribute_listener', TemplateAttributeListener::class)
->args([service('twig')])
->tag('kernel.event_subscriber')
;
};
9 changes: 4 additions & 5 deletions 9 src/Symfony/Bundle/TwigBundle/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,11 @@
"require": {
"php": ">=8.1",
"composer-runtime-api": ">=2.1",
"symfony/config": "^5.4|^6.0",
"symfony/dependency-injection": "^5.4|^6.0",
"symfony/twig-bridge": "^5.4|^6.0",
"symfony/config": "^6.1",
"symfony/dependency-injection": "^6.1",
"symfony/twig-bridge": "^6.2",
"symfony/http-foundation": "^5.4|^6.0",
"symfony/http-kernel": "^5.4|^6.0",
"symfony/polyfill-ctype": "~1.8",
"symfony/http-kernel": "^6.2",
"twig/twig": "^2.13|^3.0.4"
},
"require-dev": {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ final class ControllerArgumentsEvent extends KernelEvent
{
private ControllerEvent $controllerEvent;
private array $arguments;
private array $namedArguments;

public function __construct(HttpKernelInterface $kernel, callable|ControllerEvent $controller, array $arguments, Request $request, ?int $requestType)
{
Expand All @@ -54,6 +55,7 @@ public function getController(): callable
public function setController(callable $controller, array $attributes = null): void
{
$this->controllerEvent->setController($controller, $attributes);
unset($this->namedArguments);
}

public function getArguments(): array
Expand All @@ -64,6 +66,32 @@ public function getArguments(): array
public function setArguments(array $arguments)
{
$this->arguments = $arguments;
unset($this->namedArguments);
}

public function getNamedArguments(): array
{
if (isset($this->namedArguments)) {
return $this->namedArguments;
}

$namedArguments = [];
$arguments = $this->arguments;
$r = $this->getRequest()->attributes->get('_controller_reflectors')[1] ?? new \ReflectionFunction($this->controllerEvent->getController());

foreach ($r->getParameters() as $i => $param) {
if ($param->isVariadic()) {
$namedArguments[$param->name] = \array_slice($arguments, $i);
break;
}
if (\array_key_exists($i, $arguments)) {
$namedArguments[$param->name] = $arguments[$i];
} elseif ($param->isDefaultvalueAvailable()) {
$namedArguments[$param->name] = $param->getDefaultValue();
}
}

return $this->namedArguments = $namedArguments;
}

/**
Expand Down
4 changes: 3 additions & 1 deletion 4 src/Symfony/Component/HttpKernel/Event/ViewEvent.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,15 @@
*/
final class ViewEvent extends RequestEvent
{
public readonly ?ControllerArgumentsEvent $controllerArgumentsEvent;
private mixed $controllerResult;

public function __construct(HttpKernelInterface $kernel, Request $request, int $requestType, mixed $controllerResult)
public function __construct(HttpKernelInterface $kernel, Request $request, int $requestType, mixed $controllerResult, ControllerArgumentsEvent $controllerArgumentsEvent = null)
{
parent::__construct($kernel, $request, $requestType);

$this->controllerResult = $controllerResult;
$this->controllerArgumentsEvent = $controllerArgumentsEvent;
}

public function getControllerResult(): mixed
Expand Down
4 changes: 2 additions & 2 deletions 4 src/Symfony/Component/HttpKernel/HttpKernel.php
Original file line number Diff line number Diff line change
Expand Up @@ -156,14 +156,13 @@ private function handleRaw(Request $request, int $type = self::MAIN_REQUEST): Re
$this->dispatcher->dispatch($event, KernelEvents::CONTROLLER_ARGUMENTS);
$controller = $event->getController();
$arguments = $event->getArguments();
$request->attributes->remove('_controller_reflectors');

// call controller
$response = $controller(...$arguments);

// view
if (!$response instanceof Response) {
$event = new ViewEvent($this, $request, $type, $response);
$event = new ViewEvent($this, $request, $type, $response, $event);
$this->dispatcher->dispatch($event, KernelEvents::VIEW);

if ($event->hasResponse()) {
Expand All @@ -179,6 +178,7 @@ private function handleRaw(Request $request, int $type = self::MAIN_REQUEST): Re
throw new ControllerDoesNotReturnResponseException($msg, $controller, __FILE__, __LINE__ - 17);
}
}
$request->attributes->remove('_controller_reflectors');

return $this->filterResponse($response, $request, $type);
}
Expand Down
Loading
Morty Proxy This is a proxified and sanitized view of the page, visit original site.