My favorites | Sign in
Project Home Downloads Wiki Issues Source
Repository:
Checkout   Browse   Changes   Clones    
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
<?php

/*
* since there are no callbacks nor namespaces in Php 5.2, all classes are prefixed with JsonTemplate
* and callbacks are faked using the JsonTemplateCallback class
* when version 5.3 is out it would be better to use namespaces and real callbacks
*/

/*
* Base class for all exceptions in this module.
* Thus you can catch JsonTemplateError to catch all exceptions thrown by this module
*/
class JsonTemplateError extends Exception
{
function __construct($msg,$near=null)
{
/*
This helps people debug their templates.

If a variable isn't defined, then some context is shown in the traceback.
TODO: Attach context for other errors.
*/
parent::__construct($msg);
$this->near = $near;
if($this->near){
$this->message .= "\n\nNear: ".$this->near;
}
}
}

/*
* Base class for errors that happen during the compilation stage
*/
class JsonTemplateCompilationError extends JsonTemplateError
{

}

/*
* Base class for errors that happen when expanding the template.
*
* This class of errors generally involve the data array or the execution of
* the formatters.
*/
class JsonTemplateEvaluationError extends JsonTemplateError
{

function __construct($msg,$original_exception=null)
{
parent::__construct($msg);
$this->original_exception = $original_exception;
}
}

/*
* A bad formatter was specified, e.g. {variable|BAD}
*/
class JsonTemplateBadFormatter extends JsonTemplateCompilationError
{

}

/*
* Raised when formatters are required, and a variable is missing a formatter.
*/
class JsonTemplateMissingFormatter extends JsonTemplateCompilationError
{

}

/*
* Raised when the Template options are invalid and it can't even be compiled.
*/
class JsonTemplateConfigurationError extends JsonTemplateCompilationError
{

}

/*
* Syntax error in the template text.
*/
class JsonTemplateTemplateSyntaxError extends JsonTemplateCompilationError
{

}

/*
* The template contains a variable not defined by the data dictionary.
*/
class JsonTemplateUndefinedVariable extends JsonTemplateCompilationError
{

}

/*
* represents a callback since PHP has no equivalent
*/
abstract class JsonTemplateCallback
{
abstract public function call();
}

// calls a function passing all the parameters
class JsonTemplateFunctionCallback extends JsonTemplateCallback
{
protected $function = '';
protected $args = array();

function __construct()
{
$args = func_get_args();
$this->function = array_shift($args);
$this->args = $args;
}

function call()
{
$args = func_get_args();
$args = array_merge($this->args,$args);
return call_user_func_array($this->function,$args);
}
}

// stores the first parameter in an array
class JsonTemplateStackCallback extends JsonTemplateCallback
{
protected $stack = array();

function call()
{
$this->stack[] = func_get_arg(0);
}

function get()
{
return $this->stack;
}
}

class JsonTemplateModuleCallback extends JsonTemplateFunctionCallback
{
function call()
{
$module = JsonTemplateModule::pointer();
$args = func_get_args();
$args = array_merge($this->args,$args);
return call_user_func_array(array($module,$this->function),$args);
}
}

/*
* Receives method calls from the parser, and constructs a tree of JsonTemplateSection
* instances.
*/

class JsonTemplateProgramBuilder
{
/*
more_formatters: A function which returns a function to apply to the
value, given a format string. It can return null, in which case the
DefaultFormatters class is consulted.
*/
function __construct($more_formatters)
{
$this->current_block = new JsonTemplateSection();
$this->stack = array($this->current_block);
$this->more_formatters = $more_formatters;
}

// statement: Append a literal
function Append($statement)
{
$this->current_block->Append($statement);
}

// The user's formatters are consulted first, then the default formatters.
private function GetFormatter($format_str)
{
$func = $this->more_formatters;
if($func instanceof JsonTemplateCallback){
$formatter = $func->call($format_str);
}elseif(is_array($func)){
$formatter = $func[$format_str];
}elseif(function_exists($func)){
$formatter = $func($format_str);
}
if(!$formatter){
$formatter = JsonTemplateModule::pointer()->default_formatters[$format_str];
}
if($formatter){
return $formatter;
}else{
throw new JsonTemplateBadFormatter(sprintf('%s is not a valid formatter', $format_str));
}
}

function AppendSubstitution($name, $formatters)
{
foreach($formatters as $k=>$f){
$formatters[$k] = $this->GetFormatter($f);
}
$this->current_block->Append(new JsonTemplateModuleCallback('DoSubstitute', $name, $formatters));

}

// For sections or repeated sections
function NewSection($repeated, $section_name)
{
$new_block = new JsonTemplateSection($section_name);
if($repeated){
$func = 'DoRepeatedSection';
}else{
$func = 'DoSection';
}
$this->current_block->Append(new JsonTemplateModuleCallback($func, $new_block));
$this->stack[] = $new_block;
$this->current_block = $new_block;
}

/*
* TODO: throw errors if the clause isn't appropriate for the current block
* isn't a 'repeated section' (e.g. alternates with in a non-repeated
* section)
*/
function NewClause($name)
{
$this->current_block->NewClause($name);
}

function EndSection()
{
array_pop($this->stack);
$this->current_block = end($this->stack);
}

function Root()
{
return $this->current_block;
}
}

