AbstractRequestRateLimiter.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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. abstract class AbstractRequestRateLimiter implements RequestRateLimiterInterface
  22. {
  23. public function consume(Request $request): RateLimit
  24. {
  25. $limiters = $this->getLimiters($request);
  26. if (0 === \count($limiters)) {
  27. $limiters = [new NoLimiter()];
  28. }
  29. $minimalRateLimit = null;
  30. foreach ($limiters as $limiter) {
  31. $rateLimit = $limiter->consume(1);
  32. if (null === $minimalRateLimit || $rateLimit->getRemainingTokens() < $minimalRateLimit->getRemainingTokens()) {
  33. $minimalRateLimit = $rateLimit;
  34. }
  35. }
  36. return $minimalRateLimit;
  37. }
  38. public function reset(Request $request): void
  39. {
  40. foreach ($this->getLimiters($request) as $limiter) {
  41. $limiter->reset();
  42. }
  43. }
  44. /**
  45. * @return LimiterInterface[] a set of limiters using keys extracted from the request
  46. */
  47. abstract protected function getLimiters(Request $request): array;
  48. }