Completed
Push — master ( b23c5f...0489e6 )
by Jan-Petter
02:23
created

StatusCodeParser::codeOverride()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 8
rs 9.4285
cc 3
eloc 5
nc 4
nop 1
1
<?php
2
namespace vipnytt\RobotsTxtParser\Parser;
3
4
use vipnytt\RobotsTxtParser\Exceptions\StatusCodeException;
5
use vipnytt\RobotsTxtParser\Parser\Directives\DirectiveParserCommons;
6
use vipnytt\RobotsTxtParser\RobotsTxtInterface;
7
8
/**
9
 * Class StatusCodeParser
10
 *
11
 * @package vipnytt\RobotsTxtParser\Parser
12
 */
13
class StatusCodeParser implements RobotsTxtInterface
14
{
15
    use DirectiveParserCommons;
16
17
    /**
18
     * Valid schemes
19
     */
20
    const VALID_SCHEME = [
21
        'http',
22
        'https',
23
    ];
24
25
    /**
26
     * Status code
27
     * @var int
28
     */
29
    private $code;
30
31
    /**
32
     * Scheme
33
     * @var string|false
34
     */
35
    private $scheme;
36
37
    /**
38
     * Applicable
39
     * @var bool
40
     */
41
    private $applicable;
42
43
    /**
44
     * Constructor
45
     *
46
     * @param int|null $code - HTTP status code
47
     * @param string|false $scheme
48
     * @throws StatusCodeException
49
     */
50
    public function __construct($code, $scheme)
51
    {
52
        $this->code = $code;
53
        $this->scheme = $scheme;
54
        $this->applicable = $this->isApplicable();
55
    }
56
57
    /**
58
     * Check if URL is Applicable for Status code parsing
59
     *
60
     * @return bool
61
     * @throws StatusCodeException
62
     */
63
    private function isApplicable()
64
    {
65
        if (
66
            !in_array($this->scheme, self::VALID_SCHEME) ||
67
            $this->code === null
68
        ) {
69
            return false;
70
        } elseif (
71
            $this->code < 100 ||
72
            $this->code > 599
73
        ) {
74
            throw new StatusCodeException('Invalid HTTP status code');
75
        }
76
        return true;
77
    }
78
79
    /**
80
     * Check
81
     *
82
     * @return string|false
83
     */
84
    public function accessOverride()
85
    {
86
        if (!$this->applicable) {
87
            return false;
88
        }
89
        switch (floor($this->code / 100) * 100) {
90
            case 300:
91
            case 400:
92
                return self::DIRECTIVE_ALLOW;
93
            case 500:
94
                return self::DIRECTIVE_DISALLOW;
95
        }
96
        return false;
97
    }
98
}
99