-
-
Notifications
You must be signed in to change notification settings - Fork 2k
/
Copy pathAbstractDispatcher.zep
1094 lines (920 loc) · 31.1 KB
/
AbstractDispatcher.zep
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
/**
* This file is part of the Phalcon Framework.
*
* (c) Phalcon Team <[email protected]>
*
* For the full copyright and license information, please view the
* LICENSE.txt file that was distributed with this source code.
*/
namespace Phalcon\Dispatcher;
use Exception;
use Phalcon\Di\DiInterface;
use Phalcon\Di\AbstractInjectionAware;
use Phalcon\Dispatcher\Exception as PhalconException;
use Phalcon\Events\EventsAwareInterface;
use Phalcon\Events\ManagerInterface;
use Phalcon\Filter\FilterInterface;
use Phalcon\Mvc\Model\Binder;
use Phalcon\Mvc\Model\BinderInterface;
/**
* This is the base class for Phalcon\Mvc\Dispatcher and Phalcon\Cli\Dispatcher.
* This class can't be instantiated directly, you can use it to create your own
* dispatchers.
*/
abstract class AbstractDispatcher extends AbstractInjectionAware implements DispatcherInterface, EventsAwareInterface
{
/**
* @var object|null
*/
protected activeHandler = null;
/**
* @var array
*/
protected activeMethodMap = [];
/**
* @var string|null
*/
protected actionName = null;
/**
* @var string
*/
protected actionSuffix = "Action";
/**
* @var array
*/
protected camelCaseMap = [];
/**
* @var string
*/
protected defaultAction = "";
/**
* @var string|null
*/
protected defaultNamespace = null;
/**
* @var string|null
*/
protected defaultHandler = null;
/**
* @var array
*/
protected handlerHashes = [];
/**
* @var string|null
*/
protected handlerName = null;
/**
* @var string
*/
protected handlerSuffix = "";
/**
* @var ManagerInterface|null
*/
protected eventsManager = null;
/**
* @var bool
*/
protected finished = false;
/**
* @var bool
*/
protected forwarded = false;
/**
* @var bool
*/
protected isControllerInitialize = false;
/**
* @var mixed|null
*/
protected lastHandler = null;
/**
* @var BinderInterface|null
*/
protected modelBinder = null;
/**
* @var bool
*/
protected modelBinding = false;
/**
* @var string|null
*/
protected moduleName = null;
/**
* @var string|null
*/
protected namespaceName = null;
/**
* @var array
*/
protected params = [];
/**
* @var string|null
*/
protected previousActionName = null;
/**
* @var string|null
*/
protected previousHandlerName = null;
/**
* @var string|null
*/
protected previousNamespaceName = null;
/**
* @var string|null
*/
protected returnedValue = null;
public function callActionMethod(handler, string actionMethod, array! params = [])
{
return call_user_func_array(
[handler, actionMethod],
params
);
}
/**
* Process the results of the router by calling into the appropriate
* controller action(s) including any routing data or injected parameters.
*
* @return mixed Returns the dispatched handler class (the Controller for Mvc dispatching or a Task
* for CLI dispatching) or <tt>false</tt> if an exception occurred and the operation was
* stopped by returning <tt>false</tt> in the exception handler.
*
* @throws \Exception if any uncaught or unhandled exception occurs during the dispatcher process.
*/
public function dispatch() -> var | bool
{
bool hasService, hasEventsManager;
int numberDispatches;
var value, handler, container, namespaceName, handlerName, actionName,
params, eventsManager, handlerClass, status, actionMethod,
modelBinder, bindCacheKey, isNewHandler, handlerHash, e;
let container = <DiInterface> this->container;
if typeof container != "object" {
this->{"throwDispatchException"}(
PhalconException::containerServiceNotFound(
"related dispatching services"
),
PhalconException::EXCEPTION_NO_DI
);
return false;
}
let eventsManager = <ManagerInterface> this->eventsManager;
let hasEventsManager = typeof eventsManager == "object";
let this->finished = true;
if hasEventsManager {
try {
// Calling beforeDispatchLoop event
// Note: Allow user to forward in the beforeDispatchLoop.
if eventsManager->fire("dispatch:beforeDispatchLoop", this) === false && this->finished !== false {
return false;
}
} catch Exception, e {
// Exception occurred in beforeDispatchLoop.
/**
* The user can optionally forward now in the
* `dispatch:beforeException` event or return <tt>false</tt> to
* handle the exception and prevent it from bubbling. In the
* event the user does forward but does or does not return
* false, we assume the forward takes precedence. The returning
* false intuitively makes more sense when inside the dispatch
* loop and technically we are not here. Therefore, returning
* false only impacts whether non-forwarded exceptions are
* silently handled or bubbled up the stack. Note that this
* behavior is slightly different than other subsequent events
* handled inside the dispatch loop.
*/
let status = this->{"handleException"}(e);
if this->finished !== false {
// No forwarding
if status === false {
return false;
}
// Otherwise, bubble Exception
throw e;
}
// Otherwise, user forwarded, continue
}
}
let value = null,
handler = null,
numberDispatches = 0,
this->finished = false;
while !this->finished {
let numberDispatches++;
// Throw an exception after 256 consecutive forwards
if unlikely numberDispatches == 256 {
this->{"throwDispatchException"}(
"Dispatcher has detected a cyclic routing causing stability problems",
PhalconException::EXCEPTION_CYCLIC_ROUTING
);
break;
}
let this->finished = true;
this->resolveEmptyProperties();
if hasEventsManager {
try {
// Calling "dispatch:beforeDispatch" event
if eventsManager->fire("dispatch:beforeDispatch", this) === false || this->finished === false {
continue;
}
} catch Exception, e {
if this->{"handleException"}(e) === false || this->finished === false {
continue;
}
throw e;
}
}
let handlerClass = this->getHandlerClass();
/**
* Handlers are retrieved as shared instances from the Service
* Container
*/
let hasService = (bool) container->has(handlerClass);
if !hasService {
/**
* DI doesn't have a service with that name, try to load it
* using an autoloader
*/
let hasService = (bool) class_exists(handlerClass);
}
// If the service can be loaded we throw an exception
if !hasService {
let status = this->{"throwDispatchException"}(
handlerClass . " handler class cannot be loaded",
PhalconException::EXCEPTION_HANDLER_NOT_FOUND
);
if status === false && this->finished === false {
continue;
}
break;
}
let handler = container->getShared(handlerClass);
// Handlers must be only objects
if unlikely typeof handler !== "object" {
let status = this->{"throwDispatchException"}(
"Invalid handler returned from the services container",
PhalconException::EXCEPTION_INVALID_HANDLER
);
if status === false && this->finished === false {
continue;
}
break;
}
// Check if the handler is new (hasn't been initialized).
let handlerHash = spl_object_hash(handler);
let isNewHandler = !(isset this->handlerHashes[handlerHash]);
if isNewHandler {
let this->handlerHashes[handlerHash] = true;
}
let this->activeHandler = handler;
let namespaceName = this->namespaceName;
let handlerName = this->handlerName;
let actionName = this->actionName;
let params = this->params;
/**
* Check if the params is an array
*/
if unlikely typeof params != "array" {
/**
* An invalid parameter variable was passed throw an exception
*/
let status = this->{"throwDispatchException"}(
"Action parameters must be an Array",
PhalconException::EXCEPTION_INVALID_PARAMS
);
if status === false && this->finished === false {
continue;
}
break;
}
// Check if the method exists in the handler
let actionMethod = this->getActiveMethod();
if unlikely !is_callable([handler, actionMethod]) {
if hasEventsManager {
if eventsManager->fire("dispatch:beforeNotFoundAction", this) === false {
continue;
}
if this->finished === false {
continue;
}
}
/**
* Try to throw an exception when an action isn't defined on the
* object
*/
let status = this->{"throwDispatchException"}(
"Action '" . actionName . "' was not found on handler '" . handlerName . "'",
PhalconException::EXCEPTION_ACTION_NOT_FOUND
);
if status === false && this->finished === false {
continue;
}
break;
}
/**
* In order to ensure that the `initialize()` gets called we'll
* destroy the current handlerClass from the DI container in the
* event that an error occurs and we continue out of this block.
* This is necessary because there is a disjoin between retrieval of
* the instance and the execution of the `initialize()` event. From
* a coding perspective, it would have made more sense to probably
* put the `initialize()` prior to the beforeExecuteRoute which
* would have solved this. However, for posterity, and to remain
* consistency, we'll ensure the default and documented behavior
* works correctly.
*/
if hasEventsManager {
try {
// Calling "dispatch:beforeExecuteRoute" event
if eventsManager->fire("dispatch:beforeExecuteRoute", this) === false || this->finished === false {
container->remove(handlerClass);
continue;
}
} catch Exception, e {
if this->{"handleException"}(e) === false || this->finished === false {
container->remove(handlerClass);
continue;
}
throw e;
}
}
if method_exists(handler, "beforeExecuteRoute") {
try {
// Calling "beforeExecuteRoute" as direct method
if handler->beforeExecuteRoute(this) === false || this->finished === false {
container->remove(handlerClass);
continue;
}
} catch Exception, e {
if this->{"handleException"}(e) === false || this->finished === false {
container->remove(handlerClass);
continue;
}
throw e;
}
}
/**
* Call the "initialize" method just once per request
*
* Note: The `dispatch:afterInitialize` event is called regardless
* of the presence of an `initialize()` method. The naming is
* poor; however, the intent is for a more global "constructor
* is ready to go" or similarly "__onConstruct()" methodology.
*
* Note: In Phalcon 4.0, the `initialize()` and
* `dispatch:afterInitialize` event will be handled prior to the
* `beforeExecuteRoute` event/method blocks. This was a bug in the
* original design that was not able to change due to widespread
* implementation. With proper documentation change and blog posts
* for 4.0, this change will happen.
*
* @see https://github.com/phalcon/cphalcon/pull/13112
*/
if isNewHandler {
if method_exists(handler, "initialize") {
try {
let this->isControllerInitialize = true;
handler->initialize();
} catch Exception, e {
let this->isControllerInitialize = false;
/**
* If this is a dispatch exception (e.g. From
* forwarding) ensure we don't handle this twice. In
* order to ensure this doesn't happen all other
* exceptions thrown outside this method in this class
* should not call "throwDispatchException" but instead
* throw a normal Exception.
*/
if this->{"handleException"}(e) === false || this->finished === false {
continue;
}
throw e;
}
}
let this->isControllerInitialize = false;
/**
* Calling "dispatch:afterInitialize" event
*/
if eventsManager {
try {
if eventsManager->fire("dispatch:afterInitialize", this) === false || this->finished === false {
continue;
}
} catch Exception, e {
if this->{"handleException"}(e) === false || this->finished === false {
continue;
}
throw e;
}
}
}
if this->modelBinding {
let modelBinder = this->modelBinder;
let bindCacheKey = "_PHMB_" . handlerClass . "_" . actionMethod;
let params = modelBinder->bindToHandler(
handler,
params,
bindCacheKey,
actionMethod
);
}
/**
* Calling afterBinding
*/
if hasEventsManager {
if eventsManager->fire("dispatch:afterBinding", this) === false {
continue;
}
/**
* Check if the user made a forward in the listener
*/
if this->finished === false {
continue;
}
}
/**
* Calling afterBinding as callback and event
*/
if method_exists(handler, "afterBinding") {
if handler->afterBinding(this) === false {
continue;
}
/**
* Check if the user made a forward in the listener
*/
if this->finished === false {
continue;
}
}
/**
* Save the current handler
*/
let this->lastHandler = handler;
try {
/**
* We update the latest value produced by the latest handler
*/
let this->returnedValue = this->callActionMethod(
handler,
actionMethod,
params
);
if this->finished === false {
continue;
}
} catch Exception, e {
if this->{"handleException"}(e) === false || this->finished === false {
continue;
}
throw e;
}
/**
* Calling "dispatch:afterExecuteRoute" event
*/
if hasEventsManager {
try {
if eventsManager->fire("dispatch:afterExecuteRoute", this, value) === false || this->finished === false {
continue;
}
} catch Exception, e {
if this->{"handleException"}(e) === false || this->finished === false {
continue;
}
throw e;
}
}
/**
* Calling "afterExecuteRoute" as direct method
*/
if method_exists(handler, "afterExecuteRoute") {
try {
if handler->afterExecuteRoute(this, value) === false || this->finished === false {
continue;
}
} catch Exception, e {
if this->{"handleException"}(e) === false || this->finished === false {
continue;
}
throw e;
}
}
// Calling "dispatch:afterDispatch" event
if hasEventsManager {
try {
eventsManager->fire("dispatch:afterDispatch", this, value);
} catch Exception, e {
/**
* Still check for finished here as we want to prioritize
* `forwarding()` calls
*/
if this->{"handleException"}(e) === false || this->finished === false {
continue;
}
throw e;
}
}
}
if hasEventsManager {
try {
// Calling "dispatch:afterDispatchLoop" event
// Note: We don't worry about forwarding in after dispatch loop.
eventsManager->fire("dispatch:afterDispatchLoop", this);
} catch Exception, e {
// Exception occurred in afterDispatchLoop.
if this->{"handleException"}(e) === false {
return false;
}
// Otherwise, bubble Exception
throw e;
}
}
return handler;
}
/**
* Forwards the execution flow to another controller/action.
*
* ```php
* $this->dispatcher->forward(
* [
* "controller" => "posts",
* "action" => "index",
* ]
* );
* ```
*
* @throws \Phalcon\Exception
*/
public function forward(array forward) -> void
{
var namespaceName, controllerName, params, actionName, taskName;
if unlikely this->isControllerInitialize === true {
/**
* Note: Important that we do not throw a "throwDispatchException"
* call here. This is important because it would allow the
* application to break out of the defined logic inside the
* dispatcher which handles all dispatch exceptions.
*/
throw new PhalconException(
"Forwarding inside a controller's initialize() method is forbidden"
);
}
/**
* Save current values as previous to ensure calls to getPrevious
* methods don't return null.
*/
let this->previousNamespaceName = this->namespaceName,
this->previousHandlerName = this->handlerName,
this->previousActionName = this->actionName;
// Check if we need to forward to another namespace
if fetch namespaceName, forward["namespace"] {
let this->namespaceName = namespaceName;
}
// Check if we need to forward to another controller.
if fetch controllerName, forward["controller"] {
let this->handlerName = controllerName;
} elseif fetch taskName, forward["task"] {
let this->handlerName = taskName;
}
// Check if we need to forward to another action
if fetch actionName, forward["action"] {
let this->actionName = actionName;
}
// Check if we need to forward changing the current parameters
if fetch params, forward["params"] {
let this->params = params;
}
let this->finished = false,
this->forwarded = true;
}
/**
* Gets the latest dispatched action name
*/
public function getActionName() -> string
{
return this->actionName;
}
/**
* Gets the default action suffix
*/
public function getActionSuffix() -> string
{
return this->actionSuffix;
}
/**
* Returns the current method to be/executed in the dispatcher
*/
public function getActiveMethod() -> string
{
var activeMethodName;
if !fetch activeMethodName, this->activeMethodMap[this->actionName] {
let activeMethodName = lcfirst(
this->toCamelCase(
this->actionName
)
);
let this->activeMethodMap[this->actionName] = activeMethodName;
}
return activeMethodName . this->actionSuffix;
}
/**
* Returns bound models from binder instance
*
* ```php
* class UserController extends Controller
* {
* public function showAction(User $user)
* {
* // return array with $user
* $boundModels = $this->dispatcher->getBoundModels();
* }
* }
* ```
*/
public function getBoundModels() -> array
{
var modelBinder;
let modelBinder = this->modelBinder;
if modelBinder == null {
return [];
}
return modelBinder->getBoundModels();
}
/**
* Returns the default namespace
*/
public function getDefaultNamespace() -> string
{
return this->defaultNamespace;
}
/**
* Returns the internal event manager
*/
public function getEventsManager() -> <ManagerInterface> | null
{
return this->eventsManager;
}
/**
* Gets the default handler suffix
*/
public function getHandlerSuffix() -> string
{
return this->handlerSuffix;
}
/**
* Gets model binder
*/
public function getModelBinder() -> <BinderInterface> | null
{
return this->modelBinder;
}
/**
* Gets the module where the controller class is
*/
public function getModuleName() -> string
{
return this->moduleName;
}
/**
* Gets a namespace to be prepended to the current handler name
*/
public function getNamespaceName() -> string
{
return this->namespaceName;
}
/**
* Gets a param by its name or numeric index
*
* @param mixed param
* @param string|array filters
* @param mixed defaultValue
* @return mixed
*/
public function getParam(var param, filters = null, defaultValue = null) -> var
{
var params, filter, paramValue, container;
let params = this->params;
if !fetch paramValue, params[param] {
return defaultValue;
}
if filters === null {
return paramValue;
}
let container = this->container;
if typeof container != "object" {
this->{"throwDispatchException"}(
PhalconException::containerServiceNotFound(
"the 'filter' service"
),
PhalconException::EXCEPTION_NO_DI
);
}
let filter = <FilterInterface> container->getShared("filter");
return filter->sanitize(paramValue, filters);
}
/**
* Gets action params
*/
public function getParams() -> array
{
return this->params;
}
/**
* Check if a param exists
*/
public function hasParam(var param) -> bool
{
return isset this->params[param];
}
/**
* Checks if the dispatch loop is finished or has more pendent
* controllers/tasks to dispatch
*/
public function isFinished() -> bool
{
return this->finished;
}
/**
* Sets the action name to be dispatched
*/
public function setActionName(string actionName) -> void
{
let this->actionName = actionName;
}
/**
* Sets the default action name
*/
public function setDefaultAction(string actionName) -> void
{
let this->defaultAction = actionName;
}
/**
* Sets the default namespace
*/
public function setDefaultNamespace(string defaultNamespace) -> void
{
let this->defaultNamespace = defaultNamespace;
}
/**
* Possible class name that will be located to dispatch the request
*/
public function getHandlerClass() -> string
{
var handlerSuffix, handlerName, namespaceName, camelizedClass,
handlerClass;
this->resolveEmptyProperties();
let handlerSuffix = this->handlerSuffix,
handlerName = this->handlerName,
namespaceName = this->namespaceName;
// We don't camelize the classes if they are in namespaces
if !memstr(handlerName, "\\") {
let camelizedClass = this->toCamelCase(handlerName);
} else {
let camelizedClass = handlerName;
}
// Create the complete controller class name prepending the namespace
if namespaceName {
if !ends_with(namespaceName, "\\") {
let namespaceName .= "\\";
}
let handlerClass = namespaceName . camelizedClass . handlerSuffix;
} else {
let handlerClass = camelizedClass . handlerSuffix;
}
return handlerClass;
}
/**
* Set a param by its name or numeric index
*/
public function setParam(var param, var value) -> void
{
let this->params[param] = value;
}
/**
* Sets action params to be dispatched
*/
public function setParams(array params) -> void
{
let this->params = params;
}
/**
* Sets the latest returned value by an action manually
*/
public function setReturnedValue(var value) -> void
{
let this->returnedValue = value;
}
/**
* Sets the default action suffix
*/
public function setActionSuffix(string actionSuffix) -> void
{
let this->actionSuffix = actionSuffix;
}
/**
* Sets the events manager
*/
public function setEventsManager(<ManagerInterface> eventsManager) -> void
{
let this->eventsManager = eventsManager;
}
/**
* Sets the default suffix for the handler
*/
public function setHandlerSuffix(string handlerSuffix) -> void
{
let this->handlerSuffix = handlerSuffix;
}
/**
* Enable model binding during dispatch
*
* ```php
* $di->set(
* 'dispatcher',
* function() {
* $dispatcher = new Dispatcher();
*
* $dispatcher->setModelBinder(
* new Binder(),
* 'cache'
* );
*
* return $dispatcher;
* }
* );