Completed
Push — master ( 61b218...91a727 )
by ignace nyamagana
38:22 queued 14:57
created

Reader::select()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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