Completed
Pull Request — master (#178)
by ignace nyamagana
02:51
created

RecordSet::fetchPairs()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 16
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 16
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 10
nc 2
nop 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
namespace League\Csv;
14
15
use CallbackFilterIterator;
16
use Countable;
17
use DOMDocument;
18
use Generator;
19
use InvalidArgumentException;
20
use Iterator;
21
use IteratorAggregate;
22
use JsonSerializable;
23
use League\Csv\Config\Validator;
24
use LimitIterator;
25
26
/**
27
 * A class to extract and convert data from a CSV
28
 *
29
 * @package League.csv
30
 * @since  9.0.0
31
 *
32
 */
33
class RecordSet implements Countable, IteratorAggregate, JsonSerializable
34
{
35
    use Validator;
36
37
    /**
38
     * @var array
39
     */
40
    protected $header;
41
42
    /**
43
     * @var array
44
     */
45
    protected $flip_header;
46
47
    /**
48
     * @var Iterator
49
     */
50
    protected $iterator;
51
52
    /**
53
     * New Instance
54
     *
55
     * @param Iterator $iterator
56
     * @param array    $header
57
     */
58
    public function __construct(Iterator $iterator, array $header)
59
    {
60
        $this->iterator = $iterator;
61
        $this->header = $header;
62
        $this->flip_header = array_flip($header);
63
    }
64
65
    /**
66
     * @inheritdoc
67
     */
68
    public function __destruct()
69
    {
70
        $this->iterator = null;
71
    }
72
73
    /**
74
     * Returns a HTML table representation of the CSV Table
75
     *
76
     * @param string $class_attr optional classname
77
     *
78
     * @return string
79
     */
80
    public function toHTML($class_attr = 'table-csv-data')
81
    {
82
        $doc = $this->toXML('table', 'tr', 'td');
83
        $doc->documentElement->setAttribute('class', $class_attr);
84
85
        return $doc->saveHTML($doc->documentElement);
86
    }
87
88
    /**
89
     * Transforms a CSV into a XML
90
     *
91
     * @param string $root_name XML root node name
92
     * @param string $row_name  XML row node name
93
     * @param string $cell_name XML cell node name
94
     *
95
     * @return DOMDocument
96
     */
97
    public function toXML($root_name = 'csv', $row_name = 'row', $cell_name = 'cell')
98
    {
99
        $this->row_name = $this->validateString($row_name);
100
        $this->cell_name = $this->validateString($cell_name);
101
        $doc = new DOMDocument('1.0', 'UTF-8');
102
        $root = $doc->createElement($this->validateString($root_name));
103
        if (!empty($this->header)) {
104
            $root->appendChild($this->convertRecordToDOMNode($this->header, $doc));
105
        }
106
107
        foreach ($this->iterator as $row) {
108
            $root->appendChild($this->convertRecordToDOMNode($row, $doc));
109
        }
110
        $doc->appendChild($root);
111
112
        return $doc;
113
    }
114
115
    /**
116
     * @inheritdoc
117
     */
118
    public function getIterator()
119
    {
120
        return $this->iterator;
121
    }
122
123
    /**
124
     * @inheritdoc
125
     */
126
    public function count()
127
    {
128
        return iterator_count($this);
129
    }
130
131
    /**
132
     * @inheritdoc
133
     */
134
    public function jsonSerialize()
135
    {
136
        return $this->fetchAll();
137
    }
138
139
    /**
140
     * Returns a sequential array of all founded RecordSet
141
     *
142
     * @return array
143
     */
144
    public function fetchAll()
145
    {
146
        return iterator_to_array($this, false);
147
    }
148
149
    /**
150
     * Returns a single record from the recordSet
151
     *
152
     * @param int $offset the record offset relative to the RecordSet
153
     *
154
     * @return array
155
     */
156
    public function fetchOne($offset = 0)
157
    {
158
        $offset = $this->validateInteger($offset, 0, 'the submitted offset is invalid');
159
        $it = new LimitIterator($this->iterator, $offset, 1);
160
        $it->rewind();
161
162
        return (array) $it->current();
163
    }
164
165
    /**
166
     * Returns the next value from a specific record column
167
     *
168
     * By default if no column index is provided the first column of the founded RecordSet is returned
169
     *
170
     * @param string|int $column_index CSV column index or header field name
171
     *
172
     * @return Iterator
173
     */
174
    public function fetchColumn($column_index = 0)
175
    {
176
        $column_index = $this->filterFieldName($column_index, 'the column index value is invalid');
177
        $filter = function ($row) use ($column_index) {
178
            return isset($row[$column_index]);
179
        };
180
        $select = function ($row) use ($column_index) {
181
            return $row[$column_index];
182
        };
183
184
        return new MapIterator(new CallbackFilterIterator($this->iterator, $filter), $select);
185
    }
186
187
    /**
188
     * Filter a field name against the CSV header if any
189
     *
190
     * @param string|int $field         the field name or the field index
191
     * @param string     $error_message the associated error message
192
     *
193
     * @throws InvalidArgumentException if the field is invalid
194
     *
195
     * @return string|int
196
     */
197
    protected function filterFieldName($field, $error_message)
198
    {
199
        if (false !== array_search($field, $this->header, true)) {
200
            return $field;
201
        }
202
203
        $index = $this->validateInteger($field, 0, $error_message);
204
        if (empty($this->header)) {
205
            return $index;
206
        }
207
208
        if (false !== ($index = array_search($index, $this->flip_header, true))) {
209
            return $index;
210
        }
211
212
        throw new InvalidArgumentException($error_message);
213
    }
214
215
    /**
216
     * Fetches the next key-value pairs from a result set (first
217
     * column is the key, second column is the value).
218
     *
219
     * By default if no column index is provided:
220
     * - the first CSV column is used to provide the keys
221
     * - the second CSV column is used to provide the value
222
     *
223
     * @param string|int $offset_index The field index or name to serve as offset
224
     * @param string|int $value_index  The field index or name to serve as value
225
     *
226
     * @return Generator
227
     */
228
    public function fetchPairs($offset_index = 0, $value_index = 1)
229
    {
230
        $offset_index = $this->filterFieldName($offset_index, 'the offset column index is invalid');
231
        $value_index = $this->filterFieldName($value_index, 'the value column index is invalid');
232
        $filter = function ($row) use ($offset_index) {
233
            return isset($row[$offset_index]);
234
        };
235
        $select = function ($row) use ($offset_index, $value_index) {
236
            return [$row[$offset_index], isset($row[$value_index]) ? $row[$value_index] : null];
237
        };
238
239
        $iterator = new MapIterator(new CallbackFilterIterator($this->iterator, $filter), $select);
240
        foreach ($iterator as $row) {
241
            yield $row[0] => $row[1];
242
        }
243
    }
244
}
245