-
Notifications
You must be signed in to change notification settings - Fork 0
/
Node.php
2603 lines (1707 loc) · 56.5 KB
/
Node.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 Pronode;
class Node extends NodePrototype {
/**
* Pronode Universal Methods packs:
*/
use extString; # string manipulation methods pack
use extDateTime; # dateTime manipulation methods pack
use extArray; # array manipulation methods pack
use extNumber; # number manipulation methods pack
use extHttp; # http-related methods pack
use extDebug; # debuging methods pack
use extCode; #
/**
* Pronode system-related methods:
*/
use extCache; # cache-related methods
/**
* Turn on or off Pronode caching mechanism globally.
* False: cache off
*/
const CACHE = false;
/**
* Turn on or off Pronode routing mechanism for ->execRequest globally.
*/
const ROUTING = true;
/**
* Node origin
*/
public string $origin;
/**
* When command is executed with "/" selector, $branchNext holds an information about what
* Node will {{next}} reffer to.
*/
protected $branchNext;
/**
* Expiration time of cached Node.
*/
public $expires;
/**
* Ghost value of the data from previous Request.
* Only scalars are ghosted. Other types are nulled.
*
* @var integer|float|bool|null|Pronode/View
*/
public $ghost;
public function __construct($data, Node $parent = null, $resourceName = '') {
$this->data = &$data;
$this->resourceName = $resourceName;
if ($parent) {
$this->parent = &$parent;
$this->parent->children[$resourceName] = &$this;
}
// Just for an easier var_dumping:
$this->origin = $this->origin();
# $this->__setup();
}
/**
* Finds Nodes from all type-matched descendants, which changed their wrapped data value
* compared to the ghost.
*
* Node must provide not-null ghost property.
*
* Since only scalars and Pronode\Views "remember" their ghost value, Nodes which
* hold any other datatypes will be skipped - @see __sleep() to check dump cfg
*
* @param array $types boolean|integer|double|string|array|resource|NULL|object|__CLASS__
*
* @return Node[]
*/
public function getChangedDescendants(array $types = []) : array {
$descendants = $this->select($types);
$changed = [];
foreach ($descendants as $node) {
if (isset($node->ghost)) {
if ($node->ghost != $node->data) {
$changed[] = $node;
}
}
}
return $changed;
}
/**
*
* @return number|boolean|NULL|Pronode/View
*/
public function ghost() {
return $this->ghost;
}
/**
* Setup Node basing on wrapped data properties.
*
* Configuration stuff done here.
* Dependency Injection done here.
* Directives done here.
*/
protected function __setup() : void {
if (is_null($this->data)) return;
// For root:
if ($this->isRoot()) { // isRoot() method just checks if there is ->parent set.
// Setting default cache configuration:
$this->cacheConfiguration = $this->getCacheConfiguration();
// Setting default templates dir configuration:
if (is_object($this->data)) {
$this->templatesDir = self::getClassDir($this->data);
} else {
$this->templatesDir = __DIR__;
}
// For every child:
} else {
// Inherit cache configuration from parent:
$this->cacheConfiguration = $this->parent->cacheConfiguration;
// Inject all required dependecies from root data:
$this->injectDependencies();
// Transmit all properties given in root's pn_transmit directive to created Nodes:
$this->transmit();
}
// For everybody:
}
/**
* Checks whether client hit refresh button to reload the page:
* @return boolean
*/
public static function refreshRequested() : bool {
return isset($_SERVER['HTTP_CACHE_CONTROL']) && $_SERVER['HTTP_CACHE_CONTROL'] === 'max-age=0';
}
/**
* Get list of all available resources (public, non-static) without pn_access check.
* Combines ->data properties, ->data methods and Node->methods.
* Returns array of elements:
* ['resourceName' => 'key|property|method|xmethod'].
*
* Types:
* 'key' - array key
* 'property' - public ->data property
* 'method' - public non-static ->data method
* 'pn_method' - public non-static Node method
*/
public function getAvailableResources() : array {
$result = [];
// Those are available for any ->data type:
$nodeMethods = $this->getPublicNonStaticMethods(new Node(null));
foreach ($nodeMethods as $value) {
$result[$value] = "pn_method";
}
// Array data type:
if (is_array($this->data)) {
foreach(array_keys($this->data) as $value) {
$result[$value] = "key";
}
}
// Object data type:
if (is_object($this->data)) {
$properties = array_keys(get_object_vars($this->data));
$dataMethods = $this->getPublicNonStaticMethods($this->data);
foreach ($properties as $value) {
$result[$value] = "property";
}
foreach ($dataMethods as $value) {
$result[$value] = "method";
}
}
return array_reverse($result); // just to make ->data fields appear first
}
/**
* Get list of all public and non-static methods of given $object.
* Returns an array of $key => $value such as:
* ['methodName' => 'methodName']
*/
public static function getPublicNonStaticMethods($object) : array {
$result = [];
$reflection = new \ReflectionClass($object);
$public = $reflection->getMethods(\ReflectionMethod::IS_PUBLIC);
$static = $reflection->getMethods(\ReflectionMethod::IS_STATIC);
foreach ($public as $method) {
if (!\strtok($method->name, '__')) { // skip methods containing __ string
$result[$method->name] = $method->name;
}
}
foreach ($static as $method) {
unset($result[$method->name]);
}
unset($result['dump']);
return $result;
}
/**
* Returns an ID of the Node.
* Note that ID may be unique for current branch only in case wrapped object doesn't
* provide ->id property.
*/
public function nodeId() : ?string {
if (!is_object($this->data)) return null;
$class = get_class($this->data);
// Try to get id from wrapped object:
@$id = $this->data->id;
if (!isset($id)) {
# $id = $this->num2alpha($this->number());
$id = '';
}
return $class.$id;
}
/**
* Transmits properties from root to the Node.
* Used for global dependency broadcasting.
* Used on __setup().
*/
protected function transmit() {
$root = $this->root();
if (isset($root->pn_transmit)) {
foreach ($root->pn_transmit as $resourceName) {
$this->{$resourceName} = &$root->{$resourceName};
}
}
}
/**
* Injects dependencies from root basing on pn_di directive.
* pn_di = ['dependency1', 'dependency2'].
* Dependencies must be "public" in order to be "grabbed" from root.
*/
protected function injectDependencies() {
// Inject all required dependecies from root data:
if (is_object($this->data) && !empty($this->data->pn_di)) { // We dont use is_array since it's slow asfuk
$root = $this->root();
if (is_object($root->data)) {
foreach ($this->data->pn_di as $dependency) {
# echo "<p> Injecting dependency $dependencyName </p>";
$this->data->{$dependency} = &$root->data->{$dependency};
$this->data->{'access'.$dependency} = false; // Default dependency access configuration
$this->data->{'access'.ucfirst($dependency)} = $root->data->{'access'.$dependency}; // Copy access configuration
}
}
}
}
/**
* Search for parent property up the tree till it finds proper not-null value.
*/
protected function inherit(string $propertyName) {
if ($this->isRoot()) return $this->{$propertyName};
if (isset($this->parent->{$propertyName})) return $this->parent->{$propertyName};
return $this->parent->inherit($propertyName);
}
/**
* Defines which Node vars are to be serialized and dumped to cache.
*/
public function __sleep() {
# $vars = get_object_vars($this);
$toSerialize = ['resourceName', 'parent', 'children'];
$this->ghost = $this->data;
// Serialize scalar data:
if (is_scalar($this->ghost)) $toSerialize[] = 'ghost';
// Serialize data of type Pronode/View:
if (($this->ghost instanceof View)) $toSerialize[] = 'ghost';
return $toSerialize;
}
/**
* Defines how to display certain ->data types when casting Node to string:
*/
public function __toString() {
if ($this->data instanceof View) {
$view = $this->data;
}
$view = new View($this, $this->getTemplate());
return $view->output;
}
/**
* Returns object class definition directory.
*/
public static function getClassDir($object) {
$reflection = (new \ReflectionClass(get_class($object)))->getFileName();
$classDir = dirname($reflection);
return $classDir;
}
/**
* Checks if ->data provides given $target.
* If ->data is object, property_exists and method_exists are checked.
* if ->data is array, key_exists is checked.
*/
protected function data_provides($target) : bool {
if (is_object($this->data)) {
if (isset($this->data->{$target})) {
return true;
}
if (method_exists($this->data, $target)) {
return true;
}
}
if (is_array($this->data)) {
if (array_key_exists($target, $this->data)) return true;
}
return false;
}
/**
* Checks if Node provides given $target either by its own method
* or by accessing wrapped ->data method / property.
*/
protected function provides($target) : bool {
if (method_exists($this, $target)) {
return true;
}
return $this->data_provides($target);
}
/**
* Removes all child Nodes from children array, where data is null.
* This method is called before caching Root Node to prevent exploits like spamming system
* with calling not-existing branches.
*/
protected function clearNullChildren() : void {
foreach ($this->children as $key => $child) {
if ($child->data === null) unset($this->children[$key]);
}
}
/**
* Returns an absolute origin of Node.
* Absolute origin is an exact "address" of data in Pronode system.
*/
public function origin() : string {
if ($this->isRoot()) return '';
$node = $this;
$origin = '';
do {
if ($node->resourceName != '') {
$origin = '.'.$node->resourceName.$origin;
}
} while ($node = $node->parent);
return $origin;
}
/**
* Check if wrapped object allows Node to get $target method or property.
* ->data must implement access[Target] method or property.
* Access is granted only if access[Target] method returns true.
*
* Set ->data->access = false; to deny access to every $target inside data.
* Define ->data->access() method to dynamicaly determine access.
*/
protected function checkAccessConfiguration(string $target = '') {
# echo "<p> Checking access to $target </p>";
/**
* Predefined access configuration for certain targets:
*/
switch ($target) {
// Deny access to specific targets:
case 'exec': return false;
case 'execRequest': return false;
}
/**
* Access is true by default:
*/
$configurationVar = 'access';
$configuration = true;
if (!is_object($this->data)) return $configuration;
// Whole object check:
if (method_exists($this->data, $configurationVar)) {
$configuration = call_user_func($this->data, $configurationVar);
} else
if (property_exists($this->data, $configurationVar)) {
$configuration = $this->data->$configurationVar;
}
// Specific check:
if ($target) {
$method = $configurationVar.ucfirst($target);
$property = $configurationVar.ucfirst($target);
if (method_exists($this->data, $method)) {
$configuration = call_user_func($this->data, $method);
return $configuration;
}
if (property_exists($this->data, $property)) {
$configuration = $this->data->$property;
return $configuration;
}
}
return $configuration;
}
/**
* Gets directive setup of wrapped object.
*
* If $target is specified, this will look for resource-specific configuration,
* then (if its not provided), for general conf.
*
* Objects can provide directives via methods and properties.
* Arrays can provide directives via key => value.
* Scalars are ignored.
*
* ('pn_cache', 'html') will look for ->pn_cacheHtml directive, then for ->pn_cache.
*/
public function getDirective($directiveName, $target = '') {
$_directiveName = $directiveName . ucfirst($target);
$directive = null;
if (is_object($this->data)) {
if (isset($this->data->$_directiveName)) {
$directive = $this->data->$_directiveName;
} elseif (method_exists($this->data, $_directiveName)) {
$directive = $this->data->$_directiveName($target);
}
} elseif (is_array($this->data)) {
if (isset($this->data[$_directiveName])) {
$directive = $this->data[$_directiveName];
}
} else {
return false;
}
// If there is no target-specific directive, look for general:
if (!isset($directive) && !empty($target)) {
return $this->getDirective($directiveName);
}
return $directive;
}
/**
* Loads directive settings from Root Node.
*
* Use this method when you want directive to act globaly for all Nodes
* and be set only in one place - your root object.
*/
public function getDirectiveRoot($directiveName, $target) {
return $this->root()->getDirective($directiveName, $target);
}
/**
* Gets information about target caching from object pn_cache directive.
*
* To enable caching of EVERY target (property / method / special method), set data->cache property.
* To enable caching of certain target, set data->cache[Targetname] property.
*
* Use data->cache = true or data->cache = "public" to cache every target publicly
* Use data->cacheTargetname = true to cache specified property / method / special method publicly
*
* Use data->cache = "personal" to cache every target in client $_SESSION // TODO
* Use data->cache = "public" (equals to cache = true)
* Use data->cache = "public 1 hour" to refresh data after 3600 seconds
*
*/
public function getCacheConfiguration(string $target = '') : ?\stdClass {
if (!self :: CACHE) return null;
// Predefined cache configuration for certain targets:
switch ($target) {
}
['refmenu 10 sec deep public'];
['refmenu 10 sec deep public', 'otherResource,param 1 hour'];
'refmenu 10 sec deep public; otherResource,param 1 hour';
$directive = $this->getDirective('pn_cache', $target);
$conf = new \stdClass();
$conf->type = 'public';
$conf->deep = false;
if (is_string($directive)) {
$directiveArray = explode(';', $directive);
// Look for target-matching directive:
foreach ($directiveArray as $element) {
$targ = strtok($directive, ' ');
# if ($this->targetMatch($t)) {}
}
}
if (is_string($directive)) {
$target = strtok($directive, ' ');
$count = 0;
$directive = str_replace('public', '', $directive, $count);
if ($count) $conf->type = 'public';
$directive = str_replace('personal', '', $directive, $count);
if ($count) $conf->type = 'personal';
$directive = str_replace('deep', '', $directive, $count);
if ($count) $conf->deep = true;
$conf->time = strtotime($directive); // there should've left only strtotime-acceptable string
return $conf;
} elseif ($directive === true) { // Default settings for TRUE:
$conf->time = time() + 3600; // Set expiration time to +1 hour
return $conf;
}
return null; // Default
}
/**
* Stores Node in cache
*/
protected function toCache() {
return $this->cache_set($this->origin(), $this);
}
/**
* Gets child Node from cache and sets it among ->children[].
* Returns that Node.
*/
protected function getChildFromCache($originRelative) : ?Node {
$origin = $this->origin().$originRelative;
$node = $this->getNodeFromCache($origin);
if (!$node) return null;
$node->parent = $this;
$this->children[$originRelative] = $node;
return $node;
}
/**
* Gets Node of given $origin from cache.
* If Node is expired, cache file will be deleted and null will be returned.
*/
protected function getNodeFromCache($origin) : ?Node {
$node = $this->cache_get($origin);
if (!$node) return null;
if (time() > $node->expires) {
$this->cache_delete($origin);
return null;
}
return $node;
}
/**
* Returns an array of changed Views among descendant Nodes.
*
* @return View[]
*/
public function getChangedViews() : array {
$nodes = $this->select(['Pronode/View']);
$changedViews = [];
foreach ($nodes as $node) {
if (($view = $node->data) instanceof View) {
$ghostView = $node->ghost;
if (!$ghostView) {
$viewChanged = true;
} else {
$viewChanged = $view->output != $ghostView->output;
}
if ($viewChanged && empty($view->subviews)) {
$changedViews[] = $view;
}
}
}
return $changedViews;
}
/**
* Returns an array of Fragments containing Views changed comparing to the Ghost
*
* @return Fragment[]
*/
public function getChangedFragments() : array {
$changedViews = $this->getChangedViews();
$changedFragments = [];
foreach ($changedViews as $view) {
foreach ($view->triggeredBy as $viewTrigger) {
$changedFragments[$viewTrigger->fragment->id] = $viewTrigger->fragment;
}
}
return $changedFragments;
}
/**
* Tries to get "target" from Node.
* Despite of what kind of data is wrapped by Node, target can reffer to:
* - an object property
* - an object method w/wo params
* - Node special method
* - array key
*
* Important!
* Be careful using magic methods like __GET or __CALL while implementing your object's class.
* If you want to use such with Pronode, please notice that $target CANNOT reffer to any of
* Node's special methods. For example, your __GET wont be executed if target's name is 'html'
* or 'view', since they are Node special-use functions.
* Moreover, they can slow down your app since Node doesn't know why your __GET or __CALL
* returned NULL (it can be an actual result or just unsupported property or method).
*
* @param string $target object method / property / array's key
* @param array $params array of parameteres
* @return mixed
*/
protected function get(string $target, array $params = []) {
$data = null;
$caseFlag = 0;
$isObject = is_object($this->data);
// Object method:
if ($isObject && method_exists($this->data, $target)) {
$data = call_user_func_array([$this->data, $target], $params);
$caseFlag = 1;
} else
// Object property:
if ($isObject && property_exists($this->data, $target)) {
$data = $this->data->$target;
$caseFlag = 2;
} else
// Object magic method (__CALL)
if ($isObject && $params && method_exists($this->data, '__CALL') && !method_exists($this, $target)) {
$data = $this->data->__CALL($target, $params);
$caseFlag = 3;
} else
// Object magic property (__GET)
if ($isObject && method_exists($this->data, '__GET') && !method_exists($this, $target)) {
$data = $this->data->$target;
$caseFlag = 4;
} else
// Array property:
if ((is_array($this->data) || $this->data instanceof \ArrayAccess) && array_key_exists($target, $this->data)) {
$data = &$this->data[$target];
$caseFlag = 5;
}
// If $data is still null after __GET or __CALL use:
if ($data === null && in_array($caseFlag, [0, 3, 4])) {
// If target is unreachable in data scope, ask current Node for method.
// Calling static Pronode methods via get is disallowed by design.
if (method_exists($this, $target) && !(new \ReflectionMethod($this, $target))->isStatic()) {
$data = call_user_func_array([$this, $target], $params);
} else
// If target is unreachable in Node scope, ask Root:
if (!$this->isRoot()) {
// Decided to comment below line out. I think this is just too messy.
// Use root.command to directly ask root for property/method.
# $data = $this->root()->exec($this->createCommand($target, $params));
}
}
return $data;
}
/**
* Finds next Node on the Request Branch.
* Can be used to dynamicaly change the view.
* You can use {{next}} marker in your template and get desired view as the location.href changes:
* /articles - {{next}} will reference to $app->articles() method (eg. showing the list of articles)
* /article,12 - {{next}} will reference to $app->article(1) method (eg. showing full article of ID 12);
*/
public function next() : ?Node {
if (isset($this->branchNext)) { // ->branchNext is set in ->exec() when "/" selector is used
$command = new Command($this->branchNext);
// Child must have been created on ->execRequest()
if ($this->childExists($command->resourceName)) {
return $this->children[$command->resourceName];
}
}
return null;
}
/**
* Get last Node on the Request Branch.
*/
public function last() : Node {
// start context:
$lastNode = $this->root();
while ($next = $lastNode->next()) {
$lastNode = $next;
}
return $lastNode;
}
/**
* Finds the last Node on the Request Branch that provides given $target.
* Petforms ->data_provides check on every Node starting from the last Node on the Branch
* till the provider is found.
*/
public function lastProvider($target) : ?Node {
$node = $this->last();
do {
if ($node->data_provides($target)) {
return $node;
}
} while ($node = $node->parent());
return null;
}
/**
* Returns the parent of current Node
*/
public function parent() : ?Node {
return $this->parent;
}
/**
* Upper-search for parent of specific name.
*/
public function parentFind($name) : ?Node {
if (!$this->parent) return null;
if ($this->parent->getName() == $name) return $this->parent;
return $this->parent->{__FUNCTION__}($name);
}
/**
* Upper-search for the parent of type Object
*/
public function parentFindObject() : ?Node {
if (!$this->parent) return null;
if (is_object($this->parent->data)) return $this->parent;
return $this->parent->{__FUNCTION__}();
}
/**
* Upper-search for the parent of type Array
*/
public function parentFindArray() : ?Node {
if (!$this->parent) return null;
if (is_array($this->parent->data)) return $this->parent;