|
1
|
|
|
<?php |
|
2
|
|
|
/** |
|
3
|
|
|
* This file is part of Poloniex PHP SDK. |
|
4
|
|
|
* |
|
5
|
|
|
* For the full copyright and license information, please view the LICENSE |
|
6
|
|
|
* file that was distributed with this source code. |
|
7
|
|
|
* |
|
8
|
|
|
* @copyright 2017-2018 Chasovskih Grisha <[email protected]> |
|
9
|
|
|
* @license https://github.com/signulls/poloniex-php-sdk/blob/master/LICENSE MIT |
|
10
|
|
|
*/ |
|
11
|
|
|
|
|
12
|
|
|
namespace Poloniex\CallHistory; |
|
13
|
|
|
|
|
14
|
|
|
use Predis\Client; |
|
15
|
|
|
use DateTime; |
|
16
|
|
|
|
|
17
|
|
|
/** |
|
18
|
|
|
* Class RedisCallHistory |
|
19
|
|
|
* |
|
20
|
|
|
* @author Grisha Chasovskih <[email protected]> |
|
21
|
|
|
*/ |
|
22
|
|
|
class RedisCallHistory implements CallHistoryInterface |
|
23
|
|
|
{ |
|
24
|
|
|
/** |
|
25
|
|
|
* Client class used for connecting and executing commands on Redis. |
|
26
|
|
|
* |
|
27
|
|
|
* @var Client |
|
28
|
|
|
*/ |
|
29
|
|
|
protected $redisClient; |
|
30
|
|
|
|
|
31
|
|
|
/** |
|
32
|
|
|
* Time for cache |
|
33
|
|
|
* |
|
34
|
|
|
* @var string |
|
35
|
|
|
*/ |
|
36
|
|
|
protected $expireTime; |
|
37
|
|
|
|
|
38
|
|
|
/** |
|
39
|
|
|
* @var string |
|
40
|
|
|
*/ |
|
41
|
|
|
private $ip; |
|
42
|
|
|
|
|
43
|
|
|
/** |
|
44
|
|
|
* RedisCallHistory constructor. |
|
45
|
|
|
* |
|
46
|
|
|
* @param Client $client |
|
47
|
|
|
* @param string $expireTime |
|
48
|
|
|
*/ |
|
49
|
|
|
public function __construct(Client $client, string $expireTime = '1 hour') |
|
50
|
|
|
{ |
|
51
|
|
|
$this->ip = gethostbyname(gethostname()); |
|
52
|
|
|
$this->expireTime = $expireTime; |
|
53
|
|
|
$this->redisClient = $client; |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
|
|
/** |
|
57
|
|
|
* {@inheritdoc} |
|
58
|
|
|
*/ |
|
59
|
|
|
public function create(): void |
|
60
|
|
|
{ |
|
61
|
|
|
$this->redisClient->hincrby($this->getKey(), $this->getTime(), 1); |
|
62
|
|
|
$this->redisClient->expireat($this->getKey(), strtotime('+' . $this->expireTime)); |
|
63
|
|
|
} |
|
64
|
|
|
|
|
65
|
|
|
/** |
|
66
|
|
|
* {@inheritdoc} |
|
67
|
|
|
*/ |
|
68
|
|
|
public function isIncreased(): bool |
|
69
|
|
|
{ |
|
70
|
|
|
return $this->redisClient->hget($this->getKey(), $this->getTime()) >= self::CALLS_PER_SECOND; |
|
71
|
|
|
} |
|
72
|
|
|
|
|
73
|
|
|
/** |
|
74
|
|
|
* Create time key based by one second |
|
75
|
|
|
* |
|
76
|
|
|
* @return string |
|
77
|
|
|
*/ |
|
78
|
|
|
private function getTime(): string |
|
79
|
|
|
{ |
|
80
|
|
|
return (new DateTime())->format('Y:m:d:H:i:s'); |
|
81
|
|
|
} |
|
82
|
|
|
|
|
83
|
|
|
/** |
|
84
|
|
|
* Get key |
|
85
|
|
|
* |
|
86
|
|
|
* @return string |
|
87
|
|
|
*/ |
|
88
|
|
|
private function getKey(): string |
|
89
|
|
|
{ |
|
90
|
|
|
return 'poloniex:calls:' . $this->ip; |
|
91
|
|
|
} |
|
92
|
|
|
} |