// Represents a (repeated) section.
class JsonTemplateSection
{
/*
* Args:
* section_name: name given as an argument to the section
*/
function __construct($section_name=null)
{
$this->section_name = $section_name;
$this->current_clause = array();
$this->statements = array('default'=>&$this->current_clause);
}

function __toString()
{
try{
return sprintf('<Block %s>', $this->section_name);
}catch(Exception $e){
return $e->getMessage();
}
}

function Statements($clause='default')
{
return $this->statements[$clause];
}

function NewClause($clause_name)
{
$new_clause = array();
$this->statements[$clause_name] = &$new_clause;
$this->current_clause = &$new_clause;
}

// Append a statement to this block.
function Append($statement)
{
array_push($this->current_clause, $statement);
}
}


/*
* Allows scoped lookup of variables.
* If the variable isn't in the current context, then we search up the stack.
*/
class JsonTemplateScopedContext implements Iterator
{
protected $positions = array();

function __construct($context,$undefined_str=null)
{
$this->undefined_str=$undefined_str;
$this->stack = array($context);
$this->name_stack = array('@');
}

function __toString()
{
return sprintf("<Context %s>",implode(" ",$this->name_stack));
}

function PushSection($name)
{
$end = end($this->stack);
if(is_array($end)){
if(isset($end[$name])){
$new_context = $end[$name];
}else{
return false;
}
}elseif(is_object($end)){
// since json_decode returns StdClass
// check if scope is an object
if(property_exists($end,$name)){
$new_context = $end->$name;
}else{
return false;
}
}else{
return false;
}
$this->name_stack[] = $name;
$this->stack[] = $new_context;
return $new_context;
}

function Pop()
{
array_pop($this->name_stack);
return array_pop($this->stack);
}

function CursorValue()
{
return end($this->stack);
}

// Iterator functions
// Assumes that the top of the stack is a list.
// NOTE: Iteration alters scope
function rewind() {
$this->positions[] = 0;
$this->stack[] = array();
}

function current() {
return end($this->stack);
}

function key() {
return end($this->positions);
}

function next() {
++$this->positions[count($this->positions)-1];
}

function valid() {
$len = count($this->stack);
$pos = end($this->positions);
$items = $this->stack[$len-2];
if(is_array($items) && count($items)>$pos){
$this->stack[$len-1] = $items[$pos];
return true;
}else{
array_pop($this->stack);
array_pop($this->positions);
return false;
}
}

function Undefined($name) {
if ($this->undefined_str === null) {
throw new JsonTemplateUndefinedVariable(sprintf('%s is not defined',$name));
} else {
return $this->undefined_str;
}
}

// Get the value associated with a name in the current context. The current
// context could be an associative array or a StdClass object
function Lookup($name) {
if ($name == '@') {
return end($this->stack);
}
$parts = explode('.',$name);
$value = $this->_LookUpStack($parts[0]);
$count=count($parts);
if ($count > 1) {
for ($i = 1; $i < $count; $i++) {
$namepart=$parts[$i];
if(is_array($value)){
if(!isset($value[$namepart])){
return $this->Undefined($name);
}else{
$value= $value[$namepart];
}
}elseif(is_object($value)){
if(!property_exists($value,$namepart)){
return $this->Undefined($name);
}else{
$value= $value->$namepart;
}
} else {
return $this->Undefined($name);
}
}
}
return $value;
}

function _LookUpStack($name)
{
$i = count($this->stack)-1;
while(true){
$context = $this->stack[$i];
if ($name=='@index'){
$key=$this->key();
if($key==-1){
$i--;
} else {
return $key+1; // @index is 1-based
}
} else {
if(is_array($context)){
if(!isset($context[$name])){
$i -= 1;
}else{
return $context[$name];
}
}elseif(is_object($context)){
if(!property_exists($context,$name)){
$i -= 1;
}else{
return $context->$name;
}
}else{
$i -= 1;
}
}
if($i<= -1){
return $this->Undefined($name);
}
}
}
}


