1
|
|
|
<? |
|
|
|
|
2
|
|
|
|
3
|
|
|
namespace Funivan\PhpTokenizer\Pattern; |
4
|
|
|
|
5
|
|
|
use Funivan\PhpTokenizer\Collection; |
6
|
|
|
use Funivan\PhpTokenizer\Exception\Exception; |
7
|
|
|
use Funivan\PhpTokenizer\QuerySequence\QuerySequence; |
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* |
11
|
|
|
*/ |
12
|
|
|
class PatternMatcher implements PatternMatcherInterface { |
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* @var Collection[] |
16
|
|
|
*/ |
17
|
|
|
protected $collections = []; |
18
|
|
|
|
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* |
22
|
|
|
* @param Collection $collection |
23
|
|
|
*/ |
24
|
|
|
public function __construct(Collection $collection) { |
25
|
|
|
$this->collections[] = $collection; |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* @inheritdoc |
31
|
|
|
*/ |
32
|
|
|
public function apply(callable $pattern) { |
33
|
|
|
|
34
|
|
|
# Clear current collections. |
35
|
|
|
# We will add new one and iterate over current |
36
|
|
|
|
37
|
|
|
$collections = $this->collections; |
38
|
|
|
$this->collections = []; |
39
|
|
|
|
40
|
|
|
foreach ($collections as $collection) { |
41
|
|
|
|
42
|
|
|
$collectionsResult = $this->iterateOverCollections($pattern, $collection); |
43
|
|
|
|
44
|
|
|
foreach ($collectionsResult as $resultCollection) { |
45
|
|
|
$this->collections[] = $resultCollection; |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
return $this; |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
|
54
|
|
|
/** |
55
|
|
|
* @inheritdoc |
56
|
|
|
*/ |
57
|
|
|
public function getCollections() { |
58
|
|
|
return $this->collections; |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
|
62
|
|
|
/** |
63
|
|
|
* @param callable $pattern |
64
|
|
|
* @param Collection $collection |
65
|
|
|
* @return Collection[] |
66
|
|
|
* @throws Exception |
67
|
|
|
*/ |
68
|
|
|
protected function iterateOverCollections(callable $pattern, Collection $collection) { |
69
|
|
|
$result = []; |
70
|
|
|
|
71
|
|
|
$collection->rewind(); |
72
|
|
|
foreach ($collection as $index => $token) { |
73
|
|
|
$querySequence = new QuerySequence($collection, $index); |
74
|
|
|
$patternResult = $pattern($querySequence); |
75
|
|
|
if ($patternResult === null) { |
76
|
|
|
continue; |
77
|
|
|
} |
78
|
|
|
|
79
|
|
|
if (!($patternResult instanceof Collection)) { |
80
|
|
|
throw new Exception('Invalid result from pattern callback. Expect Collection. Given:' . gettype($patternResult)); |
81
|
|
|
} |
82
|
|
|
|
83
|
|
|
$result[] = $patternResult; |
84
|
|
|
} |
85
|
|
|
|
86
|
|
|
return $result; |
87
|
|
|
} |
88
|
|
|
|
89
|
|
|
|
90
|
|
|
} |
Short opening tags are disabled in PHP’s default configuration. In such a case, all content of this file is output verbatim to the browser without being parsed, or executed.
As a precaution to avoid these problems better use the long opening tag
<?php
.