UnderCurrent/src/Kernel/BaseKernel.php

95 lines
3.0 KiB
PHP

<?php
namespace Ardent\Undercurrent\Kernel;
use Ardent\Undercurrent\AppConfig;
use Ardent\Undercurrent\Container\ContainerInterface;
use Ardent\Undercurrent\Container\GenericContainer;
use Ardent\Undercurrent\Http\GenericRequest;
use Ardent\Undercurrent\Http\GenericResponse;
use Ardent\Undercurrent\Http\GenericRouter;
use Ardent\Undercurrent\Http\MethodEnum;
use Ardent\Undercurrent\Http\RouterConfig;
use Ardent\Undercurrent\Http\RouterInterface;
use Ardent\Undercurrent\Http\StatusEnum;
use Ardent\Undercurrent\Logger\LogContainer;
use Ardent\Undercurrent\Logger\LoggerInterface;
use Ardent\Undercurrent\View\ViewHelper;
use Ardent\Undercurrent\View\ViewInterface;
class BaseKernel
{
public function __construct(
private readonly string $rootDirectory,
)
{
}
public function run(): void
{
$appConfig = new AppConfig($this->rootDirectory, '/Template');
$container = (new GenericContainer());
$container
->alias(RouterInterface::class, GenericRouter::class)
->alias(ContainerInterface::class, GenericContainer::class)
->alias(LoggerInterface::class, LogContainer::class)
->add(GenericContainer::class, fn($container) => $container)
->add(AppConfig::class, fn() => $appConfig)
->add(GenericRouter::class)
->add(ViewHelper::class)
->add(LogContainer::class);
$this->dependencies($container);
$this->render($container);
}
private function render(GenericContainer $container): void
{
$request = new GenericRequest(
MethodEnum::from($_SERVER['REQUEST_METHOD']),
$_SERVER['REQUEST_URI'],
$_REQUEST,
);
$router = $container->get(RouterInterface::class);
$log = $container->get(LogContainer::class);
try {
$response = $router->dispatch($request);
} catch (\Throwable $e) {
$response = new GenericResponse(
$e->getMessage(),
StatusEnum::NOT_FOUND
);
//$response = $container->get(RouterConfig::class)->getExceptionRoute()->getController()::exception($e);
}
http_response_code($response->getStatus()->value);
foreach ($response->getHeaders() as $header) {
header($header);
}
echo $response->getBody();
foreach ($log->getLogs() as $log) {
echo sprintf('<p>%s</p>', $log);
}
}
protected function addControllers(ContainerInterface $container, array $controllers): void
{
$config = new RouterConfig();
foreach ($controllers as $controller) {
$container->add($controller);
$config->addController($controller);
}
$container->add(RouterConfig::class, fn() => $config);
}
protected function dependencies(ContainerInterface $container): void
{
}
}