PatternMatcher::iterateOverCollections()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 20
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 4

Importance

Changes 0
Metric Value
dl 0
loc 20
ccs 12
cts 12
cp 1
rs 9.2
c 0
b 0
f 0
cc 4
eloc 12
nc 4
nop 2
crap 4
1
<?php
2
3
  declare(strict_types=1);
4
5
  namespace Funivan\PhpTokenizer\Pattern;
6
7
  use Funivan\PhpTokenizer\Collection;
8
  use Funivan\PhpTokenizer\Exception\Exception;
9
  use Funivan\PhpTokenizer\QuerySequence\QuerySequence;
10
11
  /**
12
   *
13
   */
14
  class PatternMatcher implements PatternMatcherInterface {
15
16
    /**
17
     * @var Collection[]
18
     */
19
    protected $collections = [];
20
21
22
    /**
23
     * @param Collection $collection
24
     */
25 201
    public function __construct(Collection $collection) {
26 201
      $this->collections[] = $collection;
27 201
    }
28
29
30
    /**
31
     * @inheritdoc
32
     */
33 201
    public function apply(callable $pattern) {
34
35
      # Clear current collections.
36
      # We will add new one and iterate over current
37
38 201
      $collections = $this->collections;
39 201
      $this->collections = [];
40
41 201
      foreach ($collections as $collection) {
42
43 201
        $collectionsResult = $this->iterateOverCollections($pattern, $collection);
44
45 189
        foreach ($collectionsResult as $resultCollection) {
46 189
          $this->collections[] = $resultCollection;
47
        }
48
49
      }
50
51 189
      return $this;
52
    }
53
54
55
    /**
56
     * @inheritdoc
57
     */
58 129
    public function getCollections() {
59 129
      return $this->collections;
60
    }
61
62
63
    /**
64
     * @param callable $pattern
65
     * @param Collection $collection
66
     * @return Collection[]
67
     * @throws Exception
68
     */
69 201
    protected function iterateOverCollections(callable $pattern, Collection $collection) {
70 201
      $result = [];
71
72 201
      $collection->rewind();
73 201
      foreach ($collection as $index => $token) {
74 201
        $querySequence = new QuerySequence($collection, $index);
75 201
        $patternResult = $pattern($querySequence);
76 201
        if ($patternResult === null) {
77 192
          continue;
78
        }
79
80 135
        if (!($patternResult instanceof Collection)) {
81 9
          throw new Exception('Invalid result from pattern callback. Expect Collection. Given:' . gettype($patternResult));
82
        }
83
84 126
        $result[] = $patternResult;
85
      }
86
87 189
      return $result;
88
    }
89
90
91
  }