1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Vanderlee\Comprehend\Match; |
4
|
|
|
|
5
|
|
|
use ErrorException; |
6
|
|
|
use Vanderlee\Comprehend\Match\Output\CallbackTrait; |
7
|
|
|
use Vanderlee\Comprehend\Match\Output\ResultTrait; |
8
|
|
|
use Vanderlee\Comprehend\Match\Output\TokenTrait; |
9
|
|
|
|
10
|
|
|
/** |
11
|
|
|
* Successful match of a parser. |
12
|
|
|
* |
13
|
|
|
* @author Martijn |
14
|
|
|
*/ |
15
|
|
|
class Success extends AbstractMatch |
16
|
|
|
{ |
17
|
|
|
use TokenTrait, ResultTrait, CallbackTrait; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* Boolean state indicating whether this match has been resolved already. |
21
|
|
|
* Each match may only be resolved once to prevent conflicts. |
22
|
|
|
* |
23
|
|
|
* @var bool |
24
|
|
|
*/ |
25
|
|
|
private $resolved = false; |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* Any successful matches tbat make up this success. |
29
|
|
|
* |
30
|
|
|
* @var Success[] |
31
|
|
|
*/ |
32
|
|
|
private $successes; |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* Create a new match. |
36
|
|
|
* |
37
|
|
|
* @param int $length |
38
|
|
|
* @param Success[]|Success $successes |
39
|
|
|
*/ |
40
|
404 |
|
public function __construct($length = 0, $successes = []) |
41
|
|
|
{ |
42
|
404 |
|
parent::__construct($length); |
43
|
|
|
|
44
|
404 |
|
$this->successes = $successes; |
45
|
404 |
|
} |
46
|
|
|
|
47
|
403 |
|
public function __get(string $name) |
48
|
|
|
{ |
49
|
|
|
switch ($name) { |
50
|
403 |
|
case 'match': |
51
|
367 |
|
return true; |
52
|
403 |
|
case 'results': |
53
|
135 |
|
$results = $this->getResults(); |
54
|
135 |
|
unset($results[null]); |
55
|
|
|
|
56
|
135 |
|
return $results; |
57
|
403 |
|
case 'result': |
58
|
20 |
|
$results = $this->getResults(); |
59
|
|
|
|
60
|
20 |
|
return $results[null] |
61
|
20 |
|
?? null; |
62
|
403 |
|
case 'token': |
63
|
9 |
|
return $this->getToken(); |
64
|
|
|
} |
65
|
|
|
|
66
|
403 |
|
return parent::__get($name); |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
/** |
70
|
|
|
* Resolve any custom callbacks. |
71
|
|
|
* |
72
|
|
|
* @return $this|AbstractMatch |
73
|
|
|
* @throws ErrorException |
74
|
|
|
* |
75
|
|
|
*/ |
76
|
373 |
|
public function resolve(): AbstractMatch |
77
|
|
|
{ |
78
|
373 |
|
if ($this->resolved) { |
79
|
1 |
|
throw new ErrorException('Match already resolved'); |
80
|
|
|
} |
81
|
373 |
|
$this->resolved = true; |
82
|
|
|
|
83
|
373 |
|
$this->getCallback(); |
84
|
|
|
|
85
|
373 |
|
return $this; |
86
|
|
|
} |
87
|
|
|
|
88
|
2 |
|
public function __toString(): string |
89
|
|
|
{ |
90
|
2 |
|
return 'Successfully matched ' . $this->length . ' characters'; |
91
|
|
|
} |
92
|
|
|
} |
93
|
|
|
|