-
Notifications
You must be signed in to change notification settings - Fork 64
/
CsvView.php
394 lines (349 loc) · 11.6 KB
/
CsvView.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
<?php
declare(strict_types=1);
namespace CsvView\View;
use Cake\Core\Exception\CakeException;
use Cake\Datasource\EntityInterface;
use Cake\Utility\Hash;
use Cake\View\SerializedView;
/**
* A view class that is used for CSV responses.
*
* By setting the 'serialize' view builder option, you can specify a view variable
* that should be serialized to CSV and used as the response for the request.
* This allows you to omit templates + layouts, if your just need to emit a single view
* variable as the CSV response.
*
* In your controller, you could do the following:
*
* `$this->set(['posts' => $posts])->viewBuilder()->setOption('serialize', 'posts');`
*
* When the view is rendered, the `$posts` view variable will be serialized
* into CSV.
*
* When rendering the data, the data should be a single, flat array. If this is not the case,
* then you should also specify the `extract` view option:
*
* ```
* $extract = [
* ['id', '%d'], // Hash-compatible path, sprintf-compatible format
* 'description', // Hash-compatible path
* function ($row) { // Callable
* //return value
* }
* ];
* ```
*
* You can also define `serialize` as an array. This will create a top level object containing
* all the named view variables:
*
* ```
* $this->set(compact('posts', 'users', 'stuff'));
* $this->viewBuilder()->setOption('serialize', ['posts', 'users']);
* ```
*
* Each of the view vars in `serialize` would then be output into the CSV output.
*
* If you don't use the `serialize` option, you will need a view. You can use extended
* views to provide layout like functionality.
*
* When not using custom views, you may specify the following view options:
*
* - array `header`: (default null) A flat array of header column names
* - array `footer`: (default null) A flat array of footer column names
* - string `delimiter`: (default ',') CSV Delimiter, defaults to comma
* - string `enclosure`: (default '"') CSV Enclosure for use with fputcsv()
* - string `eol`: (default '\n') End-of-line character the csv
*
* @link https://github.com/friendsofcake/cakephp-csvview
*/
class CsvView extends SerializedView
{
/**
* CSV layouts are located in the csv sub directory of `Layouts/`
*
* @var string
*/
protected string $layoutPath = 'csv';
/**
* CSV views are always located in the 'csv' sub directory for a
* controllers views.
*
* @var string
*/
protected string $subDir = 'csv';
/**
* Whether or not to reset static variables in use
*
* @var bool
*/
protected bool $_resetStaticVariables = false;
/**
* Iconv extension.
*
* @var string
*/
public const EXTENSION_ICONV = 'iconv';
/**
* Mbstring extension.
*
* @var string
*/
public const EXTENSION_MBSTRING = 'mbstring';
/**
* List of bom signs for encodings.
*
* @var array
*/
protected array $bomMap;
/**
* BOM first appearance
*
* @var bool
*/
protected bool $isFirstBom = true;
/**
* Default config.
*
* - 'header': (default null) A flat array of header column names
* - 'footer': (default null) A flat array of footer column names
* - 'extract': (default null) An array of Hash-compatible paths or
* callable with matching 'sprintf' $format as follows:
* $extract = [
* [$path, $format],
* [$path],
* $path,
* function () { ... } // Callable
* ];
*
* If a string or unspecified, the format default is '%s'.
* - 'delimiter': (default ',') CSV Delimiter, defaults to comma
* - 'enclosure': (default '"') CSV Enclosure for use with fputcsv()
* - 'newline': (default '\n') CSV Newline replacement for use with fputcsv()
* - 'eol': (default '\n') End-of-line character the csv
* - 'bom': (default false) Adds BOM (byte order mark) header
* - 'setSeparator': (default false) Adds sep=[_delimiter] in the first line
* - 'csvEncoding': (default 'UTF-8') CSV file encoding
* - 'dataEncoding': (default 'UTF-8') Encoding of data to be serialized
* - 'transcodingExtension': (default 'iconv') PHP extension to use for character encoding conversion
*
* @var array<string, mixed>
*/
protected array $_defaultConfig = [
'extract' => null,
'footer' => null,
'header' => null,
'serialize' => null,
'delimiter' => ',',
'enclosure' => '"',
'newline' => "\n",
'eol' => PHP_EOL,
'null' => '',
'bom' => false,
'setSeparator' => false,
'csvEncoding' => 'UTF-8',
'dataEncoding' => 'UTF-8',
'transcodingExtension' => self::EXTENSION_ICONV,
];
/**
* Initalize View
*
* @return void
*/
public function initialize(): void
{
$this->bomMap = [
'UTF-32BE' => chr(0x00) . chr(0x00) . chr(0xFE) . chr(0xFF),
'UTF-32LE' => chr(0xFF) . chr(0xFE) . chr(0x00) . chr(0x00),
'UTF-16BE' => chr(0xFE) . chr(0xFF),
'UTF-16LE' => chr(0xFF) . chr(0xFE),
'UTF-8' => chr(0xEF) . chr(0xBB) . chr(0xBF),
];
if (
$this->getConfig('transcodingExtension') === static::EXTENSION_ICONV &&
!extension_loaded(self::EXTENSION_ICONV)
) {
$this->setConfig('transcodingExtension', static::EXTENSION_MBSTRING);
}
parent::initialize();
}
/**
* Mime-type this view class renders as.
*
* @return string The CSV content type.
*/
public static function contentType(): string
{
return 'text/csv';
}
/**
* Serialize view vars.
*
* @param array|string $serialize The name(s) of the view variable(s) that
* need(s) to be serialized
* @return string The serialized data or false.
*/
protected function _serialize(array|string $serialize): string
{
$this->_renderRow($this->getConfig('header'));
$this->_renderContent();
$this->_renderRow($this->getConfig('footer'));
$content = $this->_renderRow();
$this->_resetStaticVariables = true;
$this->_renderRow();
return $content;
}
/**
* Renders the body of the data to the csv
*
* @return void
* @throws \Cake\Core\Exception\CakeException
*/
protected function _renderContent(): void
{
$extract = $this->getConfig('extract');
$serialize = $this->getConfig('serialize');
if ($serialize === true) {
$serialize = array_keys($this->viewVars);
}
foreach ((array)$serialize as $viewVar) {
if (is_scalar($this->viewVars[$viewVar])) {
throw new CakeException("'" . $viewVar . "' is not an array or iterable object.");
}
foreach ($this->viewVars[$viewVar] as $_data) {
if ($_data instanceof EntityInterface) {
$_data = $_data->toArray();
}
if ($extract === null) {
$this->_renderRow($_data);
continue;
}
$values = [];
foreach ($extract as $formatter) {
if (!is_string($formatter) && is_callable($formatter)) {
$value = $formatter($_data);
} else {
$path = $formatter;
$format = null;
if (is_array($formatter)) {
[$path, $format] = $formatter;
}
if (!str_contains($path, '.')) {
$value = $_data[$path];
} else {
$value = Hash::get($_data, $path);
}
if ($format) {
$value = sprintf($format, $value);
}
}
$values[] = $value;
}
$this->_renderRow($values);
}
}
}
/**
* Aggregates the rows into a single csv
*
* @param array<string>|null $row Row data
* @return string CSV with all data to date
*/
protected function _renderRow(?array $row = null): string
{
static $csv = '';
if ($this->_resetStaticVariables) {
$csv = '';
$this->_resetStaticVariables = false;
return '';
}
$csv .= (string)$this->_generateRow($row);
return $csv;
}
/**
* Generates a single row in a csv from an array of
* data by writing the array to a temporary file and
* returning its contents
*
* @param array|null $row Row data
* @return string|false String with the row in csv-syntax, false on fputscv failure
*/
protected function _generateRow(?array $row = null): string|false
{
static $fp = false;
if (!$row) {
return '';
}
if ($fp === false) {
$stream = 'php://temp';
$fp = fopen($stream, 'r+');
if ($fp === false) {
throw new CakeException(sprintf('Cannot open stream `%s`', $stream));
}
$setSeparator = $this->getConfig('setSeparator');
if ($setSeparator) {
fwrite($fp, 'sep=' . $setSeparator . "\n");
}
} else {
ftruncate($fp, 0);
}
$null = $this->getConfig('null');
if ($null) {
foreach ($row as &$field) {
if ($field === null) {
$field = $null;
}
}
}
$delimiter = $this->getConfig('delimiter');
$enclosure = $this->getConfig('enclosure');
$newline = $this->getConfig('newline');
$row = str_replace(["\r\n", "\n", "\r"], $newline, $row);
if ($enclosure === '') {
// fputcsv does not supports empty enclosure
if (fputs($fp, implode($delimiter, $row) . "\n") === false) {
return false;
}
} else {
if (fputcsv($fp, $row, $delimiter, $enclosure) === false) {
return false;
}
}
rewind($fp);
$csv = '';
while (($buffer = fgets($fp, 4096)) !== false) {
$csv .= $buffer;
}
$eol = $this->getConfig('eol');
if ($eol !== "\n") {
$csv = str_replace("\n", $eol, $csv);
}
$dataEncoding = $this->getConfig('dataEncoding');
$csvEncoding = $this->getConfig('csvEncoding');
if ($dataEncoding !== $csvEncoding) {
$extension = $this->getConfig('transcodingExtension');
if ($extension === static::EXTENSION_ICONV) {
$csv = iconv($dataEncoding, $csvEncoding, $csv);
} elseif ($extension === static::EXTENSION_MBSTRING) {
$csv = mb_convert_encoding($csv, $csvEncoding, $dataEncoding);
}
}
// BOM must be added after encoding
$bom = $this->getConfig('bom');
if ($bom && $this->isFirstBom) {
$csv = $this->getBom($csvEncoding) . $csv;
$this->isFirstBom = false;
}
return $csv;
}
/**
* Returns the BOM for the encoding given.
*
* @param string $csvEncoding The encoding you want the BOM for
* @return string
*/
protected function getBom(string $csvEncoding): string
{
$csvEncoding = strtoupper($csvEncoding);
return $this->bomMap[$csvEncoding] ?? '';
}
}