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(string $proxy = null): void |
60
|
|
|
{ |
61
|
|
|
$key = $this->getKey($proxy); |
62
|
|
|
|
63
|
|
|
$this->redisClient->hincrby($key, $this->getTime(), 1); |
64
|
|
|
$this->redisClient->expireat($key, strtotime('+' . $this->expireTime)); |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
/** |
68
|
|
|
* {@inheritdoc} |
69
|
|
|
*/ |
70
|
|
|
public function isIncreased(string $proxy = null): bool |
71
|
|
|
{ |
72
|
|
|
return $this->redisClient->hget($this->getKey($proxy), $this->getTime()) >= self::CALLS_PER_SECOND; |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
/** |
76
|
|
|
* Create time key based by one second |
77
|
|
|
* |
78
|
|
|
* @return string |
79
|
|
|
*/ |
80
|
|
|
private function getTime(): string |
81
|
|
|
{ |
82
|
|
|
return (new DateTime())->format('Y:m:d:H:i:s'); |
83
|
|
|
} |
84
|
|
|
|
85
|
|
|
/** |
86
|
|
|
* @param string|null $proxy |
87
|
|
|
* @return string |
88
|
|
|
*/ |
89
|
|
|
private function getKey(string $proxy = null): string |
90
|
|
|
{ |
91
|
|
|
return 'poloniex:calls:' . ($proxy ?: $this->ip); |
92
|
|
|
} |
93
|
|
|
} |