You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

59 lines
1.6 KiB

3 years ago
  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.3
  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. }