-
Notifications
You must be signed in to change notification settings - Fork 10
/
Compiler.php
2357 lines (1931 loc) · 74.4 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
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* The Tale Jade Compiler.
*
* Contains a compiler that takes an Abstract Syntax Tree (AST) from
* the parser and generates Markup out of it.
*
* The Compiler can handle different markup-types.
* Currently XML and HTML5 are supported.
*
* This file is part of the Tale Jade Template Engine for PHP
*
* LICENSE:
* The code of this file is distributed under the MIT license.
* If you didn't receive a copy of the license text, you can
* read it here https://github.com/Talesoft/tale-jade/blob/master/LICENSE.md
*
* @category Presentation
* @package Tale\Jade
* @author Torben Koehn <[email protected]>
* @author Talesoft <[email protected]>
* @copyright Copyright (c) 2015-2016 Torben Köhn (http://talesoft.codes)
* @license https://github.com/Talesoft/tale-jade/blob/master/LICENSE.md MIT License
* @version 1.4.5
* @link http://jade.talesoft.codes/docs/files/Compiler.html
* @since File available since Release 1.0
*/
namespace Tale\Jade;
use Tale\ConfigurableTrait;
use Tale\Jade\Compiler\Exception;
use Tale\Jade\Parser\Node;
/**
* Compiles an AST got from the parser to valid P/X/HTML or P/XML
*
* You can control the output-style via the options
* passed to the constructor.
*
* Different output types are possible (Currently, XML ,HTML and XHTML)
*
* The main entry point is the `compile` method
*
* The generated PHTML/PXML should be evaluated, the best method
* is a simple include of a generated file
*
* Usage example:
* <code>
*
* use Tale\Jade\Compiler;
*
* $compiler = new Compiler();
*
* $phtml = $compiler->compile($jadeInput);
* //or
* $phtml = $compiler->compileFile($jadeFilePath);
*
* </code>
*
* There are different approachs to handle the compiled PHTML.
* The best and most explaining one is saving the PHTML to a file and
* including it like this:
*
* <code>
*
* file_put_contents('rendered.phtml', $phtml);
*
* //Define some variables to pass to our template
* $variables = [
* 'title' => 'My Page Title!',
* 'posts' => []
* ];
*
* //Make sure the variables are accessible by the included template
* extract($variables);
*
* //Compiler needs an $__args variables to pass arguments on to mixins
* $__args = $variables;
*
* //Include the rendered PHTML directly
* include('rendered.phtml');
* </code>
*
* You may fetch the included content with ob_start() and ob_get_clean()
* and pass it on to anything, e.g. a cache handler or return it as an
* AJAX response.
*
* @category Presentation
* @package Tale\Jade
* @author Torben Koehn <[email protected]>
* @author Talesoft <[email protected]>
* @copyright Copyright (c) 2015-2016 Torben Köhn (http://talesoft.codes)
* @license https://github.com/Talesoft/tale-jade/blob/master/LICENSE.md MIT License
* @version 1.4.5
* @link http://jade.talesoft.codes/docs/classes/Tale.Jade.Compiler.html
* @since File available since Release 1.0
*/
class Compiler
{
use ConfigurableTrait;
/**
* The Mode for HTML.
*
* Will keep elements in selfClosingElements open
* Will repeat attributes if they're in selfRepeatingAttributes
* Won't /> close any elements, will </close> elements
*/
const MODE_HTML = 0;
/**
* The Mode for XML.
*
* Will /> close all elements, will </close> elements
* Won't repeat attributes if they're in selfRepeatingAttributes
* Won't keep elements in selfClosingElements open
*/
const MODE_XML = 1;
/**
* The Mode for XHTML.
*
* Will /> close all elements, will </close> elements
* Will repeat attributes if they're in selfRepeatingAttributes
* Won't keep elements in selfClosingElements open
*/
const MODE_XHTML = 2;
/**
* The lexer that is given to the parser.
*
* @var Lexer
*/
private $lexer;
/**
* The parse this compiler instance gets its nodes off.
*
* @var Parser
*/
private $parser;
/**
* The current file stack.
*
* The bottom file is the file that is currently compiled.
* This is needed for recursive path resolving in imports
*
* @var string[]
*/
private $files;
/**
* The mixins we found in the whole input.
*
* We use this to check if a mixin exists upon call
* and to compile them all at the and (with checking,
* if they are even called)
*
* The array looks like this:
* <samp>
* [
* ['node' => Node, 'phtml' => <compiled phtml> ],
* ['node' => Node, 'phtml' => <compiled phtml> ],
* ['node' => Node, 'phtml' => <compiled phtml> ]
* ]
* </samp>
*
* Keys are the name of the mixin
*
* @var array
*/
private $mixins;
/**
* A stack of names of the mixins we actually called in the code.
*
* @var string[]
*/
private $calledMixins;
/**
* A list of all blocks in our whole input.
*
* They are only used in handleBlocks and handleBlock
*
* @var Node[]
*/
private $blocks;
/**
* The level we're currently in.
*
* This doesn't equal the current level in the parser or lexer,
* it rather represents the current indentation level
* for pretty compiling
*
* @var int
*/
private $level;
/**
* Contains the current iterator ID to avoid name collisions.
*
* @var int
*/
private $iteratorId;
/**
* Specifies wether we're ignoring pretty-mode right now and print inline
*
* @var bool
*/
private $forceInline;
/**
* Creates a new compiler instance.
*
* You can pass a modified parser or lexer.
* Notice that if you pass both, the lexer inside the parser will be used.
*
* Valid options are:
*
* pretty: Use indentation and new-lines
* or compile everything into a single line
* indent_style: The character that is used for
* indentation (Space by default)
* indent_width: The amount of characters to repeat for
* indentation (Default 2 for 2-space-indentation)
* self_closing_tags: he tags that don't need any closing in
* HTML-style languages
* self_repeating_attributes: The attributes that repeat their value to
* set them to true in HTML-style languages
* force_inlined_tags: The tags that don't allow any pretty-printing inside them
* Required for e.g. pre-tags
* doctypes: The different doctypes you can use via the
* "doctype"-directive [name => doctype-string]
* mode: Compile in HTML, XML or XHTML mode
* xhtml_modes: The mode strings that compile XHTML-style
* filters: The different filters you can use via the
* ":<filterName>"-directive [name => callback]
* filter_map: The extension-to-filter-map for
* include-filters [extension => filter]
* escape_sequences: The escape-sequences that are possible in
* scalar strings
* compile_uncalled_mixins: Always compile all mixins or leave out
* those that aren't called?
* stand_alone: Allows the rendered files to be called
* without any requirements
* allow_imports: Set to false to disable imports for this
* compiler instance. Importing will throw an
* exception. Great for demo-pages
* defaultTag: The tag to default to for
* class/id/attribute-initiated elements
* (.abc, #abc, (abc))
* quote_style: The quote-style in the markup (default: ")
* replace_mixins: Replaces mixins from top to bottom if they
* have the same name. Allows duplicated mixin names.
* echo_xml_doctype: Uses PHP's "echo" to for XML processing instructions
* This fixes problems with PHP's short open tags
* paths: The paths to resolve paths in.
* If none set, it will default to get_include_path()
* extensions: The extensions for Jade files
* (default: .jade and .jd)
* parser_options: The options for the parser if none given
* lexer_options: The options for the lexer if none given.
*
*
* @param array|null $options an array of options
* @param Parser|null $parser an existing parser instance
* @param Lexer|null $lexer an existing lexer instance
*/
public function __construct(array $options = null, Parser $parser = null, Lexer $lexer = null)
{
$this->defineOptions([
'pretty' => false,
'indent_style' => Lexer::INDENT_SPACE,
'indent_width' => 2,
'self_closing_tags' => [
'input', 'br', 'img', 'link',
'area', 'base', 'col', 'command',
'embed', 'hr', 'keygen', 'meta',
'param', 'source', 'track', 'wbr'
],
'self_repeating_attributes' => [
'selected', 'checked', 'disabled'
],
'force_inlined_tags' => [
'pre', 'code'
],
'doctypes' => [
'5' => '<!DOCTYPE html>',
'xml' => '<?xml version="1.0" encoding="utf-8"?>',
'default' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">',
'transitional' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">',
'strict' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">',
'frameset' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">',
'1.1' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">',
'basic' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML Basic 1.1//EN" "http://www.w3.org/TR/xhtml-basic/xhtml-basic11.dtd">',
'mobile' => '<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.2//EN" "http://www.openmobilealliance.org/tech/DTD/xhtml-mobile12.dtd">'
],
'mode' => self::MODE_HTML,
'xhtml_modes' => ['default', 'transitional', 'strict', 'frameset', '1.1', 'basic', 'mobile'],
'filters' => [
'plain' => 'Tale\\Jade\\Filter::filterPlain',
'css' => 'Tale\\Jade\\Filter::filterStyle',
'style' => 'Tale\\Jade\\Filter::filterStyle',
'js' => 'Tale\\Jade\\Filter::filterScript',
'script' => 'Tale\\Jade\\Filter::filterScript',
'php' => 'Tale\\Jade\\Filter::filterCode',
'code' => 'Tale\\Jade\\Filter::filterCode',
'markdown' => 'Tale\\Jade\\Filter::filterMarkdown',
'md' => 'Tale\\Jade\\Filter::filterMarkdown',
'coffeescript' => 'Tale\\Jade\\Filter::filterCoffeeScript',
'coffee' => 'Tale\\Jade\\Filter::filterCoffeeScript',
'less' => 'Tale\\Jade\\Filter::filterLess',
'stylus' => 'Tale\\Jade\\Filter::filterStylus',
'styl' => 'Tale\\Jade\\Filter::filterStylus',
'sass' => 'Tale\\Jade\\Filter::filterSass'
//TODO: What else?
],
'filter_map' => [
'jade' => 'plain',
'pug' => 'plain',
'css' => 'css',
'js' => 'js',
'php' => 'php',
'md' => 'markdown',
'coffee' => 'coffeescript',
'less' => 'less',
'styl' => 'stylus',
'sass' => 'sass',
'scss' => 'sass'
],
'escape_sequences' => [
'\n' => "\n",
'\r' => "\r",
'\t' => "\t"
],
'compile_uncalled_mixins' => false,
'stand_alone' => false,
'allow_imports' => true,
'default_tag' => 'div',
'quote_style' => '"',
'escape_charset' => 'UTF-8',
'replace_mixins' => false,
'echo_xml_doctype' => defined('HHVM_VERSION'),
'paths' => [],
'extensions' => ['.pug', '.jd', '.jade'],
'parser_options' => [],
'lexer_options' => []
], $options);
$this->lexer = $lexer ?: new Lexer($this->options['lexer_options']);
$this->parser = $parser ?: new Parser($this->options['parser_options'], $this->lexer);
}
/**
* Returns the current lexer used.
*
* @return Lexer
*/
public function getLexer()
{
return $this->lexer;
}
/**
* Returns the current parser used.
*
* @return Parser
*/
public function getParser()
{
return $this->parser;
}
/**
* Adds a path to the compiler.
*
* Files will be loaded from this path (or other paths you added before)
*
* @param string $path the directory path
*
* @return $this
*/
public function addPath($path)
{
$this->options['paths'][] = $path;
return $this;
}
/**
* Adds a filter to the compiler.
*
* This filter can then be used inside jade with the
* :<filtername> directive
*
* The callback should have the following signature:
* (\Tale\Jade\Parser\Node $node, $indent, $newLine)
* where $node is the filter-Node found,
* $indent is the current indentation respecting level and pretty-option
* and newLine is a new-line respecting the pretty-option
*
* It should return either a PHTML string or a Node-instance
*
* @param string $name the name of the filter
* @param callable $callback the filter handler callback
*
* @return $this
*/
public function addFilter($name, $callback)
{
if (!is_callable($callback))
throw new \InvalidArgumentException(
"Argument 2 of addFilter must be valid callback"
);
$this->options['filters'][$name] = $callback;
return $this;
}
/**
* Compiles a Jade-string to PHTML.
*
* The result can then be evaluated, the best method is
* a simple PHP include
*
* Look at Renderer to get this done for you
*
* If you give it a path, the directory of that path will be used
* for relative includes.
*
* @param string $input the jade input string
* @param string|null $path the path for relative includes
*
* @return mixed|string a PHTML string containing HTML and PHP
*
* @throws Exception when the compilation fails
* @throws Parser\Exception when the parsing fails
* @throws Lexer\Exception when the lexing fails
*/
public function compile($input, $path = null)
{
//Compiler reset
$this->files = $path ? [$path] : [];
$this->mixins = [];
$this->calledMixins = [];
$this->blocks = [];
$this->level = 0;
$this->iteratorId = 0;
$this->forceInline = false;
//Parse the input into an AST
$node = null;
try {
$node = $this->parser->parse($input);
} catch(\Exception $e) {
//This is needed to be able to keep track of the
//file path that is erroring
if (!($e instanceof Exception))
$this->throwException($e->getMessage());
else throw $e;
}
//There are some things we need to take care of before compilation
$this->handleImports($node);
$this->handleBlocks($node);
$this->handleMixins($node);
//The actual compilation process ($node is the very root \Tale\Jade\Parser\Node of everything)
$phtml = $this->compileNode($node);
//Reset the level again for our next operations
$this->level = 0;
//Now we append/prepend specific stuff (like mixin functions and helpers)
$mixins = $this->compileMixins();
$helpers = '';
if ($this->options['stand_alone']) {
$helpers = file_get_contents(__DIR__.'/Compiler/functions.php')."\n?>\n";
$helpers .= $this->createCode('namespace {');
}
//Put everything together
$phtml = implode('', [$helpers, $mixins, $phtml]);
if ($this->options['stand_alone'])
$phtml .= $this->createCode('}');
//Reset the files after compilation so that compileFile may resolve correctly
//Happens when you call compileFile twice on different files
//Note that Compiler only uses the include-path, when there is no file in the
//file name storage $_files
$this->files = [];
//Return the compiled PHTML
return trim($phtml);
}
/**
* Compiles a file to PHTML.
*
* The given path will automatically passed as
* compile()'s $path argument
*
* The path should always be relative to the paths-option paths
*
* @see Compiler->compile
*
* @param string $path the path to the jade file
*
* @return mixed|string the compiled PHTML
*
* @throws \Exception when the file is not found
* @throws Exception when the compilation fails
* @throws Parser\Exception when the parsing fails
* @throws Lexer\Exception when the lexing fails
*/
public function compileFile($path)
{
$fullPath = $this->resolvePath($path);
if (!$fullPath)
$this->throwException(
"Template file [$path] could not be resolved in the following paths: [".
implode(', ', $this->options['paths']).
"], Extensions: [".implode(', ', $this->options['extensions']).
"], Include path: ".get_include_path()."]\n\n".
"Make sure the paths are configured correctly. If you're missing a path, add it with the [`paths`] ".
"option or the [`->addPath`]-method."
);
return $this->compile(file_get_contents($fullPath), $fullPath);
}
/**
* Checks if the current document mode equals the mode passed.
*
* Take a look at the Compiler::MODE_* constants to see the possible
* modes
*
* @param int $mode the mode to check against
*
* @return bool
*/
protected function isMode($mode)
{
return $this->options['mode'] === $mode;
}
/**
* Checks if we're in XML document mode.
*
* @return bool
*/
protected function isXml()
{
return $this->isMode(self::MODE_XML);
}
/**
* Checks if we're in HTML document mode.
*
* @return bool
*/
protected function isHtml()
{
return $this->isMode(self::MODE_HTML);
}
/**
* Checks if we're in XHTML document mode.
*
* @return bool
*/
protected function isXhtml()
{
return $this->isMode(self::MODE_XHTML);
}
/**
* Returns wether we're allowed to do pretty-printing or not currently
*
* @return bool
*/
protected function isPretty()
{
return $this->options['pretty'] && !$this->forceInline;
}
/**
* Checks if a variables is scalar (or "not an expression").
*
* These values don't get much special handling, they are mostly
* simple attributes values like `type="button"` or `method='post'`
*
* A scalar value is either a closed string containing only
* a-z, A-Z, 0-9, _ and -, e.g. Some-Static_Value
* or a quote-enclosed string that can contain anything
* except the quote style it used
* e.g. "Some Random String", 'This can" contain quotes"'
*
* @param string $value the value to be checked
*
* @return bool
*/
protected function isScalar($value)
{
return empty($value) || preg_match('/^([a-z0-9\_\-]+|"[^"]*"|\'[^\']*\')$/i', $value) ? true : false;
}
/**
* Compiles and sanitizes a scalar value.
*
* @param string $value the scalar value
* @param bool|false $inCode is this an attribute value or not
*
* @return string
*/
protected function compileScalar($value, $inCode = false)
{
$sequences = $this->options['escape_sequences'];
foreach ($sequences as $seq => $repl) {
$value = preg_replace('/(?<!\\\\)'.preg_quote($seq, '/').'/', $repl, $value);
}
return $this->interpolate(trim($value, '\'"'), $inCode);
}
/**
* Checks if a value is a variables.
*
* A variables needs to start with $.
* After that only a-z, A-Z and _ can follow
* After that you can use any character of
* a-z, A-Z, 0-9, _, [, ], -, >, ' and "
* This will match all of the following:
*
* $__someVar
* $obj->someProperty
* $arr['someKey']
* $arr[0]
* $obj->someArray['someKey']
* etc.
*
* @param string $value the value to be checked
*
* @return bool
*/
protected function isVariable($value)
{
return preg_match('/^\$[a-z_\$](\$?\w*|\[[^\]]+\]|\->(\$?\w+|\{[^\}]+\}))*$/i', $value) ? true : false;
}
/**
* Interpolates a string value.
*
* Interpolation is initialized with # (escaped) or ! (not escaped)
*
* After that use either {} brackets for variables expressions
* or [] for Jade-expressions
*
* e.g.
*
* #{$someVariable}
* !{$someObj->someProperty}
*
* #[p This is some paragraph]
*
* If the second paragraph is true, the result will act like it is
* inside a string respecting the quoteStyle-option
*
* @param string $string The string to interpolate
* @param bool|false $inCode Is this an attribute value or not
*
* @return string the interpolated PHTML
*/
protected function interpolate($string, $inCode = false)
{
$strlen = function_exists('mb_strlen') ? 'mb_strlen': 'strlen';
$substr = function_exists('mb_substr') ? 'mb_substr' : 'substr';
$brackets = ['[' => ']', '{' => '}'];
foreach ($brackets as $open => $close) {
$match = null;
while (preg_match(
'/([?]?)([#!])'.preg_quote($open, '/').'/',
$string,
$match,
\PREG_OFFSET_CAPTURE
)) {
list(, $start) = $match[0];
list($escapeType) = $match[2];
list($checkType) = $match[1];
$start = $strlen(substr($string, 0, $start + 1)) - 1;
$prefixLen = $strlen($escapeType) + $strlen($checkType) + $strlen($open);
$offset = $start + $prefixLen;
$level = 1;
$subject = '';
do {
$char = $substr($string, $offset, 1);
if ($char === $open)
$level++;
if ($char === $close) {
$level--;
if ($level === 0)
break;
}
$subject .= $char;
$offset++;
} while ($level > 0 && $offset < $strlen($string));
if ($offset >= $strlen($string)) {
$this->throwException(
"Failed to interpolate value [`$subject`], the [`$open`]-bracket is not closed with the [`$close`]-bracket."
);
}
$len = $prefixLen + $strlen($subject) + $strlen($close);
$target = $substr($string, $start, $len);
$replacement = $subject;
switch ($open) {
case '{':
$code = $this->isVariable($subject) && $checkType !== '?'
? "isset($subject) ? $subject : ''"
: $subject;
if ($escapeType !== '!')
$code = "htmlentities($code, \\ENT_QUOTES, '".$this->options['escape_charset']."')";
$replacement = !$inCode ? $this->createShortCode($code) : '\'.('.$code.').\'';
break;
case '[':
//This is a fix for <![endif]--> in IE conditional tags
if (strtolower($subject) === 'endif')
break 2;
$node = $this->parser->parse($subject);
$code = $this->compileNode($node);
if ($escapeType === '!') {
$code = 'htmlentities('.$this->exportScalar($code).', \\ENT_QUOTES, \''.$this->options['escape_charset'].'\')';
$code = !$inCode ? $this->createShortCode($code) : '\'.('.$code.').\'';
}
$replacement = $code;
break;
}
$string = str_replace($target, $replacement, $string);
}
}
return $string;
}
/**
* Returns a new line character respecting the pretty-option.
*
* @return string
*/
protected function newLine()
{
return $this->isPretty() ? "\n" : '';
}
/**
* Returns indentation respecting the current level and the pretty-option.
*
* The $offset will be added to the current level
*
* @param int $offset an offset added to the level
*
* @return string
*/
protected function indent($offset = 0)
{
return $this->isPretty()
? str_repeat($this->options['indent_style'], ($this->level + $offset) * $this->options['indent_width'])
: '';
}
/**
* Creates a PHP code expression.
*
* By default it will have <?php ? >-style
*
* @param string $code the PHP code
* @param string $prefix the PHP start tag
* @param string $suffix the PHP end tag
*
* @return string the PHP expression
*/
protected function createCode($code, $prefix = '<?php ', $suffix = '?>')
{
if (strpos($code, "\n") !== false) {
$this->level++;
$code = implode($this->newLine().$this->indent(), preg_split("/\n[\t ]*/", $code))
.$this->newLine().$this->indent(-1);
$this->level--;
}
return $prefix.$code.$suffix;
}
/**
* Creates a <?=?>-style PHP expression.
*
* @see Compiler->createCode
*
* @param string $code the PHP expression to output
*
* @return string The PHP expression
*/
protected function createShortCode($code)
{
return $this->createCode($code, '<?=');
}
/**
* Creates a PHP comment surrounded by PHP code tags.
*
* This creates a "hidden" comment thats still visible in the PHTML
*
* @todo Maybe this should return an empty string if pretty-option is on?
*
* @param string $text the text to wrap into a comment
*
* @return string the compiled PHP comment
*/
protected function createPhpComment($text)
{
return $this->createCode($text, '<?php /* ', ' */ ?>');
}
/**
* Creates a XML-style comment (<!-- -->).
*
* @param string $text the text to wrap into a comment
*
* @return string the compiled XML comment
*/
protected function createMarkupComment($text)
{
return $this->createCode($text, '<!-- ', ' -->');
}
/**
* Compiles any Node that has a matching method for its type.
*
* e.g.
* type: document, method: compileDocument
* type: element, method: compileElement
*
* The result will be PHTML
*
* @param Node $node the Node to compile
*
* @return string the compiled PHTML
* @throws Exception when the compilation fails
*/
protected function compileNode(Node $node)
{
$method = 'compile'.ucfirst($node->type);
if (!method_exists($this, $method))
$this->throwException(
"No handler $method found for $node->type found. It seems you have customized nodes. You need to ".
"extend the Tale Jade Compiler and add own $method-method for the respective node type.",
$node
);
//resolve expansions
if (isset($node->expands)) {
$current = $node;
while (isset($current->expands)) {
$expandedNode = $current->expands;
unset($current->expands);
$current->parent->insertBefore($current, $expandedNode);
$current->parent->remove($current);
$expandedNode->append($current);
$current = $expandedNode;
}
return $this->compileNode($current);
}
return call_user_func([$this, $method], $node);
}
/**
* Compiles a document Node to PHTML.
*
* @param Node $node The document-type node
*
* @return string the compiled PHTML
*/
protected function compileDocument(Node $node)
{
return $this->compileChildren($node->children, false);
}
/**
* Compiles a doctype Node to PHTML.
*
* @param Node $node the doctype-type node
*
* @return string the compiled PHTML
*/
protected function compileDoctype(Node $node)
{
$name = $node->name;
$value = isset($this->options['doctypes'][$name]) ? $this->options['doctypes'][$name] : '<!DOCTYPE '.$name.'>';
if ($name === 'xml') {
$this->options['mode'] = self::MODE_XML;
if ($this->options['echo_xml_doctype'])
$value = "<?='$value'?>";
} else if (in_array($name, $this->options['xhtml_modes']))
$this->options['mode'] = self::MODE_XHTML;
else
$this->options['mode'] = self::MODE_HTML;
return $value;
}
/**
* Resolves a path respecting the paths given in the options.
*
* The final paths for resolving are put together as follows:
*
* when paths options not empty => Add paths of paths-option
* when paths option empty => Add paths of get_include_path()
* when current file stack not empty => Add directory of last file we
* were compiling
*
* We then look for a path with the given extension inside
* all paths we work on currently
*
* @param string $path the relative path to resolve
* @param array|string $extensions the extensions to resolve with
*