give
/
vendor
/
vendor-prefixed
/
symfony
/
http-foundation
/
RateLimiter
/
AbstractRequestRateLimiter.php
AbstractRequestRateLimiter.php in GiveWP – Donation Plugin and Fundraising Platform 4.17.0, at vendor/vendor-prefixed/symfony/http-foundation/RateLimiter/AbstractRequestRateLimiter.php
| 1 | <?php |
| 2 | |
| 3 | /* |
| 4 | * This file is part of the Symfony package. |
| 5 | * |
| 6 | * (c) Fabien Potencier <[email protected]> |
| 7 | * |
| 8 | * For the full copyright and license information, please view the LICENSE |
| 9 | * file that was distributed with this source code. |
| 10 | */ |
| 11 | |
| 12 | namespace Give\Vendors\Symfony\Component\HttpFoundation\RateLimiter; |
| 13 | |
| 14 | use Give\Vendors\Symfony\Component\HttpFoundation\Request; |
| 15 | use Symfony\Component\RateLimiter\LimiterInterface; |
| 16 | use Symfony\Component\RateLimiter\Policy\NoLimiter; |
| 17 | use Symfony\Component\RateLimiter\RateLimit; |
| 18 | |
| 19 | /** |
| 20 | * An implementation of RequestRateLimiterInterface that |
| 21 | * fits most use-cases. |
| 22 | * |
| 23 | * @author Wouter de Jong <[email protected]> |
| 24 | */ |
| 25 | abstract class AbstractRequestRateLimiter implements RequestRateLimiterInterface |
| 26 | { |
| 27 | public function consume(Request $request): RateLimit |
| 28 | { |
| 29 | $limiters = $this->getLimiters($request); |
| 30 | if (0 === \count($limiters)) { |
| 31 | $limiters = [new NoLimiter()]; |
| 32 | } |
| 33 | |
| 34 | $minimalRateLimit = null; |
| 35 | foreach ($limiters as $limiter) { |
| 36 | $rateLimit = $limiter->consume(1); |
| 37 | |
| 38 | $minimalRateLimit = $minimalRateLimit ? self::getMinimalRateLimit($minimalRateLimit, $rateLimit) : $rateLimit; |
| 39 | } |
| 40 | |
| 41 | return $minimalRateLimit; |
| 42 | } |
| 43 | |
| 44 | public function reset(Request $request): void |
| 45 | { |
| 46 | foreach ($this->getLimiters($request) as $limiter) { |
| 47 | $limiter->reset(); |
| 48 | } |
| 49 | } |
| 50 | |
| 51 | /** |
| 52 | * @return LimiterInterface[] a set of limiters using keys extracted from the request |
| 53 | */ |
| 54 | abstract protected function getLimiters(Request $request): array; |
| 55 | |
| 56 | private static function getMinimalRateLimit(RateLimit $first, RateLimit $second): RateLimit |
| 57 | { |
| 58 | if ($first->isAccepted() !== $second->isAccepted()) { |
| 59 | return $first->isAccepted() ? $second : $first; |
| 60 | } |
| 61 | |
| 62 | $firstRemainingTokens = $first->getRemainingTokens(); |
| 63 | $secondRemainingTokens = $second->getRemainingTokens(); |
| 64 | |
| 65 | if ($firstRemainingTokens === $secondRemainingTokens) { |
| 66 | return $first->getRetryAfter() < $second->getRetryAfter() ? $second : $first; |
| 67 | } |
| 68 | |
| 69 | return $firstRemainingTokens > $secondRemainingTokens ? $second : $first; |
| 70 | } |
| 71 | } |
| 72 |