/
HtmlHelper.php
1135 lines (1047 loc) · 39 KB
/
HtmlHelper.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
declare(strict_types=1);
/**
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
* @link https://cakephp.org CakePHP(tm) Project
* @since 0.9.1
* @license https://opensource.org/licenses/mit-license.php MIT License
*/
namespace Cake\View\Helper;
use Cake\Core\Configure;
use Cake\View\Helper;
use Cake\View\StringTemplateTrait;
/**
* Html Helper class for easy use of HTML widgets.
*
* HtmlHelper encloses all methods needed while working with HTML pages.
*
* @property \Cake\View\Helper\UrlHelper $Url
* @link https://book.cakephp.org/4/en/views/helpers/html.html
*/
class HtmlHelper extends Helper
{
use StringTemplateTrait;
/**
* List of helpers used by this helper
*
* @var array
*/
protected $helpers = ['Url'];
/**
* Default config for this class
*
* @var array<string, mixed>
*/
protected $_defaultConfig = [
'templates' => [
'meta' => '<meta{{attrs}}/>',
'metalink' => '<link href="{{url}}"{{attrs}}/>',
'link' => '<a href="{{url}}"{{attrs}}>{{content}}</a>',
'mailto' => '<a href="mailto:{{url}}"{{attrs}}>{{content}}</a>',
'image' => '<img src="{{url}}"{{attrs}}/>',
'tableheader' => '<th{{attrs}}>{{content}}</th>',
'tableheaderrow' => '<tr{{attrs}}>{{content}}</tr>',
'tablecell' => '<td{{attrs}}>{{content}}</td>',
'tablerow' => '<tr{{attrs}}>{{content}}</tr>',
'block' => '<div{{attrs}}>{{content}}</div>',
'blockstart' => '<div{{attrs}}>',
'blockend' => '</div>',
'tag' => '<{{tag}}{{attrs}}>{{content}}</{{tag}}>',
'tagstart' => '<{{tag}}{{attrs}}>',
'tagend' => '</{{tag}}>',
'tagselfclosing' => '<{{tag}}{{attrs}}/>',
'para' => '<p{{attrs}}>{{content}}</p>',
'parastart' => '<p{{attrs}}>',
'css' => '<link rel="{{rel}}" href="{{url}}"{{attrs}}/>',
'style' => '<style{{attrs}}>{{content}}</style>',
'charset' => '<meta charset="{{charset}}"/>',
'ul' => '<ul{{attrs}}>{{content}}</ul>',
'ol' => '<ol{{attrs}}>{{content}}</ol>',
'li' => '<li{{attrs}}>{{content}}</li>',
'javascriptblock' => '<script{{attrs}}>{{content}}</script>',
'javascriptstart' => '<script>',
'javascriptlink' => '<script src="{{url}}"{{attrs}}></script>',
'javascriptend' => '</script>',
'confirmJs' => '{{confirm}}',
],
];
/**
* Names of script & css files that have been included once
*
* @var array<string, array>
*/
protected $_includedAssets = [];
/**
* Options for the currently opened script block buffer if any.
*
* @var array<string, mixed>
*/
protected $_scriptBlockOptions = [];
/**
* Creates a link to an external resource and handles basic meta tags
*
* Create a meta tag that is output inline:
*
* ```
* $this->Html->meta('icon', 'favicon.ico');
* ```
*
* Append the meta tag to custom view block "meta":
*
* ```
* $this->Html->meta('description', 'A great page', ['block' => true]);
* ```
*
* Append the meta tag to custom view block:
*
* ```
* $this->Html->meta('description', 'A great page', ['block' => 'metaTags']);
* ```
*
* Create a custom meta tag:
*
* ```
* $this->Html->meta(['property' => 'og:site_name', 'content' => 'CakePHP']);
* ```
*
* ### Options
*
* - `block` - Set to true to append output to view block "meta" or provide
* custom block name.
*
* @param array<string, mixed>|string $type The title of the external resource, Or an array of attributes for a
* custom meta tag.
* @param array|string|null $content The address of the external resource or string for content attribute
* @param array<string, mixed> $options Other attributes for the generated tag. If the type attribute is html,
* rss, atom, or icon, the mime-type is returned.
* @return string|null A completed `<link />` element, or null if the element was sent to a block.
* @link https://book.cakephp.org/4/en/views/helpers/html.html#creating-meta-tags
*/
public function meta($type, $content = null, array $options = []): ?string
{
if (!is_array($type)) {
$types = [
'rss' => ['type' => 'application/rss+xml', 'rel' => 'alternate', 'title' => $type, 'link' => $content],
'atom' => ['type' => 'application/atom+xml', 'title' => $type, 'link' => $content],
'icon' => ['type' => 'image/x-icon', 'rel' => 'icon', 'link' => $content],
'keywords' => ['name' => 'keywords', 'content' => $content],
'description' => ['name' => 'description', 'content' => $content],
'robots' => ['name' => 'robots', 'content' => $content],
'viewport' => ['name' => 'viewport', 'content' => $content],
'canonical' => ['rel' => 'canonical', 'link' => $content],
'next' => ['rel' => 'next', 'link' => $content],
'prev' => ['rel' => 'prev', 'link' => $content],
'first' => ['rel' => 'first', 'link' => $content],
'last' => ['rel' => 'last', 'link' => $content],
];
if ($type === 'icon' && $content === null) {
$types['icon']['link'] = 'favicon.ico';
}
if (isset($types[$type])) {
$type = $types[$type];
} elseif (!isset($options['type']) && $content !== null) {
if (is_array($content) && isset($content['_ext'])) {
$type = $types[$content['_ext']];
} else {
$type = ['name' => $type, 'content' => $content];
}
} elseif (isset($options['type'], $types[$options['type']])) {
$type = $types[$options['type']];
unset($options['type']);
} else {
$type = [];
}
}
$options += $type + ['block' => null];
$out = '';
if (isset($options['link'])) {
if (is_array($options['link'])) {
$options['link'] = $this->Url->build($options['link']);
} else {
$options['link'] = $this->Url->assetUrl($options['link']);
}
if (isset($options['rel']) && $options['rel'] === 'icon') {
$out = $this->formatTemplate('metalink', [
'url' => $options['link'],
'attrs' => $this->templater()->formatAttributes($options, ['block', 'link']),
]);
$options['rel'] = 'shortcut icon';
}
$out .= $this->formatTemplate('metalink', [
'url' => $options['link'],
'attrs' => $this->templater()->formatAttributes($options, ['block', 'link']),
]);
} else {
$out = $this->formatTemplate('meta', [
'attrs' => $this->templater()->formatAttributes($options, ['block', 'type']),
]);
}
if (empty($options['block'])) {
return $out;
}
if ($options['block'] === true) {
$options['block'] = __FUNCTION__;
}
$this->_View->append($options['block'], $out);
return null;
}
/**
* Returns a charset META-tag.
*
* @param string|null $charset The character set to be used in the meta tag. If empty,
* The App.encoding value will be used. Example: "utf-8".
* @return string A meta tag containing the specified character set.
* @link https://book.cakephp.org/4/en/views/helpers/html.html#creating-charset-tags
*/
public function charset(?string $charset = null): string
{
if (empty($charset)) {
$charset = strtolower((string)Configure::read('App.encoding'));
}
return $this->formatTemplate('charset', [
'charset' => !empty($charset) ? $charset : 'utf-8',
]);
}
/**
* Creates an HTML link.
*
* If $url starts with "http://" this is treated as an external link. Else,
* it is treated as a path to controller/action and parsed with the
* UrlHelper::build() method.
*
* If the $url is empty, $title is used instead.
*
* ### Options
*
* - `escape` Set to false to disable escaping of title and attributes.
* - `escapeTitle` Set to false to disable escaping of title. Takes precedence
* over value of `escape`)
* - `confirm` JavaScript confirmation message.
*
* @param array|string $title The content to be wrapped by `<a>` tags.
* Can be an array if $url is null. If $url is null, $title will be used as both the URL and title.
* @param array|string|null $url Cake-relative URL or array of URL parameters, or
* external URL (starts with http://)
* @param array<string, mixed> $options Array of options and HTML attributes.
* @return string An `<a />` element.
* @link https://book.cakephp.org/4/en/views/helpers/html.html#creating-links
*/
public function link($title, $url = null, array $options = []): string
{
$escapeTitle = true;
if ($url !== null) {
$url = $this->Url->build($url, $options);
unset($options['fullBase']);
} else {
$url = $this->Url->build($title);
$title = htmlspecialchars_decode($url, ENT_QUOTES);
$title = h(urldecode($title));
$escapeTitle = false;
}
if (isset($options['escapeTitle'])) {
$escapeTitle = $options['escapeTitle'];
unset($options['escapeTitle']);
} elseif (isset($options['escape'])) {
$escapeTitle = $options['escape'];
}
if ($escapeTitle === true) {
$title = h($title);
} elseif (is_string($escapeTitle)) {
/** @psalm-suppress PossiblyInvalidArgument */
$title = htmlentities($title, ENT_QUOTES, $escapeTitle);
}
$templater = $this->templater();
$confirmMessage = null;
if (isset($options['confirm'])) {
$confirmMessage = $options['confirm'];
unset($options['confirm']);
}
if ($confirmMessage) {
$confirm = $this->_confirm('return true;', 'return false;');
$options['data-confirm-message'] = $confirmMessage;
$options['onclick'] = $templater->format('confirmJs', [
'confirmMessage' => h($confirmMessage),
'confirm' => $confirm,
]);
}
return $templater->format('link', [
'url' => $url,
'attrs' => $templater->formatAttributes($options),
'content' => $title,
]);
}
/**
* Creates an HTML link from route path string.
*
* ### Options
*
* - `escape` Set to false to disable escaping of title and attributes.
* - `escapeTitle` Set to false to disable escaping of title. Takes precedence
* over value of `escape`)
* - `confirm` JavaScript confirmation message.
*
* @param string $title The content to be wrapped by `<a>` tags.
* @param string $path Cake-relative route path.
* @param array $params An array specifying any additional parameters.
* Can be also any special parameters supported by `Router::url()`.
* @param array<string, mixed> $options Array of options and HTML attributes.
* @return string An `<a />` element.
* @see \Cake\Routing\Router::pathUrl()
* @link https://book.cakephp.org/4/en/views/helpers/html.html#creating-links
*/
public function linkFromPath(string $title, string $path, array $params = [], array $options = []): string
{
return $this->link($title, ['_path' => $path] + $params, $options);
}
/**
* Creates a link element for CSS stylesheets.
*
* ### Usage
*
* Include one CSS file:
*
* ```
* echo $this->Html->css('styles.css');
* ```
*
* Include multiple CSS files:
*
* ```
* echo $this->Html->css(['one.css', 'two.css']);
* ```
*
* Add the stylesheet to view block "css":
*
* ```
* $this->Html->css('styles.css', ['block' => true]);
* ```
*
* Add the stylesheet to a custom block:
*
* ```
* $this->Html->css('styles.css', ['block' => 'layoutCss']);
* ```
*
* ### Options
*
* - `block` Set to true to append output to view block "css" or provide
* custom block name.
* - `once` Whether the css file should be checked for uniqueness. If true css
* files will only be included once, use false to allow the same
* css to be included more than once per request.
* - `plugin` False value will prevent parsing path as a plugin
* - `rel` Defaults to 'stylesheet'. If equal to 'import' the stylesheet will be imported.
* - `fullBase` If true the URL will get a full address for the css file.
*
* All other options will be treated as HTML attributes. If the request contains a
* `cspStyleNonce` attribute, that value will be applied as the `nonce` attribute on the
* generated HTML.
*
* @param array<string>|string $path The name of a CSS style sheet or an array containing names of
* CSS stylesheets. If `$path` is prefixed with '/', the path will be relative to the webroot
* of your application. Otherwise, the path will be relative to your CSS path, usually webroot/css.
* @param array<string, mixed> $options Array of options and HTML arguments.
* @return string|null CSS `<link />` or `<style />` tag, depending on the type of link.
* @link https://book.cakephp.org/4/en/views/helpers/html.html#linking-to-css-files
*/
public function css($path, array $options = []): ?string
{
$options += [
'once' => true,
'block' => null,
'rel' => 'stylesheet',
'nonce' => $this->_View->getRequest()->getAttribute('cspStyleNonce'),
];
if (is_array($path)) {
$out = '';
foreach ($path as $i) {
$out .= "\n\t" . (string)$this->css($i, $options);
}
if (empty($options['block'])) {
return $out . "\n";
}
return null;
}
$url = $this->Url->css($path, $options);
$options = array_diff_key($options, ['fullBase' => null, 'pathPrefix' => null]);
if ($options['once'] && isset($this->_includedAssets[__METHOD__][$path])) {
return null;
}
unset($options['once']);
$this->_includedAssets[__METHOD__][$path] = true;
$templater = $this->templater();
if ($options['rel'] === 'import') {
$out = $templater->format('style', [
'attrs' => $templater->formatAttributes($options, ['rel', 'block']),
'content' => '@import url(' . $url . ');',
]);
} else {
$out = $templater->format('css', [
'rel' => $options['rel'],
'url' => $url,
'attrs' => $templater->formatAttributes($options, ['rel', 'block']),
]);
}
if (empty($options['block'])) {
return $out;
}
if ($options['block'] === true) {
$options['block'] = __FUNCTION__;
}
$this->_View->append($options['block'], $out);
return null;
}
/**
* Returns one or many `<script>` tags depending on the number of scripts given.
*
* If the filename is prefixed with "/", the path will be relative to the base path of your
* application. Otherwise, the path will be relative to your JavaScript path, usually webroot/js.
*
* ### Usage
*
* Include one script file:
*
* ```
* echo $this->Html->script('styles.js');
* ```
*
* Include multiple script files:
*
* ```
* echo $this->Html->script(['one.js', 'two.js']);
* ```
*
* Add the script file to a custom block:
*
* ```
* $this->Html->script('styles.js', ['block' => 'bodyScript']);
* ```
*
* ### Options
*
* - `block` Set to true to append output to view block "script" or provide
* custom block name.
* - `once` Whether the script should be checked for uniqueness. If true scripts will only be
* included once, use false to allow the same script to be included more than once per request.
* - `plugin` False value will prevent parsing path as a plugin
* - `fullBase` If true the url will get a full address for the script file.
*
* All other options will be added as attributes to the generated script tag.
* If the current request has a `cspScriptNonce` attribute, that value will
* be inserted as a `nonce` attribute on the script tag.
*
* @param array<string>|string $url String or array of javascript files to include
* @param array<string, mixed> $options Array of options, and html attributes see above.
* @return string|null String of `<script />` tags or null if block is specified in options
* or if $once is true and the file has been included before.
* @link https://book.cakephp.org/4/en/views/helpers/html.html#linking-to-javascript-files
*/
public function script($url, array $options = []): ?string
{
$defaults = [
'block' => null,
'once' => true,
'nonce' => $this->_View->getRequest()->getAttribute('cspScriptNonce'),
];
$options += $defaults;
if (is_array($url)) {
$out = '';
foreach ($url as $i) {
$out .= "\n\t" . (string)$this->script($i, $options);
}
if (empty($options['block'])) {
return $out . "\n";
}
return null;
}
$url = $this->Url->script($url, $options);
$options = array_diff_key($options, ['fullBase' => null, 'pathPrefix' => null]);
if ($options['once'] && isset($this->_includedAssets[__METHOD__][$url])) {
return null;
}
$this->_includedAssets[__METHOD__][$url] = true;
$out = $this->formatTemplate('javascriptlink', [
'url' => $url,
'attrs' => $this->templater()->formatAttributes($options, ['block', 'once']),
]);
if (empty($options['block'])) {
return $out;
}
if ($options['block'] === true) {
$options['block'] = __FUNCTION__;
}
$this->_View->append($options['block'], $out);
return null;
}
/**
* Wrap $script in a script tag.
*
* ### Options
*
* - `block` Set to true to append output to view block "script" or provide
* custom block name.
*
* @param string $script The script to wrap
* @param array<string, mixed> $options The options to use. Options not listed above will be
* treated as HTML attributes.
* @return string|null String or null depending on the value of `$options['block']`
* @link https://book.cakephp.org/4/en/views/helpers/html.html#creating-inline-javascript-blocks
*/
public function scriptBlock(string $script, array $options = []): ?string
{
$options += ['block' => null, 'nonce' => $this->_View->getRequest()->getAttribute('cspScriptNonce')];
$out = $this->formatTemplate('javascriptblock', [
'attrs' => $this->templater()->formatAttributes($options, ['block']),
'content' => $script,
]);
if (empty($options['block'])) {
return $out;
}
if ($options['block'] === true) {
$options['block'] = 'script';
}
$this->_View->append($options['block'], $out);
return null;
}
/**
* Begin a script block that captures output until HtmlHelper::scriptEnd()
* is called. This capturing block will capture all output between the methods
* and create a scriptBlock from it.
*
* ### Options
*
* - `block` Set to true to append output to view block "script" or provide
* custom block name.
*
* @param array<string, mixed> $options Options for the code block.
* @return void
* @link https://book.cakephp.org/4/en/views/helpers/html.html#creating-inline-javascript-blocks
*/
public function scriptStart(array $options = []): void
{
$this->_scriptBlockOptions = $options;
ob_start();
}
/**
* End a Buffered section of JavaScript capturing.
* Generates a script tag inline or appends to specified view block depending on
* the settings used when the scriptBlock was started
*
* @return string|null Depending on the settings of scriptStart() either a script tag or null
* @link https://book.cakephp.org/4/en/views/helpers/html.html#creating-inline-javascript-blocks
*/
public function scriptEnd(): ?string
{
$buffer = ob_get_clean();
$options = $this->_scriptBlockOptions;
$this->_scriptBlockOptions = [];
return $this->scriptBlock($buffer, $options);
}
/**
* Builds CSS style data from an array of CSS properties
*
* ### Usage:
*
* ```
* echo $this->Html->style(['margin' => '10px', 'padding' => '10px'], true);
*
* // creates
* 'margin:10px;padding:10px;'
* ```
*
* @param array<string, string> $data Style data array, keys will be used as property names, values as property values.
* @param bool $oneLine Whether the style block should be displayed on one line.
* @return string CSS styling data
* @link https://book.cakephp.org/4/en/views/helpers/html.html#creating-css-programatically
*/
public function style(array $data, bool $oneLine = true): string
{
$out = [];
foreach ($data as $key => $value) {
$out[] = $key . ':' . $value . ';';
}
if ($oneLine) {
return implode(' ', $out);
}
return implode("\n", $out);
}
/**
* Creates a formatted IMG element.
*
* This method will set an empty alt attribute if one is not supplied.
*
* ### Usage:
*
* Create a regular image:
*
* ```
* echo $this->Html->image('cake_icon.png', ['alt' => 'CakePHP']);
* ```
*
* Create an image link:
*
* ```
* echo $this->Html->image('cake_icon.png', ['alt' => 'CakePHP', 'url' => 'https://cakephp.org']);
* ```
*
* ### Options:
*
* - `url` If provided an image link will be generated and the link will point at
* `$options['url']`.
* - `fullBase` If true the src attribute will get a full address for the image file.
* - `plugin` False value will prevent parsing path as a plugin
*
* @param array|string $path Path to the image file, relative to the webroot/img/ directory.
* @param array<string, mixed> $options Array of HTML attributes. See above for special options.
* @return string completed img tag
* @link https://book.cakephp.org/4/en/views/helpers/html.html#linking-to-images
*/
public function image($path, array $options = []): string
{
if (is_string($path)) {
$path = $this->Url->image($path, $options);
} else {
$path = $this->Url->build($path, $options);
}
$options = array_diff_key($options, ['fullBase' => null, 'pathPrefix' => null]);
if (!isset($options['alt'])) {
$options['alt'] = '';
}
$url = false;
if (!empty($options['url'])) {
$url = $options['url'];
unset($options['url']);
}
$templater = $this->templater();
$image = $templater->format('image', [
'url' => $path,
'attrs' => $templater->formatAttributes($options),
]);
if ($url) {
return $templater->format('link', [
'url' => $this->Url->build($url),
'attrs' => null,
'content' => $image,
]);
}
return $image;
}
/**
* Returns a row of formatted and named TABLE headers.
*
* @param array $names Array of tablenames. Each tablename can be string, or array with name and an array with a set
* of attributes to its specific tag
* @param array<string, mixed>|null $trOptions HTML options for TR elements.
* @param array<string, mixed>|null $thOptions HTML options for TH elements.
* @return string Completed table headers
* @link https://book.cakephp.org/4/en/views/helpers/html.html#creating-table-headings
*/
public function tableHeaders(array $names, ?array $trOptions = null, ?array $thOptions = null): string
{
$out = [];
foreach ($names as $arg) {
if (!is_array($arg)) {
$content = $arg;
$attrs = $thOptions;
} elseif (isset($arg[0], $arg[1])) {
$content = $arg[0];
$attrs = $arg[1];
} else {
$content = key($arg);
$attrs = current($arg);
}
$out[] = $this->formatTemplate('tableheader', [
'attrs' => $this->templater()->formatAttributes($attrs),
'content' => $content,
]);
}
return $this->tableRow(implode(' ', $out), (array)$trOptions);
}
/**
* Returns a formatted string of table rows (TR's with TD's in them).
*
* @param array|string $data Array of table data
* @param array<string, mixed>|bool|null $oddTrOptions HTML options for odd TR elements if true useCount is used
* @param array<string, mixed>|bool|null $evenTrOptions HTML options for even TR elements
* @param bool $useCount adds class "column-$i"
* @param bool $continueOddEven If false, will use a non-static $count variable,
* so that the odd/even count is reset to zero just for that call.
* @return string Formatted HTML
* @link https://book.cakephp.org/4/en/views/helpers/html.html#creating-table-cells
*/
public function tableCells(
$data,
$oddTrOptions = null,
$evenTrOptions = null,
bool $useCount = false,
bool $continueOddEven = true
): string {
if (!is_array($data)) {
$data = [[$data]];
} elseif (empty($data[0]) || !is_array($data[0])) {
$data = [$data];
}
if ($oddTrOptions === true) {
$useCount = true;
$oddTrOptions = null;
}
if ($evenTrOptions === false) {
$continueOddEven = false;
$evenTrOptions = null;
}
if ($continueOddEven) {
static $count = 0;
} else {
$count = 0;
}
$out = [];
foreach ($data as $line) {
$count++;
$cellsOut = $this->_renderCells($line, $useCount);
$opts = $count % 2 ? $oddTrOptions : $evenTrOptions;
/** @var array<string, mixed> $options */
$options = (array)$opts;
$out[] = $this->tableRow(implode(' ', $cellsOut), $options);
}
return implode("\n", $out);
}
/**
* Renders cells for a row of a table.
*
* This is a helper method for tableCells(). Overload this method as you
* need to change the behavior of the cell rendering.
*
* @param array $line Line data to render.
* @param bool $useCount Renders the count into the row. Default is false.
* @return array<string>
*/
protected function _renderCells(array $line, bool $useCount = false): array
{
$i = 0;
$cellsOut = [];
foreach ($line as $cell) {
$cellOptions = [];
if (is_array($cell)) {
$cellOptions = $cell[1];
$cell = $cell[0];
}
if ($useCount) {
$i += 1;
if (isset($cellOptions['class'])) {
$cellOptions['class'] .= ' column-' . $i;
} else {
$cellOptions['class'] = 'column-' . $i;
}
}
$cellsOut[] = $this->tableCell((string)$cell, $cellOptions);
}
return $cellsOut;
}
/**
* Renders a single table row (A TR with attributes).
*
* @param string $content The content of the row.
* @param array<string, mixed> $options HTML attributes.
* @return string
*/
public function tableRow(string $content, array $options = []): string
{
return $this->formatTemplate('tablerow', [
'attrs' => $this->templater()->formatAttributes($options),
'content' => $content,
]);
}
/**
* Renders a single table cell (A TD with attributes).
*
* @param string $content The content of the cell.
* @param array<string, mixed> $options HTML attributes.
* @return string
*/
public function tableCell(string $content, array $options = []): string
{
return $this->formatTemplate('tablecell', [
'attrs' => $this->templater()->formatAttributes($options),
'content' => $content,
]);
}
/**
* Returns a formatted block tag, i.e DIV, SPAN, P.
*
* ### Options
*
* - `escape` Whether the contents should be html_entity escaped.
*
* @param string $name Tag name.
* @param string|null $text String content that will appear inside the div element.
* If null, only a start tag will be printed
* @param array<string, mixed> $options Additional HTML attributes of the DIV tag, see above.
* @return string The formatted tag element
*/
public function tag(string $name, ?string $text = null, array $options = []): string
{
if (isset($options['escape']) && $options['escape']) {
$text = h($text);
unset($options['escape']);
}
if ($text === null) {
$tag = 'tagstart';
} else {
$tag = 'tag';
}
return $this->formatTemplate($tag, [
'attrs' => $this->templater()->formatAttributes($options),
'tag' => $name,
'content' => $text,
]);
}
/**
* Returns a formatted DIV tag for HTML FORMs.
*
* ### Options
*
* - `escape` Whether the contents should be html_entity escaped.
*
* @param string|null $class CSS class name of the div element.
* @param string|null $text String content that will appear inside the div element.
* If null, only a start tag will be printed
* @param array<string, mixed> $options Additional HTML attributes of the DIV tag
* @return string The formatted DIV element
*/
public function div(?string $class = null, ?string $text = null, array $options = []): string
{
if (!empty($class)) {
$options['class'] = $class;
}
return $this->tag('div', $text, $options);
}
/**
* Returns a formatted P tag.
*
* ### Options
*
* - `escape` Whether the contents should be html_entity escaped.
*
* @param string|null $class CSS class name of the p element.
* @param string|null $text String content that will appear inside the p element.
* @param array<string, mixed> $options Additional HTML attributes of the P tag
* @return string The formatted P element
*/
public function para(?string $class, ?string $text, array $options = []): string
{
if (!empty($options['escape'])) {
$text = h($text);
}
if ($class) {
$options['class'] = $class;
}
$tag = 'para';
if ($text === null) {
$tag = 'parastart';
}
return $this->formatTemplate($tag, [
'attrs' => $this->templater()->formatAttributes($options),
'content' => $text,
]);
}
/**
* Returns an audio/video element
*
* ### Usage
*
* Using an audio file:
*
* ```
* echo $this->Html->media('audio.mp3', ['fullBase' => true]);
* ```
*
* Outputs:
*
* ```
* <video src="http://www.somehost.com/files/audio.mp3">Fallback text</video>
* ```
*
* Using a video file:
*
* ```
* echo $this->Html->media('video.mp4', ['text' => 'Fallback text']);
* ```
*
* Outputs:
*
* ```
* <video src="/files/video.mp4">Fallback text</video>
* ```
*
* Using multiple video files:
*
* ```
* echo $this->Html->media(
* ['video.mp4', ['src' => 'video.ogv', 'type' => "video/ogg; codecs='theora, vorbis'"]],
* ['tag' => 'video', 'autoplay']
* );
* ```
*
* Outputs:
*
* ```
* <video autoplay="autoplay">
* <source src="/files/video.mp4" type="video/mp4"/>
* <source src="/files/video.ogv" type="video/ogv; codecs='theora, vorbis'"/>
* </video>
* ```
*
* ### Options
*
* - `tag` Type of media element to generate, either "audio" or "video".
* If tag is not provided it's guessed based on file's mime type.
* - `text` Text to include inside the audio/video tag
* - `pathPrefix` Path prefix to use for relative URLs, defaults to 'files/'
* - `fullBase` If provided the src attribute will get a full address including domain name
*
* @param array|string $path Path to the video file, relative to the webroot/{$options['pathPrefix']} directory.
* Or an array where each item itself can be a path string or an associate array containing keys `src` and `type`
* @param array<string, mixed> $options Array of HTML attributes, and special options above.
* @return string Generated media element
*/
public function media($path, array $options = []): string
{
$options += [
'tag' => null,
'pathPrefix' => 'files/',
'text' => '',
];
if (!empty($options['tag'])) {
$tag = $options['tag'];
} else {