1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* It's free open-source software released under the MIT License. |
5
|
|
|
* |
6
|
|
|
* @author Anatoly Nekhay <[email protected]> |
7
|
|
|
* @copyright Copyright (c) 2018, Anatoly Nekhay |
8
|
|
|
* @license https://github.com/sunrise-php/http-message/blob/master/LICENSE |
9
|
|
|
* @link https://github.com/sunrise-php/http-message |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
namespace Sunrise\Http\Message\Response; |
13
|
|
|
|
14
|
|
|
use JsonException; |
15
|
|
|
use Psr\Http\Message\StreamInterface; |
16
|
|
|
use Sunrise\Http\Message\Exception\InvalidArgumentException; |
17
|
|
|
use Sunrise\Http\Message\Response; |
18
|
|
|
use Sunrise\Http\Message\Stream\PhpTempStream; |
19
|
|
|
|
20
|
|
|
use function json_encode; |
21
|
|
|
use function sprintf; |
22
|
|
|
|
23
|
|
|
use const JSON_THROW_ON_ERROR; |
24
|
|
|
|
25
|
|
|
final class JsonResponse extends Response |
26
|
|
|
{ |
27
|
|
|
/** |
28
|
|
|
* @param mixed $data |
29
|
|
|
* @param int<1, max> $depth |
30
|
|
|
* @psalm-param int<1, 2147483647> $depth |
31
|
|
|
* |
32
|
|
|
* @throws InvalidArgumentException |
33
|
|
|
*/ |
34
|
4 |
|
public function __construct(int $statusCode, $data, int $flags = 0, int $depth = 512) |
35
|
|
|
{ |
36
|
4 |
|
parent::__construct($statusCode); |
37
|
|
|
|
38
|
4 |
|
$this->setBody(self::createBody($data, $flags, $depth)); |
39
|
3 |
|
$this->setHeader('Content-Type', 'application/json; charset=utf-8'); |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
/** |
43
|
|
|
* @param mixed $data |
44
|
|
|
* @param int<1, max> $depth |
45
|
|
|
* @psalm-param int<1, 2147483647> $depth |
46
|
|
|
* |
47
|
|
|
* @throws InvalidArgumentException |
48
|
|
|
*/ |
49
|
4 |
|
private static function createBody($data, int $flags, int $depth): StreamInterface |
50
|
|
|
{ |
51
|
4 |
|
if ($data instanceof StreamInterface) { |
52
|
1 |
|
return $data; |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
try { |
56
|
|
|
/** @var non-empty-string $json */ |
57
|
3 |
|
$json = json_encode($data, $flags | JSON_THROW_ON_ERROR, $depth); |
58
|
1 |
|
} catch (JsonException $e) { |
59
|
1 |
|
throw new InvalidArgumentException(sprintf( |
60
|
1 |
|
'Unable to create the JSON response due to an invalid data: %s', |
61
|
1 |
|
$e->getMessage() |
62
|
1 |
|
), 0, $e); |
63
|
|
|
} |
64
|
|
|
|
65
|
2 |
|
$stream = new PhpTempStream('r+b'); |
66
|
2 |
|
$stream->write($json); |
67
|
2 |
|
$stream->rewind(); |
68
|
|
|
|
69
|
2 |
|
return $stream; |
70
|
|
|
} |
71
|
|
|
} |
72
|
|
|
|