-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathView.php
More file actions
550 lines (452 loc) · 15.8 KB
/
View.php
File metadata and controls
550 lines (452 loc) · 15.8 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
<?php
/*
* Copyright 2015 RhubarbPHP
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Rhubarb\Leaf\Views;
use Rhubarb\Crown\Application;
use Rhubarb\Crown\Deployment\DeploymentPackage;
use Rhubarb\Crown\Deployment\Deployable;
use Rhubarb\Crown\Events\Event;
use Rhubarb\Crown\Html\ResourceLoader;
use Rhubarb\Crown\Request\WebRequest;
use Rhubarb\Csrf\CsrfProtection;
use Rhubarb\Leaf\LayoutProviders\LayoutProvider;
use Rhubarb\Leaf\Leaves\BindableLeafInterface;
use Rhubarb\Leaf\Leaves\Leaf;
use Rhubarb\Leaf\Leaves\LeafDeploymentPackage;
use Rhubarb\Leaf\Leaves\LeafModel;
/**
* The base class for a View
*/
class View implements Deployable
{
/**
* The shared model between leaf and view.
*
* @var LeafModel
*/
protected $model;
/**
* The WebRequest we are generating a response for.
*
* @var WebRequest
*/
private $request;
/**
* A named collection of sub leafs populated by calling registerSubLeaf
*
* @see registerSubLeaf()
* @var Leaf[]
*/
protected $leaves = [];
/**
* True if the leaf needs a hidden state input to propogate it's state.
*
* @var bool
*/
protected $requiresStateInput = true;
/**
* True if the leaf needs a surrounding div for JS to target.
*
* @var bool
*/
protected $requiresContainerDiv = true;
/**
* Tracks the number of times a leaf name has occurred for sub leafs
*
* This is used to ensure if two leaves get added with the same name, they are differentiated by a numerical suffix.
*
* @var int[]
*/
private $namesUsed = [];
/**
* @var Event
*/
private $beforeRenderEvent;
final public function __construct(LeafModel $model)
{
$this->model = $model;
$this->beforeRenderEvent = new Event();
$this->createSubLeaves();
$this->attachModelEventHandlers();
}
/**
* An opportunity for extending classes to register handlers for model events.
*/
protected function attachModelEventHandlers()
{
}
final public function setWebRequest(WebRequest $request)
{
$this->request = $request;
$this->restoreStateIntoModel();
$this->parseRequest($request);
// Perform Data Binding
$viewIndexes = [];
// Enumerate view indexes and for each occurrence descend to the children.
foreach($request->postData as $key => $value){
if (preg_match("/".$this->model->leafPath."\(([^)]+)\)/", $key, $match)){
$viewIndexes[$match[1]] = 1;
}
}
if (count($viewIndexes)) {
foreach(array_keys($viewIndexes) as $viewIndex) {
$this->setIndex($viewIndex);
foreach ($this->leaves as $leaf) {
$leaf->setWebRequest($request);
}
}
} else {
foreach ($this->leaves as $leaf) {
$leaf->setWebRequest($request);
}
}
}
/**
* Sets a view index for subsequent renders.
*
* @param $index
*/
final protected function setIndex($index)
{
$this->model->leafIndex = $index;
$this->model->updatePath();
// Signal to all or any sub leaves that need to recompute their own path now.
$this->leafPathChanged();
}
/**
* Provides the extending class an opportunity to examine the incoming request and raise events if appropriate.
*
* @param WebRequest $request
*/
protected function parseRequest(WebRequest $request)
{
}
final public function recursivePushModelChanges()
{
$xml = '';
// Only consider model pushing if state inputs are being used to persist state.
if ($this->requiresStateInput) {
$oldState = $this->getStateString();
$newState = json_encode($this->model->getState());
if ($newState != $oldState) {
$xml .= '<model id="' . $this->model->leafPath . '"><![CDATA[' . $newState . ']]></model>';
}
}
foreach ($this->leaves as $leaf) {
$subXml = $leaf->recursivePushModelChanges();
if ($subXml) {
$xml .= $subXml;
}
}
return $xml;
}
final private function getStateString()
{
$stateKey = $this->getStateKey();
if ($this->request) {
$state = $this->request->post($stateKey);
return $state;
}
return null;
}
final private function getState()
{
$state = $this->getStateString();
if ($state !== null) {
$state = json_decode($state, true);
return $state;
}
return null;
}
final private function restoreStateIntoModel()
{
$state = $this->getState();
if ($state) {
$this->model->restoreFromState($state);
}
$this->onStateRestored();
}
protected function onStateRestored()
{
}
/**
* Called by the view's leaf class when it's leaf path is changed.
*
* This cascades down all sub view and leaves.
*/
final public function leafPathChanged()
{
foreach ($this->leaves as $leaf) {
$leaf->setName($leaf->getName(), $this->model->leafPath);
}
}
/**
* The place where extending classes should create and register new Views
*/
protected function createSubLeaves()
{
}
public function runBeforeRenderCallbacks()
{
foreach ($this->leaves as $leaf) {
$leaf->runBeforeRenderCallbacks();
}
}
/**
* @param Leaf[] ...$subLeaves
*/
final protected function registerSubLeaf(...$subLeaves)
{
foreach ($subLeaves as $subLeaf) {
// If the sub leaf isn't a Leaf but a string - we see if our Leaf host can create a leaf for us.
// This facility allows for auto creation of control leaves for rapid form development in connection
// with Stem models.
if (is_string($subLeaf)) {
$response = $this->model->createSubLeafFromNameEvent->raise($subLeaf);
if (!($response instanceof Leaf)) {
continue;
}
$subLeaf = $response;
}
$name = $subLeaf->getName();
if (isset($this->namesUsed[$name])) {
$this->namesUsed[$name]++;
$name .= $this->namesUsed[$name];
} else {
$this->namesUsed[$name] = 0;
}
$subLeaf->setName($name, $this->model->leafPath);
$this->leaves[$name] = $subLeaf;
if ($subLeaf instanceof BindableLeafInterface) {
// Setup data bindings
$event = $subLeaf->getBindingValueChangedEvent();
$event->attachHandler(function ($index = null) use ($name, $subLeaf) {
$bindingValue = $subLeaf->getValue();
$this->model->setBoundValue($name, $bindingValue, $index);
});
$event = $subLeaf->getBindingValueRequestedEvent();
$event->attachHandler(function ($index = null) use ($name) {
return $this->model->getBoundValue($name, $index);
});
}
}
}
/**
* The view should update any child leaves based upon changed model state.
*/
public function reconfigure()
{
}
/**
* @return DeploymentPackage
*/
public function getDeploymentPackage()
{
if ($this->model->isRootLeaf) {
// If we're the root leaf, we're also the host for all client side view bridge events.
// It's a real chore to have to define a view bridge just to allow child view bridges to
// fire events.
return new LeafDeploymentPackage();
}
return null;
}
protected function printViewContent()
{
}
final public function recursiveReRender()
{
$response = "";
foreach ($this->leaves as $subLeaf) {
$response .= $subLeaf->recursiveReRender();
}
return $response;
}
private static $viewBridgeRegistrationCallback = null;
/**
* An opportunity for extending classes to perform setup before the view is rendered.
*/
protected function beforeRender()
{
}
final public function renderContent($viewIndex = null)
{
if ($viewIndex !== null){
$this->setIndex($viewIndex);
}
$allDeployedUrls = [];
$viewBridges = [];
ob_start();
$oldCallback = self::$viewBridgeRegistrationCallback;
self::$viewBridgeRegistrationCallback = function ($viewBridgeName, $leafPath, $childViewBridges, $deployedUrls) use (&$viewBridges, &$allDeployedUrls) {
$viewBridges[$leafPath] = [$viewBridgeName, $childViewBridges];
$allDeployedUrls = array_merge($allDeployedUrls, $deployedUrls);
};
$this->beforeRender();
$this->beforeRenderEvent->raise();
$this->printViewContent();
self::$viewBridgeRegistrationCallback = $oldCallback;
$content = ob_get_clean();
$state = $this->model->getState();
$state = json_encode($state);
if ($this->requiresStateInput) {
$content .= '
<input type="hidden"' . ($this->model->suppressStateInputNameAttribute ? '' : ' name="' . $this->getStateKey() . '"') . ' id="' . $this->getStateKey() . '" value="' . htmlentities($state) . '" />';
}
if ($this->model->isRootLeaf && !$this->model->suppressContainingForm) {
$csrfProtector = CsrfProtection::singleton();
$content .= '<input type="hidden" class="js-' . CsrfProtection::TOKEN_COOKIE_NAME . '" name="' . CsrfProtection::TOKEN_COOKIE_NAME . '" value="' . htmlentities($csrfProtector->getCookie()) . '" />';
}
if ($this->requiresContainerDiv) {
$viewBridge = ($this->getViewBridgeName()) ? ' leaf-bridge="' . $this->getViewBridgeName() . '"' : '';
$content = '<div leaf-name="' . $this->model->leafName . '" ' . $viewBridge . ' id="' . $this->model->leafPath . '"' . $this->model->getHtmlAttributes() .
$this->model->getClassAttribute() . '>' . $content . '</div>';
}
$content = $this->wrapViewContent($content);
if ($this->model->isRootLeaf && !$this->model->suppressContainingForm) {
$content = '
<form method="post" enctype="multipart/form-data">
' . $content . '
</form>
';
}
$resourcePackage = $this->getDeploymentPackage();
$viewBridge = $this->getViewBridgeName();
if ($viewBridge) {
if ($resourcePackage) {
if (Application::current()->developerMode) {
$urls = $resourcePackage->deploy();
} else {
$urls = $resourcePackage->getDeployedUrls();
}
$allDeployedUrls = array_merge($allDeployedUrls, $urls, $this->getAdditionalResourceUrls());
}
if (self::$viewBridgeRegistrationCallback != null) {
$callback = self::$viewBridgeRegistrationCallback;
/** @var callable $callback */
$callback(
$this->getViewBridgeName(),
$this->model->leafPath,
$viewBridges,
$allDeployedUrls);
} else {
$recursiveViewBridgerPrinter = function ($viewBridgeClass, $leafPath, $childViewBridges, $recursiveViewBridgerPrinter) {
$jsCode = "new window.rhubarb.viewBridgeClasses." . $viewBridgeClass . "( '" . $leafPath . "' ";
$childCodes = [];
foreach ($childViewBridges as $childPath => $childViewBridgeDetails) {
$childCodes[] = $recursiveViewBridgerPrinter(
$childViewBridgeDetails[0],
$childPath,
$childViewBridgeDetails[1],
$recursiveViewBridgerPrinter);
}
if (count($childCodes)) {
$jsCode .= ", function(){\r\n" . implode(";\r\n", $childCodes) . "\r\n}";
}
$jsCode .= ")";
return $jsCode;
};
$jsCode = $recursiveViewBridgerPrinter(
$this->getViewBridgeName(),
$this->model->leafPath,
$viewBridges,
$recursiveViewBridgerPrinter);
$jsAndCssUrls = [];
if ($resourcePackage != null) {
$jsAndCssUrls = [];
foreach ($allDeployedUrls as $url) {
if (preg_match("/\.js$/", $url) || preg_match("/\.css$/", $url)) {
$jsAndCssUrls[] = $url;
}
}
}
ResourceLoader::addScriptCode($jsCode, array_unique($jsAndCssUrls));
}
}
if (($resourcePackage != null) && (Application::current()->developerMode)) {
$resourcePackage->deploy();
}
return $content;
}
/**
* Provides and extending View an opportunity to wrap the content with some additional HTML.
*
* @param string $content The original content
* @return string The wrapped content.
*/
protected function wrapViewContent($content)
{
return $content;
}
/**
* Returns an array of resource URLs required by this View that don't need deployed.
*
* Normally these would be externally hosted scripts and css files.
*
* @return string[]
*/
protected function getAdditionalResourceUrls()
{
return [];
}
/**
* If the leaf requires a view bridge this returns it's name.
*
* @return string|bool
*/
protected function getViewBridgeName()
{
if ($this->model->isRootLeaf) {
// If we're the root leaf, we're also the host for all client side view bridge events.
// It's a real chore to have to define a view bridge just to allow child view bridges to
// fire events.
return "ViewBridge";
}
return false;
}
/**
* @return string
*/
private function getStateKey()
{
return $this->model->leafPath . "State";
}
/**
* Gets the default layout provider and binds to the generateValueEvent event
*
* @return LayoutProvider
*/
final protected function getLayoutProvider()
{
$layout = LayoutProvider::getProvider();
$layout->generateValueEvent->attachHandler(function ($elementName) {
if (isset($this->leaves[$elementName])) {
return $this->leaves[$elementName];
}
return null;
});
return $layout;
}
protected function layoutItemsWithContainer($containerTitle = "", ...$items)
{
$layout = $this->getLayoutProvider();
$layout->printItemsWithContainer($containerTitle, ...$items);
}
protected function layoutItems($items = [])
{
$layout = $this->getLayoutProvider();
$layout->printItems($items);
}
}