Skip to content

Commit

Permalink
added validateJsonRequest method
Browse files Browse the repository at this point in the history
  • Loading branch information
killua-eu committed Aug 6, 2024
1 parent 9a8205f commit 508eb41
Showing 1 changed file with 17 additions and 0 deletions.
17 changes: 17 additions & 0 deletions src/Controllers/AbstractService.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
namespace Glued\Lib\Controllers;

use Exception;
use Glued\Lib\Exceptions\ExtendedException;
use Opis\JsonSchema\Errors\ErrorFormatter;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Symfony\Component\Yaml\Yaml;
Expand Down Expand Up @@ -82,4 +84,19 @@ public function getHealth(Request $request, Response $response, array $args = []
return $response->withJson($check);
}

public function validateJsonRequest(Request $request, Response $response, $schema): mixed
{
if (($request->getHeader('Content-Type')[0] ?? '') != 'application/json') { throw new \Exception('Content-Type header missing or not set to `application/json`.', 400); };
$doc = json_decode(json_encode($request->getParsedBody()));
$validation = $this->validator->validate((object) $doc, $schema);
if ($validation->isValid()) { $res = $doc; }
if ($validation->hasError()) {
$formatter = new ErrorFormatter();
$error = $validation->error();
$res = $formatter->formatOutput($error, "basic");
throw new ExtendedException('Json not valid', 400, details: $res);
}
return $doc;
}

}

0 comments on commit 508eb41

Please sign in to comment.