|
1
|
|
|
<?php |
|
2
|
|
|
namespace GetSky\ParserExpressions\Rules; |
|
3
|
|
|
|
|
4
|
|
|
use GetSky\ParserExpressions\Context; |
|
5
|
|
|
use GetSky\ParserExpressions\Result; |
|
6
|
|
|
|
|
7
|
|
|
/** |
|
8
|
|
|
* The sequence operator e1 e2 first invokes e1, and if e1 succeeds, |
|
9
|
|
|
* subsequently invokes e2 on the remainder of the input string leftc |
|
10
|
|
|
* unconsumed by e1, and returns the result. If either e1 or e2 fails, |
|
11
|
|
|
* then the sequence expression e1 e2 fails. |
|
12
|
|
|
* |
|
13
|
|
|
* @package GetSky\ParserExpressions\Rules |
|
14
|
|
|
* @author Alexander Getmanskii <[email protected]> |
|
15
|
|
|
*/ |
|
16
|
|
|
class Sequence extends AbstractRule |
|
17
|
|
|
{ |
|
18
|
|
|
|
|
19
|
|
|
/** |
|
20
|
|
|
* @var \GetSky\ParserExpressions\RuleInterface[] Array with subrules. |
|
21
|
|
|
*/ |
|
22
|
|
|
protected $rules; |
|
23
|
|
|
|
|
24
|
|
|
/** |
|
25
|
|
|
* @param array $rules Array with subrules |
|
26
|
|
|
* @param string $name |
|
27
|
|
|
* @param callable $action |
|
28
|
|
|
*/ |
|
29
|
4 |
|
public function __construct(array $rules, $name = "Sequence", callable $action = null) |
|
30
|
|
|
{ |
|
31
|
4 |
|
foreach ($rules as $rule) { |
|
32
|
4 |
|
$this->rules[] = $this->toRule($rule); |
|
33
|
|
|
} |
|
34
|
4 |
|
$this->name = (string) $name; |
|
35
|
4 |
|
$this->action = $action; |
|
36
|
4 |
|
} |
|
37
|
|
|
|
|
38
|
|
|
/** |
|
39
|
|
|
* {@inheritdoc} |
|
40
|
|
|
*/ |
|
41
|
1 |
|
public function scan(Context $context) |
|
42
|
|
|
{ |
|
43
|
1 |
|
$index = $context->getCursor(); |
|
44
|
1 |
|
$string = ''; |
|
45
|
1 |
|
$result = new Result($this->name); |
|
46
|
|
|
|
|
47
|
1 |
|
$context->increaseDepth(); |
|
48
|
1 |
|
foreach ($this->rules as $rule) { |
|
49
|
1 |
|
$value = $rule->scan($context); |
|
50
|
1 |
|
if ($value === false) { |
|
51
|
1 |
|
$context->setCursor($index); |
|
52
|
1 |
|
return false; |
|
53
|
1 |
|
} elseif ($value instanceof Result) { |
|
54
|
1 |
|
$string .= $value->getValue(); |
|
55
|
1 |
|
$result->addChild($value); |
|
56
|
|
|
} |
|
57
|
|
|
} |
|
58
|
1 |
|
$context->decreaseDepth(); |
|
59
|
1 |
|
$result->setValue($string, $index); |
|
60
|
1 |
|
$this->action($result); |
|
61
|
|
|
|
|
62
|
1 |
|
return $result; |
|
63
|
|
|
} |
|
64
|
|
|
} |
|
65
|
|
|
|