58 lines
1.9 KiB
PHP
58 lines
1.9 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace Ekdos\Support;
|
|
|
|
use Psr\Http\Message\ResponseInterface as Response;
|
|
|
|
/** Einheitliche JSON-Antworten. Alle Meldungen sind deutschsprachig und fuer die Oberflaeche gedacht. */
|
|
final class Json
|
|
{
|
|
public static function write(Response $response, mixed $payload, int $status = 200): Response
|
|
{
|
|
$body = json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR);
|
|
$response->getBody()->write($body);
|
|
|
|
return $response->withHeader('Content-Type', 'application/json; charset=utf-8')
|
|
->withHeader('Cache-Control', 'no-store')
|
|
->withStatus($status);
|
|
}
|
|
|
|
public static function error(Response $response, string $message, int $status): Response
|
|
{
|
|
return self::write($response, ['error' => $message], $status);
|
|
}
|
|
|
|
/** Schreibt einen bereits von n8n gelieferten JSON-Rumpf unveraendert durch. */
|
|
public static function passthrough(Response $response, string $body, int $status = 200): Response
|
|
{
|
|
$response->getBody()->write($body === '' ? '{}' : $body);
|
|
|
|
return $response->withHeader('Content-Type', 'application/json; charset=utf-8')
|
|
->withHeader('Cache-Control', 'no-store')
|
|
->withStatus($status);
|
|
}
|
|
|
|
/** Dekodiert einen n8n-Rumpf defensiv: kaputtes JSON wird zu einem leeren Array. */
|
|
public static function decode(string $body): array
|
|
{
|
|
$decoded = json_decode($body, true);
|
|
|
|
return is_array($decoded) ? $decoded : [];
|
|
}
|
|
|
|
/**
|
|
* n8n liefert Listen mal als {"tickets":[...]}, mal als nacktes Array.
|
|
* Diese Helferin nimmt beide Formen an.
|
|
*/
|
|
public static function listFrom(array $decoded, string $key): array
|
|
{
|
|
if (isset($decoded[$key]) && is_array($decoded[$key])) {
|
|
return array_values($decoded[$key]);
|
|
}
|
|
|
|
return array_is_list($decoded) ? $decoded : [];
|
|
}
|
|
}
|