-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathWireframe.module.php
1302 lines (1156 loc) · 45.4 KB
/
Wireframe.module.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
namespace ProcessWire;
/**
* Wireframe ProcessWire module
*
* Wireframe is an output framework with MVC inspired architecture for ProcessWire CMS/CMF.
* See README.md or https://wireframe-framework.com for more details.
*
* Methods provided by \Wireframe\Factory:
*
* @method static \Wireframe\Component component(string $component_name, array $args = []) Static getter (factory) method for Components.
* @method static string|Page|NullPage page($source, $args = []) Static getter (factory) method for Pages.
* @method static string|null partial(string $partial_name, array $args = []) Static getter (factory) method for Partials.
*
* @version 0.31.0
* @author Teppo Koivula <[email protected]>
* @license Mozilla Public License v2.0 https://mozilla.org/MPL/2.0/
*/
class Wireframe extends WireData implements Module, ConfigurableModule {
/**
* Config settings
*
* @var array
*/
protected $config = [];
/**
* Paths from config
*
* @var object
*/
protected $paths;
/**
* The extension for view, layout, and partial files
*
* @var null|string
*/
protected $ext;
/**
* Current Page object
*
* @var null|Page
*/
protected $page;
/**
* View object
*
* @var null|\Wireframe\View
*/
protected $view;
/**
* Controller object
*
* @var null|\Wireframe\Controller
*/
protected $controller;
/**
* Stash array
*
* Current context (Page, View, and Controller) can be stored in the stash and then restored at a later time.
* Context is stashed at the beginning of ___init() and restored at the end of ___render().
*
* @var array
*/
protected $stash = [];
/**
* Renderer object
*
* @var null|Module
*/
protected $renderer;
/**
* View data
*
* @var array
*/
protected $data = [];
/**
* Settings hash for comparison purposes
*
* @var string
*/
protected $settings_hash;
/**
* Settings hash locked?
*
* This property is used to lock the settings hash. While locked, settings hash won't get automatically updated
* by any of the Wireframe class methods that would normally update it. This helps avoid unnecessary overhead
* caused by multiple consecutive update operations.
*
* @var bool
*/
protected $settings_hash_locked = false;
/**
* Create directories automatically?
*
* Used by the module configuration screen. Contains an array of directories that should be automatically created.
*
* @var array
*/
protected $create_directories = [];
/**
* Return inputfields necessary to configure the module
*
* @param array $data Data array.
* @return InputfieldWrapper Wrapper with inputfields needed to configure the module.
*/
public function getModuleConfigInputfields(array $data) {
// init necessary parts of Wireframe
$this->setConfig();
// instantiate Wireframe Config and get all config inputfields
$config = $this->wire(new \Wireframe\Config($this, $data));
$fields = $config->getAllFields();
return $fields;
}
/**
* General purpose cache array
*
* @var array
*/
protected $cache = [];
/**
* Keep track of whether Wireframe has already been initialized
*
* This information is stored in an array for it to work properly with multi-instance support; in such cases we
* need to make sure that initOnce() is run once per ProcessWire instance.
*
* @var array
*/
protected static $initialized = [];
/**
* Initialize Wireframe
*
* @param array $settings Array of additional settings (optional). Supported settings:
* - `page` (Page): current Page object
* - `paths` (array): custom paths for Wireframe objects; views, layouts, partials, components, etc.
* - `data` (array): variables for the View, does the same thing as passing an assoc array to the render method
* - `ext` (string|null): file extension for view, layout, and partial files; default value is pulled from site config
* - `renderer` (Module|string|null): name or instance of a Renderer module, or null for none
* @return Wireframe Self-reference.
*
* @throws WireException if no valid Page object is found.
*/
public function ___init(array $settings = []): Wireframe {
// make sure that we have a valid Page
$current_page = $settings['page'] ?? $this->wire('page');
if (!$current_page instanceof Page || !$current_page->id) {
throw new WireException('No valid Page object found');
}
// check if we're currently rendering a view placeholder, in which case we'll skip most of the init process
if ($this->page && $this->page->id === $current_page->id && $this->page->_wireframe_context === 'placeholder' && $this->view) {
$this->initView([
'data' => $this->view->getArray(),
]);
$this->setView();
return $this;
}
// if page, view, controller, or data are already set, stash them
if ($this->page || $this->view || $this->controller || !empty($this->data)) {
$this->stash[] = [
'page' => $this->page,
'view' => $this->view,
'controller' => $this->controller,
'data' => $this->data,
];
if ($this->page && $this->page->id === $current_page->id && $current_page->_wireframe_controller !== null) {
// if current page is the same as the page being stashed and it has controller defined, discard it;
// we've already stashed the controller, so there's no point in leaving a reference to it in place.
$current_page->_wireframe_controller = null;
}
$this->view = null;
$this->controller = null;
$this->data = [];
}
// set current page
$this->page = $current_page;
// lock settings hash
$this->settings_hash_locked = true;
// perform init tasks that should only run once
$this->initOnce();
// set any additional settings
$this->setArray($settings);
// check for redirects
$this->checkRedirects();
// store template extension locally
if (!$this->ext) $this->setExt();
// initialize View and Controller
$this->initView();
$this->initController();
// choose the view to use
$this->setView();
// release settings hash lock and trigger an update
$this->settings_hash_locked = false;
$this->updateSettingsHash();
return $this;
}
/**
* This method performs init tasks that should only run once
*
* @return bool True on first run, false if already initialized.
*/
public function initOnce(): bool {
// bail out early if already initialized
if (static::isInitialized($this->wire()->instanceID)) return false;
// set config settings
$this->setConfig();
// attach hooks
$hooks = $this->wire(new \Wireframe\Hooks($this));
$hooks->init();
// remember that this method has been run
static::$initialized[] = $this->wire()->instanceID;
// return true on first run
return true;
}
/**
* Check if Wireframe has already been initialized
*
* As long as $instanceID is provided, this method will work on a multi-instance ProcessWire setup. If $instanceID
* is left out (null), we get it from the wire() function instead.
*
* @param null|int $instanceID ProcessWire instance ID. This parameter is optional but recommended.
* @return bool True if initialized, false if not.
*/
public static function isInitialized(int $instanceID = null): bool {
return \in_array(
$instanceID === null ? wire()->instanceID : $instanceID,
static::$initialized
);
}
/**
* Define runtime config settings
*
* If runtime config settings already exist, those will be kept, with new values overwriting existing values with
* the same name. In order to reset previously (manually) defined config values, provide default values for them.
* You can get default config values by calling the getConfigDefaults() method.
*
* @param array $config Optional configuration settings array.
* @return Wireframe Self-reference.
*/
public function ___setConfig(array $config = []): Wireframe {
// combine default config settings with custom ones
$config_merged = array_merge(
$this->getConfigDefaults(),
\is_array($this->wire('config')->wireframe) ? $this->wire('config')->wireframe : [],
$this->config,
$config
);
// check if paths or include_paths have changed
$set_paths = !isset($this->config['paths']) || $this->config['paths'] != $config_merged['paths'];
$set_include_path = !isset($this->config['include_paths']) || $this->config['include_paths'] != $config_merged['include_paths'];
// URL additions to global config settings
foreach ($config_merged['urls'] as $key => $value) {
$this->wire('config')->urls->set($key, $value);
}
// store config settings locally
$this->config = $config_merged;
// PHP include path additions
if ($set_include_path) {
$this->setIncludePath();
}
// set or update wireframe paths
if ($set_paths) {
$this->setPaths();
}
return $this;
}
/**
* Getter for runtime config settings
*
* @return array Current config settings.
*/
public function getConfig(): array {
$this->initOnce();
return $this->config;
}
/**
* Getter for default config settings
*
* If you need to customize or override any of the default config values, you can copy this array to your site
* config file (/site/config.php) as $config->wireframe, or call setConfig() with an array of override values.
*
* @return array Default config settings.
*/
public function getConfigDefaults(): array {
return [
'include_paths' => [
// '/path/to/shared/libraries/',
],
'redirect_fields' => [
// 'redirect_to_url',
// 'redirect_to_page' => [
// 'property' => 'url',
// 'permanent' => true,
// ],
],
'allow_get_view' => false,
// 'allow_get_view' => [
// 'home' => [
// 'json',
// 'rss',
// ],
// 'json',
// ],
// 'view_namespaces' => [
// 'sublayouts' => $this->wire('config')->paths->templates . 'sublayouts/',
// ],
'view_prefix' => '',
'paths' => [
'lib' => $this->wire('config')->paths->templates . "lib/",
'views' => $this->wire('config')->paths->templates . "views/",
'layouts' => $this->wire('config')->paths->templates . "layouts/",
'partials' => $this->wire('config')->paths->templates . "partials/",
'resources' => $this->wire('config')->paths->templates . "resources/",
'components' => $this->wire('config')->paths->templates . "components/",
'controllers' => $this->wire('config')->paths->templates . "controllers/",
],
'global_config_paths' => [
'partials',
],
'urls' => [
'dist' => $this->wire('config')->urls->assets . "dist/",
'resources' => $this->wire('config')->urls->templates . "resources/",
],
];
}
/**
* Set or update paths
*
* This method makes necessary site config additions/modifications and updates ProcessWire's class autoloader.
*
* Note: it's a bit of a border case, but it's probably worth noting that if this method has already been called
* *and* you've instantiated a class found from previously set paths, you *can't* instantiate a different class
* with exactly the same name from a new path. (PHP doesn't allow "uncaching" previously declared classes.)
*
* @param array $paths Paths array for overriding default values.
* @return Wireframe Self-reference.
*/
public function setPaths(array $paths = []): Wireframe {
// if called with empty paths array, get paths from config; otherwise make sure that config paths are in sync
// with values defined here (overwrite config values if they exist)
if (empty($paths)) {
$paths = $this->config['paths'];
} else if (isset($this->config['paths'])) {
$this->config['paths'] = array_merge(
$this->config['paths'],
$paths
);
}
// set or update paths stored in the global ProcessWire Config object
foreach ($this->config['global_config_paths'] as $path) {
$this->wire('config')->paths->set($path, $paths[$path] ?? null);
}
// store paths locally as an object and add Wireframe namespaces to ProcessWire's class autoloader (namespaces
// are dependent on the paths defined here, hence the tight coupling between these two methods)
$this->paths = (object) $paths;
$this->addNamespaces();
// update settings hash
$this->updateSettingsHash();
return $this;
}
/**
* Getter method for View paths
*
* @return array Paths array.
*/
public function getViewPaths(): array {
return $this->paths ? [
'view' => $this->paths->views,
'layout' => $this->paths->layouts,
'partial' => $this->paths->partials,
'component' => $this->paths->components,
] : [];
}
/**
* Store template extension in a class property
*
* @param string|null $ext Extension string for overriding the default value.
* @return Wireframe Self-reference.
*/
public function setExt(string $ext = null): Wireframe {
$this->ext = "." . ltrim($ext ?: $this->wire('config')->templateExtension, '.');
// store ext in config for use in Factory::partial()
$this->wire('config')->_wireframeTemplateExtension = $this->ext;
if ($this->view) {
$this->view->setExt($this->ext);
$this->view->setView($this->view->getView());
}
$this->updateSettingsHash();
return $this;
}
/**
* Store renderer object in a class property and update View renderer
*
* @param Module|string|null $renderer Renderer module, name of a renderer module, or null to unset.
* @param array $settings Optional array of settings for the renderer module.
* @return Wireframe Self-reference.
*/
public function setRenderer($renderer, array $settings = []): Wireframe {
$needs_init = !empty($settings);
if ($renderer === null) {
$this->renderer = null;
if ($this->view) {
$this->view->setRenderer(null);
}
} else if (\is_string($renderer)) {
$renderer = $this->wire('modules')->get($renderer);
$needs_init = true;
}
if ($renderer instanceof Module) {
if ($needs_init) {
/**
* @noinspection PhpUndefinedMethodInspection
* @disregard P1013 as it's a false positive; renderers are expected to have init() method
*/
$renderer->init($settings);
}
$this->renderer = $renderer;
/**
* @noinspection PhpUndefinedMethodInspection
* @disregard P1013 as it's a false positive; renderers are expected to have getExt() method
*/
$this->setExt($renderer->getExt());
if ($this->view && $this->view->getRenderer() != $renderer) {
$this->view->setRenderer($renderer);
}
}
$this->updateSettingsHash();
return $this;
}
/**
* Add Wireframe namespaces to ProcessWire's class autoloader
*
* This method makes ProcessWire's class autoloader aware of the Wireframe namespaces, which enables us to
* instantiate – or call static methods from – Wireframe objects without first requiring the related PHP file.
*
* If you want to add additional namespaces (or additional paths for the namespaces added here), you can access
* the $classLoader API variable directly via your own code. If you want to override namespaces added here, you
* should call $classLoader->removeNamespace($namespace, $path) before re-adding the namespace with a new path.
*/
protected function addNamespaces() {
// declare our namespaces
$namespaces = [
'Wireframe' => $this->wire('config')->paths->Wireframe . 'lib/',
'Wireframe\Component' => $this->paths->components,
'Wireframe\Controller' => $this->paths->controllers,
'Wireframe\Lib' => $this->paths->lib,
];
/** @var WireClassLoader ProcessWire's class autoloader */
$classLoader = $this->wire('classLoader');
// make class autoloader aware of our namespaces
foreach ($namespaces as $namespace => $path) {
// if namespaces have already been added, remove old ones first, just in case; this could, for an example,
// happen if paths are changed manually after calling the init method
if ($classLoader->hasNamespace($namespace)) {
$classLoader->removeNamespace($namespace);
}
// add new namespace to class autoloader
$classLoader->addNamespace($namespace, $path);
}
}
/**
* Set PHP include path
*/
protected function setIncludePath() {
// add templates directory to the include path by default
$new_include_paths = [
$this->wire('config')->paths->templates,
];
// config settings may contain additional include paths
if (!empty($this->config['include_paths'])) {
$new_include_paths = array_merge(
$new_include_paths,
$this->config['include_paths']
);
}
// validate include path(s), removing any duplicate values (new ones, as well as those that have already been
// added to the PHP include path)
$current_include_path = get_include_path();
$current_include_path_parts = empty($current_include_path) ? [] : explode(PATH_SEPARATOR, $current_include_path);
$new_include_paths = array_unique(array_filter($new_include_paths, function($path) use ($current_include_path_parts) {
return !empty($path) && !in_array($path, $current_include_path_parts);
}));
// modify PHP include path if valid paths remain
if (!empty($new_include_paths)) {
set_include_path(
$current_include_path .
PATH_SEPARATOR .
implode(PATH_SEPARATOR, $new_include_paths)
);
}
}
/**
* Check redirects
*
* This method looks for a list of redirect fields within config settings (redirect_fields). If present, it checks
* if current page has a value in one of said fields, and if that value is a valid URL we can redirect to.
*/
protected function ___checkRedirects() {
// get redirect fields from runtime configuration
$redirect_fields = $this->config['redirect_fields'] ?? null;
if (empty($redirect_fields)) {
return;
}
// check individual redirect fields one by one
foreach ($redirect_fields as $key => $value) {
// if key is an integer, value contains the field name
$field = \is_int($key) ? $value : $key;
if (!\is_string($field)) {
continue;
}
// get URL value from current page
$url = $this->page->get($field);
if ($url instanceof WireArray) {
$url = $url->first();
}
if (empty($url)) {
continue;
}
// prepare options array
$options = \is_array($value) ? $value : [];
// check if a property was provided within options array
if (!empty($options['property']) && \is_object($url)) {
$url = $url->get($options['property']);
}
// skip this item if URL is not a string, if it belongs to current page, or if it's invalid
if (!\is_string($url) || $url === $this->page->url || !$this->wire('sanitizer')->url($url)) {
continue;
}
$this->redirect($url, !empty($options['permanent']));
}
}
/**
* Perform a redirect
*
* @param string $url Redirect URL.
* @param bool $permanent Is this a permanent (301) redirect?
*/
protected function ___redirect(string $url, bool $permanent) {
$this->wire('session')->redirect($url, $permanent);
}
/**
* Initialization method for the View
*
* This method initializes the View object and the $view API variable.
*
* @param array $settings Array of additional settings (optional). Supported settings:
* - `data` (array): variables for the View
* @return \Wireframe\View View object.
*/
protected function ___initView(array $settings = []): \Wireframe\View {
// get current page's layout
$page_layout = $this->page->getLayout();
// initialize the View object (note: view file is set in the Wireframe::___setView() method)
$this->view = $this->wire(new \Wireframe\View);
$this->view->setLayout($page_layout === null ? $this->getDefaultLayout() : $page_layout);
$this->view->setTemplate($this->page->getViewTemplate());
$this->view->setViewsPath($this->paths->views);
$this->view->setLayoutsPath($this->paths->layouts);
$this->view->setExt($this->ext);
$this->view->setPage($this->page);
$this->view->setData($settings['data'] ?? $this->data);
$this->view->setPartials($this->findPartials($this->paths->partials));
$this->view->setPlaceholders(new \Wireframe\ViewPlaceholders($this->view));
$this->view->setRenderer($this->renderer);
// define the $view API variable
$this->wire('view', $this->view);
return $this->view;
}
/**
* Initialization method for the Controller
*
* Controller is optional component in Wireframe, but if a Controller file is found, we'll attempt to instantiate
* an object from it.
*
* @return \Wireframe\Controller|null Controller object or null.
*/
protected function ___initController(): ?\Wireframe\Controller {
// get a new Controller instance and store it both locally, as a run-time property of current Page object, and
// as a reference within the View object
$this->controller = $this->getController($this->page);
$this->page->_wireframe_controller = $this->controller;
$this->view->setController($this->controller);
return $this->controller;
}
/**
* Set current view
*
* Default value is 'default', but the setView() method of the $page object or GET param 'view' (if configured so)
* can be used to override the default value.
*
* @param string|null $view Optional view name, leave blank to let Wireframe figure it out automatically.
* @return Wireframe Self-reference.
*/
public function ___setView(?string $view = null): Wireframe {
// first check if a predefined view name was provided
if ($view !== null) {
$view = basename($view);
$this->view->setView($view);
$this->page->setView($view);
return $this;
}
// priority for different sources: 1) View object, 2) Page object, 3) GET param, 4) return value from the getDefaultView
// method, which (as of this writing) is always "default"
$this->view->setView(basename(
$this->view->getView()
?: ($this->page->getView()
?: ($this->getViewFromInput()
?: $this->getDefaultView()
)
)
));
return $this;
}
/**
* Get view name from input params (GET)
*
* @return string|null
*/
protected function getViewFromInput(): ?string {
// bail out early if providing view name as a GET param is not allowed
if (!$this->config['allow_get_view']) {
return null;
}
// attempt to get view name from GET param 'view'
$input = $this->wire('input');
$get_view = $input->get->view;
if (!empty($get_view) && \is_array($this->config['allow_get_view'])) {
// allowing *any* view to be accessed via a GET param might not be appropriate; using an allow list lets us
// define the specific values that are considered safe
$get_view = null;
$template = $this->view->getTemplate() ?: $this->page->getViewTemplate();
foreach ($this->config['allow_get_view'] as $get_template => $get_value) {
if (\is_string($get_template) && \is_array($get_value) && $template === $get_template) {
$get_view = \in_array($input->get->view, $get_value) ? $input->get->view : null;
break;
} else if (\is_int($get_template) && \is_string($get_value) && $input->get->view === $get_value) {
$get_view = $get_value;
break;
}
}
}
return $get_view;
}
/**
* Set current view template
*
* View template is primarily used for figuring out where the view files for current page should come from. This is
* useful in case you want to use the exact same view files for pages using different (real) templates.
*
* Note: this method should be used if you need to override view template in the Wireframe bootstrap file.
*
* @param string|null $template Template name.
* @return Wireframe Self-reference.
*/
public function setViewTemplate(?string $template): Wireframe {
if ($this->page) {
$this->page->setViewTemplate($template);
}
if ($this->view) {
$this->view->setTemplate($template);
$this->view->setView($this->view->getView());
}
return $this;
}
/**
* Set current controller
*
* Note: this method should be used if you need to override controller in the Wireframe bootstrap file.
*
* @param string|null $template Template name.
* @return Wireframe Self-reference.
*/
public function setController(?string $template): Wireframe {
$this->controller = $this->getController($this->page, $template ?? '');
if ($this->page) {
$this->page->setController($this->controller);
}
if ($this->view) {
$this->view->setController($this->controller);
}
return $this;
}
/**
* Render the Page with specified View and Layout
*
* Note: this method returns null if both view and layout file are undefined.
*
* @param array $data Array of data to send to View.
* @return string|null Rendered Page markup or null.
*/
public function ___render(array $data = []): ?string {
// params
$view = $this->view;
$paths = $this->paths;
$ext = $this->ext;
$controller = $view->getController() ?: $this->getController($this->page);
// page data (for cache key)
$page_data = $this->page->data();
// attempt to return prerendered value from cache
$cache_key = implode(':', [
'render',
$this->page->id,
empty($page_data) ? '' : md5(json_encode($page_data)),
$this->settings_hash,
empty($data) ? '' : md5(json_encode($data)),
$view->getTemplate(),
$controller === null ? '' : \get_class($controller),
$view->getFilename(),
$view->getLayout(),
$view->getExt(),
]);
if (isset($this->cache[$cache_key])) {
return $this->cache[$cache_key];
}
// process optional data array
if (!empty($data)) {
$this->set('data', array_merge(
$this->data,
$data
));
$view->addData($this->data);
}
// execute optional Controller::render()
if (!empty($controller)) {
$render_value = $controller->render();
if (\is_string($render_value)) {
return $render_value;
}
}
// render output
$output = null;
$filename = $view->getFilename();
if ($filename || $view->getLayout()) {
if ($filename) {
$view->setContext('view');
$output = $view->render();
}
$layout = $view->getLayout();
$filename = $layout ? basename($layout) : null;
if ($filename) {
// layouts make it possible to define a common base structure for multiple otherwise separate template
// and view files (DRY)
$layout_filename = $paths->layouts . $filename . $ext;
if ($ext != '.php' && !\is_file($layout_filename)) {
// layout filename not found and using custom file extension; try with the default extension (.php)
$layout_filename = $paths->layouts . $filename . '.php';
}
if (\is_file($layout_filename)) {
$view->setContext('layout');
$view->setFilename($layout_filename);
if (!$view->placeholders->has('default')) {
$view->placeholders->default = $output;
}
$output = $view->render();
}
}
}
// store value in cache
$this->cache[$cache_key] = $output;
// check if we should return an earlier context from stash
if (!empty($this->stash)) {
$stashed_context = array_pop($this->stash);
$this->page = $stashed_context['page'];
$this->view = $stashed_context['view'];
$this->wire('view', $this->view);
$this->controller = $stashed_context['controller'];
$this->data = $stashed_context['data'];
if ($this->page && $this->controller) {
$this->page->_wireframe_controller = $this->controller;
}
}
return $output;
}
/**
* PHP magic getter method
*
* This is an alias for the get() method.
*
* @param string $key Name of the variable.
* @return mixed Value of the variable, or null if it doesn't exist.
*/
public function __get($key) {
return $this->get($key);
}
/**
* PHP magic setter method
*
* This is an alias for the set() method.
*
* @param string $key Name of the variable.
* @param string $value Value for the variable.
*/
public function __set($key, $value) {
$this->set($key, $value);
}
/**
* Getter method for specific class properties
*
* Note that this differs notably from the parent class' get() method: unlike in WireData, here we limit the scope
* of the method to specific, predefined class properties instead of returning any index from the "data" array. We
* also don't support pipe ("|") separated strings or objects as arguments.
*
* @param string $key Name of property you want to retrieve.
* @return mixed Property value, or null if requested property is unrecognized.
*/
public function get($key) {
$return = null;
switch ($key) {
case 'paths':
case 'ext':
case 'page':
case 'view':
case 'controller':
case 'renderer':
$return = $this->$key;
break;
}
return $return;
}
/**
* General purpose setter method
*
* @param string $key Name of the variable.
* @param string $value Value for the variable.
* @return Wireframe Self-reference.
*
* @throws WireException if trying to set value to unrecognized property.
* @throws WireException if trying to set invalid value to a property.
*/
public function set($key, $value): Wireframe {
// value is invalid until proven valid
$invalid_value = true;
switch ($key) {
case 'data':
if (\is_array($value)) {
$invalid_value = false;
$this->$key = $value;
$this->updateSettingsHash();
}
break;
case 'page':
if ($value instanceof Page && $value->id) {
$invalid_value = false;
$this->$key = $value;
}
break;
case 'paths':
if (\is_array($value)) {
$invalid_value = false;
$this->setPaths($value);
}
break;
case 'create_directories':
// module config (saved values)
$invalid_value = false;
$this->$key = $value;
break;
case 'renderer':
// renderer module
if (\is_array($value) && !empty($value)) {
$invalid_value = false;
$this->setRenderer($value[0], $value[1] ?? []);
} else if ($value === null || \is_string($value) || $value instanceof Module) {
$invalid_value = false;
$this->setRenderer($value);
}
break;
case 'uninstall':
case 'submit_save_module':
// module config (skipped values)
$invalid_value = false;
break;
default:
throw new WireException(sprintf(
'Unable to set value for unrecognized property "%s"',
$key
));
}