Debian Codegraph @

lib/3rdParty/composer/symfony/serializer/Encoder/CsvEncoder.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\Serializer\Encoder;
13
14 use Symfony\Component\Serializer\Exception\InvalidArgumentException;
15 use Symfony\Component\Serializer\Exception\UnexpectedValueException;
16
17 /**
18 * Encodes CSV data.
19 *
20 * @author Kévin Dunglas <[email protected]>
21 * @author Oliver Hoff <[email protected]>
22 */
23 class CsvEncoder implements EncoderInterface, DecoderInterface
24 {
25 public const FORMAT = 'csv';
26 public const DELIMITER_KEY = 'csv_delimiter';
27 public const ENCLOSURE_KEY = 'csv_enclosure';
28 /**
29 * @deprecated since Symfony 7.2, to be removed in 8.0
30 */
31 public const ESCAPE_CHAR_KEY = 'csv_escape_char';
32 public const KEY_SEPARATOR_KEY = 'csv_key_separator';
33 public const HEADERS_KEY = 'csv_headers';
34 public const ESCAPE_FORMULAS_KEY = 'csv_escape_formulas';
35 public const AS_COLLECTION_KEY = 'as_collection';
36 public const NO_HEADERS_KEY = 'no_headers';
37 public const END_OF_LINE = 'csv_end_of_line';
38 public const OUTPUT_UTF8_BOM_KEY = 'output_utf8_bom';
39
40 private const UTF8_BOM = "\xEF\xBB\xBF";
41
42 private const FORMULAS_START_CHARACTERS = ['=', '-', '+', '@', "\t", "\r", "\n"];
43
44 private array $defaultContext = [
45 self::DELIMITER_KEY => ',',
46 self::ENCLOSURE_KEY => '"',
47 self::ESCAPE_CHAR_KEY => '',
48 self::END_OF_LINE => "\n",
49 self::ESCAPE_FORMULAS_KEY => false,
50 self::HEADERS_KEY => [],
51 self::KEY_SEPARATOR_KEY => '.',
52 self::NO_HEADERS_KEY => false,
53 self::AS_COLLECTION_KEY => true,
54 self::OUTPUT_UTF8_BOM_KEY => false,
55 ];
56
57 public function __construct(array $defaultContext = [])
58 {
59 if (\array_key_exists(self::ESCAPE_CHAR_KEY, $defaultContext)) {
60 trigger_deprecation('symfony/serializer', '7.2', 'Setting the "csv_escape_char" option is deprecated. The option will be removed in 8.0.');
61 }
62
63 $this->defaultContext = array_merge($this->defaultContext, $defaultContext);
64 }
65
66 public function encode(mixed $data, string $format, array $context = []): string
67 {
68 $handle = fopen('php://temp,', 'w+');
69
70 if (!is_iterable($data)) {
71 $data = [[$data]];
72 } elseif (!$data) {
73 $data = [[]];
74 } else {
75 if ($data instanceof \Traversable) {
76 // Generators can only be iterated once — convert to array to allow multiple traversals
77 $data = iterator_to_array($data);
78 }
79 // Sequential arrays of arrays are considered as collections
80 $i = 0;
81 foreach ($data as $key => $value) {
82 if ($i !== $key || !\is_array($value)) {
83 $data = [$data];
84 break;
85 }
86
87 ++$i;
88 }
89 }
90
91 [$delimiter, $enclosure, $escapeChar, $keySeparator, $headers, $escapeFormulas, $outputBom] = $this->getCsvOptions($context);
92
93 foreach ($data as &$value) {
94 $flattened = [];
95 $this->flatten($value, $flattened, $keySeparator, '', $escapeFormulas);
96 $value = $flattened;
97 }
98 unset($value);
99
100 $headers = array_merge(array_values($headers), array_diff($this->extractHeaders($data), $headers));
101 $endOfLine = $context[self::END_OF_LINE] ?? $this->defaultContext[self::END_OF_LINE];
102
103 if (!($context[self::NO_HEADERS_KEY] ?? $this->defaultContext[self::NO_HEADERS_KEY])) {
104 fputcsv($handle, $headers, $delimiter, $enclosure, $escapeChar);
105 if ("\n" !== $endOfLine && 0 === fseek($handle, -1, \SEEK_CUR)) {
106 fwrite($handle, $endOfLine);
107 }
108 }
109
110 $headers = array_fill_keys($headers, '');
111 foreach ($data as $row) {
112 fputcsv($handle, array_replace($headers, $row), $delimiter, $enclosure, $escapeChar);
113 if ("\n" !== $endOfLine && 0 === fseek($handle, -1, \SEEK_CUR)) {
114 fwrite($handle, $endOfLine);
115 }
116 }
117
118 rewind($handle);
119 $value = stream_get_contents($handle);
120 fclose($handle);
121
122 if ($outputBom) {
123 if (!preg_match('//u', $value)) {
124 throw new UnexpectedValueException('You are trying to add a UTF-8 BOM to a non UTF-8 text.');
125 }
126
127 $value = self::UTF8_BOM.$value;
128 }
129
130 return $value;
131 }
132
133 public function supportsEncoding(string $format): bool
134 {
135 return self::FORMAT === $format;
136 }
137
138 public function decode(string $data, string $format, array $context = []): mixed
139 {
140 $handle = fopen('php://temp', 'r+');
141 fwrite($handle, $data);
142 rewind($handle);
143
144 if (str_starts_with($data, self::UTF8_BOM)) {
145 fseek($handle, \strlen(self::UTF8_BOM));
146 }
147
148 $headers = null;
149 $nbHeaders = 0;
150 $headerCount = [];
151 $result = [];
152
153 [$delimiter, $enclosure, $escapeChar, $keySeparator, , , , $asCollection] = $this->getCsvOptions($context);
154
155 while (false !== ($cols = fgetcsv($handle, 0, $delimiter, $enclosure, $escapeChar))) {
156 $nbCols = \count($cols);
157
158 if (null === $headers) {
159 $nbHeaders = $nbCols;
160
161 if ($context[self::NO_HEADERS_KEY] ?? $this->defaultContext[self::NO_HEADERS_KEY]) {
162 for ($i = 0; $i < $nbCols; ++$i) {
163 $headers[] = [$i];
164 }
165 $headerCount = array_fill(0, $nbCols, 1);
166 } else {
167 foreach ($cols as $col) {
168 $header = explode($keySeparator, $col ?? '');
169 $headers[] = $header;
170 $headerCount[] = \count($header);
171 }
172
173 continue;
174 }
175 }
176
177 $item = [];
178 for ($i = 0; ($i < $nbCols) && ($i < $nbHeaders); ++$i) {
179 $depth = $headerCount[$i];
180 $arr = &$item;
181 for ($j = 0; $j < $depth; ++$j) {
182 $headerName = $headers[$i][$j];
183
184 if ('' === $headerName) {
185 $headerName = $i;
186 }
187
188 // Handle nested arrays
189 if ($j === ($depth - 1)) {
190 $arr[$headerName] = $cols[$i];
191
192 continue;
193 }
194
195 if (!isset($arr[$headerName])) {
196 $arr[$headerName] = [];
197 }
198
199 $arr = &$arr[$headerName];
200 }
201 }
202
203 $result[] = $item;
204 }
205 fclose($handle);
206
207 if ($asCollection) {
208 return $result;
209 }
210
211 if (!$result || isset($result[1])) {
212 return $result;
213 }
214
215 // If there is only one data line in the document, return it (the line), the result is not considered as a collection
216 return $result[0];
217 }
218
219 public function supportsDecoding(string $format): bool
220 {
221 return self::FORMAT === $format;
222 }
223
224 /**
225 * Flattens an array and generates keys including the path.
226 */
227 private function flatten(iterable $array, array &$result, string $keySeparator, string $parentKey = '', bool $escapeFormulas = false): void
228 {
229 foreach ($array as $key => $value) {
230 if (is_iterable($value)) {
231 $this->flatten($value, $result, $keySeparator, $parentKey.$key.$keySeparator, $escapeFormulas);
232 } else {
233 if ($escapeFormulas && \in_array(substr((string) $value, 0, 1), self::FORMULAS_START_CHARACTERS, true)) {
234 $result[$parentKey.$key] = "'".$value;
235 } else {
236 // Ensures an actual value is used when dealing with true and false
237 $result[$parentKey.$key] = false === $value ? 0 : (true === $value ? 1 : $value);
238 }
239 }
240 }
241 }
242
243 private function getCsvOptions(array $context): array
244 {
245 $delimiter = $context[self::DELIMITER_KEY] ?? $this->defaultContext[self::DELIMITER_KEY];
246 $enclosure = $context[self::ENCLOSURE_KEY] ?? $this->defaultContext[self::ENCLOSURE_KEY];
247 $escapeChar = $context[self::ESCAPE_CHAR_KEY] ?? $this->defaultContext[self::ESCAPE_CHAR_KEY];
248 $keySeparator = $context[self::KEY_SEPARATOR_KEY] ?? $this->defaultContext[self::KEY_SEPARATOR_KEY];
249 $headers = $context[self::HEADERS_KEY] ?? $this->defaultContext[self::HEADERS_KEY];
250 $escapeFormulas = $context[self::ESCAPE_FORMULAS_KEY] ?? $this->defaultContext[self::ESCAPE_FORMULAS_KEY];
251 $outputBom = $context[self::OUTPUT_UTF8_BOM_KEY] ?? $this->defaultContext[self::OUTPUT_UTF8_BOM_KEY];
252 $asCollection = $context[self::AS_COLLECTION_KEY] ?? $this->defaultContext[self::AS_COLLECTION_KEY];
253
254 if (!\is_array($headers)) {
255 throw new InvalidArgumentException(\sprintf('The "%s" context variable must be an array or null, given "%s".', self::HEADERS_KEY, get_debug_type($headers)));
256 }
257
258 return [$delimiter, $enclosure, $escapeChar, $keySeparator, $headers, $escapeFormulas, $outputBom, $asCollection];
259 }
260
261 /**
262 * @return string[]
263 */
264 private function extractHeaders(iterable $data): array
265 {
266 $headers = [];
267 $flippedHeaders = [];
268
269 foreach ($data as $row) {
270 $previousHeader = null;
271
272 foreach ($row as $header => $_) {
273 if (isset($flippedHeaders[$header])) {
274 $previousHeader = $header;
275 continue;
276 }
277
278 if (null === $previousHeader) {
279 $n = \count($headers);
280 } else {
281 $n = $flippedHeaders[$previousHeader] + 1;
282
283 for ($j = \count($headers); $j > $n; --$j) {
284 ++$flippedHeaders[$headers[$j] = $headers[$j - 1]];
285 }
286 }
287
288 $headers[$n] = $header;
289 $flippedHeaders[$header] = $n;
290 $previousHeader = $header;
291 }
292 }
293
294 return $headers;
295 }
296 }