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

Statement::headers()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 12
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 7
nc 2
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
        $offset = $this->filterInteger($offset, 0, 'the offset must be a positive integer or 0');
80
        if ($offset === $this->offset) {
81
            return $this;
82
        }
83
84
        $clone = clone $this;
85
        $clone->offset = $offset;
86
87
        return $clone;
88
    }
89
90
    /**
91
     * Set LimitIterator Count
92
     *
93
     * @param int $limit
94
     *
95
     * @return self
96
     */
97
    public function limit(int $limit = -1): self
98
    {
99
        $limit = $this->filterInteger($limit, -1, 'the limit must an integer greater or equals to -1');
100
        if ($limit === $this->limit) {
101
            return $this;
102
        }
103
104
        $clone = clone $this;
105
        $clone->limit = $limit;
106
107
        return $clone;
108
    }
109
110
    /**
111
     * Set an Iterator sorting callable function
112
     *
113
     * @param callable $callable
114
     *
115
     * @return self
116
     */
117
    public function orderBy(callable $callable): self
118
    {
119
        $clone = clone $this;
120
        $clone->order_by[] = $callable;
121
122
        return $clone;
123
    }
124
125
    /**
126
     * Set the Iterator filter method
127
     *
128
     * @param callable $callable
129
     *
130
     * @return self
131
     */
132
    public function where(callable $callable): self
133
    {
134
        $clone = clone $this;
135
        $clone->where[] = $callable;
136
137
        return $clone;
138
    }
139
140
    /**
141
     * Set the headers to be used by the RecordSet object
142
     *
143
     * @param string[] $headers
144
     *
145
     * @return self
146
     */
147
    public function headers(array $headers): self
148
    {
149
        $headers = $this->filterHeader($headers);
150
        if ($headers === $this->headers) {
151
            return $this;
152
        }
153
154
        $clone = clone $this;
155
        $clone->headers = $headers;
156
157
        return $clone;
158
    }
159
160
    /**
161
     * Returns the inner CSV Document Iterator object
162
     *
163
     * @return RecordSet
164
     */
165
    public function process(Reader $reader)
166
    {
167
        $document = $this->prepare($reader);
168
        $iterator = $this->stripBOM($document, $reader->getInputBOM(), $reader->getEnclosure());
169
        $iterator = $this->combineHeader($iterator);
170
        $iterator = $this->filterRecords($iterator);
171
        $iterator = $this->orderRecords($iterator);
172
173
        return new RecordSet(new LimitIterator($iterator, $this->offset, $this->limit), $this->headers);
174
    }
175
176
    /**
177
     * Set the computed RecordSet headers
178
     *
179
     * @param Reader $reader The CSV document Reader object
180
     *
181
     * @throws Exception If the header is not found
182
     *
183
     * @return StreamIterator|SplFileObject
184
     */
185
    protected function prepare(Reader $reader)
186
    {
187
        $csv = $reader->getDocument();
188
        $csv->setFlags(SplFileObject::READ_CSV | SplFileObject::READ_AHEAD | SplFileObject::SKIP_EMPTY);
189
        $csv->setCsvControl($reader->getDelimiter(), $reader->getEnclosure(), $reader->getEscape());
190
        $offset = $reader->getHeaderOffset();
191
        if (!empty($this->headers) || null === $offset) {
192
            return $csv;
193
        }
194
195
        $csv->seek($offset);
196
        $headers = $csv->current();
197
        if (empty($headers) || [null] === $headers) {
198
            throw new Exception('the specified header does not exist or is empty');
199
        }
200
201
        if (0 === $offset) {
202
            $headers = $this->removeBOM($headers, mb_strlen($reader->getInputBOM()), $reader->getEnclosure());
203
        }
204
        $this->headers = $this->filterHeader($headers);
205
        array_unshift($this->where, function ($row, $index) use ($offset) {
206
            return $index !== $offset;
207
        });
208
209
        return $csv;
210
    }
211
212
    /**
213
     * Remove the BOM sequence from the CSV
214
     *
215
     * @param Iterator $iterator
216
     *
217
     * @return Iterator
218
     */
219
    protected function stripBOM(Iterator $iterator, string $bom, string $enclosure): Iterator
220
    {
221
        if ('' == $bom) {
222
            return $iterator;
223
        }
224
225
        $bom_length = mb_strlen($bom);
226
        $strip_bom = function ($row, $index) use ($bom_length, $enclosure) {
227
            if (0 != $index || !is_array($row)) {
228
                return $row;
229
            }
230
231
            return $this->removeBOM($row, $bom_length, $enclosure);
232
        };
233
234
        return new MapIterator($iterator, $strip_bom);
235
    }
236
237
    /**
238
     * Add the CSV header if present
239
     *
240
     * @param Iterator $iterator
241
     *
242
     * @return Iterator
243
     */
244
    protected function combineHeader(Iterator $iterator): Iterator
245
    {
246
        if (empty($this->headers)) {
247
            return $iterator;
248
        }
249
250
        $header_count = count($this->headers);
251
        $combine = function (array $row) use ($header_count) {
252
            if ($header_count != count($row)) {
253
                $row = array_slice(array_pad($row, $header_count, null), 0, $header_count);
254
            }
255
256
            return array_combine($this->headers, $row);
257
        };
258
259
        return new MapIterator($iterator, $combine);
260
    }
261
262
    /**
263
    * Filter the Iterator
264
    *
265
    * @param Iterator $iterator
266
    *
267
    * @return Iterator
268
    */
269
    protected function filterRecords(Iterator $iterator): Iterator
270
    {
271
        $normalized_csv = function ($row) {
272
            return is_array($row) && $row != [null];
273
        };
274
        array_unshift($this->where, $normalized_csv);
275
276
        $reducer = function ($iterator, $callable) {
277
            return new CallbackFilterIterator($iterator, $callable);
278
        };
279
280
        return array_reduce($this->where, $reducer, $iterator);
281
    }
282
283
    /**
284
    * Sort the Iterator
285
    *
286
    * @param Iterator $iterator
287
    *
288
    * @return Iterator
289
    */
290
    protected function orderRecords(Iterator $iterator): Iterator
291
    {
292
        if (empty($this->order_by)) {
293
            return $iterator;
294
        }
295
296
        $obj = new ArrayIterator(iterator_to_array($iterator));
297
        $obj->uasort(function ($row_a, $row_b) {
298
            $res = 0;
299
            foreach ($this->order_by as $compare) {
300
                if (0 !== ($res = $compare($row_a, $row_b))) {
301
                    break;
302
                }
303
            }
304
305
            return $res;
306
        });
307
308
        return $obj;
309
    }
310
}
311