1 | <?php |
||
5 | class RedisRequestLogger implements RequestLoggerInterface |
||
6 | { |
||
7 | /** |
||
8 | * @var \Redis |
||
9 | */ |
||
10 | protected $redis; |
||
11 | |||
12 | /** |
||
13 | * @var string |
||
14 | */ |
||
15 | protected $key; |
||
16 | |||
17 | /** |
||
18 | * @param \Redis $redis |
||
19 | * @param string $key |
||
20 | */ |
||
21 | 6 | public function __construct(\Redis $redis, $key = 'crawler_requests') |
|
26 | |||
27 | /** |
||
28 | * @inheritdoc |
||
29 | */ |
||
30 | 6 | public function logRequest($url, \DateTime $date = null) |
|
31 | { |
||
32 | 6 | if (null === $date) { |
|
33 | $date = new \DateTime(); |
||
34 | } |
||
35 | |||
36 | 6 | $timestamp = $date->getTimestamp(); |
|
37 | 6 | $hashKey = $this->getHashKey($timestamp, $url); |
|
38 | |||
39 | 6 | $this->redis->zAdd($this->key, $timestamp, $hashKey); |
|
40 | 6 | } |
|
41 | |||
42 | /** |
||
43 | * @inheritdoc |
||
44 | */ |
||
45 | 6 | public function getRequestsSince(\DateTime $date = null) |
|
46 | { |
||
47 | 6 | $start = $date ? $date->getTimestamp() : '-inf'; |
|
48 | 6 | $end = time(); |
|
49 | |||
50 | 6 | return array_map( |
|
51 | 6 | function ($hash) { |
|
52 | 4 | list($timestamp, $url) = explode('#', $hash, 2); |
|
53 | |||
54 | 4 | return [intval($timestamp), $url]; |
|
55 | 6 | }, |
|
56 | 6 | $this->redis->zRangeByScore($this->key, $start, $end) |
|
57 | ); |
||
58 | } |
||
59 | |||
60 | /** |
||
61 | * @param int $timestamp |
||
62 | * @param string $url |
||
63 | * |
||
64 | * @return string |
||
65 | */ |
||
66 | 6 | protected function getHashKey($timestamp, $url) |
|
70 | } |
||
71 |