You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
56 lines
1.7 KiB
56 lines
1.7 KiB
<?php
|
|
|
|
namespace IQBall\Api;
|
|
|
|
use Exception;
|
|
use IQBall\Core\Action;
|
|
use IQBall\Core\Http\HttpResponse;
|
|
use IQBall\Core\Http\JsonHttpResponse;
|
|
use IQBall\Core\Validation\ValidationFail;
|
|
|
|
class API {
|
|
public static function render(HttpResponse $response): void {
|
|
http_response_code($response->getCode());
|
|
|
|
foreach ($response->getHeaders() as $header => $value) {
|
|
header("$header: $value");
|
|
}
|
|
|
|
if ($response instanceof JsonHttpResponse) {
|
|
header('Content-type: application/json');
|
|
echo $response->getJson();
|
|
} elseif (get_class($response) != HttpResponse::class) {
|
|
throw new Exception("API returned unknown Http Response");
|
|
}
|
|
}
|
|
|
|
|
|
/**
|
|
* @param array<string, mixed> $match
|
|
* @param callable $tryGetAuthorization function to return an authorisation object for the given action (if required)
|
|
* @return HttpResponse
|
|
* @throws Exception
|
|
*/
|
|
public static function handleMatch(array $match, callable $tryGetAuthorization): HttpResponse {
|
|
if (!$match) {
|
|
return new JsonHttpResponse([ValidationFail::notFound("not found")]);
|
|
}
|
|
|
|
$action = $match['target'];
|
|
if (!$action instanceof Action) {
|
|
throw new Exception("routed action is not an AppAction object.");
|
|
}
|
|
|
|
$auth = null;
|
|
|
|
if ($action->isAuthRequired()) {
|
|
$auth = call_user_func($tryGetAuthorization);
|
|
if ($auth == null) {
|
|
return new JsonHttpResponse([ValidationFail::unauthorized("Missing or invalid 'Authorization' header.")]);
|
|
}
|
|
}
|
|
|
|
return $action->run($match['params'], $auth);
|
|
}
|
|
}
|