Completed
Push — master ( 2956a0...1b99fa )
by Indra
01:56
created

RateLimitHandler::getThrottle()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 23
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 5

Importance

Changes 0
Metric Value
dl 0
loc 23
ccs 13
cts 13
cp 1
rs 8.5906
c 0
b 0
f 0
cc 5
eloc 13
nc 4
nop 1
crap 5
1
<?php
2
3
/*
4
 * This file is part of the ApiRateLimitBundle
5
 *
6
 * (c) Indra Gunawan <[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 Indragunawan\ApiRateLimitBundle\Service;
13
14
use Doctrine\Common\Annotations\AnnotationReader;
15
use Indragunawan\ApiRateLimitBundle\Annotation\ApiRateLimit;
16
use Psr\Cache\CacheItemPoolInterface;
17
use Symfony\Component\HttpFoundation\Request;
18
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
19
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
20
21
/**
22
 * @author Indra Gunawan <[email protected]>
23
 */
24
class RateLimitHandler
25
{
26
    /**
27
     * @var Cache
28
     */
29
    private $cacheItemPool;
30
31
    /**
32
     * @var TokenStorageInterface
33
     */
34
    private $tokenStorage;
35
36
    /**
37
     * @var AuthorizationCheckerInterface
38
     */
39
    private $authorizationChecker;
40
41
    /**
42
     * @var array
43
     */
44
    private $throttleConfig;
45
46
    /**
47
     * @var int
48
     */
49
    private $limit;
50
51
    /**
52
     * @var int
53
     */
54
    private $remaining;
55
56
    /**
57
     * @var int
58
     */
59
    private $reset;
60
61
    /**
62
     * @var
63
     */
64
    private $enabled = true;
65
66
    /**
67
     * @var bool
68
     */
69
    private $rateLimitExceeded = false;
70
71 6
    public function __construct(
72
        CacheItemPoolInterface $cacheItemPool,
73
        TokenStorageInterface $tokenStorage,
74
        AuthorizationCheckerInterface $authorizationChecker,
75
        array $throttleConfig
76
    ) {
77 6
        $this->cacheItemPool = $cacheItemPool;
0 ignored issues
show
Documentation Bug introduced by
It seems like $cacheItemPool of type object<Psr\Cache\CacheItemPoolInterface> is incompatible with the declared type object<Indragunawan\ApiR...itBundle\Service\Cache> of property $cacheItemPool.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
78 6
        $this->tokenStorage = $tokenStorage;
79 6
        $this->authorizationChecker = $authorizationChecker;
80 6
        $this->throttleConfig = $throttleConfig;
81 6
    }
82
83 6
    public function isEnabled()
84
    {
85 6
        return $this->enabled;
86
    }
87
88 4
    public function isRateLimitExceeded()
89
    {
90 4
        return $this->rateLimitExceeded;
91
    }
92
93 5
    public function getRateLimitInfo(): array
94
    {
95
        return [
96 5
            'limit' => $this->limit,
97 5
            'remaining' => $this->remaining,
98 5
            'reset' => $this->reset,
99
        ];
100
    }
101
102 6
    public static function generateCacheKey(string $ip, string $username = null, string $userRole = null): string
103
    {
104 6
        if (!empty($username) && !empty($userRole)) {
105 1
            return sprintf('_api_rate_limit_metadata$%s', sha1($userRole.$username));
106
        }
107
108 5
        return sprintf('_api_rate_limit_metadata$%s', sha1($ip));
109
    }
110
111 6
    public function handle(Request $request)
112
    {
113 6
        list($key, $limit, $period) = $this->getThrottle($request);
114
115 6
        $annotationReader = new AnnotationReader();
116 6
        $annotation = $annotationReader->getClassAnnotation(new \ReflectionClass($request->attributes->get('_api_resource_class')), ApiRateLimit::class);
117 6
        if (null !== $annotation) {
118 6
            $this->enabled = $annotation->enabled;
119
        }
120
121 6
        if ($this->enabled) {
122 5
            $this->decreaseRateLimitRemaining($key, $limit, $period);
123
        }
124 6
    }
125
126 5
    protected function decreaseRateLimitRemaining(string $key, int $limit, int $period)
127
    {
128 5
        $cost = 1;
129 5
        $currentTime = gmdate('U');
130
131 5
        $rateLimitInfo = $this->cacheItemPool->getItem($key);
132 5
        $rateLimit = $rateLimitInfo->get();
133 5
        if ($rateLimitInfo->isHit() && $currentTime <= $rateLimit['reset']) {
134
            // decrease existing rate limit remaining
135 2
            if ($rateLimit['remaining'] - $cost >= 0) {
136 1
                $remaining = $rateLimit['remaining'] - $cost;
137 1
                $reset = $rateLimit['reset'];
138 1
                $ttl = $rateLimit['reset'] - $currentTime;
139
            } else {
140 1
                $this->rateLimitExceeded = true;
141 1
                $this->reset = $rateLimit['reset'];
142 1
                $this->limit = $limit;
143 1
                $this->remaining = 0;
144
145 1
                return;
146
            }
147
        } else {
148
            // add / reset new rate limit remaining
149 3
            $remaining = $limit - $cost;
150 3
            $reset = $currentTime + $period;
151 3
            $ttl = $period;
152
        }
153
154
        $rateLimit = [
155 4
            'limit' => $limit,
156 4
            'remaining' => $remaining,
157 4
            'reset' => $reset,
158
        ];
159
160 4
        $rateLimitInfo->set($rateLimit);
161 4
        $rateLimitInfo->expiresAfter($ttl);
162
163 4
        $this->cacheItemPool->save($rateLimitInfo);
164
165 4
        $this->limit = $limit;
166 4
        $this->remaining = $remaining;
0 ignored issues
show
Documentation Bug introduced by
It seems like $remaining can also be of type double. However, the property $remaining is declared as type integer. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
167 4
        $this->reset = $reset;
168 4
    }
169
170 6
    private function getThrottle(Request $request)
171
    {
172 6
        if (null !== $token = $this->tokenStorage->getToken()) {
173
            // no anonymous
174 1
            if (is_object($token->getUser())) {
175 1
                foreach ($this->throttleConfig['roles'] as $role => $throttle) {
176 1
                    if ($this->authorizationChecker->isGranted($role)) {
177 1
                        $username = $token->getUsername();
178 1
                        $userRole = $role;
179 1
                        $limit = $throttle['limit'];
180 1
                        $period = $throttle['period'];
181
182 1
                        return [self::generateCacheKey($request->getClientIp(), $username, $userRole), $limit, $period];
183
                    }
184
                }
185
            }
186
        }
187
188 5
        $limit = $this->throttleConfig['default']['limit'];
189 5
        $period = $this->throttleConfig['default']['period'];
190
191 5
        return [self::generateCacheKey($request->getClientIp()), $limit, $period];
192
    }
193
}
194