Completed
Pull Request — master (#210)
by ignace nyamagana
04:08
created

Statement::computeHeader()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 24
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 4

Importance

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