Files
lean-api/src/Middleware/ApiRenderer.php
T
Dave Mc Nicoll 4b86ac9e82 - Added a new CSRF token verification Middleware.
- Added a new ActionLog middleware to catch every modifying request and save the changes made and the user who did.
- Added a new RequestLog to catch every request made whenever required.
2026-10-22 15:03:18 +00:00

105 lines
3.4 KiB
PHP

<?php
namespace Lean\Api\Middleware;
use DI\Attribute\Inject;
use Laminas\Diactoros\Response\JsonResponse;
use Lean\Factory\HttpFactory;
use Picea\Ui\Method\FormHandler;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Lean\Api\{Factory\LeanApiFormFactoryInterface, Form, Entity};
class ApiRenderer implements MiddlewareInterface {
#[Inject]
protected LeanApiFormFactoryInterface $leanApiFormFactory;
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler) : ResponseInterface
{
try {
$response = $handler->handle($request);
}
catch(\Throwable $ex) {
if (static::awaitingJson($request)) {
# $this->saveError($request, $ex);
return HttpFactory::createJsonResponse([
'status' => 'failed',
'ts' => time(),
'data' => [
# 'error_id' => $errorId,
'message' => $ex->getMessage(),
] + (getenv('DEBUG') ? [
'type' => $ex::class,
'file' => $ex->getFile(),
'line' => $ex->getLine(),
'code' => $ex->getCode(),
'backtrace' => $ex->getTrace(), ] : [])
], 500);
}
throw $ex;
}
if ($response instanceof JsonResponse) {
$payload = $response->getPayload();
# For now, we match only response having a 'data' field
if ( (is_array($payload) || $payload instanceof \ArrayAccess) && isset($payload['data'])) {
return HttpFactory::createJsonResponse([
'status' => 'success',
'ts' => time(),
] + $payload, 200);
}
}
return $response;
}
protected function saveError(ServerRequestInterface $request, \Throwable $exception) : Entity\Error
{
if ($debugFormFactory = $this->container->get(DebugFormFactoryInterface::class)) {
$request = $request->withMethod('PUT')->withParsedBody([]);
$context = $this->leanApiFormFactory->errorSaveContext($request);
$context->sets([
'message' => $exception->getMessage(),
'code' => $exception->getCode(),
'file' => $exception->getFile(),
'line' => $exception->getLine(),
'trace' => $exception->getTrace(),
]);
$form = $this->leanApiFormFactory->errorSave($entity = new Entity\Error());
new FormHandler($request, $form, $context);
}
return $entity;
}
public static function awaitingJson(ServerRequestInterface $request) : bool
{
return str_contains(strtolower($request->getHeaderLine('content-type')), 'json');
}
public static function encodeHtml(iterable& $array) : iterable
{
foreach($array as &$item) {
if (is_array($item)) {
$item = static::encodeHtml($item);
}
elseif (is_string($item)) {
$item = htmlspecialchars($item);
}
}
return $array;
}
}