/
Compiler.php
534 lines (468 loc) · 17.7 KB
/
Compiler.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
<?php
/*
* This file is a part of Solve framework.
*
* @author Alexandr Viniychuk <alexandr.viniychuk@icloud.com>
* @copyright 2009-2014, Alexandr Viniychuk
* created: 05.01.14 10:19
*/
namespace Solve\Slot;
use Solve\Slot\Blocks\BaseBlock;
use Solve\Storage\ArrayStorage;
use Solve\Utils\Inflector;
/**
* Class Compiler
* @package Solve\Slot
*
* Class Compiler is used to ...
*
* @version 1.0
* @author Alexandr Viniychuk <alexandr.viniychuk@icloud.com>
*/
class Compiler {
/**
* @var ArrayStorage tokens found stack
*/
private $_tokenStack;
/**
* @var ArrayStorage registered blocks
*/
private $_blocks;
/**
* @var array used for syntax check
*/
private $_expectations = array();
/**
* @var ArrayStorage
*/
private $_config = array(
'commentStart' => '{#',
'commentEnd' => '#}',
'tokenStart' => '{{',
'tokenEnd' => '}}',
'blockClose' => 'end',
);
private $_escapingStrategy = 'html';
/**
* @var Slot instance of SLOT class
*/
private $_slotInstance;
private $_hashesQuoted = array();
private $_hashScopeChar = '@';
private $_literalsCache = array();
/**
* @var array methods that available as system modifiers
*/
private $_predefinedMethods = array(
'empty', 'is_null', 'isset', 'var_dump'
);
/**
* @param Slot $slot
*/
public function __construct(Slot $slot = null) {
$this->_config = new ArrayStorage((array)$this->_config);
$this->_tokenStack = new ArrayStorage();
$this->_blocks = new ArrayStorage();
$this->_slotInstance = $slot;
}
/**
* Set config value partially of completely
* @param $name
* @param $value
* @return $this
*/
public function setConfig($name, $value) {
if (is_null($name)) {
$this->_config = new ArrayStorage($value);
} else {
$this->_config->setDeepValue($name, $value);
}
return $this;
}
/**
* Register functional block for compiler. Each block should be represented with Class
* @param $blockTag
* @param $info
*/
public function registerBlock($blockTag, $info) {
$this->_blocks[$blockTag] = $info;
}
/**
* @param $source
* @return mixed
*/
public function stripComments($source) {
$source = preg_replace('/' . $this->_config['commentStart'] . '.*' . $this->_config['commentEnd'] . '/sU', '', $source);
return $source;
}
public function saveLiterals($source) {
$literalTokenStart = '#' . $this->_config['tokenStart'] . '\s*literal\s*' . $this->_config['tokenEnd'] . '#';
$literalTokenEnd = '#' . $this->_config['tokenStart'] . '\s*literalend\s*' . $this->_config['tokenEnd'] . '#';
$starts = array();
preg_match_all($literalTokenStart, $source, $starts, PREG_OFFSET_CAPTURE);
if (!empty($starts[0])) {
$result = '';
$ends = array();
preg_match_all($literalTokenEnd, $source, $ends, PREG_OFFSET_CAPTURE, $starts[0][0][1]);
if (count($starts[0]) !== count($ends[0])) {
throw new \Exception('Invalid {{ literal }} tags count');
}
$literalsIndex = count($this->_literalsCache);
$previousEndIndex = 0;
foreach ($starts[0] as $index => $location) {
$result .= substr($source, $previousEndIndex, $location[1] - $previousEndIndex) . '__LITERAL'.$literalsIndex.'__';
$contentStartPosition = $location[1] + strlen($location[0]);
$this->_literalsCache[$literalsIndex] = array(
'start' => $location[1],
'end' => $ends[0][$index][1] + strlen($ends[0][$index][0]),
'content' => substr($source, $contentStartPosition, $ends[0][$index][1] - $contentStartPosition)
);
$previousEndIndex = $this->_literalsCache[$literalsIndex]['end'];
$literalsIndex++;
}
$source = $result . substr($source, $previousEndIndex);
}
return $source;
}
public function restoreLiterals($source) {
if (empty($this->_literalsCache)) return $source;
$source = preg_replace_callback('#__LITERAL(\d+)__#', array($this, 'onRestoreLiterals'), $source);
return $source;
}
private function onRestoreLiterals($matches) {
if (array_key_exists($matches[1], $this->_literalsCache)) {
$content = $this->_literalsCache[$matches[1]];
unset($this->_literalsCache[$matches[1]]);
return $content['content'];
} else {
return "";
}
}
/**
* @param string $expression
* @return string result
*/
public function compileExpression($expression) {
$expression = trim($expression);
$quotedPattern = "#(?:(?:\"(?:\\\\\"|[^\"])+\")|(?:'(?:\\'|[^'])+'))#isU";
// $matches = array();
// preg_match_all($quotedPattern, $expression, $matches);
$expression = preg_replace_callback($quotedPattern, array($this, '_quotesRegexpCallback'), $expression);
$expression = $this->_processUnquotedExpression($expression);
$expression = str_replace(array_keys($this->_hashesQuoted), $this->_hashesQuoted, $expression);
$expression = str_replace('~', '.', $expression);
return $expression;
}
private function _processUnquotedExpression($expression) {
$isSimpleExpression = true;
$highLevelHash = array();
$squareBracePattern = '#\[[^\s]+\]#ism';
$braced = array();
preg_match_all($squareBracePattern, $expression, $braced);
if (!empty($braced[0])) {
foreach ($braced[0] as $item) {
$hash = $this->getHash($item);
$highLevelHash[$hash] = '[' . $this->_processUnquotedExpression(substr($item, 1, -1)) . ']';
$expression = str_replace($item, $hash, $expression);
}
}
$simpleBracePattern = '#\((([^()]+|(?R))*)\)#ism';
$braced = array();
preg_match_all($simpleBracePattern, $expression, $braced);
if (!empty($braced[0])) {
foreach ($braced[0] as $item) {
if ($item == '()') continue;
$hash = $this->getHash($item);
$highLevelHash[$hash] = '(' . $this->_processUnquotedExpression(substr($item, 1, -1)) . ')';
$expression = str_replace($item, $hash, $expression);
}
}
if (strpos($expression, ' ') !== false) {
$spacedParts = array();
$spacePattern = '#"(?:\\\\.|[^\\\\"])*"|\S+#';
preg_match_all($spacePattern, $expression, $spacedParts);
if (!empty($spacedParts[0])) {
$expression = '';
foreach ($spacedParts[0] as $item) {
$expression .= ' ' . $this->_processUnquotedExpression($item);
}
$expression = substr($expression, 1);
$isSimpleExpression = false;
}
}
if (strpos($expression, '..') !== false) {
$rangeRegexp = '#(?P<range>(["\'._\w\d]+)\.\.(["\'._\w\d]+))#isu';
$ranges = array();
preg_match_all($rangeRegexp, $expression, $ranges);
foreach ($ranges['range'] as $range) {
$rangeParts = explode('..', $range);
$compiledRange = 'range(' . $this->compileExpression($rangeParts[0]) . ', ' . $this->compileExpression($rangeParts[1]) . ')';
$hash = $this->getHash($range);
$highLevelHash[$hash] = $compiledRange;
$expression = str_replace($range, $hash, $expression);
}
}
if ($isSimpleExpression) {
$modifiersInfo = $this->_processModifiers($expression);
$expression = $modifiersInfo[0];
if (strpos($expression, '.') !== false) {
$pointPattern = '#\.#';
$pointedParts = preg_split($pointPattern, $expression, 0, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
$expression = array_shift($pointedParts);
foreach ($pointedParts as $part) {
if ($this->checkForSimpleString($part)) {
$value = '[\'' . $part . '\']';
} else {
$value = '[' . $this->_processUnquotedExpression($part) . ']';
}
$hash = $this->getHash($value);
$highLevelHash[$hash] = $value;
$expression .= $hash;
}
}
$varPattern = '#' . $this->_hashScopeChar . '\w+' . $this->_hashScopeChar . '|(->)?\w+(\|[_\w\d:]+)?#is';
$expression = preg_replace_callback($varPattern, array($this, '_varRegexpCallback'), $expression);
if (!empty($modifiersInfo[1])) {
$expression = $modifiersInfo[1] . $expression . $modifiersInfo[2];
}
}
$highLevelHash = array_reverse($highLevelHash);
$expression = str_replace(array_keys($highLevelHash), $highLevelHash, $expression);
return $expression;
}
public function checkForSimpleString($expression) {
$matches = array();
preg_match('#[_\w]{1}[_\w\d]*#', $expression, $matches);
return $matches[0] === $expression;
}
/**
* Preg match replace callback
* @param $pregMatchResult
* @return string
*/
private function _varRegexpCallback($pregMatchResult) {
$var = $pregMatchResult[0];
if (($var[0] == $this->_hashScopeChar) && ($var[strlen($var) - 1] == $this->_hashScopeChar)) {
return $var;
}
if (is_numeric($var) || $var === "true" || $var === "false") {
return $var;
}
if (!empty($pregMatchResult[1]) && ($pregMatchResult[1] == '->')) {
return $var;
}
$info = $this->_processModifiers($var);
return $info[1] . '$__lv[\'' . $info[0] . '\']' . $info[2];
}
/**
* Preg match replace callback
* @param $pregMatchResult
* @return string
*/
private function _quotesRegexpCallback($pregMatchResult) {
$hash = $this->getHash($pregMatchResult[0]);
$this->_hashesQuoted[$hash] = $pregMatchResult[0];
return $hash;
}
private function getHash($string) {
return $this->_hashScopeChar . md5($string) . $this->_hashScopeChar;
}
/**
* Main compilartor function
* @param $source
* @return mixed
*/
public function compileSource($source) {
$source = $this->stripComments($source);
$source = $this->saveLiterals($source);
$result = preg_replace_callback('#' . $this->_config['tokenStart'] . '(.*)' . $this->_config['tokenEnd'] . '#smU', array($this, 'onTokenFound'), $source);
$result = $this->restoreLiterals($result);
return $result;
}
/**
* Since it called step by step we can create context for each tag
* @param $token
* @return string
*/
private function onTokenFound($token) {
if (is_array($token)) $token = array_pop($token);
$token = trim($token);
$tokenParts = explode(' ', $token);
$tag = array_shift($tokenParts);
$params = implode(' ', $tokenParts);
if ($this->_blocks->has($tag)) {
if ($this->_blocks->getDeepValue($tag . '/runtime')) {
$res = '<?php $this->_compiler->invokeBlock(\'' . $tag . '\', ' . $this->compileExpression($params) . '); ?>';
} else {
$res = $this->onBlockTagOpen($tag, $params);
}
} elseif (substr($tag, 0, strlen($this->_config['blockClose'])) == $this->_config['blockClose']) {
$tag = substr($tag, strlen($this->_config['blockClose']));
$res = $this->onBlockTagClose($tag, $params);
} else {
$res = $this->onVarEchoToken($token, $params);
}
return $res;
}
/**
* Add modifier surrounding for expression
* @param $expression
* @return array
* @throws \Exception
*/
private function _processModifiers($expression) {
$mStart = '';
$mEnd = '';
$rawEcho = false;
/** process modifiers */
if (strpos($expression, '|') !== false && strpos($expression, '||') === false) {
$modifiers = explode('|', $expression);
$expression = array_shift($modifiers);
foreach ($modifiers as $modifier) {
$params = array();
if (strpos($modifier, ':') !== false) {
$params = explode(':', $modifier);
$modifier = array_shift($params);
}
if ($modifier == 'raw') {
$rawEcho = true;
continue;
}
if ($this->isCallable($modifier)) {
$mStart = $modifier . '(' . $mStart;
if ($modifier !== 'raw') {
foreach ($params as $param) {
$mEnd .= ', ' . $this->compileExpression($param);
}
}
$mEnd .= ')';
} else {
throw new \Exception('SLOT compiler error: undefined modifier ' . $modifier);
}
}
}
return array(
$expression,
$mStart,
$mEnd,
$rawEcho
);
}
private function onVarEchoToken($token) {
$res = '<?php ';
$varExpression = $this->compileExpression($token);
$varValue = $varExpression;
$isFunctional = preg_match('#[-+*/\(|]+#', $varValue);
$isRaw = strpos($token, 'raw') !== false;
/** process 01.vars escaping strategies */
if ($this->getEscapingStrategy() == 'html' && $isRaw && !$isFunctional) {
if (strpos($varExpression, 'htmlentities') === false) {
$varValue = 'htmlentities(' . $varValue . ', ENT_COMPAT, "UTF-8")';
}
}
if (!$isRaw && ($isFunctional || (strpos($varValue, '$') === false))) {
$res .= 'echo ' . $varValue;
} elseif ($isRaw) {
if (strpos($token, 'raw:bool') !== false) {
$res .= 'echo ' . $varValue . '? "true" : "false"';
} else {
$res .= 'echo ' . $varValue;
}
} else {
$res .= 'echo isset(' . $varExpression . ') ? ' . $varValue . ': ""';
}
$res .= '; ?>';
return $res;
}
public function invokeBlock($tag, $params) {
echo $this->onBlockTagOpen($tag, $params);
}
/**
* @param $tag
* @param $token
* @return string
*/
private function onBlockTagOpen($tag, $token) {
if ($this->_blocks->getDeepValue($tag . '/paired')) {
$this->_expectations[] = $tag;
}
/**
* @var BaseBlock $blockObject
*/
$blockObject = $this->getBlockObject($tag, $token);
$this->_tokenStack[] = $blockObject;
return $blockObject->processBlockStart();
}
/**
* @param $tag
* @param $token
* @return string
* @throws \Exception
*/
private function onBlockTagClose($tag, $token) {
if ($this->_blocks->getDeepValue($tag . '/paired')) {
if (!empty($this->_expectations)) {
$expected = $this->_expectations[count($this->_expectations) - 1];
if ($expected != $tag) {
throw new \Exception('Error parsing template: Unexpected tag "' . $tag . '", expected: "' . $expected . '"');
} else {
array_pop($this->_expectations);
}
}
} else {
throw new \Exception('Error parsing template: Unexpected closing tag');
}
$blockObject = $this->getBlockObject($tag, $token);
return $blockObject->processBlockEnd();
}
/**
* @param $tag\
* @param $token
* @return BaseBlock
*/
private function getBlockObject($tag, $token) {
$namespace = isset($this->_blocks[$tag]['namespace']) ? $this->_blocks[$tag]['namespace'] : '\Solve\Slot\Blocks\\';
$blockClassName = $namespace . Inflector::camelize($tag . 'Block');
/**
* @var BaseBlock $blockObject
*/
$blockObject = new $blockClassName($token, $this);
return $blockObject;
}
private function isCallable($callable) {
return in_array($callable, $this->_predefinedMethods) || $callable[0] === '!' || is_callable($callable);
}
/**
* @param string $escapingStrategy
*/
public function setEscapingStrategy($escapingStrategy) {
$this->_escapingStrategy = $escapingStrategy;
}
/**
* @return string
*/
public function getEscapingStrategy() {
return $this->_escapingStrategy;
}
/**
* Set Slot instance
* @param Slot $slot
*/
public function setSlot(Slot $slot) {
$this->_slotInstance = $slot;
}
/**
* Get Slot instance
* @return Slot
*/
public function getSlot() {
return $this->_slotInstance;
}
public function parseSpacedArguments($string) {
$string = trim($string);
$spacedParts = array();
$spacePattern = '#"(?:\\\\.|[^\\\\"])*"|\S+#';
preg_match_all($spacePattern, $string, $spacedParts);
return $spacedParts[0];
}
}