ci4

Форк
0
/
Boot.php 
355 строк · 9.9 Кб
1
<?php
2

3
declare(strict_types=1);
4

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

14
namespace CodeIgniter;
15

16
use CodeIgniter\Cache\FactoriesCache;
17
use CodeIgniter\CLI\Console;
18
use CodeIgniter\Config\DotEnv;
19
use Config\Autoload;
20
use Config\Modules;
21
use Config\Optimize;
22
use Config\Paths;
23
use Config\Services;
24

25
/**
26
 * Bootstrap for the application
27
 *
28
 * @codeCoverageIgnore
29
 */
30
class Boot
31
{
32
    /**
33
     * Used by `public/index.php`
34
     *
35
     * Context
36
     *   web:     Invoked by HTTP request
37
     *   php-cli: Invoked by CLI via `php public/index.php`
38
     *
39
     * @return int Exit code.
40
     */
41
    public static function bootWeb(Paths $paths): int
42
    {
43
        static::definePathConstants($paths);
44
        if (! defined('APP_NAMESPACE')) {
45
            static::loadConstants();
46
        }
47
        static::checkMissingExtensions();
48

49
        static::loadDotEnv($paths);
50
        static::defineEnvironment();
51
        static::loadEnvironmentBootstrap($paths);
52

53
        static::loadCommonFunctions();
54
        static::loadAutoloader();
55
        static::setExceptionHandler();
56
        static::initializeKint();
57

58
        $configCacheEnabled = class_exists(Optimize::class)
59
            && (new Optimize())->configCacheEnabled;
60
        if ($configCacheEnabled) {
61
            $factoriesCache = static::loadConfigCache();
62
        }
63

64
        static::autoloadHelpers();
65

66
        $app = static::initializeCodeIgniter();
67
        static::runCodeIgniter($app);
68

69
        if ($configCacheEnabled) {
70
            static::saveConfigCache($factoriesCache);
71
        }
72

73
        // Exits the application, setting the exit code for CLI-based
74
        // applications that might be watching.
75
        return EXIT_SUCCESS;
76
    }
77

78
    /**
79
     * Used by `spark`
80
     *
81
     * @return int Exit code.
82
     */
83
    public static function bootSpark(Paths $paths): int
84
    {
85
        static::definePathConstants($paths);
86
        if (! defined('APP_NAMESPACE')) {
87
            static::loadConstants();
88
        }
89
        static::checkMissingExtensions();
90

91
        static::loadDotEnv($paths);
92
        static::defineEnvironment();
93
        static::loadEnvironmentBootstrap($paths);
94

95
        static::loadCommonFunctions();
96
        static::loadAutoloader();
97
        static::setExceptionHandler();
98
        static::initializeKint();
99
        static::autoloadHelpers();
100

101
        static::initializeCodeIgniter();
102
        $console = static::initializeConsole();
103

104
        return static::runCommand($console);
105
    }
106

107
    /**
108
     * Used by `system/Test/bootstrap.php`
109
     */
110
    public static function bootTest(Paths $paths): void
111
    {
112
        static::loadConstants();
113
        static::checkMissingExtensions();
114

115
        static::loadDotEnv($paths);
116
        static::loadEnvironmentBootstrap($paths, false);
117

118
        static::loadCommonFunctions();
119
        static::loadAutoloader();
120
        static::setExceptionHandler();
121
        static::initializeKint();
122
        static::autoloadHelpers();
123
    }
124

125
    /**
126
     * Used by `preload.php`
127
     */
128
    public static function preload(Paths $paths): void
129
    {
130
        static::definePathConstants($paths);
131
        static::loadConstants();
132
        static::defineEnvironment();
133
        static::loadEnvironmentBootstrap($paths, false);
134

135
        static::loadAutoloader();
136
    }
137

138
    /**
139
     * Load environment settings from .env files into $_SERVER and $_ENV
140
     */
141
    protected static function loadDotEnv(Paths $paths): void
142
    {
143
        require_once $paths->systemDirectory . '/Config/DotEnv.php';
144
        (new DotEnv($paths->appDirectory . '/../'))->load();
145
    }
146

147
    protected static function defineEnvironment(): void
148
    {
149
        if (! defined('ENVIRONMENT')) {
150
            // @phpstan-ignore-next-line
151
            $env = $_ENV['CI_ENVIRONMENT'] ?? $_SERVER['CI_ENVIRONMENT']
152
                ?? getenv('CI_ENVIRONMENT')
153
                ?: 'production';
154

155
            define('ENVIRONMENT', $env);
156
        }
157
    }
158

159
    protected static function loadEnvironmentBootstrap(Paths $paths, bool $exit = true): void
160
    {
161
        if (is_file($paths->appDirectory . '/Config/Boot/' . ENVIRONMENT . '.php')) {
162
            require_once $paths->appDirectory . '/Config/Boot/' . ENVIRONMENT . '.php';
163

164
            return;
165
        }
166

167
        if ($exit) {
168
            header('HTTP/1.1 503 Service Unavailable.', true, 503);
169
            echo 'The application environment is not set correctly.';
170

171
            exit(EXIT_ERROR);
172
        }
173
    }
174

175
    /**
176
     * The path constants provide convenient access to the folders throughout
177
     * the application. We have to set them up here, so they are available in
178
     * the config files that are loaded.
179
     */
180
    protected static function definePathConstants(Paths $paths): void
181
    {
182
        // The path to the application directory.
183
        if (! defined('APPPATH')) {
184
            define('APPPATH', realpath(rtrim($paths->appDirectory, '\\/ ')) . DIRECTORY_SEPARATOR);
185
        }
186

187
        // The path to the project root directory. Just above APPPATH.
188
        if (! defined('ROOTPATH')) {
189
            define('ROOTPATH', realpath(APPPATH . '../') . DIRECTORY_SEPARATOR);
190
        }
191

192
        // The path to the system directory.
193
        if (! defined('SYSTEMPATH')) {
194
            define('SYSTEMPATH', realpath(rtrim($paths->systemDirectory, '\\/ ')) . DIRECTORY_SEPARATOR);
195
        }
196

197
        // The path to the writable directory.
198
        if (! defined('WRITEPATH')) {
199
            define('WRITEPATH', realpath(rtrim($paths->writableDirectory, '\\/ ')) . DIRECTORY_SEPARATOR);
200
        }
201

202
        // The path to the tests directory
203
        if (! defined('TESTPATH')) {
204
            define('TESTPATH', realpath(rtrim($paths->testsDirectory, '\\/ ')) . DIRECTORY_SEPARATOR);
205
        }
206
    }
207

208
    protected static function loadConstants(): void
209
    {
210
        require_once APPPATH . 'Config/Constants.php';
211
    }
212

213
    protected static function loadCommonFunctions(): void
214
    {
215
        // Require app/Common.php file if exists.
216
        if (is_file(APPPATH . 'Common.php')) {
217
            require_once APPPATH . 'Common.php';
218
        }
219

220
        // Require system/Common.php
221
        require_once SYSTEMPATH . 'Common.php';
222
    }
223

224
    /**
225
     * The autoloader allows all the pieces to work together in the framework.
226
     * We have to load it here, though, so that the config files can use the
227
     * path constants.
228
     */
229
    protected static function loadAutoloader(): void
230
    {
231
        if (! class_exists(Autoload::class, false)) {
232
            require_once SYSTEMPATH . 'Config/AutoloadConfig.php';
233
            require_once APPPATH . 'Config/Autoload.php';
234
            require_once SYSTEMPATH . 'Modules/Modules.php';
235
            require_once APPPATH . 'Config/Modules.php';
236
        }
237

238
        require_once SYSTEMPATH . 'Autoloader/Autoloader.php';
239
        require_once SYSTEMPATH . 'Config/BaseService.php';
240
        require_once SYSTEMPATH . 'Config/Services.php';
241
        require_once APPPATH . 'Config/Services.php';
242

243
        // Initialize and register the loader with the SPL autoloader stack.
244
        Services::autoloader()->initialize(new Autoload(), new Modules())->register();
245
    }
246

247
    protected static function autoloadHelpers(): void
248
    {
249
        Services::autoloader()->loadHelpers();
250
    }
251

252
    protected static function setExceptionHandler(): void
253
    {
254
        Services::exceptions()->initialize();
255
    }
256

257
    protected static function checkMissingExtensions(): void
258
    {
259
        if (is_file(COMPOSER_PATH)) {
260
            return;
261
        }
262

263
        // Run this check for manual installations
264
        $missingExtensions = [];
265

266
        foreach ([
267
            'intl',
268
            'json',
269
            'mbstring',
270
        ] as $extension) {
271
            if (! extension_loaded($extension)) {
272
                $missingExtensions[] = $extension;
273
            }
274
        }
275

276
        if ($missingExtensions === []) {
277
            return;
278
        }
279

280
        $message = sprintf(
281
            'The framework needs the following extension(s) installed and loaded: %s.',
282
            implode(', ', $missingExtensions)
283
        );
284

285
        header('HTTP/1.1 503 Service Unavailable.', true, 503);
286
        echo $message;
287

288
        exit(EXIT_ERROR);
289
    }
290

291
    protected static function initializeKint(): void
292
    {
293
        Services::autoloader()->initializeKint(CI_DEBUG);
294
    }
295

296
    protected static function loadConfigCache(): FactoriesCache
297
    {
298
        $factoriesCache = new FactoriesCache();
299
        $factoriesCache->load('config');
300

301
        return $factoriesCache;
302
    }
303

304
    /**
305
     * The CodeIgniter class contains the core functionality to make
306
     * the application run, and does all the dirty work to get
307
     * the pieces all working together.
308
     */
309
    protected static function initializeCodeIgniter(): CodeIgniter
310
    {
311
        $app = Config\Services::codeigniter();
312
        $app->initialize();
313
        $context = is_cli() ? 'php-cli' : 'web';
314
        $app->setContext($context);
315

316
        return $app;
317
    }
318

319
    /**
320
     * Now that everything is set up, it's time to actually fire
321
     * up the engines and make this app do its thang.
322
     */
323
    protected static function runCodeIgniter(CodeIgniter $app): void
324
    {
325
        $app->run();
326
    }
327

328
    protected static function saveConfigCache(FactoriesCache $factoriesCache): void
329
    {
330
        $factoriesCache->save('config');
331
    }
332

333
    protected static function initializeConsole(): Console
334
    {
335
        $console = new Console();
336

337
        // Show basic information before we do anything else.
338
        // @phpstan-ignore-next-line
339
        if (is_int($suppress = array_search('--no-header', $_SERVER['argv'], true))) {
340
            unset($_SERVER['argv'][$suppress]); // @phpstan-ignore-line
341
            $suppress = true;
342
        }
343

344
        $console->showHeader($suppress);
345

346
        return $console;
347
    }
348

349
    protected static function runCommand(Console $console): int
350
    {
351
        $exit = $console->run();
352

353
        return is_int($exit) ? $exit : EXIT_SUCCESS;
354
    }
355
}
356

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.