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
{
20 function types() : array {
25 * @param int $flags json_encode() flags
27 function __construct(int $flags = 0) {
28 $this->flags
= $flags;
34 function encode($data): Body
{
35 if (is_scalar($data)) {
38 $json = json_encode($data, $this->flags
);
41 if (false === $json) {
42 throw new InvalidArgumentException(
43 "JSON encoding failed for argument ".typeof($data).
44 " \$data; ".json_last_error_msg());
46 return (new Body
)->append($json);
52 function decode(Body
$body) {
53 $data = json_decode($body);
54 if (!isset($data) && json_last_error()) {
55 throw new UnexpectedValueException("Could not decode JSON: ".
56 json_last_error_msg());