-
Notifications
You must be signed in to change notification settings - Fork 3.4k
Expand file tree
/
Copy pathView.php
More file actions
1713 lines (1523 loc) · 51.5 KB
/
View.php
File metadata and controls
1713 lines (1523 loc) · 51.5 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
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.10.0
* @license https://www.opensource.org/licenses/mit-license.php MIT License
*/
namespace Cake\View;
use Cake\Cache\Cache;
use Cake\Core\App;
use Cake\Core\Exception\CakeException;
use Cake\Core\InstanceConfigTrait;
use Cake\Core\Plugin;
use Cake\Event\EventDispatcherInterface;
use Cake\Event\EventDispatcherTrait;
use Cake\Event\EventManagerInterface;
use Cake\Http\Response;
use Cake\Http\ServerRequest;
use Cake\Log\LogTrait;
use Cake\Routing\Router;
use Cake\Utility\Inflector;
use Cake\View\Exception\MissingElementException;
use Cake\View\Exception\MissingLayoutException;
use Cake\View\Exception\MissingTemplateException;
use Generator;
use InvalidArgumentException;
use LogicException;
use Throwable;
use function Cake\Core\pluginSplit;
/**
* View, the V in the MVC triad. View interacts with Helpers and view variables passed
* in from the controller to render the results of the controller action. Often this is HTML,
* but can also take the form of JSON, XML, PDF's or streaming files.
*
* CakePHP uses a two-step-view pattern. This means that the template content is rendered first,
* and then inserted into the selected layout. This also means you can pass data from the template to the
* layout using `$this->set()`
*
* View class supports using plugins as themes. You can set
*
* ```
* public function beforeRender(\Cake\Event\EventInterface $event)
* {
* $this->viewBuilder()->setTheme('SuperHot');
* }
* ```
*
* in your Controller to use plugin `SuperHot` as a theme. Eg. If current action
* is PostsController::index() then View class will look for template file
* `plugins/SuperHot/templates/Posts/index.php`. If a theme template
* is not found for the current action the default app template file is used.
*
* @property \Cake\View\Helper\BreadcrumbsHelper $Breadcrumbs
* @property \Cake\View\Helper\FlashHelper $Flash
* @property \Cake\View\Helper\FormHelper $Form
* @property \Cake\View\Helper\HtmlHelper $Html
* @property \Cake\View\Helper\NumberHelper $Number
* @property \Cake\View\Helper\PaginatorHelper $Paginator
* @property \Cake\View\Helper\TextHelper $Text
* @property \Cake\View\Helper\TimeHelper $Time
* @property \Cake\View\Helper\UrlHelper $Url
* @property \Cake\View\ViewBlock $Blocks
* @template TSubject of \Cake\View\View
* @implements \Cake\Event\EventDispatcherInterface<TSubject>
*/
class View implements EventDispatcherInterface
{
use CellTrait {
cell as public;
}
/**
* @use \Cake\Event\EventDispatcherTrait<TSubject>
*/
use EventDispatcherTrait;
use InstanceConfigTrait;
use LogTrait;
/**
* Helpers collection
*
* @var \Cake\View\HelperRegistry|null
*/
protected ?HelperRegistry $_helpers = null;
/**
* ViewBlock instance.
*
* @var \Cake\View\ViewBlock
*/
protected ViewBlock $Blocks;
/**
* The name of the plugin.
*
* @var string|null
*/
protected ?string $plugin = null;
/**
* Name of the controller that created the View if any.
*
* @var string
*/
protected string $name = '';
/**
* A configuration array for helpers to be loaded.
*
* @var array<string, array<string, mixed>>
*/
protected array $helpers = [];
/**
* The name of the subfolder containing templates for this View.
*
* @var string
*/
protected string $templatePath = '';
/**
* The name of the template file to render. The name specified
* is the filename in `templates/<SubFolder>/` without the .php extension.
*
* @var string
*/
protected string $template = '';
/**
* The name of the layout file to render the template inside of. The name specified
* is the filename of the layout in `templates/layout/` without the .php
* extension.
*
* @var string
*/
protected string $layout = 'default';
/**
* The name of the layouts subfolder containing layouts for this View.
*
* @var string
*/
protected string $layoutPath = '';
/**
* Turns on or off CakePHP's conventional mode of applying layout files. On by default.
* Setting to off means that layouts will not be automatically applied to rendered templates.
*
* @var bool
*/
protected bool $autoLayout = true;
/**
* An array of variables
*
* @var array<string, mixed>
*/
protected array $viewVars = [];
/**
* File extension. Defaults to ".php".
*
* @var string
*/
protected string $_ext = '.php';
/**
* Sub-directory for this template file. This is often used for extension based routing.
* Eg. With an `xml` extension, $subDir would be `xml/`
*
* @var string
*/
protected string $subDir = '';
/**
* The view theme to use.
*
* @var string|null
*/
protected ?string $theme = null;
/**
* An instance of a \Cake\Http\ServerRequest object that contains information about the current request.
* This object contains all the information about a request and several methods for reading
* additional information about the request.
*
* @var \Cake\Http\ServerRequest
*/
protected ServerRequest $request;
/**
* Reference to the Response object
*
* @var \Cake\Http\Response
*/
protected Response $response;
/**
* The Cache configuration View will use to store cached elements. Changing this will change
* the default configuration elements are stored under. You can also choose a cache config
* per element.
*
* @var string
* @see \Cake\View\View::element()
*/
protected string $elementCache = 'default';
/**
* The merge strategy for config options.
* Can be MERGE_DEEP (recursive merge, default for BC) or MERGE_SHALLOW (simple merge).
*
* @var string
*/
protected string $configMergeStrategy = ViewBuilder::MERGE_DEEP;
/**
* List of variables to collect from the associated controller.
*
* @var array<string>
*/
protected array $_passedVars = [
'viewVars', 'autoLayout', 'helpers', 'template', 'layout', 'name', 'theme',
'layoutPath', 'templatePath', 'plugin', 'configMergeStrategy',
];
/**
* Default custom config options.
*
* @var array<string, mixed>
*/
protected array $_defaultConfig = [];
/**
* Holds an array of paths.
*
* @var array<string>
*/
protected array $_paths = [];
/**
* Holds an array of plugin paths.
*
* @var array<string, array<string>>
*/
protected array $_pathsForPlugin = [];
/**
* The names of views and their parents used with View::extend();
*
* @var array<string, string>
*/
protected array $_parents = [];
/**
* The currently rendering view file. Used for resolving parent files.
*
* @var string
*/
protected string $_current = '';
/**
* Currently rendering an element. Used for finding parent fragments
* for elements.
*
* @var string
*/
protected string $_currentType = '';
/**
* Content stack, used for nested templates that all use View::extend();
*
* @var array<string>
*/
protected array $_stack = [];
/**
* ViewBlock class.
*
* @var string
* @phpstan-var class-string<\Cake\View\ViewBlock>
*/
protected string $_viewBlockClass = ViewBlock::class;
/**
* Constant for view file type 'template'.
*
* @var string
*/
public const TYPE_TEMPLATE = 'template';
/**
* Constant for view file type 'element'
*
* @var string
*/
public const TYPE_ELEMENT = 'element';
/**
* Constant for view file type 'layout'
*
* @var string
*/
public const TYPE_LAYOUT = 'layout';
/**
* Constant for type used for App::path().
*
* @var string
*/
public const NAME_TEMPLATE = 'templates';
/**
* Constant for folder name containing files for overriding plugin templates.
*
* @var string
*/
public const PLUGIN_TEMPLATE_FOLDER = 'plugin';
/**
* The magic 'match-all' content type that views can use to
* behave as a fallback during content-type negotiation.
*
* @var string
*/
public const TYPE_MATCH_ALL = '_match_all_';
/**
* Constructor
*
* @param \Cake\Http\ServerRequest|null $request Request instance.
* @param \Cake\Http\Response|null $response Response instance.
* @param \Cake\Event\EventManagerInterface|null $eventManager Event manager instance.
* @param array<string, mixed> $viewOptions View options. See {@link View::$_passedVars} for list of
* options which get set as class properties.
*/
public function __construct(
?ServerRequest $request = null,
?Response $response = null,
?EventManagerInterface $eventManager = null,
array $viewOptions = [],
) {
if ($eventManager !== null) {
// Set the event manager before accessing the helper registry below
// to ensure that helpers are registered as listeners with the manager when loaded.
$this->setEventManager($eventManager);
}
foreach ($this->_passedVars as $var) {
if (isset($viewOptions[$var])) {
$this->{$var} = $viewOptions[$var];
}
}
if ($this->helpers) {
$this->helpers = $this->helpers()->normalizeArray($this->helpers);
}
$config = array_diff_key(
$viewOptions,
array_flip($this->_passedVars),
);
if ($this->configMergeStrategy === ViewBuilder::MERGE_SHALLOW) {
$this->configShallow($config);
} else {
$this->setConfig($config);
}
$request ??= Router::getRequest() ?: new ServerRequest(['base' => '', 'url' => '', 'webroot' => '/']);
$this->request = $request;
$this->response = $response ?: new Response();
$this->Blocks = new $this->_viewBlockClass();
$this->initialize();
$this->loadHelpers();
}
/**
* Initialization hook method.
*
* Properties like $helpers etc. cannot be initialized statically in your custom
* view class as they are overwritten by values from controller in constructor.
* So this method allows you to manipulate them as required after view instance
* is constructed.
*
* Helpers can be added using {@link addHelper()} method.
*
* @return void
*/
public function initialize(): void
{
$this->setContentType();
}
/**
* Set the response content-type based on the view's contentType()
*
* @return void
*/
protected function setContentType(): void
{
$viewContentType = static::contentType();
if (!$viewContentType || $viewContentType === static::TYPE_MATCH_ALL) {
return;
}
$response = $this->getResponse();
$responseType = $response->getHeaderLine('Content-Type');
if ($responseType === '' || str_starts_with($responseType, 'text/html')) {
$response = $response->withType($viewContentType);
}
$this->setResponse($response);
}
/**
* Mime-type this view class renders as.
*
* @return string Either the content type or '' which means no type.
*/
public static function contentType(): string
{
return '';
}
/**
* Gets the request instance.
*
* @return \Cake\Http\ServerRequest
* @since 3.7.0
*/
public function getRequest(): ServerRequest
{
return $this->request;
}
/**
* Sets the request objects and configures a number of controller properties
* based on the contents of the request. The properties that get set are:
*
* - $this->request - To the $request parameter
* - $this->plugin - To the value returned by $request->getParam('plugin')
*
* @param \Cake\Http\ServerRequest $request Request instance.
* @return $this
*/
public function setRequest(ServerRequest $request)
{
$this->request = $request;
$this->plugin = $request->getParam('plugin');
return $this;
}
/**
* Gets the response instance.
*
* @return \Cake\Http\Response
*/
public function getResponse(): Response
{
return $this->response;
}
/**
* Sets the response instance.
*
* @param \Cake\Http\Response $response Response instance.
* @return $this
*/
public function setResponse(Response $response)
{
$this->response = $response;
return $this;
}
/**
* Get path for templates files.
*
* @return string
*/
public function getTemplatePath(): string
{
return $this->templatePath;
}
/**
* Set path for templates files.
*
* @param string $path Path for template files.
* @return $this
*/
public function setTemplatePath(string $path)
{
$this->templatePath = $path;
return $this;
}
/**
* Get path for layout files.
*
* @return string
*/
public function getLayoutPath(): string
{
return $this->layoutPath;
}
/**
* Set path for layout files.
*
* @param string $path Path for layout files.
* @return $this
*/
public function setLayoutPath(string $path)
{
$this->layoutPath = $path;
return $this;
}
/**
* Returns if CakePHP's conventional mode of applying layout files is enabled.
* Disabled means that layouts will not be automatically applied to rendered views.
*
* @return bool
*/
public function isAutoLayoutEnabled(): bool
{
return $this->autoLayout;
}
/**
* Turns on or off CakePHP's conventional mode of applying layout files.
* On by default. Setting to off means that layouts will not be
* automatically applied to rendered views.
*
* @param bool $enable Boolean to turn on/off.
* @return $this
*/
public function enableAutoLayout(bool $enable = true)
{
$this->autoLayout = $enable;
return $this;
}
/**
* Turns off CakePHP's conventional mode of applying layout files.
* Layouts will not be automatically applied to rendered views.
*
* @return $this
*/
public function disableAutoLayout()
{
$this->autoLayout = false;
return $this;
}
/**
* Get the current view theme.
*
* @return string|null
*/
public function getTheme(): ?string
{
return $this->theme;
}
/**
* Set the view theme to use.
*
* @param string|null $theme Theme name.
* @return $this
*/
public function setTheme(?string $theme)
{
$this->theme = $theme;
return $this;
}
/**
* Get the name of the template file to render. The name specified is the
* filename in `templates/<SubFolder>/` without the .php extension.
*
* @return string
*/
public function getTemplate(): string
{
return $this->template;
}
/**
* Set the name of the template file to render. The name specified is the
* filename in `templates/<SubFolder>/` without the .php extension.
*
* @param string $name Template file name to set.
* @return $this
*/
public function setTemplate(string $name)
{
$this->template = $name;
return $this;
}
/**
* Get the name of the layout file to render the template inside of.
* The name specified is the filename of the layout in `templates/layout/`
* without the .php extension.
*
* @return string
*/
public function getLayout(): string
{
return $this->layout;
}
/**
* Set the name of the layout file to render the template inside of.
* The name specified is the filename of the layout in `templates/layout/`
* without the .php extension.
*
* @param string $name Layout file name to set.
* @return $this
*/
public function setLayout(string $name)
{
$this->layout = $name;
return $this;
}
/**
* Renders a piece of PHP with provided parameters and returns HTML, XML, or any other string.
*
* This realizes the concept of Elements, (or "partial layouts") and the $params array is used to send
* data to be used in the element. Elements can be cached improving performance by using the `cache` option.
*
* @param string $name Name of template file in the `templates/element/` folder,
* or `MyPlugin.template` to use the template element from MyPlugin. If the element
* is not found in the plugin, the normal view path cascade will be searched.
* @param array $data Array of data to be made available to the rendered view (i.e. the Element)
* @param array<string, mixed> $options Array of options. Possible keys are:
*
* - `cache` - Can either be `true`, to enable caching using the config in View::$elementCache. Or an array
* If an array, the following keys can be used:
*
* - `config` - Used to store the cached element in a custom cache configuration.
* - `key` - Used to define the key used in the Cache::write(). It will be prefixed with `element_`
*
* - `callbacks` - Set to true to fire beforeRender and afterRender helper callbacks for this element.
* Defaults to false.
* - `ignoreMissing` - Used to allow missing elements. Set to true to not throw exceptions.
* - `plugin` - setting to false will force to use the application's element from plugin templates, when the
* plugin has element with same name. Defaults to true
* @return string Rendered Element
* @throws \Cake\View\Exception\MissingElementException When an element is missing and `ignoreMissing`
* is false.
* @phpstan-param array{cache?:array|true, callbacks?:bool, plugin?:string|false, ignoreMissing?:bool} $options
*/
public function element(string $name, array $data = [], array $options = []): string
{
$options += ['callbacks' => false, 'cache' => null, 'plugin' => null, 'ignoreMissing' => false];
if (isset($options['cache'])) {
$options['cache'] = $this->_elementCache(
$name,
$data,
array_diff_key($options, ['callbacks' => false, 'plugin' => null, 'ignoreMissing' => null]),
);
}
$pluginCheck = $options['plugin'] !== false;
$file = $this->_getElementFileName($name, $pluginCheck);
if ($file && $options['cache']) {
return $this->cache(function () use ($file, $data, $options): void {
echo $this->_renderElement($file, $data, $options);
}, $options['cache']);
}
if ($file) {
return $this->_renderElement($file, $data, $options);
}
if ($options['ignoreMissing']) {
return '';
}
[$plugin, $elementName] = $this->pluginSplit($name, $pluginCheck);
$paths = iterator_to_array($this->getElementPaths($plugin));
throw new MissingElementException([$name . $this->_ext, $elementName . $this->_ext], $paths);
}
/**
* Create a cached block of view logic.
*
* This allows you to cache a block of view output into the cache
* defined in `elementCache`.
*
* This method will attempt to read the cache first. If the cache
* is empty, the $block will be run and the output stored.
*
* @param callable $block The block of code that you want to cache the output of.
* @param array<string, mixed> $options The options defining the cache key etc.
* @return string The rendered content.
* @throws \InvalidArgumentException When $options is lacking a 'key' option.
*/
public function cache(callable $block, array $options = []): string
{
$options += ['key' => '', 'config' => $this->elementCache];
if (empty($options['key'])) {
throw new InvalidArgumentException('Cannot cache content with an empty key');
}
$result = Cache::read($options['key'], $options['config']);
if ($result) {
return $result;
}
$bufferLevel = ob_get_level();
ob_start();
try {
$block();
} catch (Throwable $exception) {
while (ob_get_level() > $bufferLevel) {
ob_end_clean();
}
throw $exception;
}
$result = (string)ob_get_clean();
Cache::write($options['key'], $result, $options['config']);
return $result;
}
/**
* Checks if an element exists
*
* @param string $name Name of template file in the `templates/element/` folder,
* or `MyPlugin.template` to check the template element from MyPlugin. If the element
* is not found in the plugin, the normal view path cascade will be searched.
* @return bool Success
*/
public function elementExists(string $name): bool
{
return (bool)$this->_getElementFileName($name);
}
/**
* Renders view for given template file and layout.
*
* Render triggers helper callbacks, which are fired before and after the template are rendered,
* as well as before and after the layout. The helper callbacks are called:
*
* - `beforeRender`
* - `afterRender`
* - `beforeLayout`
* - `afterLayout`
*
* If View::$autoLayout is set to `false`, the template will be returned bare.
*
* Template and layout names can point to plugin templates or layouts. Using the `Plugin.template` syntax
* a plugin template/layout/ can be used instead of the app ones. If the chosen plugin is not found
* the template will be located along the regular view path cascade.
*
* @param string|null $template Name of template file to use
* @param string|false|null $layout Layout to use. False to disable.
* @return string Rendered content.
* @throws \Cake\Core\Exception\CakeException If there is an error in the view.
* @triggers View.beforeRender $this, [$templateFileName]
* @triggers View.afterRender $this, [$templateFileName]
*/
public function render(?string $template = null, string|false|null $layout = null): string
{
$defaultLayout = '';
$defaultAutoLayout = null;
if ($layout === false) {
$defaultAutoLayout = $this->autoLayout;
$this->autoLayout = false;
} elseif ($layout !== null) {
$defaultLayout = $this->layout;
$this->layout = $layout;
}
$templateFileName = $this->_getTemplateFileName($template);
$this->_currentType = static::TYPE_TEMPLATE;
$this->dispatchEvent('View.beforeRender', [$templateFileName]);
$this->Blocks->set('content', $this->_render($templateFileName));
$this->dispatchEvent('View.afterRender', [$templateFileName]);
if ($this->autoLayout) {
if (!$this->layout) {
throw new CakeException(
'View::$layout must be a non-empty string.' .
'To disable layout rendering use method `View::disableAutoLayout()` instead.',
);
}
$this->Blocks->set('content', $this->renderLayout('', $this->layout));
}
if ($layout !== null) {
$this->layout = $defaultLayout;
}
if ($defaultAutoLayout !== null) {
$this->autoLayout = $defaultAutoLayout;
}
return $this->Blocks->get('content');
}
/**
* Renders a layout. Returns output from _render().
*
* Several variables are created for use in layout.
*
* @param string $content Content to render in a template, wrapped by the surrounding layout.
* @param string|null $layout Layout name
* @return string Rendered output.
* @throws \Cake\Core\Exception\CakeException if there is an error in the view.
* @triggers View.beforeLayout $this, [$layoutFileName]
* @triggers View.afterLayout $this, [$layoutFileName]
*/
public function renderLayout(string $content, ?string $layout = null): string
{
$layoutFileName = $this->_getLayoutFileName($layout);
if ($content) {
$this->Blocks->set('content', $content);
}
$this->dispatchEvent('View.beforeLayout', [$layoutFileName]);
$title = $this->Blocks->get('title');
if ($title === '') {
$title = Inflector::humanize(str_replace(DIRECTORY_SEPARATOR, '/', $this->templatePath));
$this->Blocks->set('title', $title);
}
$this->_currentType = static::TYPE_LAYOUT;
$this->Blocks->set('content', $this->_render($layoutFileName));
$this->dispatchEvent('View.afterLayout', [$layoutFileName]);
return $this->Blocks->get('content');
}
/**
* Returns a list of variables available in the current View context
*
* @return array<string> Array of the set view variable names.
*/
public function getVars(): array
{
return array_keys($this->viewVars);
}
/**
* Returns the contents of the given View variable.
*
* @param string $var The view var you want the contents of.
* @param mixed $default The default/fallback content of $var.
* @return mixed The content of the named var if its set, otherwise $default.
*/
public function get(string $var, mixed $default = null): mixed
{
return $this->viewVars[$var] ?? $default;
}
/**
* Saves a variable or an associative array of variables for use inside a template.
*
* @param array|string $name A string or an array of data.
* @param mixed $value Value in case $name is a string (which then works as the key).
* Unused if $name is an associative array, otherwise serves as the values to $name's keys.
* @return $this
* @throws \Cake\Core\Exception\CakeException If the array combine operation failed.
*/
public function set(array|string $name, mixed $value = null)
{
if (is_array($name)) {
if (is_array($value)) {
$data = array_combine($name, $value);
if ($data === false) {
throw new CakeException(
'Invalid data provided for array_combine() to work: Both $name and $value require same count.',
);
}
} else {
$data = $name;
}
} else {
$data = [$name => $value];
}
$this->viewVars = $data + $this->viewVars;
return $this;
}
/**
* Get the names of all the existing blocks.
*
* @return array<string> An array containing the blocks.
* @see \Cake\View\ViewBlock::keys()
*/
public function blocks(): array
{
return $this->Blocks->keys();
}
/**
* Start capturing output for a 'block'
*
* You can use start on a block multiple times to
* append or prepend content in a capture mode.
*
* ```
* // Append content to an existing block.
* $this->start('content');
* echo $this->fetch('content');
* echo 'Some new content';
* $this->end();
*
* // Prepend content to an existing block
* $this->start('content');
* echo 'Some new content';
* echo $this->fetch('content');
* $this->end();
* ```
*
* @param string $name The name of the block to capture for.
* @return $this
* @see \Cake\View\ViewBlock::start()
*/
public function start(string $name)
{
$this->Blocks->start($name);
return $this;
}
/**
* Append to an existing or new block.
*
* Appending to a new block will create the block.
*
* @param string $name Name of the block
* @param mixed $value The content for the block. Value will be type cast
* to string.
* @return $this
* @see \Cake\View\ViewBlock::concat()
*/
public function append(string $name, mixed $value = null)
{
$this->Blocks->concat($name, $value);
return $this;
}
/**
* Prepend to an existing or new block.
*
* Prepending to a new block will create the block.
*
* @param string $name Name of the block
* @param mixed $value The content for the block. Value will be type cast
* to string.
* @return $this
* @see \Cake\View\ViewBlock::concat()
*/
public function prepend(string $name, mixed $value)
{
$this->Blocks->concat($name, $value, ViewBlock::PREPEND);
return $this;
}
/**
* Set the content for a block. This will overwrite any
* existing content.
*
* @param string $name Name of the block
* @param mixed $value The content for the block. Value will be type cast
* to string.
* @return $this
* @see \Cake\View\ViewBlock::set()
*/
public function assign(string $name, mixed $value)
{