1
|
|
|
<?php |
2
|
|
|
namespace GetSky\ParserExpressions\Rules; |
3
|
|
|
|
4
|
|
|
use GetSky\ParserExpressions\Context; |
5
|
|
|
use GetSky\ParserExpressions\Result; |
6
|
|
|
use GetSky\ParserExpressions\RuleInterface; |
7
|
|
|
|
8
|
|
|
/** |
9
|
|
|
* The zero-or-more operators consume zero or more consecutive |
10
|
|
|
* repetitions of their sub-expression e. These operators always |
11
|
|
|
* behave greedily, consuming as much input as possible and never |
12
|
|
|
* backtracking. |
13
|
|
|
* |
14
|
|
|
* @package GetSky\ParserExpressions\Rules |
15
|
|
|
* @author Alexander Getmanskii <[email protected]> |
16
|
|
|
*/ |
17
|
|
|
class ZeroOrMore extends AbstractRule |
18
|
|
|
{ |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* @var \GetSky\ParserExpressions\RuleInterface |
22
|
|
|
*/ |
23
|
|
|
protected $rule; |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* @param array|string|RuleInterface $rule |
27
|
|
|
* @param string $name |
28
|
|
|
* @param callable $action |
29
|
|
|
*/ |
30
|
1 |
|
public function __construct($rule, $name = "ZeroOrMore", callable $action = null) |
31
|
|
|
{ |
32
|
1 |
|
$this->rule = $this->toRule($rule); |
33
|
1 |
|
$this->name = (string) $name; |
34
|
1 |
|
$this->action = $action; |
35
|
1 |
|
} |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* {@inheritdoc} |
39
|
|
|
*/ |
40
|
1 |
|
public function scan(Context $context) |
41
|
|
|
{ |
42
|
1 |
|
$firstIndex = $index = $context->getCursor(); |
43
|
1 |
|
$string = ''; |
44
|
1 |
|
$result = new Result($this->name); |
45
|
|
|
|
46
|
1 |
|
$context->increaseDepth(); |
47
|
1 |
|
while ($value = $this->rule->scan($context)) { |
48
|
1 |
|
if ($value instanceof Result) { |
49
|
1 |
|
$result->addChild($value); |
50
|
1 |
|
$string .= $value->getValue(); |
51
|
1 |
|
$index = $context->getCursor(); |
52
|
|
|
} |
53
|
|
|
} |
54
|
1 |
|
$context->decreaseDepth(); |
55
|
1 |
|
$context->setCursor($index); |
56
|
|
|
|
57
|
1 |
|
if ($firstIndex != $index) { |
58
|
1 |
|
$result->setValue($string, $firstIndex); |
59
|
1 |
|
$this->action($result); |
60
|
1 |
|
return $result; |
61
|
|
|
} |
62
|
|
|
|
63
|
1 |
|
return true; |
64
|
|
|
} |
65
|
|
|
} |
66
|
|
|
|