Completed
Pull Request — master (#309)
by ignace nyamagana
01:59
created

Reader::getDocument()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 3

Importance

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