106 lines
2.6 KiB
PHP
106 lines
2.6 KiB
PHP
<?php
|
|
|
|
namespace Subcon\Zap;
|
|
use Subcon\Zap\Config\Repository;
|
|
use Subcon\Zap\ErrorHandling\Handler;
|
|
use Subcon\Zap\Http\Response;
|
|
use Subcon\Zap\Routing\Router;
|
|
|
|
class Application
|
|
{
|
|
const VERSION = '2.0.0';
|
|
|
|
protected static $instance;
|
|
|
|
protected string $basePath;
|
|
|
|
protected Repository $config;
|
|
|
|
protected Router $router;
|
|
|
|
|
|
public function __construct(string $basePath = null)
|
|
{
|
|
if(!$basePath || !file_exists($basePath) || !is_dir($basePath)) {
|
|
$basePath = implode('/', array_slice(explode('/', $_SERVER['SCRIPT_NAME']), 0, -2)) . '/';
|
|
}
|
|
|
|
//Initialize paths and load up environment and config files.
|
|
static::$instance = $this;
|
|
$this->setBasePath($basePath);
|
|
$this->initConfiguration();
|
|
$this->initErrorHandling();
|
|
$this->initRouting();
|
|
}
|
|
|
|
public static function getInstance(): static
|
|
{
|
|
return static::$instance;
|
|
}
|
|
|
|
public function getBasePath($path = '')
|
|
{
|
|
return $this->basePath . (!empty($path) ? DIRECTORY_SEPARATOR.$path : '');
|
|
}
|
|
|
|
public function getPublicPath($path = '')
|
|
{
|
|
return $this->basePath . DIRECTORY_SEPARATOR . 'public_html' . (!empty($path) ? DIRECTORY_SEPARATOR.$path : '');
|
|
}
|
|
|
|
public function getViewPath($path = '')
|
|
{
|
|
return $this->basePath . DIRECTORY_SEPARATOR . 'resources/views' . (!empty($path) ? DIRECTORY_SEPARATOR.$path : '');
|
|
}
|
|
|
|
public function getConfig()
|
|
{
|
|
return $this->config;
|
|
}
|
|
|
|
public function run()
|
|
{
|
|
if(!$this->router) {
|
|
(new Response('Could not get router instance, aborting.', 500))
|
|
->send();
|
|
}
|
|
|
|
$this->router->run();
|
|
}
|
|
|
|
|
|
protected function setBasePath($basePath): static
|
|
{
|
|
$this->basePath = rtrim($basePath, '\/');
|
|
return $this;
|
|
}
|
|
|
|
protected function initConfiguration()
|
|
{
|
|
$this->config = new Repository($this);
|
|
}
|
|
|
|
protected function initErrorHandling()
|
|
{
|
|
set_error_handler(function (int $nr, string $error, ?string $file, ?int $line) {
|
|
(new Handler($this))->reportError($nr, $error, $file, $line);
|
|
$this->sendErrorResponse();
|
|
});
|
|
|
|
set_exception_handler(function (\Throwable $e) {
|
|
(new Handler($this))->report($e);
|
|
$this->sendErrorResponse();
|
|
});
|
|
}
|
|
|
|
protected function initRouting()
|
|
{
|
|
$this->router = new Router($this);
|
|
}
|
|
|
|
protected function sendErrorResponse()
|
|
{
|
|
(new Response('Whoops, something went wrong.', 500))
|
|
->send();
|
|
}
|
|
} |