3 namespace seekat\API\ContentType\Handler
;
6 use seekat\API\ContentType\Handler
;
7 use seekat\Exception\InvalidArgumentException
;
8 use seekat\Exception\UnexpectedValueException
;
9 use function seekat\typeof
;
11 final class Json
implements Handler
{
15 function types() : array {
20 * @param int $flags json_encode() flags
22 function __construct(private readonly
int $flags = 0) {
28 function encode(mixed $data): Body
{
29 if (is_scalar($data)) {
32 $json = json_encode($data, $this->flags
);
35 if (false === $json) {
36 throw new InvalidArgumentException(
37 "JSON encoding failed for argument ".typeof($data).
38 " \$data; ".json_last_error_msg());
40 return (new Body
)->append($json);
46 function decode(Body
$body) : mixed {
47 $data = json_decode($body);
48 if (!isset($data) && json_last_error()) {
49 throw new UnexpectedValueException("Could not decode JSON: ".
50 json_last_error_msg());