summaryrefslogtreecommitdiffstats
path: root/src/Reader.php
blob: e4b5deb2c44b57733bb8fb9f1db6779dd893ee71 (plain)
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
<?php
/**
* This file is part of the League.csv library
*
* @license http://opensource.org/licenses/MIT
* @link https://github.com/thephpleague/csv/
* @version 7.1.1
* @package League.csv
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace League\Csv;

use CallbackFilterIterator;
use InvalidArgumentException;
use Iterator;
use League\Csv\Modifier\MapIterator;
use LimitIterator;
use SplFileObject;

/**
 *  A class to manage extracting and filtering a CSV
 *
 * @package League.csv
 * @since  3.0.0
 *
 */
class Reader extends AbstractCsv
{
    /**
     * @inheritdoc
     */
    protected $stream_filter_mode = STREAM_FILTER_READ;

    /**
     * Returns a Filtered Iterator
     *
     * @param callable $callable a callable function to be applied to each Iterator item
     *
     * @return Iterator
     */
    public function query(callable $callable = null)
    {
        $iterator = $this->getIterator();
        $iterator = $this->applyBomStripping($iterator);
        $iterator = new CallbackFilterIterator($iterator, function ($row) {
            return is_array($row);
        });

        $iterator = $this->applyIteratorFilter($iterator);
        $iterator = $this->applyIteratorSortBy($iterator);
        $iterator = $this->applyIteratorInterval($iterator);
        if (! is_null($callable)) {
            return new MapIterator($iterator, $callable);
        }

        return $iterator;
    }

    /**
     * Applies a callback function on the CSV
     *
     * The callback function must return TRUE in order to continue
     * iterating over the iterator.
     *
     * @param callable $callable The callback function
     *
     * @return int the iteration count
     */
    public function each(callable $callable)
    {
        $index = 0;
        $iterator = $this->query();
        $iterator->rewind();
        while ($iterator->valid() && true === $callable($iterator->current(), $iterator->key(), $iterator)) {
            ++$index;
            $iterator->next();
        }

        return $index;
    }

    /**
     * Returns a single row from the CSV
     *
     * @param int $offset
     *
     * @throws InvalidArgumentException If the $offset is not a valid Integer
     *
     * @return array
     */
    public function fetchOne($offset = 0)
    {
        $this->setOffset($offset);
        $this->setLimit(1);
        $iterator = $this->query();
        $iterator->rewind();

        return (array) $iterator->current();
    }

    /**
     * Returns a sequential array of all CSV lines
     *
     * The callable function will be applied to each Iterator item
     *
     * @param callable $callable a callable function
     *
     * @return array
     */
    public function fetchAll(callable $callable = null)
    {
        return $this->execute($this->query($callable));
    }

    /**
     * Transform the Iterator into an array
     *
     * @param Iterator $iterator
     *
     * @return array
     */
    protected function execute(Iterator $iterator)
    {
        return iterator_to_array($iterator, false);
    }

    /**
     * Returns a single column from the CSV data
     *
     * The callable function will be applied to each value to be return
     *
     * @param int      $column_index field Index
     * @param callable $callable     a callable function
     *
     * @throws InvalidArgumentException If the column index is not a positive integer or 0
     *
     * @return array
     */
    public function fetchColumn($column_index = 0, callable $callable = null)
    {
        if (false === filter_var($column_index, FILTER_VALIDATE_INT, ['options' => ['min_range' => 0]])) {
            throw new InvalidArgumentException(
                'the column index must be a positive integer or 0'
            );
        }

        $iterator = $this->query($callable);
        $iterator = new CallbackFilterIterator($iterator, function ($row) use ($column_index) {
            return array_key_exists($column_index, $row);
        });
        $iterator = new MapIterator($iterator, function ($row) use ($column_index) {
            return $row[$column_index];
        });

        return $this->execute($iterator);
    }

    /**
     * Returns a sequential array of all CSV lines;
     *
     * The rows are presented as associated arrays
     * The callable function will be applied to each Iterator item
     *
     * @param array|int $offset_or_keys the name for each key member OR the row Index to be
     *                                  used as the associated named keys
     *
     * @param callable $callable a callable function
     *
     * @throws InvalidArgumentException If the submitted keys are invalid
     *
     * @return array
     */
    public function fetchAssoc($offset_or_keys = 0, callable $callable = null)
    {
        $keys = $this->getAssocKeys($offset_or_keys);
        $this->assertValidAssocKeys($keys);
        if (! is_array($offset_or_keys)) {
            $this->addFilter(function ($row, $rowIndex) use ($offset_or_keys) {
                return is_array($row) && $rowIndex != $offset_or_keys;
            });
        }
        $keys_count = count($keys);
        $iterator   = $this->query($callable);
        $iterator   = new MapIterator($iterator, function (array $row) use ($keys, $keys_count) {
            if ($keys_count != count($row)) {
                $row = array_slice(array_pad($row, $keys_count, null), 0, $keys_count);
            }

            return array_combine($keys, $row);
        });

        return $this->execute($iterator);
    }

    /**
     * Selects the array to be used as key for the fetchAssoc method
     *
     * @param array|int $offset_or_keys the assoc key OR the row Index to be used
     *                                  as the key index
     *
     * @throws InvalidArgumentException If the row index and/or the resulting array is invalid
     *
     * @return array
     */
    protected function getAssocKeys($offset_or_keys)
    {
        if (is_array($offset_or_keys) && ! empty($offset_or_keys)) {
            return $offset_or_keys;
        }

        if (false === filter_var($offset_or_keys, FILTER_VALIDATE_INT, ['options' => ['min_range' => 0]])) {
            throw new InvalidArgumentException(
                'the row index must be a positive integer, 0 or a non empty array'
            );
        }

        return $this->getRow($offset_or_keys);
    }

    /**
     * Returns a single row from the CSV without filtering
     *
     * @param int $offset
     *
     * @throws InvalidArgumentException If the $offset is not valid or the row does not exist
     *
     * @return array
     */
    protected function getRow($offset)
    {
        $csv = $this->getIterator();
        $csv->setFlags($this->getFlags() & ~SplFileObject::READ_CSV);

        $iterator = new LimitIterator($csv, $offset, 1);
        $iterator->rewind();
        $res = $iterator->current();
        if (empty($res)) {
            throw new InvalidArgumentException('the specified row does not exist or is empty');
        }

        if (0 == $offset && $this->isBomStrippable()) {
            $res = mb_substr($res, mb_strlen($this->getInputBom()));
        }

        return str_getcsv($res, $this->delimiter, $this->enclosure, $this->escape);
    }

    /**
     * Validates the array to be used by the fetchAssoc method
     *
     * @param array $keys
     *
     * @throws InvalidArgumentException If the submitted array fails the assertion
     */
    protected function assertValidAssocKeys(array $keys)
    {
        $test = array_unique(array_filter($keys, function ($value) {
            return is_scalar($value) || (is_object($value) && method_exists($value, '__toString'));
        }));

        if ($keys !== $test) {
            throw new InvalidArgumentException('Use a flat array with unique string values');
        }
    }
}