@@ 10-30 (lines=21) @@ | ||
7 | */ |
|
8 | namespace KleijnWeb\PhpApi\Middleware\Body; |
|
9 | ||
10 | class JsonBodyParser implements BodyParser |
|
11 | { |
|
12 | /** |
|
13 | * @param string $body |
|
14 | * @return mixed |
|
15 | * @throws JsonException |
|
16 | */ |
|
17 | public function parse(string $body) |
|
18 | { |
|
19 | // Clear json_last_error() |
|
20 | json_encode(null); |
|
21 | ||
22 | $parsed = json_decode($body); |
|
23 | ||
24 | if (json_last_error() !== JSON_ERROR_NONE) { |
|
25 | throw new JsonException(json_last_error_msg()); |
|
26 | } |
|
27 | ||
28 | return $parsed; |
|
29 | } |
|
30 | } |
@@ 10-38 (lines=29) @@ | ||
7 | */ |
|
8 | namespace KleijnWeb\PhpApi\Middleware\Body; |
|
9 | ||
10 | class JsonBodySerializer implements BodySerializer |
|
11 | { |
|
12 | /** |
|
13 | * @param mixed $body |
|
14 | * @return mixed |
|
15 | * @throws JsonException |
|
16 | */ |
|
17 | public function serialize($body): string |
|
18 | { |
|
19 | // Clear json_last_error() |
|
20 | json_encode(null); |
|
21 | ||
22 | $string = json_encode($body); |
|
23 | ||
24 | if (JSON_ERROR_NONE !== json_last_error()) { |
|
25 | throw new JsonException(json_last_error_msg()); |
|
26 | } |
|
27 | ||
28 | return $string; |
|
29 | } |
|
30 | ||
31 | /** |
|
32 | * @return string |
|
33 | */ |
|
34 | public function getContentType(): string |
|
35 | { |
|
36 | return 'application/json'; |
|
37 | } |
|
38 | } |