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

RecordSet::fetchOne()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

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