Completed
Push — master ( 1b1ca0...acd14b )
by ignace nyamagana
02:52
created

Reader::createFromPath()   A

Complexity

Conditions 1
Paths 1

Duplication

Lines 0
Ratio 0 %

Size

Total Lines 4
Code Lines 2

Code Coverage

Tests 2
CRAP Score 1

Importance

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