diff --git a/src/Symfony/Bundle/FrameworkBundle/CHANGELOG.md b/src/Symfony/Bundle/FrameworkBundle/CHANGELOG.md index ce62c9cdf836b..837246455b2e7 100644 --- a/src/Symfony/Bundle/FrameworkBundle/CHANGELOG.md +++ b/src/Symfony/Bundle/FrameworkBundle/CHANGELOG.md @@ -3,7 +3,7 @@ CHANGELOG 7.3 --- - + * Add `rate_limiter` controller attribute * Add `errors.php` and `webhook.php` routing configuration files (use them instead of their XML equivalent) Before: diff --git a/src/Symfony/Component/RateLimiter/Attribute/RateLimit.php b/src/Symfony/Component/RateLimiter/Attribute/RateLimit.php new file mode 100644 index 0000000000000..0e656781d1dd1 --- /dev/null +++ b/src/Symfony/Component/RateLimiter/Attribute/RateLimit.php @@ -0,0 +1,32 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\RateLimiter\Attribute; + +/** + * Rate limit the controller. + * + * @see https://symfony.com/doc/current/rate_limiter.html + * + * @author Raziel Rodrigues + */ +#[\Attribute(\Attribute::IS_REPEATABLE | \Attribute::TARGET_METHOD)] +final class RateLimit +{ + /** + * @param string $limiter The configured limiter name + * @param string[] $methods Request methods to apply the rate limit (`[]` for all) + */ + public function __construct( + public string $limiter, + public array $methods = [] + ) {} +} diff --git a/src/Symfony/Component/RateLimiter/EventListener/RateLimitAttributeListener.php b/src/Symfony/Component/RateLimiter/EventListener/RateLimitAttributeListener.php new file mode 100644 index 0000000000000..853f83b20ef87 --- /dev/null +++ b/src/Symfony/Component/RateLimiter/EventListener/RateLimitAttributeListener.php @@ -0,0 +1,45 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\RateLimiter\EventListener; + +use Symfony\Component\EventDispatcher\EventSubscriberInterface; +use Symfony\Component\ExpressionLanguage\ExpressionLanguage; +use Symfony\Component\HttpKernel\Event\ControllerArgumentsEvent; +use Symfony\Component\HttpKernel\KernelEvents; +use Symfony\Component\RateLimiter\Attribute\RateLimit; + +/** + * Rate limit attribute listener for controller + * + * @see https://symfony.com/doc/current/rate_limiter.html + * + * @author Raziel Rodrigues + */ +class RateLimitAttributeListener implements EventSubscriberInterface +{ + public function __construct( + private ?ExpressionLanguage $expressionLanguage = null, + ) {} + + public function onKernelControllerArguments(ControllerArgumentsEvent $event): void + { + /** @var RateLimit[] $attributes */ + if (!\is_array($attributes = $event->getAttributes()[RateLimit::class] ?? null)) { + return; + } + } + + public static function getSubscribedEvents(): array + { + return [KernelEvents::CONTROLLER_ARGUMENTS => ['onKernelControllerArguments', 20]]; + } +}