Completed
Push — master ( 512542...4d85fd )
by Jan-Petter
02:22
created

RequestRateClient::get()   A

Complexity

Conditions 4
Paths 2

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

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