szurubooru/src/Dispatcher.php

51 lines
1.1 KiB
PHP
Raw Normal View History

2014-08-30 15:04:33 +02:00
<?php
namespace Szurubooru;
final class Dispatcher
{
private $router;
public function __construct(
\Szurubooru\Router $router,
\Szurubooru\Helpers\HttpHelper $httpHelper,
2014-08-30 15:04:33 +02:00
\Szurubooru\ControllerRepository $controllerRepository)
{
$this->router = $router;
$this->httpHelper = $httpHelper;
//if script fails prematurely, mark it as fail from advance
$this->httpHelper->setResponseCode(500);
2014-08-30 15:04:33 +02:00
foreach ($controllerRepository->getControllers() as $controller)
$controller->registerRoutes($router);
}
public function run()
{
global $start;
try
{
2014-08-30 22:16:00 +02:00
$code = 200;
$json = (array) $this->router->handle(
$this->httpHelper->getRequestMethod(),
$this->httpHelper->getRequestUri());
2014-08-30 15:04:33 +02:00
}
catch (\Exception $e)
{
2014-08-30 22:16:00 +02:00
$code = 400;
2014-08-30 15:04:33 +02:00
$json = [
'error' => $e->getMessage(),
'trace' => $e->getTrace(),
];
}
$end = microtime(true);
$json['__time'] = $end - $start;
2014-08-30 22:16:00 +02:00
$this->httpHelper->setResponseCode($code);
$this->httpHelper->setHeader('Content-Type', 'application/json');
$this->httpHelper->outputJSON($json);
return $json;
2014-08-30 15:04:33 +02:00
}
}