Thanks to visit codestin.com
Credit goes to github.com

Skip to content

[HttpKernel] Allow dynamic header values within the WithHttpStatus attribute #48890

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

Closed
wants to merge 2 commits into from
Closed
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
Original file line number Diff line number Diff line change
Expand Up @@ -280,6 +280,10 @@ public function load(array $configs, ContainerBuilder $container)
$container->removeDefinition('argument_resolver.backed_enum_resolver');
}

if (!class_exists(ExpressionLanguage::class)) {
$container->removeDefinition('exception_listener.expression_language');
}

$loader->load('services.php');
$loader->load('fragment_renderer.php');
$loader->load('error_renderer.php');
Expand Down
9 changes: 9 additions & 0 deletions src/Symfony/Bundle/FrameworkBundle/Resources/config/web.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
namespace Symfony\Component\DependencyInjection\Loader\Configurator;

use Symfony\Bundle\FrameworkBundle\Controller\ControllerResolver;
use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
use Symfony\Component\HttpKernel\Controller\ArgumentResolver;
use Symfony\Component\HttpKernel\Controller\ArgumentResolver\BackedEnumValueResolver;
use Symfony\Component\HttpKernel\Controller\ArgumentResolver\DateTimeValueResolver;
Expand Down Expand Up @@ -118,10 +119,18 @@
service('logger')->nullOnInvalid(),
param('kernel.debug'),
abstract_arg('an exceptions to log & status code mapping'),
service('exception_listener.expression_language')->nullOnInvalid(),
])
->tag('kernel.event_subscriber')
->tag('monolog.logger', ['channel' => 'request'])

->set('exception_listener.expression_language', ExpressionLanguage::class)
->args([service('cache.exception_listener_expression_language')->nullOnInvalid()])

->set('cache.exception_listener_expression_language')
->parent('cache.system')
->tag('cache.pool')

->set('controller.cache_attribute_listener', CacheAttributeListener::class)
->tag('kernel.event_subscriber')

Expand Down
1 change: 1 addition & 0 deletions src/Symfony/Component/HttpKernel/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ CHANGELOG
* Add `#[WithHttpStatus]` for defining status codes for exceptions
* Use an instance of `Psr\Clock\ClockInterface` to generate the current date time in `DateTimeValueResolver`
* Add `#[WithLogLevel]` for defining log levels for exceptions
* Allow dynamic values for headers specified within `#[WithHttpStatus]`

6.2
---
Expand Down
13 changes: 11 additions & 2 deletions src/Symfony/Component/HttpKernel/EventListener/ErrorListener.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
use Psr\Log\LogLevel;
use Symfony\Component\ErrorHandler\Exception\FlattenException;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\ExpressionLanguage\Expression;
use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Attribute\WithHttpStatus;
use Symfony\Component\HttpKernel\Attribute\WithLogLevel;
Expand All @@ -39,16 +41,18 @@ class ErrorListener implements EventSubscriberInterface
* @var array<class-string, array{log_level: string|null, status_code: int<100,599>|null}>
*/
protected $exceptionsMapping;
protected $expressionLanguage;

/**
* @param array<class-string, array{log_level: string|null, status_code: int<100,599>|null}> $exceptionsMapping
*/
public function __construct(string|object|array|null $controller, LoggerInterface $logger = null, bool $debug = false, array $exceptionsMapping = [])
public function __construct(string|object|array|null $controller, LoggerInterface $logger = null, bool $debug = false, array $exceptionsMapping = [], ExpressionLanguage $expressionLanguage = null)
{
$this->controller = $controller;
$this->logger = $logger;
$this->debug = $debug;
$this->exceptionsMapping = $exceptionsMapping;
$this->expressionLanguage = $expressionLanguage;
}

public function logKernelException(ExceptionEvent $event)
Expand Down Expand Up @@ -76,8 +80,13 @@ public function logKernelException(ExceptionEvent $event)
if ($attributes) {
/** @var WithHttpStatus $instance */
$instance = $attributes[0]->newInstance();
$headers = $instance->headers;

$throwable = new HttpException($instance->statusCode, $throwable->getMessage(), $throwable, $instance->headers);
foreach ($headers as $header => $value) {
$headers[$header] = $value instanceof Expression ? $this->expressionLanguage->evaluate($value, ['this' => $throwable]) : $value;
}

$throwable = new HttpException($instance->statusCode, $throwable->getMessage(), $throwable, $headers);
$event->setThrowable($throwable);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@
use Psr\Log\LogLevel;
use Symfony\Component\ErrorHandler\Exception\FlattenException;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\ExpressionLanguage\Expression;
use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Attribute\WithHttpStatus;
Expand Down Expand Up @@ -161,7 +163,7 @@ public function testHandleHttpAttribute(\Throwable $exception, int $expectedStat
{
$request = new Request();
$event = new ExceptionEvent(new TestKernel(), $request, HttpKernelInterface::MAIN_REQUEST, $exception);
$l = new ErrorListener('not used');
$l = new ErrorListener('not used', expressionLanguage: new ExpressionLanguage());
$l->logKernelException($event);
$l->onKernelException($event);

Expand Down Expand Up @@ -288,6 +290,7 @@ public static function exceptionWithAttributeProvider()
{
yield [new WithCustomUserProvidedAttribute(), 208, ['name' => 'value']];
yield [new WithGeneralAttribute(), 412, ['some' => 'thing']];
yield [new WithDynamicHeader('Example'), 404, ['name' => 'The name is Example.']];
}
}

Expand Down Expand Up @@ -353,3 +356,16 @@ class WithGeneralAttribute extends \Exception
class WarningWithLogLevelAttribute extends \Exception
{
}

#[WithHttpStatus(
statusCode: 404,
headers: [
'name' => new Expression('"The name is " ~ this.name ~ "."'),
]
)]
class WithDynamicHeader extends \Exception
{
public function __construct(public readonly string $name)
{
}
}
3 changes: 2 additions & 1 deletion src/Symfony/Component/HttpKernel/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,8 @@
"symfony/browser-kit": "",
"symfony/config": "",
"symfony/console": "",
"symfony/dependency-injection": ""
"symfony/dependency-injection": "",
"symfony/expression-language": "For setting dynamic header values within the WithHttpStatus attribute"
},
"autoload": {
"psr-4": { "Symfony\\Component\\HttpKernel\\": "" },
Expand Down