Completed
Push — master ( 49e9a0...fa7091 )
by Jan-Petter
02:11
created

Toolbox   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 70
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 11
c 1
b 0
f 0
lcom 0
cbo 1
dl 0
loc 70
rs 10

3 Methods

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