Completed
Push — master ( 1d1c50...dc3dad )
by Jan-Petter
01:55
created

ObjectTools::validateDirective()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
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 7
rs 9.4285
cc 2
eloc 4
nc 2
nop 2
1
<?php
2
namespace vipnytt\RobotsTxtParser;
3
4
trait ObjectTools
5
{
6
    /**
7
     * Check basic rule
8
     *
9
     * @param string $path
10
     * @param array $paths
11
     * @return bool
12
     */
13
    public function checkPath($path, $paths)
14
    {
15
        // bug: https://github.com/t1gor/Robots.txt-Parser-Class/issues/62
16
        foreach ($paths as $robotPath) {
17
            $escaped = strtr($robotPath, ["@" => '\@']);
18
            if (preg_match('@' . $escaped . '@', $path)) {
19
                if (mb_stripos($escaped, '$') !== false) {
20
                    if (mb_strlen($escaped) - 1 == mb_strlen($path)) {
21
                        return true;
22
                    }
23
                } else {
24
                    return true;
25
                }
26
            }
27
        }
28
        return false;
29
    }
30
31
    /**
32
     * Generate directive/rule pair
33
     *
34
     * @param string $line
35
     * @param array $whiteList
36
     * @return array|false
37
     */
38
    protected function generateRulePair($line, $whiteList)
39
    {
40
        $whiteList = array_map('mb_strtolower', $whiteList);
41
        // Split by directive and rule
42
        $pair = array_map('trim', mb_split(':', $line, 2));
43
        // Check if the line contains a rule
44
        if (
45
            empty($pair[1]) ||
46
            empty($pair[0]) ||
47
            !in_array(($pair[0] = mb_strtolower($pair[0])), $whiteList)
48
        ) {
49
            // Line does not contain any supported directive
50
            return false;
51
        }
52
        return [
53
            'directive' => $pair[0],
54
            'value' => $pair[1],
55
        ];
56
    }
57
58
    /**
59
     * Validate directive
60
     *
61
     * @param $directive
62
     * @param $directives
63
     * @return string
64
     * @throws Exceptions\ParserException
65
     */
66
    protected function validateDirective($directive, $directives)
67
    {
68
        if (!in_array($directive, $directives, true)) {
69
            throw new Exceptions\ParserException('Directive is not allowed here');
70
        }
71
        return mb_strtolower($directive);
72
    }
73
}
74