Completed
Push — master ( dbcf6b...d53ab6 )
by Peter
44:13 queued 37:37
created

RedisRequestLogger::getHashKey()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 2
crap 1
1
<?php
2
3
namespace TreeHouse\IoBundle\Scrape\Crawler\Log;
4
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')
22
    {
23 6
        $this->redis = $redis;
24 6
        $this->key = $key;
25 6
    }
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)
67
    {
68 6
        return sprintf('%d#%s', $timestamp, $url);
69
    }
70
}
71