Completed
Pull Request — master (#2)
by Jan-Petter
02:43
created

RequestRateClient::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 6
rs 9.4285
cc 1
eloc 4
nc 1
nop 3
1
<?php
2
namespace vipnytt\RobotsTxtParser\Client\Directives;
3
4
use PDO;
5
use vipnytt\RobotsTxtParser\Client\SQL\Delay\DelayHandlerSQL;
6
7
/**
8
 * Class RequestRateClient
9
 *
10
 * @package vipnytt\RobotsTxtParser\Client\Directives
11
 */
12
class RequestRateClient implements DelayInterface, ClientInterface
13
{
14
    use DirectiveClientCommons;
15
16
    /**
17
     * Base Uri
18
     * @var string
19
     */
20
    private $base;
21
22
    /**
23
     * User-agent
24
     * @var string
25
     */
26
    private $userAgent;
27
28
    /**
29
     * Rates
30
     * @var array
31
     */
32
    private $rates = [];
33
34
    /**
35
     * RequestRateClient constructor.
36
     *
37
     * @param string $baseUri
38
     * @param string $userAgent
39
     * @param array $rates
40
     */
41
    public function __construct($baseUri, $userAgent, array $rates)
42
    {
43
        $this->base = $baseUri;
44
        $this->userAgent = $userAgent;
45
        $this->rates = $rates;
46
    }
47
48
    /**
49
     * Export
50
     *
51
     * @return array
52
     */
53
    public function export()
54
    {
55
        return $this->rates;
56
    }
57
58
    /**
59
     * SQL back-end
60
     *
61
     * @param PDO $pdo
62
     * @return DelayHandlerSQL
63
     */
64
    public function sql(PDO $pdo)
65
    {
66
        return new DelayHandlerSQL($pdo, $this->base, $this->userAgent, $this->get());
67
    }
68
69
    /**
70
     * Get rate for current timestamp
71
     *
72
     * @param int|null $timestamp
73
     * @return float|int
74
     */
75
    public function get($timestamp = null)
76
    {
77
        $values = $this->determine(is_int($timestamp) ? $timestamp : time());
78
        if (
79
            count($values) > 0 &&
80
            ($rate = min($values)) > 0
81
        ) {
82
            return $rate;
83
        }
84
        return 0;
85
    }
86
87
    /**
88
     * Determine rates
89
     *
90
     * @param int $timestamp
91
     * @return float[]|int[]
92
     */
93
    private function determine($timestamp)
94
    {
95
        $values = [];
96
        foreach ($this->rates as $array) {
97
            if (
98
                !isset($array['from']) ||
99
                !isset($array['to'])
100
            ) {
101
                $values[] = $array['rate'];
102
                continue;
103
            }
104
            if ($this->isBetween($timestamp, $array['from'], $array['to'], 'Hi')) {
105
                $values[] = $array['rate'];
106
            }
107
        }
108
        return $values;
109
    }
110
}
111