# See http://google-ctemplate.googlecode.com/svn/trunk/doc/howto.html for more
# escape types.
#
# Also, we might want to take a look at Django filters.
abstract class JsonTemplateFormatter
{
abstract public function format($obj);
}

class HtmlJsonTemplateFormatter extends JsonTemplateFormatter
{
function format($str)
{
return htmlspecialchars($str,ENT_NOQUOTES);
}
}

class HtmlAttributeValueJsonTemplateFormatter extends JsonTemplateFormatter
{
function format($str)
{
return htmlspecialchars($str);
}

}

class RawJsonTemplateFormatter extends JsonTemplateFormatter
{
function format($str)
{
return $str;
}
}

class StringJsonTemplateFormatter extends JsonTemplateFormatter
{
function format($str)
{
if ($str===null)
return 'null';
return (string)$str;
}
}

class SizeJsonTemplateFormatter extends JsonTemplateFormatter
{
# Used for the length of an array or a string
function format($obj)
{
if(is_string($obj)){
return strlen($obj);
}else{
return count($obj);
}
}
}

class UrlParamsJsonTemplateFormatter extends JsonTemplateFormatter
{
# The argument is an associative array, and we get a a=1&b=2 string back.
function format($params)
{
if(is_array($parmas)){
foreach($params as $k=>$v){
$parmas[$k] = urlencode($k)."=".urlencode($v);
}
return implode("&",$params);
}else{
return urlencode($params);
}
}
}

class UrlParamValueJsonTemplateFormatter extends JsonTemplateFormatter
{
# The argument is a string 'Search query?' -> 'Search+query%3F'
function format($param)
{
return urlencode($param);
}

}

class JsonTemplateModule
{

public $section_re = '/(repeated)?\s*(section)\s+(\S+)/';
public $option_re = '/^([a-zA-Z\-]+):\s*(.*)/';
public $option_names = array('meta','format-char','default-formatter');
public $token_re_cache = array();

public $default_formatters = array(
'html' => 'HtmlJsonTemplateFormatter',
'html-attr-value' => 'HtmlAttributeValueJsonTemplateFormatter',
'htmltag' => 'HtmlAttributeValueJsonTemplateFormatter',
'raw' => 'RawJsonTemplateFormatter',
'size' => 'SizeJsonTemplateFormatter',
'url-params' => 'UrlParamsJsonTemplateFormatter',
'url-param-value' => 'UrlParamValueJsonTemplateFormatter',
'str' => 'StringJsonTemplateFormatter',
'default_formatter' => 'RawJsonTemplateFormatter',
);

static function &pointer()
{
static $singleton = null;
if(!$singleton){
$singleton = new JsonTemplateModule();
}
return $singleton;
}

/*
* Split and validate metacharacters.
*
* Example: '{}' -> ('{', '}')
*
* This is public so the syntax highlighter and other tools can use it.
*/
function SplitMeta($meta)
{
$n = strlen($meta);
if($n % 2 == 1){
throw new JsonTemplateConfigurationError(sprintf('%s has an odd number of metacharacters', $meta));
}
return array(substr($meta,0,$n/2),substr($meta,$n/2));
}

/* Return a regular expression for tokenization.
* Args:
* meta_left, meta_right: e.g. '{' and '}'
*
* - The regular expressions are memoized.
* - This function is public so the syntax highlighter can use it.
*/
function MakeTokenRegex($meta_left, $meta_right)
{
$key = $meta_left.$meta_right;
if(!in_array($key,array_keys($this->token_re_cache))){
$this->token_re_cache[$key] = '/('.preg_quote($meta_left).'.+?'.preg_quote($meta_right).'\n?)/';
}
return $this->token_re_cache[$key];
}

/*
Compile the template string, calling methods on the 'program builder'.

Args:
template_str: The template string. It should not have any compilation
options in the header -- those are parsed by FromString/FromFile
options: array of compilation options, possible keys are:
meta: The metacharacters to use
more_formatters: A function which maps format strings to
*other functions*. The resulting functions should take a data
array value (a JSON atom, or an array itself), and return a
string to be shown on the page. These are often used for HTML escaping,
etc. There is a default set of formatters available if more_formatters
is not passed.
default_formatter: The formatter to use for substitutions that are missing a
formatter. The 'str' formatter the "default default" -- it just tries
to convert the context value to a string in some unspecified manner.
builder: Something with the interface of JsonTemplateProgramBuilder

Returns:
The compiled program (obtained from the builder)

Throws:
The various subclasses of JsonTemplateCompilationError. For example, if
default_formatter=null, and a variable is missing a formatter, then
MissingFormatter is raised.

This function is public so it can be used by other tools, e.g. a syntax
checking tool run before submitting a template to source control.
*/
function CompileTemplate($template_str, $options=array(), $builder=null)
{
$options=JsonTemplate::processDefaultOptions($options);

if(!$builder){
$builder = new JsonTemplateProgramBuilder($options['more_formatters']);
}
list($meta_left,$meta_right) = $this->SplitMeta($options['meta']);

# : is meant to look like Python 3000 formatting {foo:.3f}. According to
# PEP 3101, that's also what .NET uses.
# | is more readable, but, more importantly, reminiscent of pipes, which is
# useful for multiple formatters, e.g. {name|js-string|html}
if(!in_array($options['format_char'],array(':','|'))){
throw new JsonTemplateConfigurationError(sprintf('Only format characters : and | are accepted (got %s)',$options['format_char']));
}

# Need () for preg_split
$token_re = $this->MakeTokenRegex($meta_left, $meta_right);
$tokens = preg_split($token_re, $template_str, -1, PREG_SPLIT_DELIM_CAPTURE);

# If we go to -1, then we got too many {end}. If end at 1, then we're missing
# an {end}.
$balance_counter = 0;
foreach($tokens as $i=>$token){
if(($i % 2) == 0){
if($token){
$builder->Append($token);
}
}else{
$had_newline = false;
if(substr($token,-1)=="\n"){
$token = substr($token,0,-1);
$had_newline = true;
}

assert('substr($token,0,strlen($meta_left)) == $meta_left;');
assert('substr($token,-1*strlen($meta_right)) == $meta_right;');

$token = substr($token,strlen($meta_left),-1*strlen($meta_right));


// if it is a comment
if(substr($token,0,1)=="#"){
continue;
}

$literal='';
// if it's a keyword directive
if(substr($token,0,1)=='.'){
$token = substr($token,1);
switch($token){
case 'meta-left':
$literal = $meta_left;
break;
case 'meta-right':
$literal = $meta_right;
break;
case 'space':
$literal = ' ';
break;
case 'tab':
$literal = "\t";
break;
case 'newline':
$literal = "\n";
break;
}
}
if($literal){
$builder->Append($literal);
continue;
}

if(preg_match($this->section_re,$token,$match)){
$builder->NewSection($match[1],$match[3]);
$balance_counter += 1;
continue;
}

if(in_array($token,array('or','alternates with'))){
$builder->NewClause($token);
continue;
}

if($token == 'end'){
$balance_counter -= 1;
if($balance_counter < 0){
# TODO: Show some context for errors
throw new JsonTemplateTemplateSyntaxError(sprintf(
'Got too many %s.end%s statements. You may have mistyped an '.
"earlier %s.section%s or %s.repeated section%s directive.",
$meta_left, $meta_right,$meta_left, $meta_right,$meta_left, $meta_right));
}
$builder->EndSection();
if($had_newline){
$builder->Append("\n");
}
continue;
}

# Now we know the directive is a substitution.
$parts = explode($options['format_char'],$token);
if(count($parts) == 1){
if(!$options['default_formatter']){
throw new JsonTemplateMissingFormatter('This template requires explicit formatters.');
# If no formatter is specified, the default is the 'str' formatter,
# which the user can define however they desire.
}
$name = $token;
$formatters = array($options['default_formatter']);
}else{
$name = array_shift($parts);
$formatters = $parts;
}

$builder->AppendSubstitution($name,$formatters);
if($had_newline){
$builder->Append("\n");
}
}
}

if($balance_counter != 0){
throw new JsonTemplateTemplateSyntaxError(sprintf('Got too few %send%s statements', $meta_left, $meta_right));
}
return $builder->Root();
}


// Like FromString, but takes a file.
static function FromFile($f, $constructor='JsonTemplate')
{
if(is_string($f)){
$string = file_get_contents($f);
}else{
while(!feof($f)){
$string .= fgets($f,1024)."\n";
}
}
return $this->FromString($string,$constructor);
}

/*
Parse a template from a string, using a simple file format.

This is useful when you want to include template options in a data file,
rather than in the source code.

The format is similar to HTTP or E-mail headers. The first lines of the file
can specify template options, such as the metacharacters to use. One blank
line must separate the options from the template body.

Example:

default-formatter: none
meta: {{}}
format-char: :
<blank line required>
Template goes here: {{variable:html}}
*/

function FromString($string, $constructor='JsonTemplate')
{
$options = array();
$lines = explode("\n",$string);
foreach($lines as $k=>$line){
if(preg_match($this->option_re,$line,$match)){
# Accept something like 'Default-Formatter: raw'. This syntax is like
# HTTP/E-mail headers.
$name = strtolower($match[1]);
$value = trim($match[2]);
if(in_array($name,$this->option_names)){
$name = str_replace('-','_',$name);
if($name == 'default_formatter' && strtolower($value) == 'none'){
$value = null;
}
$options[$name] = $value;
}else{
break;
}
}else{
break;
}
}

if($options){
if(trim($line)){
throw new JsonTemplateCompilationError(sprintf(
'Must be one blank line between template options and body (got %s)',$line));
}
$body = implode("\n",array_slice($lines,$k+1));
}else{
# There were no options, so no blank line is necessary.
$body = $string;
}
return new $constructor($body,$options);
}

// {repeated section foo}
function DoRepeatedSection($args, $context, $callback)
{
$block = $args;

if($block->section_name == '@'){
# If the name is @, we stay in the enclosing context, but assume it's a
# list, and repeat this block many times.
$items = $context->Lookup('@');
if(!is_array($items)){
throw new JsonTemplateEvaluationError(sprintf('Expected a list; got %s', gettype($items)));
}
$pushed = false;
}else{
$items = $context->PushSection($block->section_name);
$pushed = true;
}

if($items){
$last_index = count($items) - 1;
$statements = $block->Statements();
$alt_statements = $block->Statements('alternates with');
# NOTE: Iteration mutates the context!
foreach($context as $i=>$data){
# Execute the statements in the block for every item in the list. Execute
# the alternate block on every iteration except the last.
# Each item could be an atom (string, integer, etc.) or a dictionary.
$this->Execute($statements, $context, $callback);
if($i != $last_index){
$this->Execute($alt_statements, $context, $callback);
}
}
}else{
$this->Execute($block->Statements('or'), $context, $callback);
}

if($pushed){
$context->Pop();
}

}

// {section foo}
function DoSection($args, $context, $callback)
{
$block = $args;
# If a section isn't present in the dictionary, or is None, then don't show it
# at all.
if($context->PushSection($block->section_name)){
$this->Execute($block->Statements(), $context, $callback);
$context->Pop();
}else{
# empty list, none, false, etc.
# $context->Pop();
$this->Execute($block->Statements('or'), $context, $callback);
}
}

// Variable substitution, e.g. {foo}
function DoSubstitute($name, $formatters, $context, $callback=null)
{
if(!($context instanceof JsonTemplateScopedContext)){
throw new JsonTemplateEvaluationError(sprintf('Error not valid context %s',$context));
}
# So we can have {.section is_new}new since {@}{.end}. Hopefully this idiom
# is OK.

if($name == '@'){
$value = $context->CursorValue();
}else{
try{
$value = $context->Lookup($name);
}catch(JsonTemplateUndefinedVariable $e){
throw $e;
}catch(Exception $e){
throw new JsonTemplateEvaluationError(sprintf(
'Error evaluating %s in context %s: %s', $name, $context, $e->getMessage()
));
}
}

foreach($formatters as $f){
try{
$formatter = new $f();
$value = $formatter->format($value);
}catch(Exception $e){
throw new JsonTemplateEvaluationError(sprintf(
'Formatting value %s with formatter %s raised exception: %s',
$value, $f, $e), $e);
}
}
if($callback instanceof JsonTemplateCallback){
return $callback->call($value);
}elseif(is_string($callback)){
return $callback($value);
}else{
return $value;
}
}

/*
* Execute a bunch of template statements in a ScopedContext.
* Args:
* callback: Strings are "written" to this callback function.
*
* This is called in a mutually recursive fashion.
*/
function Execute($statements, $context, $callback)
{
if(!is_array($statements)){
$statements = array($statements);
}
foreach($statements as $i=>$statement){
if(is_string($statement)){
if($callback instanceof JsonTemplateCallback){
$callback->call($statement);
}elseif(is_string($callback)){
$callback($statement);
}
}else{
try{
if($statement instanceof JsonTemplateCallback){
$statement->call($context, $callback);
}
}catch(JsonTemplateUndefinedVariable $e){
# Show context for statements
$start = max(0,$i-3);
$end = $i+3;
$e->near = array_slice($statements,$start,$end);
throw $e;
}
}
}
}

/*
Free function to expands a template string with a data dictionary.

This is useful for cases where you don't care about saving the result of
compilation (similar to re.match('.*', s) vs DOT_STAR.match(s))
*/
function expand($template_str, $data, $options=array())
{
$t = new JsonTemplate($template_str, $options);
return $t->expand($data);
}

}


