1 | <?php |
||
14 | class Rules |
||
15 | { |
||
16 | const DEFAULT_UA = '*'; |
||
17 | |||
18 | /** |
||
19 | * The collection of rules |
||
20 | * @var array |
||
21 | */ |
||
22 | protected $collection = []; |
||
23 | |||
24 | /** |
||
25 | * Default rule used if robots.txt is empty |
||
26 | * @var Rule |
||
27 | */ |
||
28 | private $defaultRule; |
||
29 | |||
30 | 4 | public function __construct() |
|
35 | |||
36 | /** |
||
37 | * Add a new rule to the collection |
||
38 | * @param string $userAgent |
||
39 | * @param Rule $rule |
||
40 | * @return Rules |
||
41 | */ |
||
42 | 4 | public function add($userAgent, Rule $rule) |
|
57 | |||
58 | /** |
||
59 | * Check if the URL match for the given UA or not |
||
60 | * @param string $userAgent |
||
61 | * @param string $url |
||
62 | * @return boolean |
||
63 | */ |
||
64 | 1 | public function match($userAgent, $url) |
|
71 | |||
72 | /** |
||
73 | * Retrieve rules for a given UA |
||
74 | * @param string $userAgent |
||
75 | * @return null|Rule |
||
76 | */ |
||
77 | 3 | public function get($userAgent) |
|
78 | { |
||
79 | 3 | $item = null; |
|
80 | 3 | $iterator = new \ArrayIterator($this->collection); |
|
81 | 3 | iterator_apply( |
|
82 | 3 | $iterator, |
|
83 | 3 | function (\ArrayIterator $iterator, $userAgent) use (&$item) { |
|
84 | 3 | if ($iterator->key() != Rules::DEFAULT_UA && |
|
85 | 3 | preg_match($iterator->key(), $userAgent) === 1 ) { |
|
86 | 1 | $item = $iterator->current(); |
|
87 | 1 | return false; |
|
88 | } |
||
89 | 3 | return true; |
|
90 | 3 | }, |
|
91 | 3 | [$iterator, $userAgent] |
|
92 | 3 | ); |
|
93 | |||
94 | 3 | return $item!==null? |
|
95 | 3 | $item: |
|
96 | 3 | (isset($this->collection[self::DEFAULT_UA])? |
|
97 | 3 | $this->collection[self::DEFAULT_UA]: |
|
98 | 3 | null); |
|
99 | } |
||
100 | |||
101 | /** |
||
102 | * Update the UA to make a valid regexp |
||
103 | * @param string $userAgent |
||
104 | * @return string |
||
105 | */ |
||
106 | 4 | private function handleUa($userAgent) |
|
113 | } |
||
114 |