X-Git-Url: https://git.m6w6.name/?a=blobdiff_plain;f=lib%2FAPI%2FContentType%2FHandler%2FJson.php;fp=lib%2FAPI%2FContentType%2FHandler%2FJson.php;h=d5b6a5847754246bf6591fd156e1df6f95f4630d;hb=2121556150be871684b5046af7cf250b8219128d;hp=0000000000000000000000000000000000000000;hpb=cac6bea94e6cde142c951566fa6387ffa54eb3cb;p=m6w6%2Fseekat diff --git a/lib/API/ContentType/Handler/Json.php b/lib/API/ContentType/Handler/Json.php new file mode 100644 index 0000000..d5b6a58 --- /dev/null +++ b/lib/API/ContentType/Handler/Json.php @@ -0,0 +1,60 @@ +flags = $flags; + } + + /** + * @inheritdoc + */ + function encode($data): Body { + if (is_scalar($data)) { + $json = $data; + } else { + $json = json_encode($data, $this->flags); + } + + if (false === $json) { + throw new InvalidArgumentException( + "JSON encoding failed for argument ".typeof($data). + " \$data; ".json_last_error_msg()); + } + return (new Body)->append($json); + } + + /** + * @inheritdoc + */ + function decode(Body $body) { + $data = json_decode($body); + if (!isset($data) && json_last_error()) { + throw new UnexpectedValueException("Could not decode JSON: ". + json_last_error_msg()); + } + return $data; + } +}