|
|
|
@ -6,6 +6,7 @@ use App\Http\HttpCodes;
|
|
|
|
|
use App\Http\HttpRequest;
|
|
|
|
|
use App\Http\HttpResponse;
|
|
|
|
|
use App\Http\JsonHttpResponse;
|
|
|
|
|
use App\Http\ViewHttpResponse;
|
|
|
|
|
use App\Validation\ValidationFail;
|
|
|
|
|
|
|
|
|
|
class Control {
|
|
|
|
@ -17,14 +18,18 @@ class Control {
|
|
|
|
|
* THe callback must accept an HttpRequest, and return an HttpResponse object.
|
|
|
|
|
* @return HttpResponse
|
|
|
|
|
*/
|
|
|
|
|
public static function runChecked(array $schema, callable $run): HttpResponse {
|
|
|
|
|
public static function runChecked(array $schema, callable $run, bool $errorInJson): HttpResponse {
|
|
|
|
|
$request_body = file_get_contents('php://input');
|
|
|
|
|
$payload_obj = json_decode($request_body);
|
|
|
|
|
if (!$payload_obj instanceof \stdClass) {
|
|
|
|
|
return new JsonHttpResponse([new ValidationFail("bad-payload", "request body is not a valid json object"), HttpCodes::BAD_REQUEST]);
|
|
|
|
|
$fail = new ValidationFail("bad-payload", "request body is not a valid json object");
|
|
|
|
|
if($errorInJson) {
|
|
|
|
|
return new JsonHttpResponse([$fail, HttpCodes::BAD_REQUEST]);
|
|
|
|
|
}
|
|
|
|
|
return ViewHttpResponse::twig("error.html.twig", ["failures" => [$fail]], HttpCodes::BAD_REQUEST);
|
|
|
|
|
}
|
|
|
|
|
$payload = get_object_vars($payload_obj);
|
|
|
|
|
return self::runCheckedFrom($payload, $schema, $run);
|
|
|
|
|
return self::runCheckedFrom($payload, $schema, $run, $errorInJson);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
@ -35,16 +40,22 @@ class Control {
|
|
|
|
|
* THe callback must accept an HttpRequest, and return an HttpResponse object.
|
|
|
|
|
* @return HttpResponse
|
|
|
|
|
*/
|
|
|
|
|
public static function runCheckedFrom(array $data, array $schema, callable $run): HttpResponse {
|
|
|
|
|
public static function runCheckedFrom(array $data, array $schema, callable $run, bool $errorInJson): HttpResponse {
|
|
|
|
|
$fails = [];
|
|
|
|
|
$request = HttpRequest::from($data, $fails, $schema);
|
|
|
|
|
|
|
|
|
|
if (!empty($fails)) {
|
|
|
|
|
if($errorInJson) {
|
|
|
|
|
return new JsonHttpResponse($fails, HttpCodes::BAD_REQUEST);
|
|
|
|
|
}
|
|
|
|
|
return ViewHttpResponse::twig("error.html.twig", ['failures' => $fails], HttpCodes::BAD_REQUEST);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return call_user_func_array($run, [$request]);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
}
|