Completed
Pull Request — master (#210)
by ignace nyamagana
03:12
created

RecordSet   A

Complexity

Total Complexity 27

Size/Duplication

Total Lines 304
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 27
lcom 1
cbo 3
dl 0
loc 304
ccs 90
cts 90
cp 1
rs 10
c 0
b 0
f 0

16 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A __destruct() 0 4 1
A getHeader() 0 4 1
A toHTML() 0 7 1
A toXML() 0 11 2
A toDOMNode() 0 15 3
A convertToUtf8() 0 21 3
A getIterator() 0 4 1
A count() 0 4 1
A jsonSerialize() 0 4 1
A fetchAll() 0 4 1
A fetchOne() 0 8 1
A fetchColumn() 0 13 1
B getFieldIndex() 0 17 5
A fetchPairs() 0 19 2
A setConversionInputEncoding() 0 12 2
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 CallbackFilterIterator;
18
use Countable;
19
use DOMDocument;
20
use DOMElement;
21
use Generator;
22
use Iterator;
23
use IteratorAggregate;
24
use JsonSerializable;
25
use LimitIterator;
26
27
/**
28
 * A class to manage extracting and filtering a CSV
29
 *
30
 * @package League.csv
31
 * @since   9.0.0
32
 * @author  Ignace Nyamagana Butera <[email protected]>
33
 *
34
 */
35
class RecordSet implements JsonSerializable, IteratorAggregate, Countable
36
{
37
    use ValidatorTrait;
38
39
    /**
40
     * The CSV iterator result
41
     *
42
     * @var Iterator
43
     */
44
    protected $iterator;
45
46
    /**
47
     * The CSV header
48
     *
49
     * @var array
50
     */
51
    protected $header = [];
52
53
    /**
54
     * Charset Encoding for the CSV
55
     *
56
     * This information is used when converting the CSV to XML or JSON
57
     *
58
     * @var string
59
     */
60
    protected $conversion_input_encoding = 'UTF-8';
61
62
    /**
63
     * New instance
64
     *
65
     * @param Iterator $iterator a CSV iterator created from Statement
66
     * @param array    $header   the CSV header
67
     */
68 106
    public function __construct(Iterator $iterator, array $header = [])
69
    {
70 106
        $this->iterator = $iterator;
71 106
        $this->header = $header;
72 106
    }
73
74
    /**
75
     * @inheritdoc
76
     */
77 106
    public function __destruct()
78
    {
79 106
        $this->iterator = null;
80 106
    }
81
82
    /**
83
     * Returns the column header associate with the RecordSet
84
     *
85
     * @return string[]
86
     */
87 6
    public function getHeader()
88
    {
89 6
        return $this->header;
90
    }
91
92
    /**
93
     * Returns a HTML table representation of the CSV Table
94
     *
95
     * @param string $class_attr optional classname
96
     *
97
     * @return string
98
     */
99 4
    public function toHTML(string $class_attr = 'table-csv-data'): string
100
    {
101 4
        $doc = $this->toXML('table', 'tr', 'td');
102 4
        $doc->documentElement->setAttribute('class', $class_attr);
103
104 4
        return $doc->saveHTML($doc->documentElement);
105
    }
106
107
    /**
108
     * Transforms a CSV into a XML
109
     *
110
     * @param string $root_name XML root node name
111
     * @param string $row_name  XML row node name
112
     * @param string $cell_name XML cell node name
113
     *
114
     * @return DOMDocument
115
     */
116 6
    public function toXML(string $root_name = 'csv', string $row_name = 'row', string $cell_name = 'cell'): DOMDocument
117
    {
118 6
        $doc = new DOMDocument('1.0', 'UTF-8');
119 6
        $root = $doc->createElement($root_name);
120 6
        foreach ($this->convertToUtf8($this->iterator) as $row) {
121 6
            $root->appendChild($this->toDOMNode($doc, $row, $row_name, $cell_name));
122
        }
123 6
        $doc->appendChild($root);
124
125 6
        return $doc;
126
    }
127
128
    /**
129
     * convert a Record into a DOMNode
130
     *
131
     * @param DOMDocument $doc       The DOMDocument
132
     * @param array       $row       The CSV record
133
     * @param string      $row_name  XML row node name
134
     * @param string      $cell_name XML cell node name
135
     *
136
     * @return DOMElement
137
     */
138 6
    protected function toDOMNode(DOMDocument $doc, array $row, string $row_name, string $cell_name): DOMElement
139
    {
140 6
        $rowElement = $doc->createElement($row_name);
141 6
        foreach ($row as $name => $value) {
142 6
            $content = $doc->createTextNode($value);
143 6
            $cell = $doc->createElement($cell_name);
144 6
            if (!empty($this->header)) {
145 4
                $cell->setAttribute('title', $name);
146
            }
147 6
            $cell->appendChild($content);
148 6
            $rowElement->appendChild($cell);
149
        }
150
151 6
        return $rowElement;
152
    }
153
154
    /**
155
     * Convert Csv file into UTF-8
156
     *
157
     * @param Iterator $iterator
158
     *
159
     * @return Iterator
160
     */
161 8
    protected function convertToUtf8(Iterator $iterator): Iterator
162
    {
163 8
        if (stripos($this->conversion_input_encoding, 'UTF-8') !== false) {
164 6
            return $iterator;
165
        }
166
167
        $convert_cell = function ($value) {
168 2
            return mb_convert_encoding((string) $value, 'UTF-8', $this->conversion_input_encoding);
169 2
        };
170
171
        $convert_row = function (array $row) use ($convert_cell) {
172 2
            $res = [];
173 2
            foreach ($row as $key => $value) {
174 2
                $res[$convert_cell($key)] = $convert_cell($value);
175
            }
176
177 2
            return $res;
178 2
        };
179
180 2
        return new MapIterator($iterator, $convert_row);
181
    }
182
183
    /**
184
     * @inheritdoc
185
     */
186 2
    public function getIterator(): Iterator
187
    {
188 2
        return $this->iterator;
189
    }
190
191
    /**
192
     * @inheritdoc
193
     */
194 2
    public function count()
195
    {
196 2
        return iterator_count($this->iterator);
197
    }
198
199
    /**
200
     * @inheritdoc
201
     */
202 2
    public function jsonSerialize()
203
    {
204 2
        return iterator_to_array($this->convertToUtf8($this->iterator), false);
205
    }
206
207
    /**
208
     * Returns a sequential array of all CSV lines
209
     *
210
     * @return array
211
     */
212 62
    public function fetchAll(): array
213
    {
214 62
        return iterator_to_array($this->iterator);
215
    }
216
217
    /**
218
     * Returns a single row from the CSV
219
     *
220
     * By default if no offset is provided the first row of the CSV is selected
221
     *
222
     * @param int $offset the CSV row offset
223
     *
224
     * @return array
225
     */
226 6
    public function fetchOne(int $offset = 0): array
227
    {
228 6
        $offset = $this->filterInteger($offset, 0, 'the submitted offset is invalid');
229 4
        $it = new LimitIterator($this->iterator, $offset, 1);
230 4
        $it->rewind();
231
232 4
        return (array) $it->current();
233
    }
234
235
    /**
236
     * Returns the next value from a single CSV column
237
     *
238
     * By default if no column index is provided the first column of the CSV is selected
239
     *
240
     * @param string|int $column CSV column index
241
     *
242
     * @return Iterator
243
     */
244 14
    public function fetchColumn($column = 0): Iterator
245
    {
246 14
        $column = $this->getFieldIndex($column, 'the column index value is invalid');
247
        $filter = function (array $row) use ($column) {
248 12
            return isset($row[$column]);
249 12
        };
250
251
        $select = function ($row) use ($column) {
252 8
            return $row[$column];
253 12
        };
254
255 12
        return new MapIterator(new CallbackFilterIterator($this->iterator, $filter), $select);
256
    }
257
258
    /**
259
     * Filter a field name against the CSV header if any
260
     *
261
     * @param string|int $field         the field name or the field index
262
     * @param string     $error_message the associated error message
263
     *
264
     * @throws Exception if the field is invalid
265
     *
266
     * @return string|int
267
     */
268 22
    protected function getFieldIndex($field, $error_message)
269
    {
270 22
        if (false !== array_search($field, $this->header, true) || is_string($field)) {
271 2
            return $field;
272
        }
273
274 20
        $index = $this->filterInteger($field, 0, $error_message);
275 20
        if (empty($this->header)) {
276 16
            return $index;
277
        }
278
279 4
        if (false !== ($index = array_search($index, array_flip($this->header), true))) {
280 2
            return $index;
281
        }
282
283 2
        throw new Exception($error_message);
284
    }
285
286
    /**
287
     * Fetches the next key-value pairs from a result set (first
288
     * column is the key, second column is the value).
289
     *
290
     * By default if no column index is provided:
291
     * - the first CSV column is used to provide the keys
292
     * - the second CSV column is used to provide the value
293
     *
294
     * @param string|int $offset_index The column index to serve as offset
295
     * @param string|int $value_index  The column index to serve as value
296
     *
297
     * @return Generator
298
     */
299 8
    public function fetchPairs($offset_index = 0, $value_index = 1): Generator
300
    {
301 8
        $offset = $this->getFieldIndex($offset_index, 'the offset index value is invalid');
302 8
        $value = $this->getFieldIndex($value_index, 'the value index value is invalid');
303
304
        $filter = function ($row) use ($offset) {
305 8
            return isset($row[$offset]);
306 8
        };
307
308 8
        $select = function ($row) use ($offset, $value) {
309 6
            return [$row[$offset], $row[$value] ?? null];
310 8
        };
311
312 8
        $it = new MapIterator(new CallbackFilterIterator($this->iterator, $filter), $select);
313
314 8
        foreach ($it as $row) {
315 6
            yield $row[0] => $row[1];
316
        }
317 8
    }
318
319
    /**
320
     * Sets the CSV encoding charset
321
     *
322
     * @param string $str
323
     *
324
     * @return static
325
     */
326 4
    public function setConversionInputEncoding(string $str): self
327
    {
328 4
        $str = str_replace('_', '-', $str);
329 4
        $str = filter_var($str, FILTER_SANITIZE_STRING, ['flags' => FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH]);
330 4
        $str = trim($str);
331 4
        if ('' === $str) {
332 2
            throw new Exception('you should use a valid charset');
333
        }
334 2
        $this->conversion_input_encoding = strtoupper($str);
335
336 2
        return $this;
337
    }
338
}
339