Debian Codegraph @

lib/3rdParty/composer/symfony/http-foundation/StreamedJsonResponse.php

raw symbols SCIP
1 <?php
2
3 /*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <[email protected]>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12 namespace Symfony\Component\HttpFoundation;
13
14 /**
15 * StreamedJsonResponse represents a streamed HTTP response for JSON.
16 *
17 * A StreamedJsonResponse uses a structure and generics to create an
18 * efficient resource-saving JSON response.
19 *
20 * It is recommended to use flush() function after a specific number of items to directly stream the data.
21 *
22 * @see flush()
23 *
24 * @author Alexander Schranz <[email protected]>
25 *
26 * Example usage:
27 *
28 * function loadArticles(): \Generator
29 * // some streamed loading
30 * yield ['title' => 'Article 1'];
31 * yield ['title' => 'Article 2'];
32 * yield ['title' => 'Article 3'];
33 * // recommended to use flush() after every specific number of items
34 * }),
35 *
36 * $response = new StreamedJsonResponse(
37 * // json structure with generators in which will be streamed
38 * [
39 * '_embedded' => [
40 * 'articles' => loadArticles(), // any generator which you want to stream as list of data
41 * ],
42 * ],
43 * );
44 */
45 class StreamedJsonResponse extends StreamedResponse
46 {
47 private const PLACEHOLDER = '__symfony_json__';
48
49 /**
50 * @param mixed[] $data JSON Data containing PHP generators which will be streamed as list of data or a Generator
51 * @param int $status The HTTP status code (200 "OK" by default)
52 * @param array<string, string|string[]> $headers An array of HTTP headers
53 * @param int $encodingOptions Flags for the json_encode() function
54 */
55 public function __construct(
56 private readonly iterable $data,
57 int $status = 200,
58 array $headers = [],
59 private int $encodingOptions = JsonResponse::DEFAULT_ENCODING_OPTIONS,
60 ) {
61 parent::__construct($this->stream(...), $status, $headers);
62
63 if (!$this->headers->get('Content-Type')) {
64 $this->headers->set('Content-Type', 'application/json');
65 }
66 }
67
68 private function stream(): void
69 {
70 $jsonEncodingOptions = \JSON_THROW_ON_ERROR | $this->encodingOptions;
71 $keyEncodingOptions = $jsonEncodingOptions & ~\JSON_NUMERIC_CHECK;
72
73 $this->streamData($this->data, $jsonEncodingOptions, $keyEncodingOptions);
74 }
75
76 private function streamData(mixed $data, int $jsonEncodingOptions, int $keyEncodingOptions): void
77 {
78 if (\is_array($data)) {
79 $this->streamArray($data, $jsonEncodingOptions, $keyEncodingOptions);
80
81 return;
82 }
83
84 if (is_iterable($data) && !$data instanceof \JsonSerializable) {
85 $this->streamIterable($data, $jsonEncodingOptions, $keyEncodingOptions);
86
87 return;
88 }
89
90 echo json_encode($data, $jsonEncodingOptions);
91 }
92
93 private function streamArray(array $data, int $jsonEncodingOptions, int $keyEncodingOptions): void
94 {
95 $generators = [];
96
97 array_walk_recursive($data, static function (&$item, $key) use (&$generators) {
98 if (self::PLACEHOLDER === $key) {
99 // if the placeholder is already in the structure it should be replaced with a new one that explode
100 // works like expected for the structure
101 $generators[] = $key;
102 }
103
104 // generators should be used but for better DX all kind of Traversable and objects are supported
105 if (\is_object($item)) {
106 $generators[] = $item;
107 $item = self::PLACEHOLDER;
108 } elseif (self::PLACEHOLDER === $item) {
109 // if the placeholder is already in the structure it should be replaced with a new one that explode
110 // works like expected for the structure
111 $generators[] = $item;
112 }
113 });
114
115 $jsonParts = explode('"'.self::PLACEHOLDER.'"', json_encode($data, $jsonEncodingOptions));
116
117 foreach ($generators as $index => $generator) {
118 // send first and between parts of the structure
119 echo $jsonParts[$index];
120
121 $this->streamData($generator, $jsonEncodingOptions, $keyEncodingOptions);
122 }
123
124 // send last part of the structure
125 echo $jsonParts[array_key_last($jsonParts)];
126 }
127
128 private function streamIterable(iterable $iterable, int $jsonEncodingOptions, int $keyEncodingOptions): void
129 {
130 $isFirstItem = true;
131 $startTag = '[';
132
133 foreach ($iterable as $key => $item) {
134 if ($isFirstItem) {
135 $isFirstItem = false;
136 // depending on the first elements key the generator is detected as a list or map
137 // we can not check for a whole list or map because that would hurt the performance
138 // of the streamed response which is the main goal of this response class
139 if (0 !== $key) {
140 $startTag = '{';
141 }
142
143 echo $startTag;
144 } else {
145 // if not first element of the generic, a separator is required between the elements
146 echo ',';
147 }
148
149 if ('{' === $startTag) {
150 echo json_encode((string) $key, $keyEncodingOptions).':';
151 }
152
153 $this->streamData($item, $jsonEncodingOptions, $keyEncodingOptions);
154 }
155
156 if ($isFirstItem) { // indicates that the generator was empty
157 echo '[';
158 }
159
160 echo '[' === $startTag ? ']' : '}';
161 }
162 }