-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
CodeIgniter.php
1157 lines (981 loc) · 32.8 KB
/
CodeIgniter.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
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <[email protected]>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter;
use Closure;
use CodeIgniter\Cache\ResponseCache;
use CodeIgniter\Debug\Timer;
use CodeIgniter\Events\Events;
use CodeIgniter\Exceptions\FrameworkException;
use CodeIgniter\Exceptions\PageNotFoundException;
use CodeIgniter\Filters\Filters;
use CodeIgniter\HTTP\CLIRequest;
use CodeIgniter\HTTP\DownloadResponse;
use CodeIgniter\HTTP\Exceptions\RedirectException;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\Method;
use CodeIgniter\HTTP\RedirectResponse;
use CodeIgniter\HTTP\Request;
use CodeIgniter\HTTP\ResponsableInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\HTTP\URI;
use CodeIgniter\Router\Exceptions\RedirectException as DeprecatedRedirectException;
use CodeIgniter\Router\RouteCollectionInterface;
use CodeIgniter\Router\Router;
use Config\App;
use Config\Cache;
use Config\Feature;
use Config\Kint as KintConfig;
use Config\Services;
use Exception;
use Kint;
use Kint\Renderer\CliRenderer;
use Kint\Renderer\RichRenderer;
use Locale;
use LogicException;
use Throwable;
/**
* This class is the core of the framework, and will analyse the
* request, route it to a controller, and send back the response.
* Of course, there are variations to that flow, but this is the brains.
*
* @see \CodeIgniter\CodeIgniterTest
*/
class CodeIgniter
{
/**
* The current version of CodeIgniter Framework
*/
public const CI_VERSION = '4.5.7';
/**
* App startup time.
*
* @var float|null
*/
protected $startTime;
/**
* Total app execution time
*
* @var float
*/
protected $totalTime;
/**
* Main application configuration
*
* @var App
*/
protected $config;
/**
* Timer instance.
*
* @var Timer
*/
protected $benchmark;
/**
* Current request.
*
* @var CLIRequest|IncomingRequest|null
*/
protected $request;
/**
* Current response.
*
* @var ResponseInterface
*/
protected $response;
/**
* Router to use.
*
* @var Router
*/
protected $router;
/**
* Controller to use.
*
* @var (Closure(mixed...): ResponseInterface|string)|string|null
*/
protected $controller;
/**
* Controller method to invoke.
*
* @var string
*/
protected $method;
/**
* Output handler to use.
*
* @var string
*/
protected $output;
/**
* Cache expiration time
*
* @var int seconds
*
* @deprecated 4.4.0 Moved to ResponseCache::$ttl. No longer used.
*/
protected static $cacheTTL = 0;
/**
* Context
* web: Invoked by HTTP request
* php-cli: Invoked by CLI via `php public/index.php`
*
* @phpstan-var 'php-cli'|'web'
*/
protected ?string $context = null;
/**
* Whether to enable Control Filters.
*/
protected bool $enableFilters = true;
/**
* Whether to return Response object or send response.
*
* @deprecated 4.4.0 No longer used.
*/
protected bool $returnResponse = false;
/**
* Application output buffering level
*/
protected int $bufferLevel;
/**
* Web Page Caching
*/
protected ResponseCache $pageCache;
/**
* Constructor.
*/
public function __construct(App $config)
{
$this->startTime = microtime(true);
$this->config = $config;
$this->pageCache = Services::responsecache();
}
/**
* Handles some basic app and environment setup.
*
* @return void
*/
public function initialize()
{
// Set default locale on the server
Locale::setDefault($this->config->defaultLocale ?? 'en');
// Set default timezone on the server
date_default_timezone_set($this->config->appTimezone ?? 'UTC');
}
/**
* Checks system for missing required PHP extensions.
*
* @return void
*
* @throws FrameworkException
*
* @codeCoverageIgnore
*
* @deprecated 4.5.0 Moved to system/bootstrap.php.
*/
protected function resolvePlatformExtensions()
{
$requiredExtensions = [
'intl',
'json',
'mbstring',
];
$missingExtensions = [];
foreach ($requiredExtensions as $extension) {
if (! extension_loaded($extension)) {
$missingExtensions[] = $extension;
}
}
if ($missingExtensions !== []) {
throw FrameworkException::forMissingExtension(implode(', ', $missingExtensions));
}
}
/**
* Initializes Kint
*
* @return void
*
* @deprecated 4.5.0 Moved to Autoloader.
*/
protected function initializeKint()
{
if (CI_DEBUG) {
$this->autoloadKint();
$this->configureKint();
} elseif (class_exists(Kint::class)) {
// In case that Kint is already loaded via Composer.
Kint::$enabled_mode = false;
// @codeCoverageIgnore
}
helper('kint');
}
/**
* @deprecated 4.5.0 Moved to Autoloader.
*/
private function autoloadKint(): void
{
// If we have KINT_DIR it means it's already loaded via composer
if (! defined('KINT_DIR')) {
spl_autoload_register(function ($class): void {
$class = explode('\\', $class);
if (array_shift($class) !== 'Kint') {
return;
}
$file = SYSTEMPATH . 'ThirdParty/Kint/' . implode('/', $class) . '.php';
if (is_file($file)) {
require_once $file;
}
});
require_once SYSTEMPATH . 'ThirdParty/Kint/init.php';
}
}
/**
* @deprecated 4.5.0 Moved to Autoloader.
*/
private function configureKint(): void
{
$config = new KintConfig();
Kint::$depth_limit = $config->maxDepth;
Kint::$display_called_from = $config->displayCalledFrom;
Kint::$expanded = $config->expanded;
if (isset($config->plugins) && is_array($config->plugins)) {
Kint::$plugins = $config->plugins;
}
$csp = Services::csp();
if ($csp->enabled()) {
RichRenderer::$js_nonce = $csp->getScriptNonce();
RichRenderer::$css_nonce = $csp->getStyleNonce();
}
RichRenderer::$theme = $config->richTheme;
RichRenderer::$folder = $config->richFolder;
RichRenderer::$sort = $config->richSort;
if (isset($config->richObjectPlugins) && is_array($config->richObjectPlugins)) {
RichRenderer::$value_plugins = $config->richObjectPlugins;
}
if (isset($config->richTabPlugins) && is_array($config->richTabPlugins)) {
RichRenderer::$tab_plugins = $config->richTabPlugins;
}
CliRenderer::$cli_colors = $config->cliColors;
CliRenderer::$force_utf8 = $config->cliForceUTF8;
CliRenderer::$detect_width = $config->cliDetectWidth;
CliRenderer::$min_terminal_width = $config->cliMinWidth;
}
/**
* Launch the application!
*
* This is "the loop" if you will. The main entry point into the script
* that gets the required class instances, fires off the filters,
* tries to route the response, loads the controller and generally
* makes all the pieces work together.
*
* @param bool $returnResponse Used for testing purposes only.
*
* @return ResponseInterface|void
*/
public function run(?RouteCollectionInterface $routes = null, bool $returnResponse = false)
{
if ($this->context === null) {
throw new LogicException(
'Context must be set before run() is called. If you are upgrading from 4.1.x, '
. 'you need to merge `public/index.php` and `spark` file from `vendor/codeigniter4/framework`.'
);
}
$this->pageCache->setTtl(0);
$this->bufferLevel = ob_get_level();
$this->startBenchmark();
$this->getRequestObject();
$this->getResponseObject();
Events::trigger('pre_system');
$this->benchmark->stop('bootstrap');
$this->benchmark->start('required_before_filters');
// Start up the filters
$filters = Services::filters();
// Run required before filters
$possibleResponse = $this->runRequiredBeforeFilters($filters);
// If a ResponseInterface instance is returned then send it back to the client and stop
if ($possibleResponse instanceof ResponseInterface) {
$this->response = $possibleResponse;
} else {
try {
$this->response = $this->handleRequest($routes, config(Cache::class), $returnResponse);
} catch (DeprecatedRedirectException|ResponsableInterface $e) {
$this->outputBufferingEnd();
if ($e instanceof DeprecatedRedirectException) {
$e = new RedirectException($e->getMessage(), $e->getCode(), $e);
}
$this->response = $e->getResponse();
} catch (PageNotFoundException $e) {
$this->response = $this->display404errors($e);
} catch (Throwable $e) {
$this->outputBufferingEnd();
throw $e;
}
}
$this->runRequiredAfterFilters($filters);
// Is there a post-system event?
Events::trigger('post_system');
if ($returnResponse) {
return $this->response;
}
$this->sendResponse();
}
/**
* Run required before filters.
*/
private function runRequiredBeforeFilters(Filters $filters): ?ResponseInterface
{
$possibleResponse = $filters->runRequired('before');
$this->benchmark->stop('required_before_filters');
// If a ResponseInterface instance is returned then send it back to the client and stop
if ($possibleResponse instanceof ResponseInterface) {
return $possibleResponse;
}
return null;
}
/**
* Run required after filters.
*/
private function runRequiredAfterFilters(Filters $filters): void
{
$filters->setResponse($this->response);
// Run required after filters
$this->benchmark->start('required_after_filters');
$response = $filters->runRequired('after');
$this->benchmark->stop('required_after_filters');
if ($response instanceof ResponseInterface) {
$this->response = $response;
}
}
/**
* Invoked via php-cli command?
*/
private function isPhpCli(): bool
{
return $this->context === 'php-cli';
}
/**
* Web access?
*/
private function isWeb(): bool
{
return $this->context === 'web';
}
/**
* Disables Controller Filters.
*/
public function disableFilters(): void
{
$this->enableFilters = false;
}
/**
* Handles the main request logic and fires the controller.
*
* @return ResponseInterface
*
* @throws PageNotFoundException
* @throws RedirectException
*
* @deprecated $returnResponse is deprecated.
*/
protected function handleRequest(?RouteCollectionInterface $routes, Cache $cacheConfig, bool $returnResponse = false)
{
if ($this->request instanceof IncomingRequest && $this->request->getMethod() === 'CLI') {
return $this->response->setStatusCode(405)->setBody('Method Not Allowed');
}
$routeFilters = $this->tryToRouteIt($routes);
// $uri is URL-encoded.
$uri = $this->request->getPath();
if ($this->enableFilters) {
/** @var Filters $filters */
$filters = service('filters');
// If any filters were specified within the routes file,
// we need to ensure it's active for the current request
if ($routeFilters !== null) {
$filters->enableFilters($routeFilters, 'before');
$oldFilterOrder = config(Feature::class)->oldFilterOrder ?? false;
if (! $oldFilterOrder) {
$routeFilters = array_reverse($routeFilters);
}
$filters->enableFilters($routeFilters, 'after');
}
// Run "before" filters
$this->benchmark->start('before_filters');
$possibleResponse = $filters->run($uri, 'before');
$this->benchmark->stop('before_filters');
// If a ResponseInterface instance is returned then send it back to the client and stop
if ($possibleResponse instanceof ResponseInterface) {
$this->outputBufferingEnd();
return $possibleResponse;
}
if ($possibleResponse instanceof IncomingRequest || $possibleResponse instanceof CLIRequest) {
$this->request = $possibleResponse;
}
}
$returned = $this->startController();
// Closure controller has run in startController().
if (! is_callable($this->controller)) {
$controller = $this->createController();
if (! method_exists($controller, '_remap') && ! is_callable([$controller, $this->method], false)) {
throw PageNotFoundException::forMethodNotFound($this->method);
}
// Is there a "post_controller_constructor" event?
Events::trigger('post_controller_constructor');
$returned = $this->runController($controller);
} else {
$this->benchmark->stop('controller_constructor');
$this->benchmark->stop('controller');
}
// If $returned is a string, then the controller output something,
// probably a view, instead of echoing it directly. Send it along
// so it can be used with the output.
$this->gatherOutput($cacheConfig, $returned);
if ($this->enableFilters) {
/** @var Filters $filters */
$filters = service('filters');
$filters->setResponse($this->response);
// Run "after" filters
$this->benchmark->start('after_filters');
$response = $filters->run($uri, 'after');
$this->benchmark->stop('after_filters');
if ($response instanceof ResponseInterface) {
$this->response = $response;
}
}
// Skip unnecessary processing for special Responses.
if (
! $this->response instanceof DownloadResponse
&& ! $this->response instanceof RedirectResponse
) {
// Save our current URI as the previous URI in the session
// for safer, more accurate use with `previous_url()` helper function.
$this->storePreviousURL(current_url(true));
}
unset($uri);
return $this->response;
}
/**
* You can load different configurations depending on your
* current environment. Setting the environment also influences
* things like logging and error reporting.
*
* This can be set to anything, but default usage is:
*
* development
* testing
* production
*
* @codeCoverageIgnore
*
* @return void
*
* @deprecated 4.4.0 No longer used. Moved to index.php and spark.
*/
protected function detectEnvironment()
{
// Make sure ENVIRONMENT isn't already set by other means.
if (! defined('ENVIRONMENT')) {
define('ENVIRONMENT', env('CI_ENVIRONMENT', 'production'));
}
}
/**
* Load any custom boot files based upon the current environment.
*
* If no boot file exists, we shouldn't continue because something
* is wrong. At the very least, they should have error reporting setup.
*
* @return void
*
* @deprecated 4.5.0 Moved to system/bootstrap.php.
*/
protected function bootstrapEnvironment()
{
if (is_file(APPPATH . 'Config/Boot/' . ENVIRONMENT . '.php')) {
require_once APPPATH . 'Config/Boot/' . ENVIRONMENT . '.php';
} else {
// @codeCoverageIgnoreStart
header('HTTP/1.1 503 Service Unavailable.', true, 503);
echo 'The application environment is not set correctly.';
exit(EXIT_ERROR); // EXIT_ERROR
// @codeCoverageIgnoreEnd
}
}
/**
* Start the Benchmark
*
* The timer is used to display total script execution both in the
* debug toolbar, and potentially on the displayed page.
*
* @return void
*/
protected function startBenchmark()
{
if ($this->startTime === null) {
$this->startTime = microtime(true);
}
$this->benchmark = Services::timer();
$this->benchmark->start('total_execution', $this->startTime);
$this->benchmark->start('bootstrap');
}
/**
* Sets a Request object to be used for this request.
* Used when running certain tests.
*
* @param CLIRequest|IncomingRequest $request
*
* @return $this
*
* @internal Used for testing purposes only.
* @testTag
*/
public function setRequest($request)
{
$this->request = $request;
return $this;
}
/**
* Get our Request object, (either IncomingRequest or CLIRequest).
*
* @return void
*/
protected function getRequestObject()
{
if ($this->request instanceof Request) {
$this->spoofRequestMethod();
return;
}
if ($this->isPhpCli()) {
Services::createRequest($this->config, true);
} else {
Services::createRequest($this->config);
}
$this->request = service('request');
$this->spoofRequestMethod();
}
/**
* Get our Response object, and set some default values, including
* the HTTP protocol version and a default successful response.
*
* @return void
*/
protected function getResponseObject()
{
$this->response = Services::response($this->config);
if ($this->isWeb()) {
$this->response->setProtocolVersion($this->request->getProtocolVersion());
}
// Assume success until proven otherwise.
$this->response->setStatusCode(200);
}
/**
* Force Secure Site Access? If the config value 'forceGlobalSecureRequests'
* is true, will enforce that all requests to this site are made through
* HTTPS. Will redirect the user to the current page with HTTPS, as well
* as set the HTTP Strict Transport Security header for those browsers
* that support it.
*
* @param int $duration How long the Strict Transport Security
* should be enforced for this URL.
*
* @return void
*
* @deprecated 4.5.0 No longer used. Moved to ForceHTTPS filter.
*/
protected function forceSecureAccess($duration = 31_536_000)
{
if ($this->config->forceGlobalSecureRequests !== true) {
return;
}
force_https($duration, $this->request, $this->response);
}
/**
* Determines if a response has been cached for the given URI.
*
* @return false|ResponseInterface
*
* @throws Exception
*
* @deprecated 4.5.0 PageCache required filter is used. No longer used.
* @deprecated 4.4.2 The parameter $config is deprecated. No longer used.
*/
public function displayCache(Cache $config)
{
$cachedResponse = $this->pageCache->get($this->request, $this->response);
if ($cachedResponse instanceof ResponseInterface) {
$this->response = $cachedResponse;
$this->totalTime = $this->benchmark->getElapsedTime('total_execution');
$output = $this->displayPerformanceMetrics($cachedResponse->getBody());
$this->response->setBody($output);
return $this->response;
}
return false;
}
/**
* Tells the app that the final output should be cached.
*
* @deprecated 4.4.0 Moved to ResponseCache::setTtl(). No longer used.
*
* @return void
*/
public static function cache(int $time)
{
static::$cacheTTL = $time;
}
/**
* Caches the full response from the current request. Used for
* full-page caching for very high performance.
*
* @return bool
*
* @deprecated 4.4.0 No longer used.
*/
public function cachePage(Cache $config)
{
$headers = [];
foreach ($this->response->headers() as $header) {
$headers[$header->getName()] = $header->getValueLine();
}
return cache()->save($this->generateCacheName($config), serialize(['headers' => $headers, 'output' => $this->output]), static::$cacheTTL);
}
/**
* Returns an array with our basic performance stats collected.
*/
public function getPerformanceStats(): array
{
// After filter debug toolbar requires 'total_execution'.
$this->totalTime = $this->benchmark->getElapsedTime('total_execution');
return [
'startTime' => $this->startTime,
'totalTime' => $this->totalTime,
];
}
/**
* Generates the cache name to use for our full-page caching.
*
* @deprecated 4.4.0 No longer used.
*/
protected function generateCacheName(Cache $config): string
{
if ($this->request instanceof CLIRequest) {
return md5($this->request->getPath());
}
$uri = clone $this->request->getUri();
$query = $config->cacheQueryString
? $uri->getQuery(is_array($config->cacheQueryString) ? ['only' => $config->cacheQueryString] : [])
: '';
return md5((string) $uri->setFragment('')->setQuery($query));
}
/**
* Replaces the elapsed_time and memory_usage tag.
*
* @deprecated 4.5.0 PerformanceMetrics required filter is used. No longer used.
*/
public function displayPerformanceMetrics(string $output): string
{
return str_replace(
['{elapsed_time}', '{memory_usage}'],
[(string) $this->totalTime, number_format(memory_get_peak_usage() / 1024 / 1024, 3)],
$output
);
}
/**
* Try to Route It - As it sounds like, works with the router to
* match a route against the current URI. If the route is a
* "redirect route", will also handle the redirect.
*
* @param RouteCollectionInterface|null $routes A collection interface to use in place
* of the config file.
*
* @return list<string>|string|null Route filters, that is, the filters specified in the routes file
*
* @throws RedirectException
*/
protected function tryToRouteIt(?RouteCollectionInterface $routes = null)
{
$this->benchmark->start('routing');
if (! $routes instanceof RouteCollectionInterface) {
$routes = service('routes')->loadRoutes();
}
// $routes is defined in Config/Routes.php
$this->router = Services::router($routes, $this->request);
// $uri is URL-encoded.
$uri = $this->request->getPath();
$this->outputBufferingStart();
$this->controller = $this->router->handle($uri);
$this->method = $this->router->methodName();
// If a {locale} segment was matched in the final route,
// then we need to set the correct locale on our Request.
if ($this->router->hasLocale()) {
$this->request->setLocale($this->router->getLocale());
}
$this->benchmark->stop('routing');
return $this->router->getFilters();
}
/**
* Determines the path to use for us to try to route to, based
* on the CLI/IncomingRequest path.
*
* @return string
*
* @deprecated 4.5.0 No longer used.
*/
protected function determinePath()
{
return $this->request->getPath();
}
/**
* Now that everything has been setup, this method attempts to run the
* controller method and make the script go. If it's not able to, will
* show the appropriate Page Not Found error.
*
* @return ResponseInterface|string|void
*/
protected function startController()
{
$this->benchmark->start('controller');
$this->benchmark->start('controller_constructor');
// Is it routed to a Closure?
if (is_object($this->controller) && ($this->controller::class === 'Closure')) {
$controller = $this->controller;
return $controller(...$this->router->params());
}
// No controller specified - we don't know what to do now.
if (! isset($this->controller)) {
throw PageNotFoundException::forEmptyController();
}
// Try to autoload the class
if (
! class_exists($this->controller, true)
|| ($this->method[0] === '_' && $this->method !== '__invoke')
) {
throw PageNotFoundException::forControllerNotFound($this->controller, $this->method);
}
}
/**
* Instantiates the controller class.
*
* @return Controller
*/
protected function createController()
{
assert(is_string($this->controller));
$class = new $this->controller();
$class->initController($this->request, $this->response, Services::logger());
$this->benchmark->stop('controller_constructor');
return $class;
}
/**
* Runs the controller, allowing for _remap methods to function.
*
* CI4 supports three types of requests:
* 1. Web: URI segments become parameters, sent to Controllers via Routes,
* output controlled by Headers to browser
* 2. PHP CLI: accessed by CLI via php public/index.php, arguments become URI segments,
* sent to Controllers via Routes, output varies
*
* @param Controller $class
*
* @return false|ResponseInterface|string|void
*/
protected function runController($class)
{
// This is a Web request or PHP CLI request
$params = $this->router->params();
// The controller method param types may not be string.
// So cannot set `declare(strict_types=1)` in this file.
$output = method_exists($class, '_remap')
? $class->_remap($this->method, ...$params)
: $class->{$this->method}(...$params);
$this->benchmark->stop('controller');
return $output;
}
/**
* Displays a 404 Page Not Found error. If set, will try to
* call the 404Override controller/method that was set in routing config.
*
* @return ResponseInterface|void
*/
protected function display404errors(PageNotFoundException $e)
{
$this->response->setStatusCode($e->getCode());
// Is there a 404 Override available?
if ($override = $this->router->get404Override()) {
$returned = null;
if ($override instanceof Closure) {
echo $override($e->getMessage());
} elseif (is_array($override)) {
$this->benchmark->start('controller');
$this->benchmark->start('controller_constructor');
$this->controller = $override[0];
$this->method = $override[1];
$controller = $this->createController();
$returned = $controller->{$this->method}($e->getMessage());
$this->benchmark->stop('controller');
}
unset($override);
$cacheConfig = config(Cache::class);
$this->gatherOutput($cacheConfig, $returned);
return $this->response;
}
$this->outputBufferingEnd();
// Throws new PageNotFoundException and remove exception message on production.
throw PageNotFoundException::forPageNotFound(
(ENVIRONMENT !== 'production' || ! $this->isWeb()) ? $e->getMessage() : null
);
}
/**
* Gathers the script output from the buffer, replaces some execution
* time tag in the output and displays the debug toolbar, if required.
*
* @param Cache|null $cacheConfig Deprecated. No longer used.
* @param ResponseInterface|string|null $returned
*
* @deprecated $cacheConfig is deprecated.
*
* @return void
*/
protected function gatherOutput(?Cache $cacheConfig = null, $returned = null)
{
$this->output = $this->outputBufferingEnd();