107 lines
2.3 KiB
PHP
107 lines
2.3 KiB
PHP
<?php
|
|
|
|
namespace App;
|
|
|
|
use App\ErrorHandler\CustomHtmlErrorRenderer;
|
|
use App\Middlewares\ThrottleMiddleware;
|
|
use Dotenv\Dotenv;
|
|
use Dotenv\Exception\InvalidPathException;
|
|
use Slim\Factory\AppFactory;
|
|
|
|
require_once __DIR__ . '/helpers.php';
|
|
|
|
class Kernel
|
|
{
|
|
private static $app;
|
|
private static $env;
|
|
|
|
private static function _build()
|
|
{
|
|
self::$app = AppFactory::create();
|
|
|
|
self::loadEnv();
|
|
self::loadRoutes();
|
|
self::loadMiddlewares();
|
|
}
|
|
|
|
private static function loadRoutes()
|
|
{
|
|
require_once __DIR__ . '/Routes/web.php';
|
|
}
|
|
|
|
private static function loadMiddlewares()
|
|
{
|
|
// Add Routing Middleware
|
|
self::$app->addRoutingMiddleware();
|
|
|
|
self::$app->add(new ThrottleMiddleware);
|
|
|
|
/**
|
|
* Add Error Handling Middleware
|
|
*
|
|
* @param bool $displayErrorDetails -> Should be set to false in production
|
|
* @param bool $logErrors -> Parameter is passed to the default ErrorHandler
|
|
* @param bool $logErrorDetails -> Display error details in error log
|
|
* which can be replaced by a callable of your choice.
|
|
|
|
* Note: This middleware should be added last. It will not handle any exceptions/errors
|
|
* for middleware added after it.
|
|
*/
|
|
$errorMiddleware = self::$app->addErrorMiddleware(
|
|
env('displayError', false),
|
|
env('logErrors', false),
|
|
env('logErrorDetails', false)
|
|
);
|
|
$errorHandler = $errorMiddleware->getDefaultErrorHandler();
|
|
$errorHandler->registerErrorRenderer('text/html', CustomHtmlErrorRenderer::class);
|
|
}
|
|
|
|
private static function loadEnv()
|
|
{
|
|
try {
|
|
self::$env = Dotenv::createImmutable(__DIR__ . '/..')->load();
|
|
} catch (InvalidPathException $e) {
|
|
// no env file present
|
|
}
|
|
}
|
|
|
|
public static function app()
|
|
{
|
|
return self::$app;
|
|
}
|
|
|
|
public static function env(string $key, $default = null)
|
|
{
|
|
$value = self::$env[$key] ?? $default;
|
|
|
|
if ($value === false) {
|
|
return $default;
|
|
}
|
|
|
|
switch (strtolower($value)) {
|
|
case 'true':
|
|
case '(true)':
|
|
return true;
|
|
|
|
case 'false':
|
|
case '(false)':
|
|
return false;
|
|
|
|
case 'empty':
|
|
case '(empty)':
|
|
return '';
|
|
|
|
case 'null':
|
|
case '(null)':
|
|
return;
|
|
}
|
|
|
|
return $value;
|
|
}
|
|
|
|
public static function run()
|
|
{
|
|
self::_build();
|
|
self::$app->run();
|
|
}
|
|
}
|