Passed
Push — master ( 357b9b...ef7620 )
by Limon
02:56
created

AdblockParser::getRules()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
namespace Limonte;
3
4
class AdblockParser
5
{
6
    private $rules;
7
8
    public function __construct($rules = [])
9
    {
10
        $this->rules = [];
11
        $this->addRules($rules);
12
    }
13
14
    /**
15
     * @param  string[]  $rules
16
     */
17
    public function addRules($rules)
18
    {
19
        foreach ($rules as $rule) {
20
            try {
21
                $this->rules[] = new AdblockRule($rule);
22
            } catch (InvalidRuleException $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
23
            }
24
        }
25
26
        // Sort rules, eceptions first
27
        usort($this->rules, function ($a, $b) {
28
            return (int)$a->isException() < (int)$b->isException();
29
        });
30
    }
31
32
    /**
33
     * @param  string|array  $path
34
     */
35
    public function loadRules($path)
36
    {
37
        // single resource
38
        if (is_string($path)) {
39
            $content = @file_get_contents($path);
40
            if ($content) {
41
                $rules = preg_split("/(\r\n|\n|\r)/", $content);
42
                $this->addRules($rules);
43
            }
44
        // array of resources
45
        } elseif (is_array($path)) {
46
            foreach ($path as $item) {
47
                $this->loadRules($item);
48
            }
49
        }
50
    }
51
52
    /**
53
     * @return  []
0 ignored issues
show
Documentation introduced by
The doc-type [] could not be parsed: Unknown type name "" at position 0. [(view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
54
     */
55
    public function getRules()
56
    {
57
        return $this->rules;
58
    }
59
60
    /**
61
     * @param  string  $url
62
     *
63
     * @return boolean
64
     */
65
    public function shouldBlock($url)
66
    {
67
        foreach ($this->rules as $rule) {
68
            if ($rule->isComment() || $rule->isHtml()) {
69
                continue;
70
            }
71
72
            if ($rule->matchUrl($url)) {
73
                if ($rule->isException()) {
74
                    return false;
75
                }
76
                return true;
77
            }
78
        }
79
80
        return false;
81
    }
82
83
    /**
84
     * @param  string  $url
85
     *
86
     * @return boolean
87
     */
88
    public function shouldNotBlock($url)
89
    {
90
        return !$this->shouldBlock($url);
91
    }
92
}
93