|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Vanderlee\Comprehend\Builder; |
|
4
|
|
|
|
|
5
|
|
|
use Vanderlee\Comprehend\Core\ArgumentsTrait; |
|
6
|
|
|
use Vanderlee\Comprehend\Core\Context; |
|
7
|
|
|
use Vanderlee\Comprehend\Parser\Parser; |
|
8
|
|
|
|
|
9
|
|
|
/** |
|
10
|
|
|
* Dynamically (lazy) binding parser |
|
11
|
|
|
* |
|
12
|
|
|
* @author Martijn |
|
13
|
|
|
*/ |
|
14
|
|
|
class RuleBinding extends Parser |
|
15
|
|
|
{ |
|
16
|
|
|
use ArgumentsTrait; |
|
17
|
|
|
|
|
18
|
|
|
private $rule; |
|
19
|
|
|
private $arguments; |
|
20
|
|
|
|
|
21
|
17 |
|
public function __construct(&$rule, $arguments = []) |
|
22
|
|
|
{ |
|
23
|
17 |
|
$this->rule = &$rule; |
|
24
|
17 |
|
$this->arguments = $arguments; |
|
25
|
17 |
|
} |
|
26
|
|
|
|
|
27
|
29 |
|
private function getParser() |
|
28
|
|
|
{ |
|
29
|
29 |
|
$rule = &$this->rule; |
|
30
|
|
|
|
|
31
|
29 |
|
if ($rule instanceof Parser) { |
|
32
|
10 |
|
return clone $rule; |
|
33
|
|
|
} |
|
34
|
|
|
|
|
35
|
22 |
|
if (is_callable($rule)) { |
|
36
|
|
|
// Generator function (should return Parser) |
|
37
|
15 |
|
$instance = $rule(...$this->arguments); |
|
38
|
15 |
|
if (!($instance instanceof Parser)) { |
|
39
|
1 |
|
throw new \InvalidArgumentException("Generator function does not return Parser"); |
|
40
|
|
|
} |
|
41
|
14 |
|
return $instance; |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
16 |
|
if (is_string($rule) && class_exists($rule) && is_subclass_of($rule, Parser::class)) { |
|
45
|
|
|
// Class name of a Parser class |
|
46
|
10 |
|
return new $rule(...$this->arguments); |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
6 |
|
if (is_array($rule) || is_string($rule) || is_int($rule)) { |
|
50
|
|
|
// S-C-S Array syntax, plain text or ASCII-code |
|
51
|
6 |
|
return self::getArgument($rule); |
|
52
|
|
|
} |
|
53
|
|
|
|
|
54
|
|
|
throw new \RuntimeException(sprintf('Cannot dynamically bind definition type `%1$s`', |
|
55
|
|
|
is_object($this->rule) |
|
56
|
|
|
? get_class($this->rule) |
|
57
|
|
|
: gettype($this->rule))); |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
28 |
|
protected function parse(&$input, $offset, Context $context) |
|
61
|
|
|
{ |
|
62
|
28 |
|
$match = $this->getParser()->parse($input, $offset, $context); |
|
63
|
27 |
|
if ($match->match) { |
|
64
|
25 |
|
return $this->success($input, $offset, $match->length, $match); |
|
|
|
|
|
|
65
|
|
|
} |
|
66
|
|
|
|
|
67
|
11 |
|
return $this->failure($input, $offset, $match->length); |
|
68
|
|
|
} |
|
69
|
|
|
|
|
70
|
4 |
|
public function __toString() |
|
71
|
|
|
{ |
|
72
|
|
|
/** @noinspection HtmlUnknownTag */ |
|
73
|
4 |
|
return $this->rule |
|
74
|
4 |
|
? (string)$this->getParser() |
|
75
|
4 |
|
: '<undefined>'; |
|
76
|
|
|
} |
|
77
|
|
|
|
|
78
|
|
|
} |
|
79
|
|
|
|