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
<?php
/*
* This file is part of the ICanBoogie package.
*
* (c) Olivier Laviale <olivier.laviale@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace ICanBoogie;
use ICanBoogie\Binding\Event\CoreBindings as EventBindings;
use ICanBoogie\Binding\HTTP\CoreBindings as HTTPBindings;
use ICanBoogie\HTTP\Request;
use ICanBoogie\HTTP\Response;
use ICanBoogie\HTTP\Status;
use ICanBoogie\Storage\Storage;
/**
* Core of the ICanBoogie framework.
*
* @property-read bool $is_configured `true` if the core is configured, `false` otherwise.
* @property-read bool $is_booting `true` if the core is booting, `false` otherwise.
* @property-read bool $is_booted `true` if the core is booted, `false` otherwise.
* @property-read bool $is_running `true` if the core is running, `false` otherwise.
* @property Config $configs Configurations manager.
* @property Storage $vars Persistent variables registry.
* @property Session $session User's session.
* @property string $language Locale language.
* @property string|int $timezone Time zone.
* @property array $config The "core" configuration.
* @property-read LoggerInterface $logger The message logger.
* @property-read Storage $storage_for_configs
*/
class Core
{
use PrototypeTrait;
use EventBindings, HTTPBindings;
/**
* Status of the application.
*/
const STATUS_VOID = 0;
const STATUS_INSTANTIATING = 1;
const STATUS_INSTANTIATED = 2;
const STATUS_CONFIGURING = 3;
const STATUS_CONFIGURED = 4;
const STATUS_BOOTING = 5;
const STATUS_BOOTED = 6;
const STATUS_RUNNING = 7;
const STATUS_TERMINATED = 8;
/**
* One of `STATUS_*`.
*
* @var int
*/
static private $status = self::STATUS_VOID;
/**
* Whether the core is configured.
*
* @return bool `true` if the core is configured, `false` otherwise.
*/
protected function get_is_configured()
{
return self::$status >= self::STATUS_CONFIGURED;
}
/**
* Whether the core is booting.
*
* @return bool `true` if the core is booting, `false` otherwise.
*/
protected function get_is_booting()
{
return self::$status === self::STATUS_BOOTING;
}
/**
* Whether the core is booted.
*
* @return bool `true` if the core is booted, `false` otherwise.
*/
protected function get_is_booted()
{
return self::$status >= self::STATUS_BOOTED;
}
/**
* Whether the core is running.
*
* @return bool `true` if the core is running, `false` otherwise.
*/
protected function get_is_running()
{
return self::$status === self::STATUS_RUNNING;
}
/**
* Options passed during construct.
*
* @var array
*/
static private $construct_options = [];
/**
* @var Core
*/
static private $instance;
/**
* Returns the unique instance of the core object.
*
* @return Core The core object.
*/
static public function get()
{
return self::$instance;
}
/**
* Constructor.
*
* @param array $options Initial options to create the core object.
*
* @throws CoreAlreadyInstantiated in attempt to create a second instance.
*/
public function __construct(array $options = [])
{
$this->assert_not_instantiated();
self::$status = self::STATUS_INSTANTIATING;
self::$instance = $this;
self::$construct_options = $options;
if (!date_default_timezone_get())
{
date_default_timezone_set('UTC');
}
$this->bind_object_class();
$this->configs = $this->create_config_manager($options['config-path'], $options['config-constructor']);
$this->apply_config($this->config);
self::$status = self::STATUS_INSTANTIATED;
}
/**
* Asserts that the class is not instantiated yet.
*
* @throws CoreAlreadyInstantiated if the class is already instantiated.
*/
private function assert_not_instantiated()
{
if (self::$instance)
{
throw new CoreAlreadyInstantiated;
}
}
/**
* Asserts that the application is not booted yet.
*
* @throws CoreAlreadyBooted if the application is already booted.
*/
public function assert_not_booted()
{
if (self::$status >= self::STATUS_BOOTING)
{
throw new CoreAlreadyBooted;
}
}
/**
* Asserts that the application is not running yet.
*
* @throws CoreAlreadyRunning if the application is already running.
*/
public function assert_not_running()
{
if (self::$status >= self::STATUS_RUNNING)
{
throw new CoreAlreadyRunning;
}
}
/**
* Binds the object class to our instance.
*/
private function bind_object_class()
{
Prototype::from(Prototyped::class)['get_app'] = function() {
return $this;
};
}
/**
* Returns configuration manager.
*
* @param array $paths Path list.
* @param array $synthesizers Configuration synthesizers.
*
* @return Config
*/
protected function create_config_manager(array $paths, array $synthesizers)
{
return new Config($paths, $synthesizers);
}
/**
* Applies low-level configuration.
*
* @param array $config
*/
protected function apply_config(array $config)
{
$error_handler = $config['error_handler'];
if ($error_handler)
{
set_error_handler($error_handler);
}
$exception_handler = $config['exception_handler'];
if ($exception_handler)
{
set_exception_handler($exception_handler);
}
if ($config['cache configs'])
{
$this->configs->cache = $this->storage_for_configs;
}
}
/**
* Creates a storage engine.
*
* @param string|callable $engine A class name or a callable.
*
* @return Storage
*/
protected function create_storage($engine)
{
if (class_exists($engine))
{
return new $engine;
}
if (is_string($engine) && version_compare(PHP_VERSION, 7, '<') && strpos($engine, '::') !== false)
{
$engine = explode('::', $engine);
}
return $engine($this);
}
/**
* Creates storage engine for synthesized configs.
*
* @param string|callable $engine A class name or a callable.
*
* @return Storage
*/
protected function create_storage_for_configs($engine)
{
return $this->create_storage($engine);
}
/**
* @return Storage
*/
protected function get_storage_for_configs()
{
static $storage;
return $storage
?: $storage = $this->create_storage_for_configs($this->config['storage_for_configs']);
}
/**
* Creates storage engine for variables.
*
* @param string|callable $engine A class name or a callable.
*
* @return Storage
*/
protected function create_storage_for_vars($engine)
{
return $this->create_storage($engine);
}
/**
* Returns the non-volatile variables registry.
*
* @return Storage
*/
protected function lazy_get_vars()
{
return $this->create_storage_for_vars($this->config['storage_for_vars']);
}
/**
* Returns the _core_ configuration.
*
* @return array
*/
protected function lazy_get_config()
{
return array_merge_recursive($this->configs['core'], self::$construct_options);
}
/**
* @var string The working time zone.
*/
private $timezone;
/**
* Sets the working time zone.
*
* When the time zone is set the default time zone is also set with
* {@link date_default_timezone_set()}.
*
* @param TimeZone|string|int $timezone An instance of {@link TimeZone},
* the name of a time zone, or numeric equivalent e.g. 3600.
*/
protected function set_timezone($timezone)
{
if (is_numeric($timezone))
{
$timezone = timezone_name_from_abbr(null, $timezone, 0);
}
$this->timezone = TimeZone::from($timezone);
date_default_timezone_set((string) $this->timezone);
}
/**
* Returns the working time zone.
*
* If the time zone is not defined yet it defaults to the value of
* {@link date_default_timezone_get()} or "UTC".
*
* @return TimeZone
*/
protected function get_timezone()
{
if (!$this->timezone)
{
$this->timezone = TimeZone::from(date_default_timezone_get() ?: 'UTC');
}
return $this->timezone;
}
/**
* Changes the status of the application.
*
* @param int $status
* @param callable $callable
*
* @return mixed
*/
protected function change_status($status, callable $callable)
{
self::$status = $status;
$rc = $callable();
self::$status = $status + 1;
return $rc;
}
/**
* Configures the application.
*
* The `configure` event of class {@link Core\ConfigureEvent} is fired after the application
* is configured. Event hooks may use this event to further configure the application.
*/
protected function configure()
{
$this->change_status(self::STATUS_CONFIGURING, function() {
Debug::configure($this->configs['debug']);
Prototype::configure($this->configs['prototype']);
$this->events;
new Core\ConfigureEvent($this);
});
}
/**
* Boot the modules and configure Debug, Prototype and Events.
*
* The `boot` event of class {@link Core\BootEvent} is fired after the boot is finished.
*
* The `ICANBOOGIE_READY_TIME_FLOAT` key is added to the `$_SERVER` super global with the
* micro-time at which the boot finished.
*
* @throws CoreAlreadyBooted in attempt to boot the core twice.
*/
public function boot()
{
$this->assert_not_booted();
if (!$this->is_configured)
{
$this->configure();
}
$this->change_status(self::STATUS_BOOTING, function() {
new Core\BootEvent($this);
$_SERVER['ICANBOOGIE_READY_TIME_FLOAT'] = microtime(true);
});
}
/**
* Run the application.
*
* In order to avoid error messages triggered by PHP fatal errors to be send with a 200 (Ok)
* HTTP code, the HTTP code is changed to 500 before the core is run (and booted). When the
* process runs properly the HTTP code is changed to the appropriate value by the response.
*
* The {@link boot()} method is invoked if the core has not booted yet.
*
* @param Request|null $request The request to handle. If `null`, the initial request is used.
*/
public function __invoke(Request $request = null)
{
$this->initialize_response_header();
$this->assert_not_running();
if (!$this->is_booted)
{
$this->boot();
}
$this->change_status(self::STATUS_RUNNING, function() use ($request) {
if (!$request)
{
$request = $this->initial_request;
}
$this->run($request);
$response = $request();
$response();
$this->terminate($request, $response);
});
}
/**
* Fires the `ICanBoogie\Core::run` event.
*
* @param Request $request
*/
protected function run(Request $request)
{
new Core\RunEvent($this, $request);
}
/**
* Terminate the application.
*
* The method throws the `ICanBoogie\Core::terminate` event of class
* {@link Core\TerminateEvent}.
*
* @param Request $request
* @param Response $response
*/
protected function terminate(Request $request, Response $response)
{
new Core\TerminateEvent($this, $request, $response);
}
/**
* Initializes default response header.
*
* The default response has the {@link Status::INTERNAL_SERVER_ERROR} status code and
* the appropriate header fields so it is not cached. That way, if something goes wrong
* and an error message is displayed it won't be cached by a proxi.
*/
protected function initialize_response_header()
{
http_response_code(Status::INTERNAL_SERVER_ERROR);
// @codeCoverageIgnoreStart
if (!headers_sent())
{
header('Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0');
header('Pragma: no-cache');
header('Expires: 0');
}
// @codeCoverageIgnoreEnd
}
}
/*
* Possessions don't touch you in your heart.
* Possessions only tear you apart.
* Possessions cannot kiss you good night.
* Possessions will never hold you tight.
*/