1 | <?php |
||
9 | class PathLimitProcessor |
||
10 | { |
||
11 | private $pathLimits; |
||
12 | |||
13 | 13 | function __construct(array $pathLimits) |
|
14 | { |
||
15 | 13 | $this->pathLimits = $pathLimits; |
|
16 | |||
17 | // Clean up any extra slashes from the config |
||
18 | 13 | foreach ($this->pathLimits as &$pathLimit) { |
|
19 | 12 | $pathLimit['path'] = trim($pathLimit['path'], '/'); |
|
20 | 13 | } |
|
21 | |||
22 | // Order the configs so that the most specific paths |
||
23 | // are matched first |
||
24 | 13 | usort($this->pathLimits, function($a, $b) { |
|
25 | 4 | return substr_count($b['path'], '/') - substr_count($a['path'], '/'); |
|
26 | 13 | }); |
|
27 | 13 | } |
|
28 | |||
29 | 10 | public function getRateLimit(Request $request) |
|
30 | { |
||
31 | 10 | $path = trim(urldecode($request->getPathInfo()), '/'); |
|
32 | 10 | $method = $request->getMethod(); |
|
33 | |||
34 | 10 | foreach ($this->pathLimits as $pathLimit) { |
|
35 | 9 | if ($this->requestMatched($pathLimit, $path, $method)) { |
|
36 | 8 | return new RateLimit(array( |
|
37 | 8 | 'limit' => $pathLimit['limit'], |
|
38 | 8 | 'period' => $pathLimit['period'], |
|
39 | 8 | 'methods' => $pathLimit['methods'] |
|
40 | 8 | )); |
|
41 | } |
||
42 | 2 | } |
|
43 | |||
44 | 2 | return null; |
|
45 | } |
||
46 | |||
47 | 3 | public function getMatchedPath(Request $request) |
|
48 | { |
||
49 | 3 | $path = trim($request->getPathInfo(), '/'); |
|
50 | 3 | $method = $request->getMethod(); |
|
51 | |||
52 | 3 | foreach ($this->pathLimits as $pathLimit) { |
|
53 | 3 | if ($this->requestMatched($pathLimit, $path, $method)) { |
|
54 | 3 | return $pathLimit['path']; |
|
55 | } |
||
56 | } |
||
57 | |||
58 | return ''; |
||
59 | } |
||
60 | |||
61 | 12 | private function requestMatched($pathLimit, $path, $method) |
|
66 | |||
67 | 12 | private function methodMatched(array $expectedMethods, $method) |
|
68 | { |
||
69 | 12 | foreach ($expectedMethods as $expectedMethod) { |
|
77 | |||
78 | 12 | private function pathMatched($expectedPath, $path) |
|
95 | } |