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

RequestRateParser   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 90
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 4
Bugs 0 Features 0
Metric Value
wmc 10
c 4
b 0
f 0
lcom 1
cbo 2
dl 0
loc 90
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A add() 0 17 4
A client() 0 4 1
A render() 0 16 4
1
<?php
2
namespace vipnytt\RobotsTxtParser\Parser\Directives;
3
4
use vipnytt\RobotsTxtParser\Client\Directives\RequestRateClient;
5
use vipnytt\RobotsTxtParser\RobotsTxtInterface;
6
7
/**
8
 * Class RequestRateParser
9
 *
10
 * @package vipnytt\RobotsTxtParser\Parser\Directives
11
 */
12
class RequestRateParser implements ParserInterface, RobotsTxtInterface
13
{
14
    use DirectiveParserCommons;
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
     * RequestRate array
30
     * @var array
31
     */
32
    private $requestRates = [];
33
34
    /**
35
     * RequestRate constructor.
36
     *
37
     * @param string $base
38
     * @param string $userAgent
39
     */
40
    public function __construct($base, $userAgent)
41
    {
42
        $this->base = $base;
43
        $this->userAgent = $userAgent;
44
    }
45
46
    /**
47
     * Add
48
     *
49
     * @param string $line
50
     * @return bool
51
     */
52
    public function add($line)
53
    {
54
        $array = preg_split('/\s+/', $line, 2);
55
        $result = [
56
            'rate' => $this->draftParseRate($array[0]),
57
        ];
58
        if ($result['rate'] === false) {
59
            return false;
60
        } elseif (
61
            !empty($array[1]) &&
62
            ($times = $this->draftParseTime($array[1])) !== false
63
        ) {
64
            $result = array_merge($result, $times);
65
        }
66
        $this->requestRates[] = $result;
67
        return true;
68
    }
69
70
    /**
71
     * Client
72
     *
73
     * @return RequestRateClient
74
     */
75
    public function client()
76
    {
77
        return new RequestRateClient($this->base, $this->userAgent, $this->requestRates);
78
    }
79
80
    /**
81
     * Render
82
     *
83
     * @return string[]
84
     */
85
    public function render()
86
    {
87
        $result = [];
88
        foreach ($this->requestRates as $array) {
89
            $suffix = 's';
90
            if (
91
                isset($array['from']) &&
92
                isset($array['to'])
93
            ) {
94
                $suffix .= ' ' . $array['from'] . '-' . $array['to'];
95
            }
96
            $result[] = self::DIRECTIVE_REQUEST_RATE . ':1/' . $array['rate'] . $suffix;
97
        }
98
        sort($result);
99
        return $result;
100
    }
101
}
102