-
Notifications
You must be signed in to change notification settings - Fork 611
/
Extension.php
1731 lines (1586 loc) · 63 KB
/
Extension.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
/**
* @link https://craftcms.com/
* @copyright Copyright (c) Pixel & Tonic, Inc.
* @license https://craftcms.github.io/license/
*/
namespace craft\web\twig;
use CommerceGuys\Addressing\Formatter\FormatterInterface;
use Countable;
use Craft;
use craft\base\ElementInterface;
use craft\base\FieldLayoutProviderInterface;
use craft\base\MissingComponentInterface;
use craft\base\PluginInterface;
use craft\elements\Address;
use craft\elements\Asset;
use craft\elements\User;
use craft\errors\AssetException;
use craft\helpers\App;
use craft\helpers\ArrayHelper;
use craft\helpers\DateTimeHelper;
use craft\helpers\Db;
use craft\helpers\Gql;
use craft\helpers\Html;
use craft\helpers\HtmlPurifier;
use craft\helpers\Json;
use craft\helpers\MoneyHelper;
use craft\helpers\Sequence;
use craft\helpers\StringHelper;
use craft\helpers\Template as TemplateHelper;
use craft\helpers\UrlHelper;
use craft\i18n\Locale;
use craft\models\EntryType;
use craft\web\twig\nodevisitors\EventTagAdder;
use craft\web\twig\nodevisitors\EventTagFinder;
use craft\web\twig\nodevisitors\GetAttrAdjuster;
use craft\web\twig\nodevisitors\Profiler;
use craft\web\twig\tokenparsers\CacheTokenParser;
use craft\web\twig\tokenparsers\DdTokenParser;
use craft\web\twig\tokenparsers\DeprecatedTokenParser;
use craft\web\twig\tokenparsers\DumpTokenParser;
use craft\web\twig\tokenparsers\ExitTokenParser;
use craft\web\twig\tokenparsers\HeaderTokenParser;
use craft\web\twig\tokenparsers\HookTokenParser;
use craft\web\twig\tokenparsers\NamespaceTokenParser;
use craft\web\twig\tokenparsers\NavTokenParser;
use craft\web\twig\tokenparsers\PaginateTokenParser;
use craft\web\twig\tokenparsers\RedirectTokenParser;
use craft\web\twig\tokenparsers\RegisterResourceTokenParser;
use craft\web\twig\tokenparsers\RequireAdminTokenParser;
use craft\web\twig\tokenparsers\RequireEditionTokenParser;
use craft\web\twig\tokenparsers\RequireGuestTokenParser;
use craft\web\twig\tokenparsers\RequireLoginTokenParser;
use craft\web\twig\tokenparsers\RequirePermissionTokenParser;
use craft\web\twig\tokenparsers\SwitchTokenParser;
use craft\web\twig\tokenparsers\TagTokenParser;
use craft\web\twig\variables\CraftVariable;
use craft\web\View;
use DateInterval;
use DateTime;
use DateTimeInterface;
use DateTimeZone;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use IteratorAggregate;
use Money\Money;
use Throwable;
use Traversable;
use Twig\Environment as TwigEnvironment;
use Twig\Error\RuntimeError;
use Twig\Extension\AbstractExtension;
use Twig\Extension\GlobalsInterface;
use Twig\TwigFilter;
use Twig\TwigFunction;
use Twig\TwigTest;
use yii\base\InvalidArgumentException;
use yii\base\InvalidConfigException;
use yii\db\Exception;
use yii\db\Expression;
use yii\db\QueryInterface;
use yii\helpers\Markdown;
use function twig_date_converter;
use function twig_date_format_filter;
/**
* Class Extension
*
* @author Pixel & Tonic, Inc. <support@pixelandtonic.com>
* @since 3.0.0
*/
class Extension extends AbstractExtension implements GlobalsInterface
{
/**
* @var View|null
*/
protected ?View $view = null;
/**
* @var TwigEnvironment|null
*/
protected ?TwigEnvironment $environment = null;
/**
* Constructor
*
* @param View $view
* @param TwigEnvironment $environment
*/
public function __construct(View $view, TwigEnvironment $environment)
{
$this->view = $view;
$this->environment = $environment;
}
/**
* @inheritdoc
*/
public function getNodeVisitors(): array
{
return [
new Profiler(),
new GetAttrAdjuster(),
new EventTagFinder(),
new EventTagAdder(),
];
}
/**
* @inheritdoc
*/
public function getTokenParsers(): array
{
return [
new CacheTokenParser(),
new DeprecatedTokenParser(),
new DdTokenParser(),
new DumpTokenParser(),
new ExitTokenParser(),
new HeaderTokenParser(),
new HookTokenParser(),
new RegisterResourceTokenParser('css', TemplateHelper::class . '::css', [
'allowTagPair' => true,
'allowOptions' => true,
]),
new RegisterResourceTokenParser('html', 'Craft::$app->getView()->registerHtml', [
'allowTagPair' => true,
'allowPosition' => true,
]),
new RegisterResourceTokenParser('js', TemplateHelper::class . '::js', [
'allowTagPair' => true,
'allowPosition' => true,
'allowRuntimePosition' => true,
'allowOptions' => true,
]),
new RegisterResourceTokenParser('script', 'Craft::$app->getView()->registerScript', [
'allowTagPair' => true,
'allowPosition' => true,
'allowOptions' => true,
'defaultPosition' => View::POS_END,
]),
new NamespaceTokenParser(),
new NavTokenParser(),
new PaginateTokenParser(),
new RedirectTokenParser(),
new RequireAdminTokenParser(),
new RequireEditionTokenParser(),
new RequireLoginTokenParser(),
new RequireGuestTokenParser(),
new RequirePermissionTokenParser(),
new SwitchTokenParser(),
new TagTokenParser(),
];
}
/**
* @inheritdoc
*/
public function getFilters(): array
{
$security = Craft::$app->getSecurity();
return [
new TwigFilter('address', [$this, 'addressFilter'], ['is_safe' => ['html']]),
new TwigFilter('append', [$this, 'appendFilter'], ['is_safe' => ['html']]),
new TwigFilter('ascii', [StringHelper::class, 'toAscii']),
new TwigFilter('atom', [$this, 'atomFilter'], ['needs_environment' => true]),
new TwigFilter('attr', [$this, 'attrFilter'], ['is_safe' => ['html']]),
new TwigFilter('base64_decode', 'base64_decode'),
new TwigFilter('base64_encode', 'base64_encode'),
new TwigFilter('boolean', 'boolval'),
new TwigFilter('camel', [$this, 'camelFilter']),
new TwigFilter('column', [ArrayHelper::class, 'getColumn']),
new TwigFilter('contains', [ArrayHelper::class, 'contains']),
new TwigFilter('currency', [$this, 'currencyFilter']),
new TwigFilter('date', [$this, 'dateFilter'], ['needs_environment' => true]),
new TwigFilter('datetime', [$this, 'datetimeFilter'], ['needs_environment' => true]),
new TwigFilter('diff', 'array_diff'),
new TwigFilter('duration', [DateTimeHelper::class, 'humanDuration']),
new TwigFilter('encenc', [$this, 'encencFilter']),
new TwigFilter('explodeClass', [Html::class, 'explodeClass']),
new TwigFilter('explodeStyle', [Html::class, 'explodeStyle']),
new TwigFilter('filesize', [$this, 'filesizeFilter']),
new TwigFilter('filter', [$this, 'filterFilter'], ['needs_environment' => true]),
new TwigFilter('filterByValue', [ArrayHelper::class, 'where'], ['deprecated' => '3.5.0', 'alternative' => 'where']),
new TwigFilter('firstWhere', [ArrayHelper::class, 'firstWhere']),
new TwigFilter('flatten', [Arr::class, 'flatten']),
new TwigFilter('group', [$this, 'groupFilter']),
new TwigFilter('hash', [$security, 'hashData']),
new TwigFilter('httpdate', [$this, 'httpdateFilter'], ['needs_environment' => true]),
new TwigFilter('id', [Html::class, 'id']),
new TwigFilter('index', [ArrayHelper::class, 'index']),
new TwigFilter('indexOf', [$this, 'indexOfFilter']),
new TwigFilter('integer', 'intval'),
new TwigFilter('intersect', 'array_intersect'),
new TwigFilter('float', 'floatval'),
new TwigFilter('json_encode', [$this, 'jsonEncodeFilter']),
new TwigFilter('json_decode', [Json::class, 'decode']),
new TwigFilter('kebab', [$this, 'kebabFilter']),
new TwigFilter('length', [$this, 'lengthFilter'], ['needs_environment' => true]),
new TwigFilter('lcfirst', [$this, 'lcfirstFilter']),
new TwigFilter('literal', [$this, 'literalFilter']),
new TwigFilter('map', [$this, 'mapFilter'], ['needs_environment' => true]),
new TwigFilter('markdown', [$this, 'markdownFilter'], ['is_safe' => ['html']]),
new TwigFilter('md', [$this, 'markdownFilter'], ['is_safe' => ['html']]),
new TwigFilter('merge', [$this, 'mergeFilter']),
new TwigFilter('money', [$this, 'moneyFilter']),
new TwigFilter('multisort', [$this, 'multisortFilter']),
new TwigFilter('namespace', [$this->view, 'namespaceInputs'], ['is_safe' => ['html']]),
new TwigFilter('namespaceAttributes', [Html::class, 'namespaceAttributes'], ['is_safe' => ['html']]),
new TwigFilter('ns', [$this->view, 'namespaceInputs'], ['is_safe' => ['html']]),
new TwigFilter('namespaceInputName', [$this->view, 'namespaceInputName']),
new TwigFilter('namespaceInputId', [$this->view, 'namespaceInputId']),
new TwigFilter('number', [$this, 'numberFilter']),
new TwigFilter('parseAttr', [$this, 'parseAttrFilter']),
new TwigFilter('parseRefs', [$this, 'parseRefsFilter'], ['is_safe' => ['html']]),
new TwigFilter('pascal', [$this, 'pascalFilter']),
new TwigFilter('percentage', [$this, 'percentageFilter']),
new TwigFilter('prepend', [$this, 'prependFilter'], ['is_safe' => ['html']]),
new TwigFilter('purify', [$this, 'purifyFilter'], ['is_safe' => ['html']]),
new TwigFilter('push', [$this, 'pushFilter']),
new TwigFilter('reduce', [$this, 'reduceFilter'], ['needs_environment' => true]),
new TwigFilter('removeClass', [$this, 'removeClassFilter'], ['is_safe' => ['html']]),
new TwigFilter('replace', [$this, 'replaceFilter']),
new TwigFilter('rss', [$this, 'rssFilter'], ['needs_environment' => true]),
new TwigFilter('snake', [$this, 'snakeFilter']),
new TwigFilter('sort', [$this, 'sortFilter'], ['needs_environment' => true]),
new TwigFilter('string', 'strval'),
new TwigFilter('time', [$this, 'timeFilter'], ['needs_environment' => true]),
new TwigFilter('timestamp', [$this, 'timestampFilter']),
new TwigFilter('translate', [$this, 'translateFilter']),
new TwigFilter('truncate', [$this, 'truncateFilter']),
new TwigFilter('t', [$this, 'translateFilter']),
new TwigFilter('ucfirst', [$this, 'ucfirstFilter']),
new TwigFilter('ucwords', [$this, 'ucwordsFilter'], ['needs_environment' => true]),
new TwigFilter('unique', 'array_unique'),
new TwigFilter('unshift', [$this, 'unshiftFilter']),
new TwigFilter('values', 'array_values'),
new TwigFilter('where', [ArrayHelper::class, 'where']),
new TwigFilter('widont', [$this, 'widontFilter'], ['is_safe' => ['html']]),
new TwigFilter('without', [$this, 'withoutFilter']),
new TwigFilter('withoutKey', [$this, 'withoutKeyFilter']),
];
}
/**
* @inheritdoc
*/
public function getTests(): array
{
return [
new TwigTest('array', function($obj): bool {
return is_array($obj);
}),
new TwigTest('boolean', function($obj): bool {
return is_bool($obj);
}),
new TwigTest('callable', function($obj): bool {
return is_callable($obj);
}),
new TwigTest('countable', function($obj): bool {
if (!function_exists('is_countable')) {
return is_array($obj) || $obj instanceof Countable;
}
return is_countable($obj);
}),
new TwigTest('float', function($obj): bool {
return is_float($obj);
}),
new TwigTest('instance of', function($obj, $class) {
return $obj instanceof $class;
}),
new TwigTest('integer', function($obj): bool {
return is_int($obj);
}),
new TwigTest('missing', function($obj) {
return $obj instanceof MissingComponentInterface;
}),
new TwigTest('numeric', function($obj): bool {
return is_numeric($obj);
}),
new TwigTest('object', function($obj): bool {
return is_object($obj);
}),
new TwigTest('resource', function($obj): bool {
return is_resource($obj);
}),
new TwigTest('scalar', function($obj): bool {
return is_scalar($obj);
}),
new TwigTest('string', function($obj): bool {
return is_string($obj);
}),
];
}
/**
* @param Address|null $address
* @param array $options
* @param FormatterInterface|null $formatter
* @return string
* @since 4.0.0
*/
public function addressFilter(?Address $address, array $options = [], FormatterInterface $formatter = null): string
{
if ($address === null) {
return '';
}
return Craft::$app->getAddresses()->formatAddress($address, $options, $formatter);
}
/**
* Outputs a value from a Money object.
*
* @param Money|null $money
* @param string|null $formatLocale
* @return string|null
*/
public function moneyFilter(?Money $money, ?string $formatLocale = null): ?string
{
if ($money === null) {
return null;
}
return MoneyHelper::toString($money, $formatLocale);
}
/**
* Translates the given message.
*
* @param mixed $message The message to be translated.
* @param string|array|null $category the message category.
* @param array|string|null $params The parameters that will be used to replace the corresponding placeholders in the message.
* @param string|null $language The language code (e.g. `en-US`, `en`). If this is null, the current
* [[\yii\base\Application::language|application language]] will be used.
* @return string the translated message.
*/
public function translateFilter(mixed $message, mixed $category = null, mixed $params = null, ?string $language = null): string
{
// The front end site doesn't need to specify the category
/** @noinspection CallableParameterUseCaseInTypeContextInspection */
if (is_array($category)) {
/** @noinspection CallableParameterUseCaseInTypeContextInspection */
$language = $params;
/** @noinspection CallableParameterUseCaseInTypeContextInspection */
$params = $category;
$category = 'site';
} elseif ($category === null) {
$category = 'site';
}
if ($params === null) {
$params = [];
}
try {
return Craft::t($category, (string)$message, $params, $language);
} catch (InvalidConfigException) {
return $message;
}
}
/**
* Truncates the string to a given length, while ensuring that it does not split words.
*
* @param string $string The string to truncate
* @param int $length The maximum number of characters for the truncated string
* @param string $suffix The string that should be appended to `$string`, if it must be truncated
* @param bool $splitSingleWord Whether to split up `$string` if it only contains one word
* @return string The truncated string
* @since 3.5.10
*/
public function truncateFilter(string $string, int $length, string $suffix = '…', bool $splitSingleWord = true): string
{
// Override default behavior where the substring would be returned in this case
if ($string === '' || $length <= 0) {
return $string;
}
return StringHelper::safeTruncate($string, $length, $suffix, $splitSingleWord);
}
/**
* Uppercases the first character of a multibyte string.
*
* @param mixed $string The multibyte string.
* @return string The string with the first character converted to upercase.
*/
public function ucfirstFilter(mixed $string): string
{
return StringHelper::upperCaseFirst((string)$string);
}
/**
* Uppercases the first character of each word in a string.
*
* @param TwigEnvironment $env
* @param string $string
* @return string
*/
public function ucwordsFilter(TwigEnvironment $env, string $string): string
{
Craft::$app->getDeprecator()->log('ucwords', 'The `|ucwords` filter has been deprecated. Use `|title` instead.');
$charset = $env->getCharset();
if ($charset) {
return mb_convert_case($string, MB_CASE_TITLE, $charset);
}
return ucwords(strtolower($string));
}
/**
* Lowercases the first character of a multibyte string.
*
* @param mixed $string The multibyte string.
* @return string The string with the first character converted to lowercase.
*/
public function lcfirstFilter(mixed $string): string
{
return StringHelper::lowercaseFirst((string)$string);
}
/**
* kebab-cases a string.
*
* @param mixed $string The string
* @param string $glue The string used to glue the words together (default is a hyphen)
* @param bool $lower Whether the string should be lowercased (default is true)
* @param bool $removePunctuation Whether punctuation marks should be removed (default is true)
* @return string The kebab-cased string
*/
public function kebabFilter(mixed $string, string $glue = '-', bool $lower = true, bool $removePunctuation = true): string
{
return StringHelper::toKebabCase((string)$string, $glue, $lower, $removePunctuation);
}
/**
* camelCases a string.
*
* @param mixed $string The string
* @return string
*/
public function camelFilter(mixed $string): string
{
return StringHelper::toCamelCase((string)$string);
}
/**
* PascalCases a string.
*
* @param mixed $string The string
* @return string
*/
public function pascalFilter(mixed $string): string
{
return StringHelper::toPascalCase((string)$string);
}
/**
* snake_cases a string.
*
* @param mixed $string The string
* @return string
*/
public function snakeFilter(mixed $string): string
{
return StringHelper::toSnakeCase((string)$string);
}
/**
* Sorts an array.
*
* @param TwigEnvironment $env
* @param iterable $array
* @param string|callable|null $arrow
* @return array
* @throws RuntimeError
* @since 4.3.2
*/
public function sortFilter(TwigEnvironment $env, iterable $array, string|callable|null $arrow = null): array
{
$this->_checkFilterSupport($arrow);
return twig_sort_filter($env, $array, $arrow);
}
/**
* Reduces an array.
*
* @param TwigEnvironment $env
* @param mixed $array
* @param mixed $arrow
* @param mixed $initial
* @return mixed
* @throws RuntimeError
* @since 4.4.16
*/
public function reduceFilter(TwigEnvironment $env, mixed $array, mixed $arrow, mixed $initial = null): mixed
{
$this->_checkFilterSupport($arrow);
return twig_array_reduce($env, $array, $arrow, $initial);
}
/**
* Maps an array.
*
* @param TwigEnvironment $env
* @param mixed $array
* @param mixed $arrow
* @return array
* @throws RuntimeError
* @since 4.4.16
*/
public function mapFilter(TwigEnvironment $env, mixed $array, mixed $arrow = null): array
{
$this->_checkFilterSupport($arrow);
return twig_array_map($env, $array, $arrow);
}
/**
* Formats the value as a currency number.
*
* @param mixed $value
* @param string|null $currency
* @param array $options
* @param array $textOptions
* @param bool $stripZeros
* @return string
* @since 3.6.0
*/
public function currencyFilter(mixed $value, ?string $currency = null, array $options = [], array $textOptions = [], bool $stripZeros = false): string
{
if ($value === null || $value === '') {
return '';
}
try {
return Craft::$app->getFormatter()->asCurrency($value, $currency, $options, $textOptions, $stripZeros);
} catch (InvalidArgumentException) {
return $value;
}
}
/**
* Formats the value in bytes as a size in human-readable form, for example `12 kB`.
*
* @param mixed $value
* @param int|null $decimals
* @param array $options
* @param array $textOptions
* @return string
* @since 3.6.0
*/
public function filesizeFilter(mixed $value, ?int $decimals = null, array $options = [], array $textOptions = []): string
{
if ($value === null || $value === '') {
return '';
}
try {
return Craft::$app->getFormatter()->asShortSize($value, $decimals, $options, $textOptions);
} catch (InvalidArgumentException) {
return $value;
}
}
/**
* Formats the value as a decimal number.
*
* @param mixed $value
* @param int|null $decimals
* @param array $options
* @param array $textOptions
* @return string
* @since 3.6.0
*/
public function numberFilter(mixed $value, ?int $decimals = null, array $options = [], array $textOptions = []): string
{
if ($value === null || $value === '') {
return '';
}
try {
return Craft::$app->getFormatter()->asDecimal($value, $decimals, $options, $textOptions);
} catch (InvalidArgumentException) {
return $value;
}
}
/**
* Formats the value as a percent number with "%" sign.
*
* @param mixed $value
* @param int|null $decimals
* @param array $options
* @param array $textOptions
* @return string
* @since 3.6.0
*/
public function percentageFilter(mixed $value, ?int $decimals = null, array $options = [], array $textOptions = []): string
{
if ($value === null || $value === '') {
return '';
}
try {
return Craft::$app->getFormatter()->asPercent($value, $decimals, $options, $textOptions);
} catch (InvalidArgumentException) {
return $value;
}
}
/**
* Formats the value as a human-readable timestamp.
*
* @param mixed $value
* @param string|null $format
* @param bool $withPreposition
* @return string
* @since 3.6.0
*/
public function timestampFilter(mixed $value, ?string $format = null, bool $withPreposition = false): string
{
if ($value === null || $value === '') {
return '';
}
try {
return Craft::$app->getFormatter()->asTimestamp($value, $format, $withPreposition);
} catch (InvalidArgumentException) {
return $value;
}
}
/**
* This method will JSON encode a variable. We're overriding Twig's default implementation to set some stricter
* encoding options on text/html/xml requests.
*
* @param mixed $value The value to JSON encode.
* @param int|null $options Either null or a bitmask consisting of JSON_HEX_QUOT, JSON_HEX_TAG, JSON_HEX_AMP,
* JSON_HEX_APOS, JSON_NUMERIC_CHECK, JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES,
* JSON_FORCE_OBJECT
* @param int $depth The maximum depth
* @return string|false The JSON encoded value.
*/
public function jsonEncodeFilter(mixed $value, ?int $options = null, int $depth = 512): string|false
{
if ($options === null) {
if (
!Craft::$app->getRequest()->getIsConsoleRequest() &&
in_array(Craft::$app->getResponse()->getContentType(), ['text/html', 'application/xhtml+xml'], true)
) {
$options = JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_QUOT;
} else {
$options = 0;
}
}
// todo: remove the $depth arg in Craft 5
if ($depth !== 512) {
return json_encode($value, $options, $depth);
}
return Json::encode($value, $options);
}
/**
* Inserts a non-breaking space between the last two words of a string.
*
* @param string $string
* @return string
* @since 3.7.0
*/
public function widontFilter(string $string): string
{
return Html::widont($string);
}
/**
* Returns an array without certain values.
*
* @param mixed $arr
* @param mixed $exclude
* @param bool $strict
* @return array
*/
public function withoutFilter(mixed $arr, mixed $exclude, bool $strict = false): array
{
$arr = (array)$arr;
if (!is_array($exclude)) {
$exclude = [$exclude];
}
foreach ($exclude as $value) {
ArrayHelper::removeValue($arr, $value, $strict);
}
return $arr;
}
/**
* Returns an array without a certain key.
*
* @param mixed $arr
* @param string|string[] $key
* @return array
* @since 3.2.0
*/
public function withoutKeyFilter(mixed $arr, array|string $key): array
{
$arr = (array)$arr;
if (!is_array($key)) {
$key = [$key];
}
foreach ($key as $k) {
ArrayHelper::remove($arr, $k);
}
return $arr;
}
/**
* Parses an HTML tag to find its attributes.
*
* @param string $tag The HTML tag to parse
* @return array The parsed HTML tag attributes
* @throws InvalidArgumentException if `$tag` doesn't contain a valid HTML tag
* @since 3.4.0
*/
public function parseAttrFilter(string $tag): array
{
try {
return Html::parseTagAttributes($tag, 0, $start, $end, true);
} catch (InvalidArgumentException $e) {
Craft::warning($e->getMessage(), __METHOD__);
return [];
}
}
/**
* Parses a string for reference tags.
*
* @param mixed $str
* @param int|null $siteId
* @return string
*/
public function parseRefsFilter(mixed $str, ?int $siteId = null): string
{
return Craft::$app->getElements()->parseRefs((string)$str, $siteId);
}
/**
* Prepends HTML to the beginning of given tag.
*
* @param string $tag The HTML tag that `$html` should be prepended to
* @param string $html The HTML to prepend to `$tag`.
* @param string|null $ifExists What to do if `$tag` already contains a child of the same type as the element
* defined by `$html`. Set to `'keep'` if no action should be taken, or `'replace'` if it should be replaced
* by `$tag`.
* @return string The modified HTML
* @since 3.3.0
*/
public function prependFilter(string $tag, string $html, ?string $ifExists = null): string
{
try {
return Html::prependToTag($tag, $html, $ifExists);
} catch (InvalidArgumentException $e) {
Craft::warning($e->getMessage(), __METHOD__);
return $tag;
}
}
/**
* Purifies the given HTML using HTML Purifier.
*
* @param string|null $html The HTML to be purified
* @param string|array|null $config The HTML Purifier config. This can either be the name of a JSON file within
* `config/htmlpurifier/` (sans `.json` extension) or a config array.
* @return string|null The purified HTML
* @since 3.4.0
*/
public function purifyFilter(?string $html, array|string|null $config = null): ?string
{
if ($html === null) {
return null;
}
if (is_string($config)) {
$path = Craft::$app->getPath()->getConfigPath() . DIRECTORY_SEPARATOR . 'htmlpurifier' .
DIRECTORY_SEPARATOR . $config . '.json';
$config = null;
if (!is_file($path)) {
Craft::warning("No HTML Purifier config found at $path.");
} else {
try {
$config = Json::decode(file_get_contents($path));
} catch (InvalidArgumentException) {
Craft::warning("Invalid HTML Purifier config at $path.");
}
}
}
return HtmlPurifier::process($html, $config);
}
/**
* Pushes one or more items onto the end of an array.
*
* @param array $array
* @return array
* @since 3.5.0
*/
public function pushFilter(array $array): array
{
$args = func_get_args();
array_shift($args);
array_push($array, ...$args);
return $array;
}
/**
* Prepends one or more items to the beginning of an array.
*
* @param array $array
* @return array
* @since 3.5.0
*/
public function unshiftFilter(array $array): array
{
$args = func_get_args();
array_shift($args);
array_unshift($array, ...$args);
return $array;
}
/**
* Removes a class (or classes) from the given HTML tag.
*
* @param string $tag The HTML tag to modify
* @param string|string[] $class
* @return string The modified HTML tag
* @since 3.7.0
*/
public function removeClassFilter(string $tag, array|string $class): string
{
try {
$oldClasses = Html::parseTagAttributes($tag)['class'] ?? [];
$newClasses = array_filter($oldClasses, function(string $oldClass) use ($class) {
return is_string($class) ? $oldClass !== $class : !in_array($oldClass, $class, true);
});
$newTag = Html::modifyTagAttributes($tag, ['class' => false]);
if (!empty($newClasses)) {
$newTag = Html::modifyTagAttributes($newTag, ['class' => $newClasses]);
}
return $newTag;
} catch (InvalidArgumentException $e) {
Craft::warning($e->getMessage(), __METHOD__);
return $tag;
}
}
/**
* Replaces Twig's |replace filter, adding support for passing in separate
* search and replace arrays.
*
* @param mixed $str
* @param mixed $search
* @param mixed $replace
* @param bool|null $regex
* @return mixed
*/
public function replaceFilter(mixed $str, mixed $search, mixed $replace = null, ?bool $regex = null): mixed
{
if ($search instanceof Traversable) {
$search = iterator_to_array($search);
}
// Are they using the standard Twig syntax?
if (is_array($search) && $replace === null) {
// If there aren’t any regex patterns, we can safely use strtr()
if (
$regex === false ||
(
$regex === null &&
!ArrayHelper::contains(array_keys($search), fn(string $str) => $this->isRegex($str))
)
) {
return strtr($str, $search);
}
} else {
$search = [$search => $replace];
}
foreach ($search as $s => $r) {
// Is this a regular expression?
if ($regex ?? $this->isRegex($s)) {
$str = preg_replace($s, $r, $str);
} else {
// Otherwise use str_replace
$str = str_replace($s, $r, $str);
}
}
return $str;
}
private function isRegex(string $str): bool
{
if (!preg_match('/^\/([^\r\n]+)\/([imsxADSUXJun]*)$/', $str, $match)) {
return false;
}
// make sure there's no unescaped slashes within it
if (preg_match('/(?<!\\\)\//', $match[1])) {
return false;
}
return true;
}
/**
* Extending Twig's |date filter so we can run any translations on the output.
*
* @param TwigEnvironment $env
* @param DateTimeInterface|DateInterval|string $date A date
* @param string|null $format The target format, null to use the default
* @param DateTimeZone|string|false|null $timezone The target timezone, null to use the default, false to leave unchanged
* @param string|null $locale The target locale the date should be formatted for. By default, the current system locale will be used.
* @return string
*/
public function dateFilter(TwigEnvironment $env, mixed $date, ?string $format = null, mixed $timezone = null, ?string $locale = null): string
{
if ($date instanceof DateInterval) {
return twig_date_format_filter($env, $date, $format, $timezone);
}
// Is this a custom PHP date format?
if ($format !== null && !in_array($format, [Locale::LENGTH_SHORT, Locale::LENGTH_MEDIUM, Locale::LENGTH_LONG, Locale::LENGTH_FULL], true)) {
if (str_starts_with($format, 'icu:')) {
$format = substr($format, 4);
} else {
$format = StringHelper::ensureLeft($format, 'php:');
}
}
$date = twig_date_converter($env, $date, $timezone);
$formatter = $locale ? Craft::$app->getI18n()->getLocaleById($locale)->getFormatter() : Craft::$app->getFormatter();
$fmtTimeZone = $formatter->timeZone;
$formatter->timeZone = $timezone !== null ? $date->getTimezone()->getName() : $formatter->timeZone;
$formatted = $formatter->asDate(DateTime::createFromInterface($date), $format);
$formatter->timeZone = $fmtTimeZone;
return $formatted;
}
/**
* Appends HTML to the end of the given tag.
*
* @param string $tag The HTML tag that `$html` should be appended to
* @param string $html The HTML to append to `$tag`.
* @param string|null $ifExists What to do if `$tag` already contains a child of the same type as the element
* defined by `$html`. Set to `'keep'` if no action should be taken, or `'replace'` if it should be replaced
* by `$tag`.
* @return string The modified HTML
* @since 3.3.0
*/
public function appendFilter(string $tag, string $html, ?string $ifExists = null): string
{
try {
return Html::appendToTag($tag, $html, $ifExists);
} catch (InvalidArgumentException $e) {
Craft::warning($e->getMessage(), __METHOD__);
return $tag;
}
}