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