-
Notifications
You must be signed in to change notification settings - Fork 821
/
CoreKernel.php
675 lines (581 loc) · 18.9 KB
/
CoreKernel.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
<?php
namespace SilverStripe\Core;
use InvalidArgumentException;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;
use Psr\Log\LoggerInterface;
use SilverStripe\Config\Collections\CachedConfigCollection;
use SilverStripe\Control\Director;
use SilverStripe\Control\HTTPResponse;
use SilverStripe\Control\HTTPResponse_Exception;
use SilverStripe\Core\Cache\ManifestCacheFactory;
use SilverStripe\Core\Config\ConfigLoader;
use SilverStripe\Core\Config\CoreConfigFactory;
use SilverStripe\Core\Injector\Injector;
use SilverStripe\Core\Injector\InjectorLoader;
use SilverStripe\Core\Injector\SilverStripeServiceConfigurationLocator;
use SilverStripe\Core\Manifest\ClassLoader;
use SilverStripe\Core\Manifest\ClassManifest;
use SilverStripe\Core\Manifest\ModuleLoader;
use SilverStripe\Core\Manifest\ModuleManifest;
use SilverStripe\Dev\DebugView;
use SilverStripe\Dev\Install\DatabaseAdapterRegistry;
use SilverStripe\Logging\ErrorHandler;
use SilverStripe\ORM\DB;
use SilverStripe\View\PublicThemes;
use SilverStripe\View\SSViewer;
use SilverStripe\View\ThemeManifest;
use SilverStripe\View\ThemeResourceLoader;
use SilverStripe\Dev\Deprecation;
/**
* Simple Kernel container
*/
class CoreKernel implements Kernel
{
/**
* @var Kernel
*/
protected $nestedFrom = null;
/**
* @var Injector
*/
protected $container = null;
/**
* @var string
*/
protected $enviroment = null;
/**
* @var ClassLoader
*/
protected $classLoader = null;
/**
* @var ModuleLoader
*/
protected $moduleLoader = null;
/**
* @var ConfigLoader
*/
protected $configLoader = null;
/**
* @var InjectorLoader
*/
protected $injectorLoader = null;
/**
* @var ThemeResourceLoader
*/
protected $themeResourceLoader = null;
protected $basePath = null;
/**
* Indicates whether the Kernel has been booted already
*
* @var bool
*/
private $booted = false;
/**
* Indicates whether the Kernel has been flushed on boot
* Unitialized before boot
*
* @var bool
*/
private $flush;
/**
* Create a new kernel for this application
*
* @param string $basePath Path to base dir for this application
*/
public function __construct($basePath)
{
$this->basePath = $basePath;
// Initialise the dependency injector as soon as possible, as it is
// subsequently used by some of the following code
$injectorLoader = InjectorLoader::inst();
$injector = new Injector(array('locator' => SilverStripeServiceConfigurationLocator::class));
$injectorLoader->pushManifest($injector);
$this->setInjectorLoader($injectorLoader);
// Manifest cache factory
$manifestCacheFactory = $this->buildManifestCacheFactory();
// Class loader
$classLoader = ClassLoader::inst();
$classLoader->pushManifest(new ClassManifest($basePath, $manifestCacheFactory));
$this->setClassLoader($classLoader);
// Module loader
$moduleLoader = ModuleLoader::inst();
$moduleManifest = new ModuleManifest($basePath, $manifestCacheFactory);
$moduleLoader->pushManifest($moduleManifest);
$this->setModuleLoader($moduleLoader);
// Config loader
// @todo refactor CoreConfigFactory
$configFactory = new CoreConfigFactory($manifestCacheFactory);
$configManifest = $configFactory->createRoot();
$configLoader = ConfigLoader::inst();
$configLoader->pushManifest($configManifest);
$this->setConfigLoader($configLoader);
// Load template manifest
$themeResourceLoader = ThemeResourceLoader::inst();
$themeResourceLoader->addSet(SSViewer::PUBLIC_THEME, new PublicThemes());
$themeResourceLoader->addSet(SSViewer::DEFAULT_THEME, new ThemeManifest(
$basePath,
null, // project is defined in config, and this argument is deprecated
$manifestCacheFactory
));
$this->setThemeResourceLoader($themeResourceLoader);
}
/**
* Get the environment type
*
* @return string
*
* @deprecated 5.0 use Director::get_environment_type() instead. Since 5.0 it should return only if kernel overrides. No checking SESSION or Environment.
*/
public function getEnvironment()
{
// Check set
if ($this->enviroment) {
return $this->enviroment;
}
// Check saved session
$env = $this->sessionEnvironment();
if ($env) {
return $env;
}
// Check getenv
if ($env = Environment::getEnv('SS_ENVIRONMENT_TYPE')) {
return $env;
}
return self::LIVE;
}
/**
* Check or update any temporary environment specified in the session.
*
* @return null|string
*
* @deprecated 5.0 Use Director::get_session_environment_type() instead
*/
protected function sessionEnvironment()
{
if (!$this->booted) {
// session is not initialyzed yet, neither is manifest
return null;
}
return Director::get_session_environment_type();
}
public function boot($flush = false)
{
$this->flush = $flush;
$this->bootPHP();
$this->bootManifests($flush);
$this->bootErrorHandling();
$this->bootDatabaseEnvVars();
$this->bootConfigs();
$this->bootDatabaseGlobals();
$this->validateDatabase();
$this->booted = true;
}
/**
* Include all _config.php files
*/
protected function bootConfigs()
{
global $project;
$projectBefore = $project;
$config = ModuleManifest::config();
// After loading all other app manifests, include _config.php files
$this->getModuleLoader()->getManifest()->activateConfig();
if ($project && $project !== $projectBefore) {
Deprecation::notice('5.0', '$project global is deprecated');
$config->set('project', $project);
}
}
/**
* Load default database configuration from the $database and $databaseConfig globals
*/
protected function bootDatabaseGlobals()
{
// Now that configs have been loaded, we can check global for database config
global $databaseConfig;
global $database;
// Case 1: $databaseConfig global exists. Merge $database in as needed
if (!empty($databaseConfig)) {
if (!empty($database)) {
$databaseConfig['database'] = $this->getDatabasePrefix() . $database . $this->getDatabaseSuffix();
}
// Only set it if its valid, otherwise ignore $databaseConfig entirely
if (!empty($databaseConfig['database'])) {
DB::setConfig($databaseConfig);
return;
}
}
// Case 2: $database merged into existing config
if (!empty($database)) {
$existing = DB::getConfig();
$existing['database'] = $this->getDatabasePrefix() . $database . $this->getDatabaseSuffix();
DB::setConfig($existing);
}
}
/**
* Load default database configuration from environment variable
*/
protected function bootDatabaseEnvVars()
{
// Set default database config
$databaseConfig = $this->getDatabaseConfig();
$databaseConfig['database'] = $this->getDatabaseName();
DB::setConfig($databaseConfig);
}
/**
* Check that the database configuration is valid, throwing an HTTPResponse_Exception if it's not
*
* @throws HTTPResponse_Exception
*/
protected function validateDatabase()
{
$databaseConfig = DB::getConfig();
// Gracefully fail if no DB is configured
if (empty($databaseConfig['database'])) {
$this->detectLegacyEnvironment();
$this->redirectToInstaller();
}
}
/**
* Check if there's a legacy _ss_environment.php file
*
* @throws HTTPResponse_Exception
*/
protected function detectLegacyEnvironment()
{
// Is there an _ss_environment.php file?
if (!file_exists($this->basePath . '/_ss_environment.php') &&
!file_exists(dirname($this->basePath) . '/_ss_environment.php')
) {
return;
}
// Build error response
$dv = new DebugView();
$body = implode([
$dv->renderHeader(),
$dv->renderInfo(
"Configuration Error",
Director::absoluteBaseURL()
),
$dv->renderParagraph(
'You need to replace your _ss_environment.php file with a .env file, or with environment variables.<br><br>'
. 'See the <a href="https://docs.silverstripe.org/en/4/getting_started/environment_management/">'
. 'Environment Management</a> docs for more information.'
),
$dv->renderFooter()
]);
// Raise error
$response = new HTTPResponse($body, 500);
throw new HTTPResponse_Exception($response);
}
/**
* If missing configuration, redirect to install.php
*/
protected function redirectToInstaller()
{
// Error if installer not available
if (!file_exists(Director::publicFolder() . '/install.php')) {
throw new HTTPResponse_Exception(
'SilverStripe Framework requires database configuration defined via .env',
500
);
}
// Redirect to installer
$response = new HTTPResponse();
$response->redirect(Director::absoluteURL('install.php'));
throw new HTTPResponse_Exception($response);
}
/**
* Load database config from environment
*
* @return array
*/
protected function getDatabaseConfig()
{
/** @skipUpgrade */
$databaseConfig = [
"type" => Environment::getEnv('SS_DATABASE_CLASS') ?: 'MySQLDatabase',
"server" => Environment::getEnv('SS_DATABASE_SERVER') ?: 'localhost',
"username" => Environment::getEnv('SS_DATABASE_USERNAME') ?: null,
"password" => Environment::getEnv('SS_DATABASE_PASSWORD') ?: null,
];
// Set the port if called for
$dbPort = Environment::getEnv('SS_DATABASE_PORT');
if ($dbPort) {
$databaseConfig['port'] = $dbPort;
}
// Set the timezone if called for
$dbTZ = Environment::getEnv('SS_DATABASE_TIMEZONE');
if ($dbTZ) {
$databaseConfig['timezone'] = $dbTZ;
}
// For schema enabled drivers:
$dbSchema = Environment::getEnv('SS_DATABASE_SCHEMA');
if ($dbSchema) {
$databaseConfig["schema"] = $dbSchema;
}
// For SQlite3 memory databases (mainly for testing purposes)
$dbMemory = Environment::getEnv('SS_DATABASE_MEMORY');
if ($dbMemory) {
$databaseConfig["memory"] = $dbMemory;
}
// Allow database adapters to handle their own configuration
DatabaseAdapterRegistry::autoconfigure($databaseConfig);
return $databaseConfig;
}
/**
* @return string
*/
protected function getDatabasePrefix()
{
return Environment::getEnv('SS_DATABASE_PREFIX') ?: '';
}
/**
* @return string
*/
protected function getDatabaseSuffix()
{
return Environment::getEnv('SS_DATABASE_SUFFIX') ?: '';
}
/**
* Get name of database
*
* @return string
*/
protected function getDatabaseName()
{
// Check globals
global $database;
if (!empty($database)) {
return $this->getDatabasePrefix() . $database . $this->getDatabaseSuffix();
}
global $databaseConfig;
if (!empty($databaseConfig['database'])) {
return $databaseConfig['database']; // Note: Already includes prefix
}
// Check environment
$database = Environment::getEnv('SS_DATABASE_NAME');
if ($database) {
return $this->getDatabasePrefix() . $database . $this->getDatabaseSuffix();
}
// Auto-detect name
$chooseName = Environment::getEnv('SS_DATABASE_CHOOSE_NAME');
if ($chooseName) {
// Find directory to build name from
$loopCount = (int)$chooseName;
$databaseDir = $this->basePath;
for ($i = 0; $i < $loopCount-1; $i++) {
$databaseDir = dirname($databaseDir);
}
// Build name
$database = str_replace('.', '', basename($databaseDir));
$prefix = $this->getDatabasePrefix();
if ($prefix) {
$prefix = 'SS_';
} else {
// If no prefix, hard-code prefix into database global
$prefix = '';
$database = 'SS_' . $database;
}
return $prefix . $database;
}
// no DB name (may be optional for some connectors)
return null;
}
/**
* Initialise PHP with default variables
*/
protected function bootPHP()
{
if ($this->getEnvironment() === self::LIVE) {
// limited to fatal errors and warnings in live mode
error_reporting(E_ALL & ~(E_DEPRECATED | E_STRICT | E_NOTICE));
} else {
// Report all errors in dev / test mode
error_reporting(E_ALL | E_STRICT);
}
/**
* Ensure we have enough memory
*/
Environment::increaseMemoryLimitTo('64M');
// Ensure we don't run into xdebug's fairly conservative infinite recursion protection limit
if (function_exists('xdebug_enable')) {
$current = ini_get('xdebug.max_nesting_level');
if ((int)$current < 200) {
ini_set('xdebug.max_nesting_level', 200);
}
}
/**
* Set default encoding
*/
mb_http_output('UTF-8');
mb_internal_encoding('UTF-8');
mb_regex_encoding('UTF-8');
/**
* Enable better garbage collection
*/
gc_enable();
}
/**
* @return ManifestCacheFactory
*/
protected function buildManifestCacheFactory()
{
return new ManifestCacheFactory([
'namespace' => 'manifestcache',
'directory' => TempFolder::getTempFolder($this->basePath),
]);
}
/**
* @return bool
*/
protected function getIncludeTests()
{
return false;
}
/**
* Boot all manifests
*
* @param bool $flush
*/
protected function bootManifests($flush)
{
// Setup autoloader
$this->getClassLoader()->init($this->getIncludeTests(), $flush);
// Find modules
$this->getModuleLoader()->init($this->getIncludeTests(), $flush);
// Flush config
if ($flush) {
$config = $this->getConfigLoader()->getManifest();
if ($config instanceof CachedConfigCollection) {
$config->setFlush(true);
}
}
// tell modules to sort, now that config is available
$this->getModuleLoader()->getManifest()->sort();
// Find default templates
$defaultSet = $this->getThemeResourceLoader()->getSet('$default');
if ($defaultSet instanceof ThemeManifest) {
$defaultSet->setProject(
ModuleManifest::config()->get('project')
);
$defaultSet->init($this->getIncludeTests(), $flush);
}
}
/**
* Turn on error handling
*/
protected function bootErrorHandling()
{
// Register error handler
$errorHandler = Injector::inst()->get(ErrorHandler::class);
$errorHandler->start();
// Register error log file
$errorLog = Environment::getEnv('SS_ERROR_LOG');
if ($errorLog) {
$logger = Injector::inst()->get(LoggerInterface::class);
if ($logger instanceof Logger) {
$logger->pushHandler(new StreamHandler($this->basePath . '/' . $errorLog, Logger::WARNING));
} else {
user_error("SS_ERROR_LOG setting only works with Monolog, you are using another logger", E_USER_WARNING);
}
}
}
public function shutdown()
{
}
public function nest()
{
// Clone this kernel, nesting config / injector manifest containers
$kernel = clone $this;
$kernel->setConfigLoader($this->configLoader->nest());
$kernel->setInjectorLoader($this->injectorLoader->nest());
$kernel->nestedFrom = $this;
return $kernel;
}
public function activate()
{
$this->configLoader->activate();
$this->injectorLoader->activate();
// Self register
$this->getInjectorLoader()
->getManifest()
->registerService($this, Kernel::class);
return $this;
}
public function getNestedFrom()
{
return $this->nestedFrom;
}
public function getContainer()
{
return $this->getInjectorLoader()->getManifest();
}
public function setInjectorLoader(InjectorLoader $injectorLoader)
{
$this->injectorLoader = $injectorLoader;
$injectorLoader
->getManifest()
->registerService($this, Kernel::class);
return $this;
}
public function getInjectorLoader()
{
return $this->injectorLoader;
}
public function getClassLoader()
{
return $this->classLoader;
}
public function setClassLoader(ClassLoader $classLoader)
{
$this->classLoader = $classLoader;
return $this;
}
public function getModuleLoader()
{
return $this->moduleLoader;
}
public function setModuleLoader(ModuleLoader $moduleLoader)
{
$this->moduleLoader = $moduleLoader;
return $this;
}
public function setEnvironment($environment)
{
if (!in_array($environment, [self::DEV, self::TEST, self::LIVE, null])) {
throw new InvalidArgumentException(
"Director::set_environment_type passed '$environment'. It should be passed dev, test, or live"
);
}
$this->enviroment = $environment;
return $this;
}
public function getConfigLoader()
{
return $this->configLoader;
}
public function setConfigLoader($configLoader)
{
$this->configLoader = $configLoader;
return $this;
}
public function getThemeResourceLoader()
{
return $this->themeResourceLoader;
}
public function setThemeResourceLoader($themeResourceLoader)
{
$this->themeResourceLoader = $themeResourceLoader;
return $this;
}
/**
* Returns whether the Kernel has been flushed on boot
*
* @return bool|null null if the kernel hasn't been booted yet
*/
public function isFlushed()
{
return $this->flush;
}
}