• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

codeigniter4 / CodeIgniter4 / 18293416558

06 Oct 2025 08:22PM UTC coverage: 84.359% (+0.03%) from 84.325%
18293416558

Pull #9745

github

web-flow
Merge 663daeb42 into 3473349b6
Pull Request #9745: feat(app): Added controller attributes

142 of 158 new or added lines in 5 files covered. (89.87%)

55 existing lines in 1 file now uncovered.

21234 of 25171 relevant lines covered (84.36%)

195.22 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

68.85
/system/CodeIgniter.php
1
<?php
2

3
/**
4
 * This file is part of CodeIgniter 4 framework.
5
 *
6
 * (c) CodeIgniter Foundation <admin@codeigniter.com>
7
 *
8
 * For the full copyright and license information, please view
9
 * the LICENSE file that was distributed with this source code.
10
 */
11

12
namespace CodeIgniter;
13

14
use Closure;
15
use CodeIgniter\Cache\ResponseCache;
16
use CodeIgniter\Debug\Timer;
17
use CodeIgniter\Events\Events;
18
use CodeIgniter\Exceptions\LogicException;
19
use CodeIgniter\Exceptions\PageNotFoundException;
20
use CodeIgniter\Filters\Filters;
21
use CodeIgniter\HTTP\CLIRequest;
22
use CodeIgniter\HTTP\DownloadResponse;
23
use CodeIgniter\HTTP\Exceptions\RedirectException;
24
use CodeIgniter\HTTP\IncomingRequest;
25
use CodeIgniter\HTTP\Method;
26
use CodeIgniter\HTTP\RedirectResponse;
27
use CodeIgniter\HTTP\Request;
28
use CodeIgniter\HTTP\ResponsableInterface;
29
use CodeIgniter\HTTP\ResponseInterface;
30
use CodeIgniter\HTTP\URI;
31
use CodeIgniter\Router\RouteCollectionInterface;
32
use CodeIgniter\Router\Router;
33
use Config\App;
34
use Config\Cache;
35
use Config\Feature;
36
use Config\Kint as KintConfig;
37
use Config\Services;
38
use Exception;
39
use Kint;
40
use Kint\Renderer\CliRenderer;
41
use Kint\Renderer\RichRenderer;
42
use Locale;
43
use Throwable;
44

45
/**
46
 * This class is the core of the framework, and will analyse the
47
 * request, route it to a controller, and send back the response.
48
 * Of course, there are variations to that flow, but this is the brains.
49
 *
50
 * @see \CodeIgniter\CodeIgniterTest
51
 */