/*
Represents a compiled template.

Like many template systems, the template string is compiled into a program,
and then it can be expanded any number of times. For example, in a web app,
you can compile the templates once at server startup, and use the expand()
method at request handling time. expand() uses the compiled representation.

There are various options for controlling parsing -- see CompileTemplate.
Don't go crazy with metacharacters. {}, [], {{}} or <> should cover nearly
any circumstance, e.g. generating HTML, CSS XML, JavaScript, C programs, text
files, etc.
*/

class JsonTemplate
{
protected $program;

/*
* This function add the passed options to the default options.
* If the passed options are in object form, they are converted
* to associative array form first, so the class can always
* access options in the array notation.
*/
static function processDefaultOptions($options){
if(is_string($options)){
$options = json_decode($options);
}
$default_options = array(
'undefined_str' => null,
'meta' => '{}',
'format_char' => '|',
'more_formatters' => null,
'default_formatter' => 'str',
);
if(is_object($options)){
$options = array_merge($default_options,get_object_vars($options));
}else if(is_array($options)){
$options = array_merge($default_options,$options);
}else{
$options = $default_options;
}
return $options;
}
/*
Args:
template_str: The template string.

It also accepts all the compile options that CompileTemplate does.
*/
function __construct($template_str, $options=array(), $builder=null)
{
$options=self::processDefaultOptions($options);

$this->compile_options=$options;
$this->template_str = $template_str;
$this->program = JsonTemplateModule::pointer()->CompileTemplate($template_str, $options, $builder);
}

#
# Public API
#

/*
Low level method to expands the template piece by piece.

Args:
data: The JSON data dictionary.
callback: A callback which should be called with each expanded token.

Example: You can pass 'f.write' as the callback to write directly to a file
handle.
*/
function render($data, $callback=null)
{
if(is_string($data)){
$data = json_decode($data);
}
$JM=JsonTemplateModule::pointer();
return $JM->Execute(
$this->program->Statements(),
new JsonTemplateScopedContext($data,$this->compile_options['undefined_str']),
$callback
);
}

/*
Expands the template with the given data dictionary, returning a string.

This is a small wrapper around render(), and is the most convenient
interface.

Args:
data_dict: The JSON data dictionary.

Returns:
The return value could be a str() or unicode() instance, depending on the
the type of the template string passed in, and what the types the strings
in the dictionary are.
*/
function expand($data)
{
return implode('',$this->tokenstream($data));
}

/*
returns a list of tokens resulting from expansion.
*/
function tokenstream($data)
{
$c = new JsonTemplateStackCallback();
$tokens = $this->render($data,$c);
return $c->get();
}
}

?>

Change log

2871627c3dc8 by sroussey on Oct 9, 2009   Diff
Fix up my previous commits related to
escaping meta chars.

Fix tests for meta chars.

Fix PHP bug discovered by new tests (that
actually run).
Go to: 
Project members, sign in to write a code review

Older revisions

be5e676b86a1 by "Andy Chu <a...@chubot.org> on Oct 5, 2009   Diff
- Change $index to @index.  {@index}
is like {@} -- "the index we're _at_"
- Make it 1-based
95684c9cf940 by sroussey on Oct 5, 2009   Diff
Fix broken implementation of meta-
left, et al
856b30882605 by sroussey on Oct 1, 2009   Diff
Make PHP file easily used for projects
without need of editing, moved test
code to _cmd file to drive it from the
command line.
All revisions of this file

File info

Size: 27372 bytes, 1091 lines
Powered by Google Project Hosting