-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathHelpers.php
More file actions
executable file
·800 lines (750 loc) · 25.6 KB
/
Helpers.php
File metadata and controls
executable file
·800 lines (750 loc) · 25.6 KB
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
<?php
/**
* Helpers
*
* a collection of helper function. normally a function like
* function ($sender, $name, $arguments) $arguments is unscaped arguments and
* is a string, not array
*
* @category Xamin
* @package Handlebars
* @author fzerorubigd <fzerorubigd@gmail.com>
* @author Behrooz Shabani <everplays@gmail.com>
* @author Mardix <https://github.com/mardix>
* @copyright 2012 (c) ParsPooyesh Co
* @copyright 2013 (c) Behrooz Shabani
* @copyright 2014 (c) Mardix
* @license MIT
* @link http://voodoophp.org/docs/handlebars
*/
namespace Handlebars;
use DateTime;
use InvalidArgumentException;
use Traversable;
use LogicException;
class Helpers
{
/**
* @var array array of helpers
*/
protected $helpers = [];
private $tpl = [];
protected $builtinHelpers = [
"if",
"each",
"with",
"unless",
"bindAttr",
"upper", // Put all chars in uppercase
"lower", // Put all chars in lowercase
"capitalize", // Capitalize just the first word
"capitalize_words", // Capitalize each words
"reverse", // Reverse a string
"format_date", // Format a date
"inflect", // Inflect the wording based on count ie. 1 album, 10 albums
"default", // If a variable is null, it will use the default instead
"truncate", // Truncate section
"raw", // Return the source as is without converting
"repeat", // Repeat a section
"define", // Define a block to be used using "invoke"
"invoke", // Invoke a block that was defined with "define"
];
/**
* Create new helper container class
*
* @param array $helpers array of name=>$value helpers
* @throws \InvalidArgumentException when $helpers is not an array
* (or traversable) or helper is not a callable
*/
public function __construct($helpers = null)
{
foreach($this->builtinHelpers as $helper) {
$helperName = $this->underscoreToCamelCase($helper);
$this->add($helper, [$this, "helper{$helperName}"]);
}
if ($helpers != null) {
if (!is_array($helpers) && !$helpers instanceof Traversable) {
throw new InvalidArgumentException(
'HelperCollection constructor expects an array of helpers'
);
}
foreach ($helpers as $name => $helper) {
$this->add($name, $helper);
}
}
}
/**
* Add a new helper to helpers
*
* @param string $name helper name
* @param callable $helper a function as a helper
*
* @throws \InvalidArgumentException if $helper is not a callable
* @return void
*/
public function add($name, $helper)
{
if (!is_callable($helper)) {
throw new InvalidArgumentException("$name Helper is not a callable.");
}
$this->helpers[$name] = $helper;
}
/**
* Check if $name helper is available
*
* @param string $name helper name
*
* @return boolean
*/
public function has($name)
{
return array_key_exists($name, $this->helpers);
}
/**
* Get a helper. __magic__ method :)
*
* @param string $name helper name
*
* @throws \InvalidArgumentException if $name is not available
* @return callable helper function
*/
public function __get($name)
{
if (!$this->has($name)) {
throw new InvalidArgumentException('Unknown helper :' . $name);
}
return $this->helpers[$name];
}
/**
* Check if $name helper is available __magic__ method :)
*
* @param string $name helper name
*
* @return boolean
* @see Handlebras_Helpers::has
*/
public function __isset($name)
{
return $this->has($name);
}
/**
* Add a new helper to helpers __magic__ method :)
*
* @param string $name helper name
* @param callable $helper a function as a helper
*
* @return void
*/
public function __set($name, $helper)
{
$this->add($name, $helper);
}
/**
* Unset a helper
*
* @param string $name helper name to remove
* @return void
*/
public function __unset($name)
{
unset($this->helpers[$name]);
}
/**
* Check whether a given helper is present in the collection.
*
* @param string $name helper name
* @throws \InvalidArgumentException if the requested helper is not present.
* @return void
*/
public function remove($name)
{
if (!$this->has($name)) {
throw new InvalidArgumentException('Unknown helper: ' . $name);
}
unset($this->helpers[$name]);
}
/**
* Clear the helper collection.
*
* Removes all helpers from this collection
*
* @return void
*/
public function clear()
{
$this->helpers = [];
}
/**
* Check whether the helper collection is empty.
*
* @return boolean True if the collection is empty
*/
public function isEmpty()
{
return empty($this->helpers);
}
/**
* Create handler for the 'if' helper.
*
* {{#if condition}}
* Something here
* {{else if condition}}
* something else if here
* {{else if condition}}
* something else if here
* {{else}}
* something else here
* {{/if}}
*
* @param \Handlebars\Template $template template that is being rendered
* @param \Handlebars\Context $context context object
* @param array $args passed arguments to helper
* @param string $source part of template that is wrapped
* within helper
*
* @return mixed
*/
public function helperIf($template, $context, $args, $source)
{
$tpl = $template->getEngine()->loadString('{{#if ' . $args . '}}' . $source . '{{/if}}');
$tree = $tpl->getTree();
$tmp = $context->get($args);
if ($tmp) {
$token = 'else';
foreach ($tree[0]['nodes'] as $node) {
$name = trim(isset($node['name']) ? $node['name'] : '');
if ($name && substr($name, 0, 7) == 'else if') {
$token = $node['name'];
break;
}
}
$template->setStopToken($token);
$buffer = $template->render($context);
$template->setStopToken(false);
$template->discard();
return $buffer;
} else {
foreach ($tree[0]['nodes'] as $key => $node) {
$name = trim(isset($node['name']) ? $node['name'] : '');
if ($name && substr($name, 0, 7) == 'else if') {
$template->setStopToken($node['name']);
$template->discard();
$template->setStopToken(false);
$args = $this->parseArgs($context, substr($name, 7));
$token = 'else';
$remains = array_slice($tree[0]['nodes'], $key + 1);
foreach ($remains as $remain) {
$name = trim(isset($remain['name']) ? $remain['name'] : '');
if ($name && substr($name, 0, 7) == 'else if') {
$token = $remain['name'];
break;
}
}
if (isset($args[0]) && $args[0]) {
$template->setStopToken($token);
$buffer = $template->render($context);
$template->setStopToken(false);
$template->discard();
return $buffer;
} else if ($token != 'else') {
continue;
} else {
return $this->renderElse($template, $context);
}
}
}
return $this->renderElse($template, $context);
}
}
/**
* Create handler for the 'each' helper.
* example {{#each people}} {{name}} {{/each}}
* example with slice: {{#each people[0:10]}} {{name}} {{/each}}
* example with else
* {{#each Array}}
* {{.}}
* {{else}}
* Nothing found
* {{/each}}
*
* @param \Handlebars\Template $template template that is being rendered
* @param \Handlebars\Context $context context object
* @param array $args passed arguments to helper
* @param string $source part of template that is wrapped
* within helper
*
* @return mixed
*/
public function helperEach($template, $context, $args, $source)
{
list($keyname, $slice_start, $slice_end) = $this->extractSlice($args);
$tmp = $context->get($keyname);
if (is_array($tmp) || $tmp instanceof Traversable) {
$tmp = array_slice($tmp, isset($slice_start) ? $slice_start : 0, $slice_end, true);
$buffer = '';
$islist = array_values($tmp) === $tmp;
if (is_array($tmp) && ! count($tmp)) {
return $this->renderElse($template, $context);
} else {
$itemCount = -1;
if ($islist) {
$itemCount = count($tmp);
}
foreach ($tmp as $key => $var) {
$tpl = clone $template;
if ($islist) {
$context->pushIndex($key);
// If data variables are enabled, push the data related to this #each context
if ($template->getEngine()->isDataVariablesEnabled()) {
$context->pushData([
Context::DATA_KEY => $key,
Context::DATA_INDEX => $key,
Context::DATA_LAST => $key == ($itemCount - 1),
Context::DATA_FIRST => $key == 0,
]);
}
} else {
$context->pushKey($key);
// If data variables are enabled, push the data related to this #each context
if ($template->getEngine()->isDataVariablesEnabled()) {
$context->pushData([
Context::DATA_KEY => $key,
]);
}
}
$context->push($var);
$tpl->setStopToken('else');
$buffer .= $tpl->render($context);
$context->pop();
if ($islist) {
$context->popIndex();
} else {
$context->popKey();
}
if ($template->getEngine()->isDataVariablesEnabled()) {
$context->popData();
}
}
return $buffer;
}
} else {
return $this->renderElse($template, $context);
}
}
/**
* Applying the DRY principle here.
* This method help us render {{else}} portion of a block
* @param \Handlebars\Template $template
* @param \Handlebars\Context $context
* @return string
*/
private function renderElse($template, $context)
{
$template->setStopToken('else');
$template->discard();
$template->setStopToken(false);
return $template->render($context);
}
/**
* Create handler for the 'unless' helper.
* {{#unless condition}}
* Something here
* {{else}}
* something else here
* {{/unless}}
* @param \Handlebars\Template $template template that is being rendered
* @param \Handlebars\Context $context context object
* @param array $args passed arguments to helper
* @param string $source part of template that is wrapped
* within helper
*
* @return mixed
*/
public function helperUnless($template, $context, $args, $source)
{
$tmp = $context->get($args);
if (!$tmp) {
$template->setStopToken('else');
$buffer = $template->render($context);
$template->setStopToken(false);
$template->discard();
return $buffer;
} else {
return $this->renderElse($template, $context);
}
}
/**
* Create handler for the 'with' helper.
* Needed for compatibility with PHP 5.2 since it doesn't support anonymous
* functions.
*
* @param \Handlebars\Template $template template that is being rendered
* @param \Handlebars\Context $context context object
* @param array $args passed arguments to helper
* @param string $source part of template that is wrapped
* within helper
*
* @return mixed
*/
public function helperWith($template, $context, $args, $source)
{
$tmp = $context->get($args);
$context->push($tmp);
$buffer = $template->render($context);
$context->pop();
return $buffer;
}
/**
* Create handler for the 'bindAttr' helper.
* Needed for compatibility with PHP 5.2 since it doesn't support anonymous
* functions.
*
* @param \Handlebars\Template $template template that is being rendered
* @param \Handlebars\Context $context context object
* @param array $args passed arguments to helper
* @param string $source part of template that is wrapped
* within helper
*
* @return mixed
*/
public function helperBindAttr($template, $context, $args, $source)
{
return $args;
}
/**
* To uppercase string
*
* {{#upper data}}
*
* @param \Handlebars\Template $template template that is being rendered
* @param \Handlebars\Context $context context object
* @param array $args passed arguments to helper
* @param string $source part of template that is wrapped
* within helper
*
* @return string
*/
public function helperUpper($template, $context, $args, $source)
{
return strtoupper($context->get($args));
}
/**
* To lowercase string
*
* {{#lower data}}
*
* @param \Handlebars\Template $template template that is being rendered
* @param \Handlebars\Context $context context object
* @param array $args passed arguments to helper
* @param string $source part of template that is wrapped
* within helper
*
* @return string
*/
public function helperLower($template, $context, $args, $source)
{
return strtolower($context->get($args));
}
/**
* to capitalize first letter
*
* {{#capitalize}}
*
* @param \Handlebars\Template $template template that is being rendered
* @param \Handlebars\Context $context context object
* @param array $args passed arguments to helper
* @param string $source part of template that is wrapped
* within helper
*
* @return string
*/
public function helperCapitalize($template, $context, $args, $source)
{
return ucfirst($context->get($args));
}
/**
* To capitalize first letter in each word
*
* {{#capitalize_words data}}
*
* @param \Handlebars\Template $template template that is being rendered
* @param \Handlebars\Context $context context object
* @param array $args passed arguments to helper
* @param string $source part of template that is wrapped
* within helper
*
* @return string
*/
public function helperCapitalizeWords($template, $context, $args, $source)
{
return ucwords($context->get($args));
}
/**
* To reverse a string
*
* {{#reverse data}}
*
* @param \Handlebars\Template $template template that is being rendered
* @param \Handlebars\Context $context context object
* @param array $args passed arguments to helper
* @param string $source part of template that is wrapped
* within helper
*
* @return string
*/
public function helperReverse($template, $context, $args, $source)
{
return strrev($context->get($args));
}
/**
* Format a date
*
* {{#format_date date 'Y-m-d @h:i:s'}}
*
* @param \Handlebars\Template $template template that is being rendered
* @param \Handlebars\Context $context context object
* @param array $args passed arguments to helper
* @param string $source part of template that is wrapped
* within helper
*
* @return mixed
*/
public function helperFormatDate($template, $context, $args, $source)
{
preg_match("/(.*?)\s+(?:(?:\"|\')(.*?)(?:\"|\'))/", $args, $m);
$keyname = $m[1];
$format = $m[2];
$date = $context->get($keyname);
if ($format) {
$dt = new DateTime;
if (is_numeric($date)) {
$dt = (new DateTime)->setTimestamp($date);
} else {
$dt = new DateTime($date);
}
return $dt->format($format);
} else {
return $date;
}
}
/**
* {{inflect count 'album' 'albums'}}
* {{inflect count '%d album' '%d albums'}}
*
* @param \Handlebars\Template $template template that is being rendered
* @param \Handlebars\Context $context context object
* @param array $args passed arguments to helper
* @param string $source part of template that is wrapped
* within helper
*
* @return mixed
*/
public function helperInflect($template, $context, $args, $source)
{
preg_match("/(.*?)\s+(?:(?:\"|\')(.*?)(?:\"|\'))\s+(?:(?:\"|\')(.*?)(?:\"|\'))/", $args, $m);
$keyname = $m[1];
$singular = $m[2];
$plurial = $m[3];
$value = $context->get($keyname);
$inflect = ($value <= 1) ? $singular : $plurial;
return sprintf($inflect, $value);
}
/**
* Provide a default fallback
*
* {{default title "No title available"}}
*
* @param \Handlebars\Template $template template that is being rendered
* @param \Handlebars\Context $context context object
* @param array $args passed arguments to helper
* @param string $source part of template that is wrapped
* within helper
*
* @return string
*/
public function helperDefault($template, $context, $args, $source)
{
preg_match("/(.*?)\s+(?:(?:\"|\')(.*?)(?:\"|\'))/", trim($args), $m);
$keyname = $m[1];
$default = $m[2];
$value = $context->get($keyname);
return ($value) ?: $default;
}
/**
* Truncate a string to a length, and append and ellipsis if provided
* {{#truncate content 5 "..."}}
*
*
* @param \Handlebars\Template $template template that is being rendered
* @param \Handlebars\Context $context context object
* @param array $args passed arguments to helper
* @param string $source part of template that is wrapped
* within helper
*
* @return string
*/
public function helperTruncate($template, $context, $args, $source)
{
preg_match("/(.*?)\s+(.*?)\s+(?:(?:\"|\')(.*?)(?:\"|\'))/", trim($args), $m);
$keyname = $m[1];
$limit = $m[2];
$ellipsis = $m[3];
$value = substr($context->get($keyname), 0, $limit);
if ($ellipsis && strlen($context->get($keyname)) > $limit) {
$value .= $ellipsis;
}
return $value;
}
/**
* Return the data source as is
*
* {{#raw}} {{/raw}}
*
* @param \Handlebars\Template $template template that is being rendered
* @param \Handlebars\Context $context context object
* @param array $args passed arguments to helper
* @param string $source part of template that is wrapped
* within helper
*
* @return mixed
*/
public function helperRaw($template, $context, $args, $source)
{
return $source;
}
/**
* Repeat section $x times.
*
* {{#repeat 10}}
* This section will be repeated 10 times
* {{/repeat}}
*
*
* @param \Handlebars\Template $template template that is being rendered
* @param \Handlebars\Context $context context object
* @param array $args passed arguments to helper
* @param string $source part of template that is wrapped
* within helper
*
* @return string
*/
public function helperRepeat($template, $context, $args, $source)
{
$buffer = $template->render($context);
return str_repeat($buffer, intval($args));
}
/**
* Define a section to be used later by using 'invoke'
*
* --> Define a section: hello
* {{#define hello}}
* Hello World!
*
* How is everything?
* {{/define}}
*
* --> This is how it is called
* {{#invoke hello}}
*
*
* @param \Handlebars\Template $template template that is being rendered
* @param \Handlebars\Context $context context object
* @param array $args passed arguments to helper
* @param string $source part of template that is wrapped
* within helper
*
* @return null
*/
public function helperDefine($template, $context, $args, $source)
{
$this->tpl["DEFINE"][$args] = clone($template);
}
/**
* Invoke a section that was created using 'define'
*
* --> Define a section: hello
* {{#define hello}}
* Hello World!
*
* How is everything?
* {{/define}}
*
* --> This is how it is called
* {{#invoke hello}}
*
*
* @param \Handlebars\Template $template template that is being rendered
* @param \Handlebars\Context $context context object
* @param array $args passed arguments to helper
* @param string $source part of template that is wrapped
* within helper
*
* @return null
*/
public function helperInvoke($template, $context, $args, $source)
{
if (! isset($this->tpl["DEFINE"][$args])) {
throw new LogicException("Can't INVOKE '{$args}'. '{$args}' was not DEFINE ");
}
return $this->tpl["DEFINE"][$args]->render($context);
}
/**
* Change underscore helper name to CamelCase
*
* @param string $string
* @return string
*/
private function underscoreToCamelCase($string)
{
return str_replace(' ', '', ucwords(str_replace('_', ' ', $string)));
}
/**
* slice
* Allow to split the data that will be returned
* #loop[start:end] => starts at start trhough end -1
* #loop[start:] = Starts at start though the rest of the array
* #loop[:end] = Starts at the beginning through end -1
* #loop[:] = A copy of the whole array
*
* #loop[-1]
* #loop[-2:] = Last two items
* #loop[:-2] = Everything except last two items
*
* @param string $string
* @return Array [tag_name, slice_start, slice_end]
*/
private function extractSlice($string)
{
preg_match("/^([\w\._\-]+)(?:\[([\-0-9]*?:[\-0-9]*?)\])?/i", $string, $m);
$slice_start = $slice_end = null;
if (isset($m[2])) {
list($slice_start, $slice_end) = explode(":", $m[2]);
$slice_start = (int) $slice_start;
$slice_end = $slice_end ? (int) $slice_end : null;
}
return [$m[1], $slice_start, $slice_end];
}
/**
* Parse avariable from current args
*
* @param \Handlebars\Context $context context object
* @param array $args passed arguments to helper
* @return array
*/
private function parseArgs($context, $args)
{
$args = preg_replace('/\s+/', ' ', trim($args));
$eles = explode(' ', $args);
foreach ($eles as $key => $ele) {
if (in_array(substr($ele, 0, 1), ['\'', '"'])) {
$val = trim($ele, '\'"');
} else if (is_numeric($ele)) {
$val = $ele;
} else {
$val = $context->get($ele);
}
$eles[$key] = $val;
}
return $eles;
}
}