update to PHP-8.1
[m6w6/seekat] / lib / API / ContentType / Handler / Json.php
1 <?php
2
3 namespace seekat\API\ContentType\Handler;
4
5 use http\Message\Body;
6 use seekat\API\ContentType\Handler;
7 use seekat\Exception\InvalidArgumentException;
8 use seekat\Exception\UnexpectedValueException;
9 use function seekat\typeof;
10
11 final class Json implements Handler {
12 /**
13 * @inheritdoc
14 */
15 function types() : array {
16 return ["json"];
17 }
18
19 /**
20 * @param int $flags json_encode() flags
21 */
22 function __construct(private readonly int $flags = 0) {
23 }
24
25 /**
26 * @inheritdoc
27 */
28 function encode(mixed $data): Body {
29 if (is_scalar($data)) {
30 $json = $data;
31 } else {
32 $json = json_encode($data, $this->flags);
33 }
34
35 if (false === $json) {
36 throw new InvalidArgumentException(
37 "JSON encoding failed for argument ".typeof($data).
38 " \$data; ".json_last_error_msg());
39 }
40 return (new Body)->append($json);
41 }
42
43 /**
44 * @inheritdoc
45 */
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());
51 }
52 return $data;
53 }
54 }