-
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathDispatcher.php
More file actions
522 lines (464 loc) · 16.8 KB
/
Dispatcher.php
File metadata and controls
522 lines (464 loc) · 16.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
<?php
namespace GT\WebEngine\Dispatch;
use Closure;
use GT\Config\Config;
use GT\Dom\Element;
use GT\Dom\HTMLDocument;
use GT\DomTemplate\BindableCache;
use GT\DomTemplate\Binder;
use GT\DomTemplate\ComponentBinder;
use GT\DomTemplate\DocumentBinder;
use GT\DomTemplate\ElementBinder;
use GT\DomTemplate\HTMLAttributeBinder;
use GT\DomTemplate\HTMLAttributeCollection;
use GT\DomTemplate\ListBinder;
use GT\DomTemplate\ListElementCollection;
use GT\DomTemplate\PlaceholderBinder;
use GT\DomTemplate\TableBinder;
use GT\Http\Request;
use GT\Http\Response;
use GT\Http\ResponseStatusException\ClientError\HttpNotFound;
use GT\Http\ResponseStatusException\ResponseStatusException;
use GT\Http\StatusCode;
use GT\Http\Stream;
use GT\Input\Input;
use GT\Input\InputData\InputData;
use GT\Json\Schema\JsonDocument;
use GT\Routing\Assembly;
use GT\Routing\BaseRouter;
use GT\Routing\Path\DynamicPath;
use GT\ServiceContainer\Container;
use GT\ServiceContainer\Injector;
use GT\WebEngine\Init\RequestInit;
use GT\WebEngine\Init\RouterInit;
use GT\WebEngine\Init\SessionInit;
use GT\WebEngine\Init\ViewModelInit;
use GT\WebEngine\Logic\AppAutoloader;
use GT\WebEngine\Logic\LogicExecutor;
use GT\WebEngine\Logic\LogicStreamHandler;
use GT\WebEngine\Logic\ViewModelProcessor;
use GT\WebEngine\Service\ContainerFactory;
use GT\WebEngine\View\HTMLView;
use GT\WebEngine\View\JSONView;
use GT\WebEngine\View\NullView;
use GT\WebEngine\View\ViewStreamer;
use Throwable;
/**
* @SuppressWarnings("PHPMD.TooManyFields")
* @SuppressWarnings("PHPMD.ExcessiveClassComplexity")
*/
class Dispatcher {
private Config $config;
private Request $request;
/** @var array<string, array<string, string|array<string, string>>> */
private array $globals;
private Closure $finishCallback;
private AppAutoloader $appAutoloader;
private LogicStreamHandler $logicStreamHandler;
private Input $input;
private Response $response;
private Container $serviceContainer;
private Injector $injector;
private NullView|JSONView|HTMLView $view;
private HTMLDocument|JsonDocument $viewModel;
private ?ViewModelProcessor $viewModelProcessor;
private BaseRouter $router;
private ?SessionInit $sessionInit = null;
private Assembly $logicAssembly;
private Assembly $viewAssembly;
private LogicExecutor $logicExecutor;
private ViewStreamer $viewStreamer;
private HeaderManager $headerManager;
private Closure $viewInitCb;
private bool $redirectPrepared = false;
/**
* @param array<string, array<string, string|array<string, string>>> $globals
* @SuppressWarnings("PHPMD.ExcessiveMethodLength")
* @SuppressWarnings("PHPMD.ExcessiveParameterList")
*/
// phpcs:disable Generic.Metrics.CyclomaticComplexity.TooHigh
public function __construct(
Config $config,
Request $request,
array $globals,
Closure $finishCallback,
?int $errorStatus = null,
?AppAutoloader $appAutoloader = null,
?LogicStreamHandler $logicStreamHandler = null,
?RequestInit $requestInit = null,
?RouterInit $routerInit = null,
?SessionInit $sessionInit = null,
?ViewModelInit $viewModelInit = null,
?LogicExecutor $logicExecutor = null,
?ViewStreamer $viewStreamer = null,
?HeaderManager $headerManager = null,
) {
// Set the first Dispatcher dependencies - these are required to be passed from
// the Application, so come first as non-nullable:
$this->config = $config;
$this->request = $request;
$this->globals = $globals;
$this->finishCallback = $finishCallback;
// Next, we set up the response and service container, which will be used by the
// Dispatcher dependencies throughout the request-response lifecycle.
$this->response = $this->setupResponse();
$containerFactory = new ContainerFactory();
$this->serviceContainer = $containerFactory->create($this->config);
$this->injector = new Injector($this->serviceContainer);
$this->serviceContainer->set($this->request);
$this->serviceContainer->set($this->response);
$this->serviceContainer->set($this->request->getUri());
// The following Dispatcher dependencies are all nullable. They don't expect to
// be passed from the Application, so will default to null. The reason for this
// is that unit tests can pass mocked versions of all dependencies to produce a
// predictable application state without requiring a real web browser context.
$appNamespace = $config->getString("app.namespace");
$this->appAutoloader = $appAutoloader ?? new AppAutoloader(
$appNamespace,
$config->getString("app.class_dir"),
);
$this->appAutoloader->setup();
// TODO: I think it makes sense to initialise and setup the logic stream handler just before the logic executor is set up.
$this->logicStreamHandler = $logicStreamHandler ?? new LogicStreamHandler();
$this->logicStreamHandler->setup();
$pathNormaliser = new PathNormaliser();
/** @var \GT\Http\Uri $requestUri */
$requestUri = $request->getUri();
$requestInit = $requestInit ?? new RequestInit(
$pathNormaliser,
$requestUri,
$config->getBool("app.force_trailing_slash") ?? true,
$this->response->redirect(...),
$this->globals["_GET"],
$this->globals["_POST"],
$this->globals["_FILES"],
$this->globals["_SERVER"],
);
$this->input = $requestInit->getInput();
$this->serviceContainer->set($this->input);
$this->serviceContainer->set($requestInit->getServerInfo());
if($this->isRedirectPrepared()) {
$this->redirectPrepared = true;
return;
}
$routerInit = $routerInit ?? new RouterInit(
$this->request,
$this->response,
$this->serviceContainer,
$appNamespace,
$this->config->getString("router.router_file"),
$this->config->getString("router.router_class"),
dirname(__FILE__, 3) . DIRECTORY_SEPARATOR . "router.default.php",
"\\GT\\WebEngine\\DefaultRouter",
$this->config->getInt("router.redirect_response_code"),
$this->config->getString("router.default_content_type"),
$errorStatus,
);
$view = $routerInit->getView();
$this->serviceContainer->set($view);
$this->view = $view;
$this->viewModel = $routerInit->getViewModel();
$this->serviceContainer->set($this->viewModel);
$this->router = $routerInit->getBaseRouter();
$this->serviceContainer->set($this->router);
$dynamicPath = $routerInit->getDynamicPath();
$this->serviceContainer->set($dynamicPath);
$this->viewAssembly = $routerInit->getViewAssembly();
$this->logicAssembly = $routerInit->getLogicAssembly();
$sessionInit = $sessionInit ?? new SessionInit(
$this->config->getString("session.name"),
$this->config->getString("session.handler"),
$this->config->getString("session.path"),
$this->config->getBool("session.use_trans_sid") ?? false,
$this->config->getBool("session.use_cookies") ?? false,
$this->globals["_COOKIE"],
);
$this->sessionInit = $sessionInit;
$this->serviceContainer->set($sessionInit->getSession());
$viewModelInit = $viewModelInit ?? new ViewModelInit(
$this->viewModel,
$this->config->getString("view.component_directory"),
$this->config->getString("view.partial_directory"),
);
$this->viewModelProcessor = $viewModelInit->getViewModelProcessor();
$this->viewInitCb = $this->viewModel instanceof HTMLDocument
? function()use($viewModelInit):void {
$documentBinder = $this->serviceContainer->get(Binder::class);
assert($documentBinder instanceof DocumentBinder);
$viewModelInit->initHTMLDocument(
$documentBinder,
$this->serviceContainer->get(HTMLAttributeBinder::class),
$this->serviceContainer->get(ListBinder::class),
$this->serviceContainer->get(TableBinder::class),
$this->serviceContainer->get(ElementBinder::class),
$this->serviceContainer->get(PlaceholderBinder::class),
$this->serviceContainer->get(HTMLAttributeCollection::class),
$this->serviceContainer->get(ListElementCollection::class),
$this->serviceContainer->get(BindableCache::class),
);
}
: static fn() => null;
$this->logicExecutor = $logicExecutor ?? new LogicExecutor(
$appNamespace,
$this->injector,
);
$this->viewStreamer = $viewStreamer ?? new ViewStreamer();
$this->headerManager = $headerManager ?? new HeaderManager();
}
// phpcs:enable Generic.Metrics.CyclomaticComplexity.TooHigh
public function generateResponse():Response {
if($this->redirectPrepared) {
return $this->response;
}
// The routing is now complete and all services are properly configured. This
// function's responsibility is to execute the logic that builds the response.
// Since this involves running user code that may throw errors, we execute each
// step individually to ensure proper error handling throughout the process.
if(!$this->viewAssembly->containsDistinctFile() && !$this->logicAssembly->containsDistinctFile()) {
$this->response = $this->response->withStatus(StatusCode::NOT_FOUND);
throw new HttpNotFound();
}
$this->processResponse();
if(!$this->response->getStatusCode()) {
$this->response = $this->response->withStatus(StatusCode::OK);
}
return $this->response;
}
public function generateErrorResponse(Throwable $throwable):Response {
$this->serviceContainer->set($throwable);
$errorStatusCode = StatusCode::INTERNAL_SERVER_ERROR;
if($throwable instanceof ResponseStatusException) {
$errorStatusCode = $throwable->getHttpCode();
}
if(!$this->viewAssembly->containsDistinctFile()) {
throw new ErrorPageNotFoundException(code: $errorStatusCode);
}
$this->processResponse($throwable);
$this->response = $this->response->withStatus($errorStatusCode);
return $this->response;
}
public function generateBasicErrorResponse(
Throwable $actualThrowable,
Throwable $innerThrowable,
):Response {
// TODO: Handle innerThrowable for if there's an error thrown in WebEngine itself.
$errorStatusCode = $this->response->getStatusCode();
$errorType = get_class($actualThrowable);
$errorMessage = $actualThrowable->getMessage();
$detail = "";
$errorPageDir = $this->config->getString("app.error_page_dir");
if(!$errorMessage) {
if($actualThrowable instanceof HttpNotFound) {
$errorMessage = "The server could not find the requested resource.";
if(!$this->config->getBool("app.production")) {
$detail .= " Additionally, there was no error page found in your "
. "application at <strong>$errorPageDir/$errorStatusCode.html</strong>";
}
}
}
if($errorStatusCode >= 500 && !$this->config->getBool("app.production")) {
$detail .= implode(":", [
$actualThrowable->getFile(),
$actualThrowable->getLine(),
]) . "\n\n";
foreach($actualThrowable->getTrace() as $i => $t) {
if(isset($t["file"]) && str_ends_with($t["file"], "/vendor/phpgt/servicecontainer/src/Injector.php")) {
break;
}
$detail .= "#$i\n";
foreach($t as $key => $value) {
$detail .= "$key:\t$value\n";
}
}
}
// TODO: Load this HTML from a file in the root of WebEngine!
$html = <<<HTML
<!doctype html>
<h1>Error $errorStatusCode</h1>
<h2>$errorType</h2>
<p>$errorMessage</p>
<p style="white-space: pre">$detail</p>
HTML;
$body = new Stream();
$body->write($html);
$response = new Response(null, null, $this->request);
$response = $response->withBody($body);
return $response->withStatus($errorStatusCode);
}
private function setupResponse():Response {
$response = new Response(null, null, $this->request);
$response->setExitCallback(function() {
($this->finishCallback)($this->response);
});
return $response;
}
private function handleLogicExecution(
Assembly $logicAssembly,
Input $input,
?Element $component = null,
):void {
$extraArgs = [];
if($component) {
$binder = new ComponentBinder($this->viewModel);
$binder->setDependencies(
$this->serviceContainer->get(ElementBinder::class),
$this->serviceContainer->get(PlaceholderBinder::class),
$this->serviceContainer->get(TableBinder::class),
$this->serviceContainer->get(ListBinder::class),
$this->serviceContainer->get(ListElementCollection::class),
$this->serviceContainer->get(BindableCache::class),
);
$binder->setComponentBinderDependencies($component);
$extraArgs[Binder::class] = $binder;
$extraArgs[Element::class] = $component;
// This is a temporary fix while repos transition to the GT namespace:
$legacyBinderClass = Binder::class[0] . strtolower(Binder::class[1]) . substr(Binder::class, 2);
$legacyElementClass = Element::class[0] . strtolower(Element::class[1]) . substr(Element::class, 2);
$extraArgs[$legacyBinderClass] = $binder;
$extraArgs[$legacyElementClass] = $component;
}
foreach($this->logicExecutor->invoke($logicAssembly, "go_before", $extraArgs) as $file) {
// Force generator execution even when debug output is disabled.
continue;
}
// TODO: No need to have the whole Input class. Just pass a nullable string in called $doMethod, from $input->getString("do")
$input->when("do")->call(
function(InputData $data)use($logicAssembly, $extraArgs) {
$doName = "do_" . str_replace(
"-",
"_",
$data->getString("do"),
);
foreach($this->logicExecutor->invoke($logicAssembly, $doName, $extraArgs) as $file) {
// Force generator execution even when debug output is disabled.
continue;
}
}
);
foreach($this->logicExecutor->invoke($logicAssembly, "go", $extraArgs) as $file) {
// Force generator execution even when debug output is disabled.
continue;
}
foreach($this->logicExecutor->invoke($logicAssembly, "go_after", $extraArgs) as $file) {
// Force generator execution even when debug output is disabled.
continue;
}
}
/**
* @return void
*/
// phpcs:disable Generic.Metrics.CyclomaticComplexity.TooHigh
public function processResponse(
?Throwable $errorThrowable = null,
):void {
$dynamicPath = $this->serviceContainer->get(DynamicPath::class);
$this->viewModelProcessor?->processDynamicPath(
$this->viewModel,
$dynamicPath,
);
$componentList = $this->viewModelProcessor?->processPartialContent(
$this->viewModel,
$this->viewAssembly,
);
// TODO: CSRF handling - needs to be done on any POST request.
($this->viewInitCb)();
if($errorThrowable) {
$this->bindErrorDetails($errorThrowable);
}
foreach($componentList ?? [] as $componentLogic) {
$assembly = $componentLogic->assembly;
$componentElement = $componentLogic->component;
$this->serviceContainer->set($componentElement);
try {
$this->handleLogicExecution(
$assembly,
$this->input,
$componentElement,
);
}
catch(Throwable $throwable) {
if(!$errorThrowable) {
throw $throwable;
}
}
}
try {
$this->handleLogicExecution(
$this->logicAssembly,
$this->input,
);
}
catch(Throwable $throwable) {
if(!$errorThrowable) {
throw $throwable;
}
}
if($responseWithHeader = $this->headerManager->applyWithHeader(
$this->response->getResponseHeaders(),
$this->response->withHeader(...)
)) {
$this->response = $responseWithHeader;
}
$documentBinder = $this->serviceContainer->get(Binder::class);
assert($documentBinder instanceof DocumentBinder);
$documentBinder->cleanupDocument();
$this->viewStreamer->stream($this->view, $this->viewModel);
}
// phpcs:enable Generic.Metrics.CyclomaticComplexity.TooHigh
public function getSessionInit():?SessionInit {
return $this->sessionInit;
}
private function isRedirectPrepared():bool {
$status = $this->response->getStatusCode();
if($status < 300 || $status >= 400) {
return false;
}
return $this->response->hasHeader("Location");
}
// phpcs:disable Generic.Metrics.CyclomaticComplexity.TooHigh
private function bindErrorDetails(Throwable $throwable):void {
$trace = $throwable->getTrace();
array_unshift($trace, [
"file" => $throwable->getFile(),
"line" => $throwable->getLine(),
"class" => get_class($throwable) . "(\"" . $throwable->getMessage() . "\")",
]);
foreach($trace as $i => $traceItem) {
if(isset($traceItem["file"])) {
$cwd = getcwd() . DIRECTORY_SEPARATOR;
if(str_starts_with($traceItem["file"], $cwd)) {
$trace[$i]["file"] = substr($traceItem["file"], strlen($cwd));
}
}
if(isset($traceItem["file"]) && str_starts_with($traceItem["file"], "gt-logic-stream://")) {
$trace = array_slice($trace, 0, $i + 1);
break;
}
}
$binder = $this->serviceContainer->get(Binder::class);
$binder->bindValue($throwable->getMessage());
if(!$this->config->getBool("app.production")) {
$traceString = "";
foreach($trace as $i => $traceItem) {
$traceString .= "#$i ";
if(isset($traceItem["class"])) {
$traceString .= $traceItem["class"];
if(isset($traceItem["function"])) {
$traceString .= "::";
$traceString .= $traceItem["function"];
}
$traceString .= " -> ";
}
if(isset($traceItem["file"])) {
$traceString .= $traceItem["file"];
}
if(isset($traceItem["line"])) {
$traceString .= "(" . $traceItem["line"] . ")";
}
$traceString .= "\n";
}
$binder->bindKeyValue("trace", $traceString);
}
}
// phpcs:enable Generic.Metrics.CyclomaticComplexity.TooHigh
}