AbstractRequestRateLimiter.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. $minimalRateLimit = $minimalRateLimit ? self::getMinimalRateLimit($minimalRateLimit, $rateLimit) : $rateLimit;
  33. }
  34. return $minimalRateLimit;
  35. }
  36. public function reset(Request $request): void
  37. {
  38. foreach ($this->getLimiters($request) as $limiter) {
  39. $limiter->reset();
  40. }
  41. }
  42. /**
  43. * @return LimiterInterface[] a set of limiters using keys extracted from the request
  44. */
  45. abstract protected function getLimiters(Request $request): array;
  46. private static function getMinimalRateLimit(RateLimit $first, RateLimit $second): RateLimit
  47. {
  48. if ($first->isAccepted() !== $second->isAccepted()) {
  49. return $first->isAccepted() ? $second : $first;
  50. }
  51. $firstRemainingTokens = $first->getRemainingTokens();
  52. $secondRemainingTokens = $second->getRemainingTokens();
  53. if ($firstRemainingTokens === $secondRemainingTokens) {
  54. return $first->getRetryAfter() < $second->getRetryAfter() ? $second : $first;
  55. }
  56. return $firstRemainingTokens > $secondRemainingTokens ? $second : $first;
  57. }
  58. }