Completed
Pull Request — master (#210)
by ignace nyamagana
02:13
created

Statement::offset()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 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 ArrayIterator;
18
use CallbackFilterIterator;
19
use Iterator;
20
use League\Csv\Config\ValidatorTrait;
21
use LimitIterator;
22
use SplFileObject;
23
24
/**
25
 *  A trait to manage filtering a CSV
26
 *
27
 * @package League.csv
28
 * @since  9.0.0
29
 *
30
 */
31
class Statement
32
{
33
    use ValidatorTrait;
34
35
    /**
36
     * Callables to filter the iterator
37
     *
38
     * @var callable[]
39
     */
40
    protected $where = [];
41
42
    /**
43
     * Callables to sort the iterator
44
     *
45
     * @var callable[]
46
     */
47
    protected $order_by = [];
48
49
    /**
50
     * iterator Offset
51
     *
52
     * @var int
53
     */
54
    protected $offset = 0;
55
56
    /**
57
     * iterator maximum length
58
     *
59
     * @var int
60
     */
61
    protected $limit = -1;
62
63
    /**
64
     * CSV headers
65
     *
66
     * @var string[]
67
     */
68
    protected $headers = [];
69
70
    /**
71
     * Set LimitIterator Offset
72
     *
73
     * @param $offset
74
     *
75
     * @return self
76
     */
77
    public function offset(int $offset = 0): self
78
    {
79
        $this->offset = $this->filterInteger($offset, 0, 'the offset must be a positive integer or 0');
80
81
        return $this;
82
    }
83
84
    /**
85
     * Set LimitIterator Count
86
     *
87
     * @param int $limit
88
     *
89
     * @return self
90
     */
91
    public function limit(int $limit = -1): self
92
    {
93
        $this->limit = $this->filterInteger($limit, -1, 'the limit must an integer greater or equals to -1');
94
95
        return $this;
96
    }
97
98
    /**
99
     * Set an Iterator sorting callable function
100
     *
101
     * @param callable $callable
102
     *
103
     * @return self
104
     */
105
    public function orderBy(callable $callable): self
106
    {
107
        $this->order_by[] = $callable;
108
109
        return $this;
110
    }
111
112
    /**
113
     * Set the Iterator filter method
114
     *
115
     * @param callable $callable
116
     *
117
     * @return self
118
     */
119
    public function where(callable $callable): self
120
    {
121
        $this->where[] = $callable;
122
123
        return $this;
124
    }
125
126
    /**
127
     * Set the headers to be used by the RecordSet object
128
     *
129
     * @param string[] $headers
130
     *
131
     * @return self
132
     */
133
    public function headers(array $headers): self
134
    {
135
        $this->headers = $this->filterHeader($headers);
136
137
        return $this;
138
    }
139
140
    /**
141
     * Returns the inner CSV Document Iterator object
142
     *
143
     * @return RecordSet
144
     */
145
    public function process(Reader $reader)
146
    {
147
        $bom = $reader->getInputBOM();
148
        $enclosure = $reader->getEnclosure();
149
        $this->prepare($reader);
150
151
        $csv = $reader->getDocument();
152
        $csv->setFlags(SplFileObject::READ_AHEAD | SplFileObject::READ_CSV | SplFileObject::SKIP_EMPTY);
153
154
        $iterator = $this->stripBOM($csv, $bom, $enclosure);
155
        $iterator = $this->addHeader($iterator);
156
        $iterator = $this->filterRecords($iterator);
157
        $iterator = $this->orderRecords($iterator);
158
159
        return new RecordSet(
160
            new LimitIterator($iterator, $this->offset, $this->limit),
161
            $this->headers
162
        );
163
    }
164
165
    /**
166
     * Set the computed RecordSet headers
167
     *
168
     * @param Reader $reader
169
     */
170
    protected function prepare(Reader $reader)
171
    {
172
        if (!empty($this->headers)) {
173
            return;
174
        }
175
176
        $this->headers = $reader->getHeader();
177
        $header_offset = $reader->getHeaderOffset();
178
        if (null !== $header_offset) {
179
            $strip_header = function ($row, $index) use ($header_offset) {
180
                return $index !== $header_offset;
181
            };
182
            array_unshift($this->where, $strip_header);
183
        }
184
    }
185
186
    /**
187
     * Remove the BOM sequence from the CSV
188
     *
189
     * @param Iterator $iterator
190
     *
191
     * @return Iterator
192
     */
193
    protected function stripBOM(Iterator $iterator, string $bom, string $enclosure): Iterator
194
    {
195
        if ('' == $bom) {
196
            return $iterator;
197
        }
198
199
        $bom_length = mb_strlen($bom);
200
        $strip_bom = function ($row, $index) use ($bom_length, $enclosure) {
201
            if (0 != $index || !is_array($row)) {
202
                return $row;
203
            }
204
205
            return $this->removeBOM($row, $bom_length, $enclosure);
206
        };
207
208
        return new MapIterator($iterator, $strip_bom);
209
    }
210
211
    /**
212
     * Add the CSV header if present
213
     *
214
     * @param Iterator $iterator
215
     *
216
     * @return Iterator
217
     */
218
    protected function addHeader(Iterator $iterator): Iterator
219
    {
220
        if (empty($this->headers)) {
221
            return $iterator;
222
        }
223
224
        $header_count = count($this->headers);
225
        $combine = function (array $row) use ($header_count) {
226
            if ($header_count != count($row)) {
227
                $row = array_slice(array_pad($row, $header_count, null), 0, $header_count);
228
            }
229
230
            return array_combine($this->headers, $row);
231
        };
232
233
        return new MapIterator($iterator, $combine);
234
    }
235
236
    /**
237
    * Filter the Iterator
238
    *
239
    * @param Iterator $iterator
240
    *
241
    * @return Iterator
242
    */
243
    protected function filterRecords(Iterator $iterator): Iterator
244
    {
245
        $normalized_csv = function ($row) {
246
            return is_array($row) && $row != [null];
247
        };
248
        array_unshift($this->where, $normalized_csv);
249
250
        $reducer = function ($iterator, $callable) {
251
            return new CallbackFilterIterator($iterator, $callable);
252
        };
253
254
        return array_reduce($this->where, $reducer, $iterator);
255
    }
256
257
    /**
258
    * Sort the Iterator
259
    *
260
    * @param Iterator $iterator
261
    *
262
    * @return Iterator
263
    */
264
    protected function orderRecords(Iterator $iterator): Iterator
265
    {
266
        if (empty($this->order_by)) {
267
            return $iterator;
268
        }
269
270
        $obj = new ArrayIterator(iterator_to_array($iterator));
271
        $obj->uasort(function ($row_a, $row_b) {
272
            $res = 0;
273
            foreach ($this->order_by as $compare) {
274
                if (0 !== ($res = $compare($row_a, $row_b))) {
275
                    break;
276
                }
277
            }
278
279
            return $res;
280
        });
281
282
        return $obj;
283
    }
284
}
285