szurubooru/src/Dispatcher.php

79 lines
2.1 KiB
PHP
Raw Normal View History

2014-08-30 15:04:33 +02:00
<?php
namespace Szurubooru;
final class Dispatcher
{
private $router;
private $config;
private $databaseConnection;
2014-09-04 19:21:18 +02:00
private $authService;
private $tokenService;
2014-08-30 15:04:33 +02:00
public function __construct(
\Szurubooru\Router $router,
\Szurubooru\Config $config,
\Szurubooru\DatabaseConnection $databaseConnection,
\Szurubooru\Helpers\HttpHelper $httpHelper,
2014-09-04 19:21:18 +02:00
\Szurubooru\Services\AuthService $authService,
\Szurubooru\Services\TokenService $tokenService,
2014-08-30 15:04:33 +02:00
\Szurubooru\ControllerRepository $controllerRepository)
{
$this->router = $router;
$this->config = $config;
$this->databaseConnection = $databaseConnection;
$this->httpHelper = $httpHelper;
//if script fails prematurely, mark it as fail from advance
$this->httpHelper->setResponseCode(500);
2014-09-04 19:21:18 +02:00
$this->authService = $authService;
$this->tokenService = $tokenService;
2014-08-30 15:04:33 +02:00
foreach ($controllerRepository->getControllers() as $controller)
$controller->registerRoutes($router);
}
public function run($requestMethod, $requestUri)
2014-08-30 15:04:33 +02:00
{
try
{
2014-08-30 22:16:00 +02:00
$code = 200;
2014-09-04 19:21:18 +02:00
$this->authorizeFromRequestHeader();
$json = (array) $this->router->handle($requestMethod, $requestUri);
2014-08-30 15:04:33 +02:00
}
catch (\Exception $e)
{
2014-08-30 22:16:00 +02:00
$code = 400;
2014-09-16 14:42:46 +02:00
$trace = $e->getTrace();
foreach ($trace as &$item)
unset($item['args']);
2014-08-30 15:04:33 +02:00
$json = [
'error' => $e->getMessage(),
2014-09-16 14:42:46 +02:00
'trace' => $trace,
2014-08-30 15:04:33 +02:00
];
}
$end = microtime(true);
$json['__time'] = $end - \Szurubooru\Bootstrap::getStartTime();
if ($this->config->misc->dumpSqlIntoQueries)
{
$json['__queries'] = $this->databaseConnection->getPDO()->getQueryCount();
$json['__statements'] = $this->databaseConnection->getPDO()->getStatements();
}
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
}
2014-09-04 19:21:18 +02:00
private function authorizeFromRequestHeader()
{
$loginTokenName = $this->httpHelper->getRequestHeader('X-Authorization-Token');
if ($loginTokenName)
{
$token = $this->tokenService->getByName($loginTokenName);
$this->authService->loginFromToken($token);
}
2014-09-04 19:21:18 +02:00
}
2014-08-30 15:04:33 +02:00
}