AbstractRequestRateLimiter.php 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\HttpFoundation\RateLimiter;
  11. use Symfony\Component\HttpFoundation\Request;
  12. use Symfony\Component\RateLimiter\LimiterInterface;
  13. use Symfony\Component\RateLimiter\Policy\NoLimiter;
  14. use Symfony\Component\RateLimiter\RateLimit;
  15. /**
  16. * An implementation of RequestRateLimiterInterface that
  17. * fits most use-cases.
  18. *
  19. * @author Wouter de Jong <wouter@wouterj.nl>
  20. *
  21. * @experimental in 5.2
  22. */
  23. abstract class AbstractRequestRateLimiter implements RequestRateLimiterInterface
  24. {
  25. public function consume(Request $request): RateLimit
  26. {
  27. $limiters = $this->getLimiters($request);
  28. if (0 === \count($limiters)) {
  29. $limiters = [new NoLimiter()];
  30. }
  31. $minimalRateLimit = null;
  32. foreach ($limiters as $limiter) {
  33. $rateLimit = $limiter->consume(1);
  34. if (null === $minimalRateLimit || $rateLimit->getRemainingTokens() < $minimalRateLimit->getRemainingTokens()) {
  35. $minimalRateLimit = $rateLimit;
  36. }
  37. }
  38. return $minimalRateLimit;
  39. }
  40. public function reset(Request $request): void
  41. {
  42. foreach ($this->getLimiters($request) as $limiter) {
  43. $limiter->reset();
  44. }
  45. }
  46. /**
  47. * @return LimiterInterface[] a set of limiters using keys extracted from the request
  48. */
  49. abstract protected function getLimiters(Request $request): array;
  50. }