1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace api\components; |
4
|
|
|
|
5
|
|
|
use Yii; |
6
|
|
|
use yii\base\Action; |
7
|
|
|
use yii\filters\RateLimitInterface; |
8
|
|
|
use yii\web\Request; |
9
|
|
|
|
10
|
|
|
/** |
11
|
|
|
* Class IpLimiter |
12
|
|
|
* @package api\components |
13
|
|
|
*/ |
14
|
|
|
class IpLimiter implements RateLimitInterface |
15
|
|
|
{ |
16
|
|
|
/** |
17
|
|
|
* Разрешенное количество запросов |
18
|
|
|
*/ |
19
|
|
|
const RATE_LIMIT = 10; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* Время в секундах |
23
|
|
|
*/ |
24
|
|
|
const RATE_LIMIT_TIME = 60; |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* @var string |
28
|
|
|
*/ |
29
|
|
|
public $allowance; |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* @var string |
33
|
|
|
*/ |
34
|
|
|
public $allowance_updated_at; |
35
|
|
|
|
36
|
|
|
/** |
37
|
|
|
* @var string |
38
|
|
|
*/ |
39
|
|
|
private $cache_key = 'limitRelate'; |
40
|
|
|
|
41
|
|
|
/** |
42
|
|
|
* @param Request $request |
43
|
|
|
* @param Action $action |
44
|
|
|
* @return array |
45
|
|
|
*/ |
46
|
|
|
public function getRateLimit($request, $action) |
47
|
|
|
{ |
48
|
|
|
return [self::RATE_LIMIT, self::RATE_LIMIT_TIME]; |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
/** |
52
|
|
|
* @param Request $request |
53
|
|
|
* @param Action $action |
54
|
|
|
* @return array |
55
|
|
|
*/ |
56
|
|
|
public function loadAllowance($request, $action) |
57
|
|
|
{ |
58
|
|
|
$cache = Yii::$app->cache; |
59
|
|
|
$data = $cache->get($this->cache_key); |
60
|
|
|
if ($data = unserialize($data)) { |
61
|
|
|
return [$data['allowance'], $data['allowance_updated_at']]; |
62
|
|
|
} |
63
|
|
|
return [$this->allowance, $this->allowance_updated_at]; |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
/** |
67
|
|
|
* @param Request $request |
68
|
|
|
* @param Action $action |
69
|
|
|
* @param int $allowance |
70
|
|
|
* @param int $timestamp |
71
|
|
|
*/ |
72
|
|
|
public function saveAllowance($request, $action, $allowance, $timestamp) |
73
|
|
|
{ |
74
|
|
|
$array = [ |
75
|
|
|
'allowance' => $allowance, |
76
|
|
|
'allowance_updated_at' => $timestamp, |
77
|
|
|
]; |
78
|
|
|
$cache = Yii::$app->cache; |
79
|
|
|
if ($cache->get($this->cache_key)) { |
80
|
|
|
$cache->delete($this->cache_key); |
81
|
|
|
} |
82
|
|
|
$cache->add($this->cache_key, serialize($array), self::RATE_LIMIT_TIME); |
83
|
|
|
} |
84
|
|
|
} |
85
|
|
|
|