52
class CodeIgniter
53
{
54
    /**
55
     * The current version of CodeIgniter Framework
56
     */
57
    public const CI_VERSION = '4.6.3';
58

59
    /**
60
     * App startup time.
61
     *
62
     * @var float|null
63
     */
64
    protected $startTime;
65

66
    /**
67
     * Total app execution time
68
     *
69
     * @var float
70
     */
71
    protected $totalTime;
72

73
    /**
74
     * Main application configuration
75
     *
76
     * @var App
77
     */
78
    protected $config;
79

80
    /**
81
     * Timer instance.
82
     *
83
     * @var Timer
84
     */
85
    protected $benchmark;
86

87
    /**
88
     * Current request.
89
     *
90
     * @var CLIRequest|IncomingRequest|null
91
     */
92
    protected $request;
93

94
    /**
95
     * Current response.
96
     *
97
     * @var ResponseInterface
98
     */
99
    protected $response;
100

101
    /**
102
     * Router to use.
103
     *
104
     * @var Router
105
     */
106
    protected $router;
107

108
    /**
109
     * Controller to use.
110
     *
111
     * @var (Closure(mixed...): ResponseInterface|string)|string|null
112
     */
113
    protected $controller;
114

115
    /**
116
     * Controller method to invoke.
117
     *
118
     * @var string
119
     */
120
    protected $method;
121

122
    /**
123
     * Output handler to use.
124
     *
125
     * @var string
126
     */
127
    protected $output;
128

129
    /**
130
     * Cache expiration time
131
     *
132
     * @var int seconds
133
     *
134
     * @deprecated 4.4.0 Moved to ResponseCache::$ttl. No longer used.
135
     */
136
    protected static $cacheTTL = 0;
137

138
    /**
139
     * Context
140
     *  web:     Invoked by HTTP request
141
     *  php-cli: Invoked by CLI via `php public/index.php`
142
     *
143
     * @var 'php-cli'|'web'|null
144
     */
145
    protected ?string $context = null;
146

147
    /**
148
     * Whether to enable Control Filters.
149
     */
150
    protected bool $enableFilters = true;
151

152
    /**
153
     * Whether to return Response object or send response.
154
     *
155
     * @deprecated 4.4.0 No longer used.
156
     */
157
    protected bool $returnResponse = false;
158

159
    /**
160
     * Application output buffering level
161
     */
162
    protected int $bufferLevel;
163

164
    /**
165
     * Web Page Caching
166
     */
167
    protected ResponseCache $pageCache;
168

169
    /**
170
     * Constructor.
171
     */
172
    public function __construct(App $config)
173
    {
174
        $this->startTime = microtime(true);
6,824✔
175
        $this->config    = $config;
6,824✔
176

177
        $this->pageCache = Services::responsecache();
6,824✔
178
    }
179

180
    /**
181
     * Handles some basic app and environment setup.
182
     *
183
     * @return void
184
     */
185
    public function initialize()
186
    {
187
        // Set default locale on the server
188
        Locale::setDefault($this->config->defaultLocale ?? 'en');
6,824✔
189

190
        // Set default timezone on the server
191
        date_default_timezone_set($this->config->appTimezone ?? 'UTC');
6,824✔
192
    }
193

194
    /**
195
     * Initializes Kint
196
     *
197
     * @return void
198
     *
199
     * @deprecated 4.5.0 Moved to Autoloader.
200
     */
201
    protected function initializeKint()
202
    {
UNCOV
203
        if (CI_DEBUG) {
×
204
            $this->autoloadKint();
×
205
            $this->configureKint();
×
206
        } elseif (class_exists(Kint::class)) {
×
207
            // In case that Kint is already loaded via Composer.
UNCOV
208
            Kint::$enabled_mode = false;
×
209
            // @codeCoverageIgnore
210
        }
211

UNCOV
212
        helper('kint');
×
213
    }
214

215
    /**
216
     * @deprecated 4.5.0 Moved to Autoloader.
217
     */
218
    private function autoloadKint(): void
219
    {
220
        // If we have KINT_DIR it means it's already loaded via composer
UNCOV
221
        if (! defined('KINT_DIR')) {
×
222
            spl_autoload_register(function ($class): void {
×
223
                $class = explode('\\', $class);
×
224

UNCOV
225
                if (array_shift($class) !== 'Kint') {
×
226
                    return;
×
227
                }
228

UNCOV
229
                $file = SYSTEMPATH . 'ThirdParty/Kint/' . implode('/', $class) . '.php';
×
230

UNCOV
231
                if (is_file($file)) {
×
232
                    require_once $file;
×
233
                }
UNCOV
234
            });
×
235

UNCOV
236
            require_once SYSTEMPATH . 'ThirdParty/Kint/init.php';
×
237
        }
238
    }
239

240
    /**
241
     * @deprecated 4.5.0 Moved to Autoloader.
242
     */
243
    private function configureKint(): void
244
    {
UNCOV
245
        $config = new KintConfig();
×
246

UNCOV
247
        Kint::$depth_limit         = $config->maxDepth;
×
248
        Kint::$display_called_from = $config->displayCalledFrom;
×
249
        Kint::$expanded            = $config->expanded;
×
250

UNCOV
251
        if (isset($config->plugins) && is_array($config->plugins)) {
×
252
            Kint::$plugins = $config->plugins;
×
253
        }
254

UNCOV
255
        $csp = Services::csp();
×
256
        if ($csp->enabled()) {
×
257
            RichRenderer::$js_nonce  = $csp->getScriptNonce();
×
258
            RichRenderer::$css_nonce = $csp->getStyleNonce();
×
259
        }
260

UNCOV
261
        RichRenderer::$theme  = $config->richTheme;
×
262
        RichRenderer::$folder = $config->richFolder;
×
263

UNCOV
264
        if (isset($config->richObjectPlugins) && is_array($config->richObjectPlugins)) {
×
265
            RichRenderer::$value_plugins = $config->richObjectPlugins;
×
266
        }
UNCOV
267
        if (isset($config->richTabPlugins) && is_array($config->richTabPlugins)) {
×
268
            RichRenderer::$tab_plugins = $config->richTabPlugins;
×
269
        }
270

UNCOV
271
        CliRenderer::$cli_colors         = $config->cliColors;
×
272
        CliRenderer::$force_utf8         = $config->cliForceUTF8;
×
273
        CliRenderer::$detect_width       = $config->cliDetectWidth;
×
274
        CliRenderer::$min_terminal_width = $config->cliMinWidth;
×
275
    }
276

277
    /**
278
     * Launch the application!
279
     *
280
     * This is "the loop" if you will. The main entry point into the script
281
     * that gets the required class instances, fires off the filters,
282
     * tries to route the response, loads the controller and generally
283
     * makes all the pieces work together.
284
     *
285
     * @param bool $returnResponse Used for testing purposes only.
286
     *
287
     * @return ResponseInterface|null
288
     */
289
    public function run(?RouteCollectionInterface $routes = null, bool $returnResponse = false)
290
    {
291
        if ($this->context === null) {
97✔
UNCOV
292
            throw new LogicException(
×
293
                'Context must be set before run() is called. If you are upgrading from 4.1.x, '
×
294
                . 'you need to merge `public/index.php` and `spark` file from `vendor/codeigniter4/framework`.',
×
295
            );
×
296
        }
297

298
        $this->pageCache->setTtl(0);
97✔
299
        $this->bufferLevel = ob_get_level();
97✔
300

301
        $this->startBenchmark();
97✔
302

303
        $this->getRequestObject();
97✔
304
        $this->getResponseObject();
97✔
305

306
        Events::trigger('pre_system');
97✔
307

308
        $this->benchmark->stop('bootstrap');
97✔
309

310
        $this->benchmark->start('required_before_filters');
97✔
311
        // Start up the filters
312
        $filters = Services::filters();
97✔
313
        // Run required before filters
314
        $possibleResponse = $this->runRequiredBeforeFilters($filters);
97✔
315

316
        // If a ResponseInterface instance is returned then send it back to the client and stop
317
        if ($possibleResponse instanceof ResponseInterface) {
97✔
318
            $this->response = $possibleResponse;
3✔
319
        } else {
320
            try {
321
                $this->response = $this->handleRequest($routes, config(Cache::class), $returnResponse);
96✔
322
            } catch (ResponsableInterface $e) {
18✔
323
                $this->outputBufferingEnd();
6✔
324

325
                $this->response = $e->getResponse();
6✔
326
            } catch (PageNotFoundException $e) {
12✔
327
                $this->response = $this->display404errors($e);
12✔
UNCOV
328
            } catch (Throwable $e) {
×
329
                $this->outputBufferingEnd();
×
330

UNCOV
331
                throw $e;
×
332
            }
333
        }
334

335
        $this->runRequiredAfterFilters($filters);
89✔
336

337
        // Is there a post-system event?
338
        Events::trigger('post_system');
89✔
339

340
        if ($returnResponse) {
89✔
341
            return $this->response;
36✔
342
        }
343

344
        $this->sendResponse();
53✔
345

346
        return null;
53✔
347
    }
348

349
    /**
350
     * Run required before filters.
351
     */
352
    private function runRequiredBeforeFilters(Filters $filters): ?ResponseInterface
353
    {
354
        $possibleResponse = $filters->runRequired('before');
97✔
355
        $this->benchmark->stop('required_before_filters');
97✔
356

357
        // If a ResponseInterface instance is returned then send it back to the client and stop
358
        if ($possibleResponse instanceof ResponseInterface) {
97✔
359
            return $possibleResponse;
3✔
360
        }
361

362
        return null;
96✔
363
    }
364

365
    /**
366
     * Run required after filters.
367
     */
368
    private function runRequiredAfterFilters(Filters $filters): void
369
    {
370
        $filters->setResponse($this->response);
89✔
371

372
        // Run required after filters
373
        $this->benchmark->start('required_after_filters');
89✔
374
        $response = $filters->runRequired('after');
89✔
375
        $this->benchmark->stop('required_after_filters');
89✔
376

377
        if ($response instanceof ResponseInterface) {
89✔
378
            $this->response = $response;
89✔
379
        }
380
    }
381

382
    /**
383
     * Invoked via php-cli command?
384
     */
385
    private function isPhpCli(): bool
386
    {
387
        return $this->context === 'php-cli';
59✔
388
    }
389

390
    /**
391
     * Web access?
392
     */
393
    private function isWeb(): bool
394
    {
395
        return $this->context === 'web';
97✔
396
    }
397

398
    /**
399
     * Disables Controller Filters.
400
     */
401
    public function disableFilters(): void
402
    {
403
        $this->enableFilters = false;
1✔
404
    }
405

406
    /**
407
     * Handles the main request logic and fires the controller.
408
     *
409
     * @return ResponseInterface
410
     *
411
     * @throws PageNotFoundException
412
     * @throws RedirectException
413
     *
414
     * @deprecated $returnResponse is deprecated.
415
     */
416
    protected function handleRequest(?RouteCollectionInterface $routes, Cache $cacheConfig, bool $returnResponse = false)
417
    {
418
        if ($this->request instanceof IncomingRequest && $this->request->getMethod() === 'CLI') {
96✔
419
            return $this->response->setStatusCode(405)->setBody('Method Not Allowed');
1✔
420
        }
421

422
        $routeFilters = $this->tryToRouteIt($routes);
95✔
423

424
        // $uri is URL-encoded.
425
        $uri = $this->request->getPath();
78✔
426

427
        if ($this->enableFilters) {
78✔
428
            /** @var Filters $filters */
429
            $filters = service('filters');
77✔
430

431
            // If any filters were specified within the routes file,
432
            // we need to ensure it's active for the current request
433
            if ($routeFilters !== null) {
77✔
434
                $filters->enableFilters($routeFilters, 'before');
77✔
435

436
                $oldFilterOrder = config(Feature::class)->oldFilterOrder ?? false;
77✔
437
                if (! $oldFilterOrder) {
77✔
438
                    $routeFilters = array_reverse($routeFilters);
77✔
439
                }
440

441
                $filters->enableFilters($routeFilters, 'after');
77✔
442
            }
443

444
            // Run "before" filters
445
            $this->benchmark->start('before_filters');
77✔
446
            $possibleResponse = $filters->run($uri, 'before');
77✔
447
            $this->benchmark->stop('before_filters');
77✔
448

449
            // If a ResponseInterface instance is returned then send it back to the client and stop
450
            if ($possibleResponse instanceof ResponseInterface) {
77✔
451
                $this->outputBufferingEnd();
1✔
452

453
                return $possibleResponse;
1✔
454
            }
455

456
            if ($possibleResponse instanceof IncomingRequest || $possibleResponse instanceof CLIRequest) {
76✔
457
                $this->request = $possibleResponse;
76✔
458
            }
459
        }
460

461
        $returned = $this->startController();
77✔
462

463
        // If startController returned a Response (from an attribute or Closure), use it
464
        if ($returned instanceof ResponseInterface) {
76✔
465
            $this->gatherOutput($cacheConfig, $returned);
8✔
466
        }
467
        // Closure controller has run in startController().
468
        elseif (! is_callable($this->controller)) {
69✔
469
            $controller = $this->createController();
47✔
470

471
            if (! method_exists($controller, '_remap') && ! is_callable([$controller, $this->method], false)) {
47✔
UNCOV
472
                throw PageNotFoundException::forMethodNotFound($this->method);
×
473
            }
474

475
            // Is there a "post_controller_constructor" event?
476
            Events::trigger('post_controller_constructor');
47✔
477

478
            $returned = $this->runController($controller);
47✔
479
        } else {
480
            $this->benchmark->stop('controller_constructor');
22✔
481
            $this->benchmark->stop('controller');
22✔
482
        }
483

484
        // If $returned is a string, then the controller output something,
485
        // probably a view, instead of echoing it directly. Send it along
486
        // so it can be used with the output.
487
        $this->gatherOutput($cacheConfig, $returned);
76✔
488

489
        if ($this->enableFilters) {
76✔
490
            /** @var Filters $filters */
491
            $filters = service('filters');
75✔
492
            $filters->setResponse($this->response);
75✔
493

494
            // Run "after" filters
495
            $this->benchmark->start('after_filters');
75✔
496
            $response = $filters->run($uri, 'after');
75✔
497
            $this->benchmark->stop('after_filters');
75✔
498

499
            if ($response instanceof ResponseInterface) {
75✔
500
                $this->response = $response;
75✔
501
            }
502
        }
503

504
        // Execute controller attributes' after() methods AFTER framework filters
505
        $this->benchmark->start('route_attributes_after');
76✔
506
        $this->response = $this->router->executeAfterAttributes($this->request, $this->response);
76✔
507
        $this->benchmark->stop('route_attributes_after');
76✔
508

509
        // Skip unnecessary processing for special Responses.
510
        if (
511
            ! $this->response instanceof DownloadResponse
76✔
512
            && ! $this->response instanceof RedirectResponse
76✔
513
        ) {
514
            // Save our current URI as the previous URI in the session
515
            // for safer, more accurate use with `previous_url()` helper function.
516
            $this->storePreviousURL(current_url(true));
74✔
517
        }
518

519
        unset($uri);
76✔
520

521
        return $this->response;
76✔
522
    }
523

524
    /**
525
     * You can load different configurations depending on your
526
     * current environment. Setting the environment also influences
527
     * things like logging and error reporting.
528
     *
529
     * This can be set to anything, but default usage is:
530
     *
531
     *     development
532
     *     testing
533
     *     production
534
     *
535
     * @codeCoverageIgnore
536
     *
537
     * @return void
538
     *
539
     * @deprecated 4.4.0 No longer used. Moved to index.php and spark.
540
     */
541
    protected function detectEnvironment()
542
    {
543
        // Make sure ENVIRONMENT isn't already set by other means.
UNCOV
544
        if (! defined('ENVIRONMENT')) {
×
UNCOV
545
            define('ENVIRONMENT', env('CI_ENVIRONMENT', 'production'));
×
546
        }
547
    }
548

549
    /**
550
     * Load any custom boot files based upon the current environment.
551
     *
552
     * If no boot file exists, we shouldn't continue because something
553
     * is wrong. At the very least, they should have error reporting setup.
554
     *
555
     * @return void
556
     *
557
     * @deprecated 4.5.0 Moved to system/bootstrap.php.
558
     */
559
    protected function bootstrapEnvironment()
560
    {
UNCOV
561
        if (is_file(APPPATH . 'Config/Boot/' . ENVIRONMENT . '.php')) {
×
UNCOV
562
            require_once APPPATH . 'Config/Boot/' . ENVIRONMENT . '.php';
×
563
        } else {
564
            // @codeCoverageIgnoreStart
565
            header('HTTP/1.1 503 Service Unavailable.', true, 503);
×
UNCOV
566
            echo 'The application environment is not set correctly.';
×
567

568
            exit(EXIT_ERROR); // EXIT_ERROR
×
569
            // @codeCoverageIgnoreEnd
570
        }
571
    }
572

573
    /**
574
     * Start the Benchmark
575
     *
576
     * The timer is used to display total script execution both in the
577
     * debug toolbar, and potentially on the displayed page.
578
     *
579
     * @return void
580
     */
581
    protected function startBenchmark()
582
    {
583
        if ($this->startTime === null) {
97✔
UNCOV
584
            $this->startTime = microtime(true);
×
585
        }
586

587
        $this->benchmark = Services::timer();
97✔
588
        $this->benchmark->start('total_execution', $this->startTime);
97✔
589
        $this->benchmark->start('bootstrap');
97✔
590
    }
591

592
    /**
593
     * Sets a Request object to be used for this request.
594
     * Used when running certain tests.
595
     *
596
     * @param CLIRequest|IncomingRequest $request
597
     *
598
     * @return $this
599
     *
600
     * @internal Used for testing purposes only.
601
     * @testTag
602
     */
603
    public function setRequest($request)
604
    {
605
        $this->request = $request;
38✔
606

607
        return $this;
38✔
608
    }
609

610
    /**
611
     * Get our Request object, (either IncomingRequest or CLIRequest).
612
     *
613
     * @return void
614
     */
615
    protected function getRequestObject()
616
    {
617
        if ($this->request instanceof Request) {
97✔
618
            $this->spoofRequestMethod();
40✔
619

620
            return;
40✔
621
        }
622

623
        if ($this->isPhpCli()) {
59✔
UNCOV
624
            Services::createRequest($this->config, true);
×
625
        } else {
626
            Services::createRequest($this->config);
59✔
627
        }
628

629
        $this->request = service('request');
59✔
630

631
        $this->spoofRequestMethod();
59✔
632
    }
633

634
    /**
635
     * Get our Response object, and set some default values, including
636
     * the HTTP protocol version and a default successful response.
637
     *
638
     * @return void
639
     */
640
    protected function getResponseObject()
641
    {
642
        $this->response = Services::response($this->config);
97✔
643

644
        if ($this->isWeb()) {
97✔
645
            $this->response->setProtocolVersion($this->request->getProtocolVersion());
97✔
646
        }
647

648
        // Assume success until proven otherwise.
649
        $this->response->setStatusCode(200);
97✔
650
    }
651

652
    /**
653
     * Force Secure Site Access? If the config value 'forceGlobalSecureRequests'
654
     * is true, will enforce that all requests to this site are made through
655
     * HTTPS. Will redirect the user to the current page with HTTPS, as well
656
     * as set the HTTP Strict Transport Security header for those browsers
657
     * that support it.
658
     *
659
     * @param int $duration How long the Strict Transport Security
660
     *                      should be enforced for this URL.
661
     *
662
     * @return void
663
     *
664
     * @deprecated 4.5.0 No longer used. Moved to ForceHTTPS filter.
665
     */
666
    protected function forceSecureAccess($duration = 31_536_000)
667
    {
UNCOV
668
        if ($this->config->forceGlobalSecureRequests !== true) {
×
UNCOV
669
            return;
×
670
        }
671

672
        force_https($duration, $this->request, $this->response);
×
673
    }
674

675
    /**
676
     * Determines if a response has been cached for the given URI.
677
     *
678
     * @return false|ResponseInterface
679
     *
680
     * @throws Exception
681
     *
682
     * @deprecated 4.5.0 PageCache required filter is used. No longer used.
683
     * @deprecated 4.4.2 The parameter $config is deprecated. No longer used.
684
     */
685
    public function displayCache(Cache $config)
686
    {
UNCOV
687
        $cachedResponse = $this->pageCache->get($this->request, $this->response);
×
UNCOV
688
        if ($cachedResponse instanceof ResponseInterface) {
×
UNCOV
689
            $this->response = $cachedResponse;
×
690

691
            $this->totalTime = $this->benchmark->getElapsedTime('total_execution');
×
692
            $output          = $this->displayPerformanceMetrics($cachedResponse->getBody());
×
UNCOV
693
            $this->response->setBody($output);
×
694

695
            return $this->response;
×
696
        }
697

698
        return false;
×
699
    }
700

701
    /**
702
     * Tells the app that the final output should be cached.
703
     *
704
     * @deprecated 4.4.0 Moved to ResponseCache::setTtl(). No longer used.
705
     *
706
     * @return void
707
     */
708
    public static function cache(int $time)
709
    {
710
        static::$cacheTTL = $time;
1✔
711
    }
712

713
    /**
714
     * Caches the full response from the current request. Used for
715
     * full-page caching for very high performance.
716
     *
717
     * @return bool
718
     *
719
     * @deprecated 4.4.0 No longer used.
720
     */
721
    public function cachePage(Cache $config)
722
    {
UNCOV
723
        $headers = [];
×
724

UNCOV
725
        foreach ($this->response->headers() as $header) {
×
726
            $headers[$header->getName()] = $header->getValueLine();
×
727
        }
728

729
        return cache()->save($this->generateCacheName($config), serialize(['headers' => $headers, 'output' => $this->output]), static::$cacheTTL);
×
730
    }
731

732
    /**
733
     * Returns an array with our basic performance stats collected.
734
     */
735
    public function getPerformanceStats(): array
736
    {
737
        // After filter debug toolbar requires 'total_execution'.
UNCOV
738
        $this->totalTime = $this->benchmark->getElapsedTime('total_execution');
×
739

UNCOV
740
        return [
×
741
            'startTime' => $this->startTime,
×
UNCOV
742
            'totalTime' => $this->totalTime,
×
743
        ];
×
744
    }
745

746
    /**
747
     * Generates the cache name to use for our full-page caching.
748
     *
749
     * @deprecated 4.4.0 No longer used.
750
     */
751
    protected function generateCacheName(Cache $config): string
752
    {
UNCOV
753
        if ($this->request instanceof CLIRequest) {
×
UNCOV
754
            return md5($this->request->getPath());
×
755
        }
756

757
        $uri = clone $this->request->getUri();
×
758

UNCOV
759
        $query = $config->cacheQueryString
×
760
            ? $uri->getQuery(is_array($config->cacheQueryString) ? ['only' => $config->cacheQueryString] : [])
×
UNCOV
761
            : '';
×
762

763
        return md5((string) $uri->setFragment('')->setQuery($query));
×
764
    }
765

766
    /**
767
     * Replaces the elapsed_time and memory_usage tag.
768
     *
769
     * @deprecated 4.5.0 PerformanceMetrics required filter is used. No longer used.
770
     */
771
    public function displayPerformanceMetrics(string $output): string
772
    {
UNCOV
773
        return str_replace(
×
UNCOV
774
            ['{elapsed_time}', '{memory_usage}'],
×
UNCOV
775
            [(string) $this->totalTime, number_format(memory_get_peak_usage() / 1024 / 1024, 3)],
×
776
            $output,
×
777
        );
×
778
    }
779

780
    /**
781
     * Try to Route It - As it sounds like, works with the router to
782
     * match a route against the current URI. If the route is a
783
     * "redirect route", will also handle the redirect.
784
     *
785
     * @param RouteCollectionInterface|null $routes A collection interface to use in place
786
     *                                              of the config file.
787
     *
788
     * @return list<string>|string|null Route filters, that is, the filters specified in the routes file
789
     *
790
     * @throws RedirectException
791
     */
792
    protected function tryToRouteIt(?RouteCollectionInterface $routes = null)
793
    {
794
        $this->benchmark->start('routing');
95✔
795

796
        if (! $routes instanceof RouteCollectionInterface) {
95✔
797
            $routes = service('routes')->loadRoutes();
36✔
798
        }
799

800
        // $routes is defined in Config/Routes.php
801
        $this->router = Services::router($routes, $this->request);
95✔
802

803
        // $uri is URL-encoded.
804
        $uri = $this->request->getPath();
95✔
805

806
        $this->outputBufferingStart();
95✔
807

808
        $this->controller = $this->router->handle($uri);
95✔
809
        $this->method     = $this->router->methodName();
78✔
810

811
        // If a {locale} segment was matched in the final route,
812
        // then we need to set the correct locale on our Request.
813
        if ($this->router->hasLocale()) {
78✔
UNCOV
814
            $this->request->setLocale($this->router->getLocale());
×
815
        }
816

817
        $this->benchmark->stop('routing');
78✔
818

819
        return $this->router->getFilters();
78✔
820
    }
821

822
    /**
823
     * Determines the path to use for us to try to route to, based
824
     * on the CLI/IncomingRequest path.
825
     *
826
     * @return string
827
     *
828
     * @deprecated 4.5.0 No longer used.
829
     */
830
    protected function determinePath()
831
    {
UNCOV
832
        return $this->request->getPath();
×
833
    }
834

835
    /**
836
     * Now that everything has been setup, this method attempts to run the
837
     * controller method and make the script go. If it's not able to, will
838
     * show the appropriate Page Not Found error.
839
     *
840
     * @return ResponseInterface|string|null
841
     */
842
    protected function startController()
843
    {
844
        $this->benchmark->start('controller');
78✔
845
        $this->benchmark->start('controller_constructor');
78✔
846

847
        // Is it routed to a Closure?
848
        if (is_object($this->controller) && ($this->controller::class === 'Closure')) {
78✔
849
            $controller = $this->controller;
29✔
850

851
            return $controller(...$this->router->params());
29✔
852
        }
853

854
        // No controller specified - we don't know what to do now.
855
        if (! isset($this->controller)) {
49✔
UNCOV
856
            throw PageNotFoundException::forEmptyController();
×
857
        }
858

859
        // Try to autoload the class
860
        if (
861
            ! class_exists($this->controller, true)
49✔
862
            || ($this->method[0] === '_' && $this->method !== '__invoke')
49✔
863
        ) {
UNCOV
864
            throw PageNotFoundException::forControllerNotFound($this->controller, $this->method);
×
865
        }
866

867
        // Execute route attributes' before() methods
868
        // This runs after routing/validation but BEFORE expensive controller instantiation
869
        $this->benchmark->start('route_attributes_before');
49✔
870
        $attributeResponse = $this->router->executeBeforeAttributes($this->request);
49✔
871
        $this->benchmark->stop('route_attributes_before');
48✔
872

873
        // If attribute returns a Response, short-circuit
874
        if ($attributeResponse instanceof ResponseInterface) {
48✔
875
            $this->benchmark->stop('controller_constructor');
1✔
876
            $this->benchmark->stop('controller');
1✔
877

878
            return $attributeResponse;
1✔
879
        }
880

881
        // If attribute returns a modified Request, use it
882
        if ($attributeResponse instanceof Request) {
48✔
883
            $this->request = $attributeResponse;
48✔
884
        }
885

886
        return null;
48✔
887
    }
888

889
    /**
890
     * Instantiates the controller class.
891
     *
892
     * @return Controller
893
     */
894
    protected function createController()
895
    {
896
        assert(is_string($this->controller));
897

898
        $class = new $this->controller();
50✔
899
        $class->initController($this->request, $this->response, Services::logger());
50✔
900

901
        $this->benchmark->stop('controller_constructor');
50✔
902

903
        return $class;
50✔
904
    }
905

906
    /**
907
     * Runs the controller, allowing for _remap methods to function.
908
     *
909
     * CI4 supports three types of requests:
910
     *  1. Web: URI segments become parameters, sent to Controllers via Routes,
911
     *      output controlled by Headers to browser
912
     *  2. PHP CLI: accessed by CLI via php public/index.php, arguments become URI segments,
913
     *      sent to Controllers via Routes, output varies
914
     *
915
     * @param Controller $class
916
     *
917
     * @return false|ResponseInterface|string|void
918
     */
919
    protected function runController($class)
920
    {
921
        // This is a Web request or PHP CLI request
922
        $params = $this->router->params();
47✔
923

924
        // The controller method param types may not be string.
925
        // So cannot set `declare(strict_types=1)` in this file.
926
        $output = method_exists($class, '_remap')
47✔
UNCOV
927
            ? $class->_remap($this->method, ...$params)
×
928
            : $class->{$this->method}(...$params);
47✔
929

930
        $this->benchmark->stop('controller');
47✔
931

932
        return $output;
47✔
933
    }
934

935
    /**
936
     * Displays a 404 Page Not Found error. If set, will try to
937
     * call the 404Override controller/method that was set in routing config.
938
     *
939
     * @return ResponseInterface|void
940
     */
941
    protected function display404errors(PageNotFoundException $e)
942
    {
943
        $this->response->setStatusCode($e->getCode());
12✔
944

945
        // Is there a 404 Override available?
946
        $override = $this->router->get404Override();
12✔
947

948
        if ($override !== null) {
12✔
949
            $returned = null;
4✔
950

951
            if ($override instanceof Closure) {
4✔
952
                echo $override($e->getMessage());
1✔
953
            } elseif (is_array($override)) {
3✔
954
                $this->benchmark->start('controller');
3✔
955
                $this->benchmark->start('controller_constructor');
3✔
956

957
                $this->controller = $override[0];
3✔
958
                $this->method     = $override[1];
3✔
959

960
                $controller = $this->createController();
3✔
961

962
                $returned = $controller->{$this->method}($e->getMessage());
3✔
963

964
                $this->benchmark->stop('controller');
3✔
965
            }
966

967
            unset($override);
4✔
968

969
            $cacheConfig = config(Cache::class);
4✔
970
            $this->gatherOutput($cacheConfig, $returned);
4✔
971

972
            return $this->response;
4✔
973
        }
974

975
        $this->outputBufferingEnd();
8✔
976

977
        // Throws new PageNotFoundException and remove exception message on production.
978
        throw PageNotFoundException::forPageNotFound(
8✔
979
            (ENVIRONMENT !== 'production' || ! $this->isWeb()) ? $e->getMessage() : null,
8✔
980
        );
8✔
981
    }
982

983
    /**
984
     * Gathers the script output from the buffer, replaces some execution
985
     * time tag in the output and displays the debug toolbar, if required.
986
     *
987
     * @param Cache|null                    $cacheConfig Deprecated. No longer used.
988
     * @param ResponseInterface|string|null $returned
989
     *
990
     * @deprecated $cacheConfig is deprecated.
991
     *
992
     * @return void
993
     */
994
    protected function gatherOutput(?Cache $cacheConfig = null, $returned = null)
995
    {
996
        $this->output = $this->outputBufferingEnd();
80✔
997

998
        if ($returned instanceof DownloadResponse) {
80✔
999
            $this->response = $returned;
1✔
1000

1001
            return;
1✔
1002
        }
1003
        // If the controller returned a response object,
1004
        // we need to grab the body from it so it can
1005
        // be added to anything else that might have been
1006
        // echoed already.
1007
        // We also need to save the instance locally
1008
        // so that any status code changes, etc, take place.
1009
        if ($returned instanceof ResponseInterface) {
79✔
1010
            $this->response = $returned;
26✔
1011
            $returned       = $returned->getBody();
26✔
1012
        }
1013

1014
        if (is_string($returned)) {
79✔
1015
            $this->output .= $returned;
71✔
1016
        }
1017

1018
        $this->response->setBody($this->output);
79✔
1019
    }
1020

1021
    /**
1022
     * If we have a session object to use, store the current URI
1023
     * as the previous URI. This is called just prior to sending the
1024
     * response to the client, and will make it available next request.
1025
     *
1026
     * This helps provider safer, more reliable previous_url() detection.
1027
     *
1028
     * @param string|URI $uri
1029
     *
1030
     * @return void
1031
     */
1032
    public function storePreviousURL($uri)
1033
    {
1034
        // Ignore CLI requests
1035
        if (! $this->isWeb()) {
74✔
UNCOV
1036
            return;
×
1037
        }
1038
        // Ignore AJAX requests
1039
        if (method_exists($this->request, 'isAJAX') && $this->request->isAJAX()) {
74✔
UNCOV
1040
            return;
×
1041
        }
1042

1043
        // Ignore unroutable responses
1044
        if ($this->response instanceof DownloadResponse || $this->response instanceof RedirectResponse) {
74✔
1045
            return;
×
1046
        }
1047

1048
        // Ignore non-HTML responses
1049
        if (! str_contains($this->response->getHeaderLine('Content-Type'), 'text/html')) {
74✔
1050
            return;
12✔
1051
        }
1052

1053
        // This is mainly needed during testing...
1054
        if (is_string($uri)) {
62✔
UNCOV
1055
            $uri = new URI($uri);
×
1056
        }
1057

1058
        if (isset($_SESSION)) {
62✔
1059
            session()->set('_ci_previous_url', URI::createURIString(
62✔
1060
                $uri->getScheme(),
62✔
1061
                $uri->getAuthority(),
62✔
1062
                $uri->getPath(),
62✔
1063
                $uri->getQuery(),
62✔
1064
                $uri->getFragment(),
62✔
1065
            ));
62✔
1066
        }
1067
    }
1068

1069
    /**
1070
     * Modifies the Request Object to use a different method if a POST
1071
     * variable called _method is found.
1072
     *
1073
     * @return void
1074
     */
1075
    public function spoofRequestMethod()
1076
    {
1077
        // Only works with POSTED forms
1078
        if ($this->request->getMethod() !== Method::POST) {
97✔
1079
            return;
82✔
1080
        }
1081

1082
        $method = $this->request->getPost('_method');
16✔
1083

1084
        if ($method === null) {
16✔
1085
            return;
14✔
1086
        }
1087

1088
        // Only allows PUT, PATCH, DELETE
1089
        if (in_array($method, [Method::PUT, Method::PATCH, Method::DELETE], true)) {
2✔
1090
            $this->request = $this->request->setMethod($method);
1✔
1091
        }
1092
    }
1093

1094
    /**
1095
     * Sends the output of this request back to the client.
1096
     * This is what they've been waiting for!
1097
     *
1098
     * @return void
1099
     */
1100
    protected function sendResponse()
1101
    {
1102
        $this->response->send();
53✔
1103
    }
1104

1105
    /**
1106
     * Exits the application, setting the exit code for CLI-based applications
1107
     * that might be watching.
1108
     *
1109
     * Made into a separate method so that it can be mocked during testing
1110
     * without actually stopping script execution.
1111
     *
1112
     * @param int $code
1113
     *
1114
     * @deprecated 4.4.0 No longer Used. Moved to index.php.
1115
     *
1116
     * @return void
1117
     */
1118
    protected function callExit($code)
1119
    {
UNCOV
1120
        exit($code); // @codeCoverageIgnore
×
1121
    }
1122

1123
    /**
1124
     * Sets the app context.
1125
     *
1126
     * @param 'php-cli'|'web' $context
1127
     *
1128
     * @return $this
1129
     */
1130
    public function setContext(string $context)
1131
    {
1132
        $this->context = $context;
39✔
1133

1134
        return $this;
39✔
1135
    }
1136

1137
    protected function outputBufferingStart(): void
1138
    {
1139
        $this->bufferLevel = ob_get_level();
95✔
1140
        ob_start();
95✔
1141
    }
1142

1143
    protected function outputBufferingEnd(): string
1144
    {
1145
        $buffer = '';
95✔
1146

1147
        while (ob_get_level() > $this->bufferLevel) {
95✔
1148
            $buffer .= ob_get_contents();
95✔
1149
            ob_end_clean();
95✔
1150
        }
1151

1152
        return $buffer;
95✔
1153
    }
1154
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc