-
Notifications
You must be signed in to change notification settings - Fork 0
/
MacroParser.php
91 lines (82 loc) · 2.43 KB
/
MacroParser.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
<?php
namespace daliaIT\rough;
use Exception,
RuntimeException;
class MacroParser
{
protected
#:IMacroLib
$macroLib,
#:string
$pattern = '/^([ \t]*)#@(.*?)(?:@#|#(.*?)#@#)/sm',
#:array
$options = array(
'indentOutput' => true,
'stripMacros' => false,
);
#:this
public function __construct(IMacroLib $lib){
$this->macroLib = $lib;
}
#_string
public function replace($input,array $options=array()){
$lib =$this->macroLib;
$argParser = new MacroArgParser();
$parser = $this;
$options = array_replace($this->options,$options);
$callback = function($matches) use ($lib,$argParser,$parser,$options){
$indent = $matches[1];
$macroString = $matches[2];
$args = $argParser->parse($macroString);
$name = array_shift($args);
try{
$output = $lib->runMacro($name,$args,$parser);
} catch(Exception $e){
throw new RuntimeException(
"Processing macro string '$macroString' failed with message:\n"
.$e->getMessage()
);
}
if(!$options['stripMacros']){
$output = "#@$macroString#\n$output#@#";
}
if($options['indentOutput']){
$buffer = array();
foreach(explode("\n",$output) as $line){
$buffer[] = "$indent$line";
}
$output = implode("\n",$buffer);
unset($buffer);
}
return $output;
};
return preg_replace_callback($this->pattern, $callback, $input);
}
#@access public public macroLib IMacroLib#
#:IMacroLib
public function getMacroLib(){
return $this->macroLib;
}
#:this
public function setMacroLib(IMacroLib $value){
$this->macroLib = $value;
return $this;
}
#@#
#@access public public pattern string#
#:string
public function getPattern(){
return $this->pattern;
}
#:this
public function setPattern($value){
if(! is_string($value)){
throw new \InvalidArgumentException(
__METHOD__ .' expects a string but got a '.gettype($value)
);
}
$this->pattern = $value;
return $this;
}
#@#
}