Completed
Push — master ( 6a3d0e...4c67e5 )
by ignace nyamagana
23s queued 21s
created

Reader::jsonSerialize()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 0
dl 0
loc 4
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * League.Csv (https://csv.thephpleague.com)
5
 *
6
 * (c) Ignace Nyamagana Butera <[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
declare(strict_types=1);
13
14
namespace League\Csv;
15
16
use BadMethodCallException;
17
use CallbackFilterIterator;
18
use Countable;
19
use Generator;
20
use Iterator;
21
use IteratorAggregate;
22
use JsonSerializable;
23
use League\Csv\Polyfill\EmptyEscapeParser;
24
use SplFileObject;
25
use TypeError;
26
use function array_combine;
27
use function array_filter;
28
use function array_pad;
29
use function array_slice;
30
use function array_unique;
31
use function gettype;
32
use function is_array;
33
use function iterator_count;
34
use function iterator_to_array;
35
use function mb_strlen;
36
use function mb_substr;
37
use function sprintf;
38
use function strlen;
39
use function substr;
40
use const PHP_VERSION_ID;
41
use const STREAM_FILTER_READ;
42
43
/**
44
 * A class to parse and read records from a CSV document.
45
 *
46
 * @method array fetchOne(int $nth_record = 0) Returns a single record from the CSV
47
 * @method Generator fetchColumn(string|int $column_index) Returns the next value from a single CSV record field
48
 * @method Generator fetchPairs(string|int $offset_index = 0, string|int $value_index = 1) Fetches the next key-value pairs from the CSV document
49
 */
50
class Reader extends AbstractCsv implements Countable, IteratorAggregate, JsonSerializable
51
{
52
    /**
53
     * header offset.
54
     *
55
     * @var int|null
56
     */
57
    protected $header_offset;
58
59
    /**
60
     * header record.
61
     *
62
     * @var string[]
63
     */
64
    protected $header = [];
65
66
    /**
67
     * records count.
68
     *
69
     * @var int
70
     */
71
    protected $nb_records = -1;
72
73
    /**
74
     * {@inheritdoc}
75
     */
76
    protected $stream_filter_mode = STREAM_FILTER_READ;
77
78
    /**
79
     * {@inheritdoc}
80
     */
81 3
    public static function createFromPath(string $path, string $open_mode = 'r', $context = null)
82
    {
83 3
        return parent::createFromPath($path, $open_mode, $context);
84
    }
85
86
    /**
87
     * {@inheritdoc}
88
     */
89 27
    protected function resetProperties()
90
    {
91 27
        parent::resetProperties();
92 27
        $this->nb_records = -1;
93 27
        $this->header = [];
94 27
    }
95
96
    /**
97
     * Returns the header offset.
98
     *
99
     * If no CSV header offset is set this method MUST return null
100
     *
101
     * @return int|null
102
     */
103 15
    public function getHeaderOffset()
104
    {
105 15
        return $this->header_offset;
106
    }
107
108
    /**
109
     * Returns the CSV record used as header.
110
     *
111
     * The returned header is represented as an array of string values
112
     *
113
     * @return string[]
114
     */
115 21
    public function getHeader(): array
116
    {
117 21
        if (null === $this->header_offset) {
118 15
            return $this->header;
119
        }
120
121 9
        if ([] !== $this->header) {
122 3
            return $this->header;
123
        }
124
125 9
        $this->header = $this->setHeader($this->header_offset);
126
127 6
        return $this->header;
128
    }
129
130
    /**
131
     * Determine the CSV record header.
132
     *
133
     * @throws Exception If the header offset is set and no record is found or is the empty array
134
     *
135
     * @return string[]
136
     */
137 12
    protected function setHeader(int $offset): array
138
    {
139 12
        $header = $this->seekRow($offset);
140 12
        if (false === $header || [] === $header) {
141 6
            throw new Exception(sprintf('The header record does not exist or is empty at offset: `%s`', $offset));
142
        }
143
144 6
        if (0 === $offset) {
145 3
            return $this->removeBOM($header, mb_strlen($this->getInputBOM()), $this->enclosure);
146
        }
147
148 3
        return $header;
149
    }
150
151
    /**
152
     * Returns the row at a given offset.
153
     *
154
     * @return array|false
155
     */
156 12
    protected function seekRow(int $offset)
157
    {
158 12
        foreach ($this->getDocument() as $index => $record) {
159 12
            if ($offset === $index) {
160 9
                return $record;
161
            }
162
        }
163
164 9
        return false;
165
    }
166
167
    /**
168
     * Returns the document as an Iterator.
169
     */
170 18
    protected function getDocument(): Iterator
171
    {
172 18
        if (70400 > PHP_VERSION_ID && '' === $this->escape) {
173 6
            $this->document->setCsvControl($this->delimiter, $this->enclosure);
174
175 6
            return EmptyEscapeParser::parse($this->document);
176
        }
177
178 12
        $this->document->setFlags(SplFileObject::READ_CSV | SplFileObject::READ_AHEAD | SplFileObject::SKIP_EMPTY);
179 12
        $this->document->setCsvControl($this->delimiter, $this->enclosure, $this->escape);
180 12
        $this->document->rewind();
181
182 12
        return $this->document;
183
    }
184
185
    /**
186
     * Strip the BOM sequence from a record.
187
     *
188
     * @param string[] $record
189
     *
190
     * @return string[]
191
     */
192 12
    protected function removeBOM(array $record, int $bom_length, string $enclosure): array
193
    {
194 12
        if (0 === $bom_length) {
195 3
            return $record;
196
        }
197
198 9
        $record[0] = mb_substr($record[0], $bom_length);
199 9
        if ($enclosure.$enclosure != substr($record[0].$record[0], strlen($record[0]) - 1, 2)) {
200 6
            return $record;
201
        }
202
203 3
        $record[0] = substr($record[0], 1, -1);
204
205 3
        return $record;
206
    }
207
208
    /**
209
     * {@inheritdoc}
210
     */
211 9
    public function __call($method, array $arguments)
212
    {
213 9
        static $whitelisted = ['fetchColumn' => 1, 'fetchOne' => 1, 'fetchPairs' => 1];
214 9
        if (isset($whitelisted[$method])) {
215 3
            return (new ResultSet($this->getRecords(), $this->getHeader()))->$method(...$arguments);
216
        }
217
218 6
        throw new BadMethodCallException(sprintf('%s::%s() method does not exist', static::class, $method));
219
    }
220
221
    /**
222
     * {@inheritdoc}
223
     */
224 3
    public function count(): int
225
    {
226 3
        if (-1 === $this->nb_records) {
227 3
            $this->nb_records = iterator_count($this->getRecords());
228
        }
229
230 3
        return $this->nb_records;
231
    }
232
233
    /**
234
     * {@inheritdoc}
235
     */
236 6
    public function getIterator(): Iterator
237
    {
238 6
        return $this->getRecords();
239
    }
240
241
    /**
242
     * {@inheritdoc}
243
     */
244 3
    public function jsonSerialize(): array
245
    {
246 3
        return iterator_to_array($this->getRecords(), false);
247
    }
248
249
    /**
250
     * Returns the CSV records as an iterator object.
251
     *
252
     * Each CSV record is represented as a simple array containing strings or null values.
253
     *
254
     * If the CSV document has a header record then each record is combined
255
     * to the header record and the header record is removed from the iterator.
256
     *
257
     * If the CSV document is inconsistent. Missing record fields are
258
     * filled with null values while extra record fields are strip from
259
     * the returned object.
260
     *
261
     * @param string[] $header an optional header to use instead of the CSV document header
262
     */
263 21
    public function getRecords(array $header = []): Iterator
264
    {
265 21
        $header = $this->computeHeader($header);
266 18
        $normalized = static function ($record): bool {
267 18
            return is_array($record) && $record != [null];
268 18
        };
269
270 18
        $bom = '';
271 18
        if ($this->is_input_bom_skipped) {
272 15
            $bom = $this->getInputBOM();
273
        }
274
275 18
        $document = $this->getDocument();
276 18
        $records = $this->stripBOM(new CallbackFilterIterator($document, $normalized), $bom);
277 18
        if (null !== $this->header_offset) {
278 6
            $records = new CallbackFilterIterator($records, function (array $record, int $offset): bool {
279 6
                return $offset !== $this->header_offset;
280 6
            });
281
        }
282
283 18
        return $this->combineHeader($records, $header);
284
    }
285
286
    /**
287
     * Returns the header to be used for iteration.
288
     *
289
     * @param string[] $header
290
     *
291
     * @throws Exception If the header contains non unique column name
292
     *
293
     * @return string[]
294
     */
295 27
    protected function computeHeader(array $header)
296
    {
297 27
        if ([] === $header) {
298 24
            $header = $this->getHeader();
299
        }
300
301 27
        if ($header === array_unique(array_filter($header, 'is_string'))) {
302 24
            return $header;
303
        }
304
305 3
        throw new Exception('The header record must be empty or a flat array with unique string values');
306
    }
307
308
    /**
309
     * Combine the CSV header to each record if present.
310
     *
311
     * @param string[] $header
312
     */
313 33
    protected function combineHeader(Iterator $iterator, array $header): Iterator
314
    {
315 33
        if ([] === $header) {
316 24
            return $iterator;
317
        }
318
319 12
        $field_count = count($header);
320 12
        $mapper = static function (array $record) use ($header, $field_count): array {
321 12
            if (count($record) != $field_count) {
322 6
                $record = array_slice(array_pad($record, $field_count, null), 0, $field_count);
323
            }
324
325 12
            return array_combine($header, $record);
326 12
        };
327
328 12
        return new MapIterator($iterator, $mapper);
329
    }
330
331
    /**
332
     * Strip the BOM sequence from the returned records if necessary.
333
     */
334 27
    protected function stripBOM(Iterator $iterator, string $bom): Iterator
335
    {
336 27
        if ('' === $bom) {
337 18
            return $iterator;
338
        }
339
340 9
        $bom_length = mb_strlen($bom);
341 9
        $mapper = function (array $record, int $index) use ($bom_length): array {
342 9
            if (0 !== $index) {
343 3
                return $record;
344
            }
345
346 9
            return $this->removeBOM($record, $bom_length, $this->enclosure);
347 9
        };
348
349 9
        return new MapIterator($iterator, $mapper);
350
    }
351
352
    /**
353
     * Selects the record to be used as the CSV header.
354
     *
355
     * Because the header is represented as an array, to be valid
356
     * a header MUST contain only unique string value.
357
     *
358
     * @param int|null $offset the header record offset
359
     *
360
     * @throws Exception if the offset is a negative integer
361
     *
362
     * @return static
363
     */
364 24
    public function setHeaderOffset($offset): self
365
    {
366 24
        if ($offset === $this->header_offset) {
367 12
            return $this;
368
        }
369
370 12
        if (!is_nullable_int($offset)) {
371 3
            throw new TypeError(sprintf(__METHOD__.'() expects 1 Argument to be null or an integer %s given', gettype($offset)));
372
        }
373
374 9
        if (null !== $offset && 0 > $offset) {
375 3
            throw new Exception(__METHOD__.'() expects 1 Argument to be greater or equal to 0');
376
        }
377
378 6
        $this->header_offset = $offset;
379 6
        $this->resetProperties();
380
381 6
        return $this;
382
    }
383
}
384