PHP8
[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 * @var int
14 */
15 private $flags;
16
17 /**
18 * @inheritdoc
19 */
20 function types() : array {
21 return ["json"];
22 }
23
24 /**
25 * @param int $flags json_encode() flags
26 */
27 function __construct(int $flags = 0) {
28 $this->flags = $flags;
29 }
30
31 /**
32 * @inheritdoc
33 */
34 function encode($data): Body {
35 if (is_scalar($data)) {
36 $json = $data;
37 } else {
38 $json = json_encode($data, $this->flags);
39 }
40
41 if (false === $json) {
42 throw new InvalidArgumentException(
43 "JSON encoding failed for argument ".typeof($data).
44 " \$data; ".json_last_error_msg());
45 }
46 return (new Body)->append($json);
47 }
48
49 /**
50 * @inheritdoc
51 */
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());
57 }
58 return $data;
59 }
60 }