1
|
|
|
<?php |
2
|
|
|
namespace GetSky\ParserExpressions\Rules; |
3
|
|
|
|
4
|
|
|
use GetSky\ParserExpressions\Context; |
5
|
|
|
use GetSky\ParserExpressions\Result; |
6
|
|
|
|
7
|
|
|
/** |
8
|
|
|
* This rule is triggered at the first match.The choice operator e1 / e2 |
9
|
|
|
* first invokes e1, and if e1 succeeds, returns its result immediately. |
10
|
|
|
* Otherwise, if e1 fails, then the choice operator backtracks to the |
11
|
|
|
* original input position at which it invoked e1, but then calls e2 |
12
|
|
|
* instead, returning e2's result. |
13
|
|
|
* |
14
|
|
|
* @package GetSky\ParserExpressions\Rules |
15
|
|
|
* @author Alexander Getmanskii <[email protected]> |
16
|
|
|
*/ |
17
|
|
|
class FirstOf extends AbstractRule |
18
|
|
|
{ |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* @var \GetSky\ParserExpressions\RuleInterface[] Array with subrules. |
22
|
|
|
*/ |
23
|
|
|
protected $rules; |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* @var string |
27
|
|
|
*/ |
28
|
|
|
protected $name; |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* @param array $rules Array with subrules. |
32
|
|
|
* @param string $name Label for rule. |
33
|
|
|
* @param callable $action |
34
|
|
|
*/ |
35
|
3 |
|
public function __construct(array $rules, $name = "FirstOf", callable $action = null) |
36
|
|
|
{ |
37
|
3 |
|
foreach ($rules as $rule) { |
38
|
3 |
|
$this->rules[] = $this->toRule($rule); |
39
|
|
|
} |
40
|
3 |
|
$this->name = (string) $name; |
41
|
3 |
|
$this->action = $action; |
42
|
3 |
|
} |
43
|
|
|
|
44
|
|
|
/** |
45
|
|
|
* {@inheritdoc} |
46
|
|
|
*/ |
47
|
1 |
|
public function scan(Context $context) |
48
|
|
|
{ |
49
|
1 |
|
$index = $context->getCursor(); |
50
|
1 |
|
$context->increaseDepth(); |
51
|
|
|
|
52
|
1 |
|
foreach ($this->rules as $rule) { |
53
|
1 |
|
$value = $rule->scan($context); |
54
|
1 |
|
if ($value instanceof Result) { |
55
|
1 |
|
$result = new Result($this->name); |
56
|
1 |
|
$result->addChild($value); |
57
|
1 |
|
$result->setValue($value->getValue(), $index); |
58
|
1 |
|
$this->action($result); |
59
|
|
|
|
60
|
1 |
|
return $result; |
61
|
|
|
} |
62
|
1 |
|
$context->setCursor($index); |
63
|
|
|
} |
64
|
|
|
|
65
|
1 |
|
$context->decreaseDepth(); |
66
|
1 |
|
$context->setCursor($index); |
67
|
1 |
|
$context->error($this, $index); |
68
|
1 |
|
return false; |
69
|
|
|
} |
70
|
|
|
} |
71
|
|
|
|