1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Vanderlee\Comprehend\Match\Output; |
4
|
|
|
|
5
|
|
|
trait ResultTrait |
6
|
|
|
{ |
7
|
|
|
/** |
8
|
|
|
* Map of resolved result callbacks. |
9
|
|
|
* |
10
|
|
|
* @var array|null |
11
|
|
|
*/ |
12
|
|
|
private $resultCache = null; |
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* List of partial-resolvable result callbacks. |
16
|
|
|
* |
17
|
|
|
* @var callable[] |
18
|
|
|
*/ |
19
|
|
|
private $resultCallbacks = []; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* Add a callback to this match, to be called after parsing is finished and |
23
|
|
|
* only if this match was part of the matched rules. |
24
|
|
|
* |
25
|
|
|
* @param callable $callback |
26
|
|
|
* |
27
|
|
|
* @return $this |
28
|
|
|
*/ |
29
|
401 |
|
public function addResultCallback(callable $callback) |
30
|
|
|
{ |
31
|
401 |
|
$this->resultCallbacks[] = $callback; |
32
|
|
|
|
33
|
401 |
|
return $this; |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
/** |
37
|
|
|
* Handle all registered result callbacks for this match and any matches |
38
|
|
|
* at deeper levels of this match. |
39
|
|
|
* |
40
|
|
|
* @param array $results map of result-key => value |
41
|
|
|
*/ |
42
|
146 |
|
private function processResultCallbacks(&$results) |
43
|
|
|
{ |
44
|
|
|
/** @var self $success */ |
45
|
146 |
|
foreach ($this->successes as $success) { |
46
|
89 |
|
$success->processResultCallbacks($results); |
47
|
|
|
} |
48
|
|
|
|
49
|
146 |
|
foreach ($this->resultCallbacks as $callback) { |
50
|
145 |
|
$callback($results); |
51
|
|
|
} |
52
|
146 |
|
} |
53
|
|
|
|
54
|
|
|
/** |
55
|
|
|
* Pre-calculate results. |
56
|
|
|
* |
57
|
|
|
* @return array |
58
|
|
|
*/ |
59
|
146 |
|
public function getResults() |
60
|
|
|
{ |
61
|
146 |
|
if ($this->resultCache === null) { |
62
|
146 |
|
$this->resultCache = []; |
63
|
146 |
|
$this->processResultCallbacks($this->resultCache); |
64
|
|
|
} |
65
|
|
|
|
66
|
146 |
|
return $this->resultCache; |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
//@todo deprecate? Saves no time and is part of collection |
70
|
11 |
|
public function getResult(string $name = null, $default = null) |
71
|
|
|
{ |
72
|
11 |
|
$results = $this->getResults(); |
73
|
|
|
|
74
|
11 |
|
return $results[$name] |
75
|
11 |
|
?? $default; |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
//@todo deprecate? Saves no time and is part of collection |
79
|
3 |
|
public function hasResult(string $name = null): bool |
80
|
|
|
{ |
81
|
3 |
|
return isset($this->getResults()[$name]); |
82
|
|
|
} |
83
|
|
|
} |
84
|
|
|
|