-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathTable.php
More file actions
271 lines (240 loc) · 8.71 KB
/
Table.php
File metadata and controls
271 lines (240 loc) · 8.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
<?php
namespace frictionlessdata\tableschema;
use frictionlessdata\tableschema\DataSources\CsvDataSource;
use frictionlessdata\tableschema\Exceptions\DataSourceException;
/**
* represents a data source which validates against a table schema
* provides interfaces for validating the data and iterating over it
* casts all values to their native values according to the table schema.
*/
class Table implements \Iterator
{
public $csvDialect;
/**
* @param DataSources\DataSourceInterface $dataSource
* @param Schema $schema
* @param object $csvDialect
*
* @throws Exceptions\DataSourceException
*/
public function __construct($dataSource, $schema = null, $csvDialect = null)
{
$this->csvDialect = new CsvDialect($csvDialect);
if (!is_a($dataSource, 'frictionlessdata\\tableschema\\DataSources\\BaseDataSource')) {
// TODO: more advanced data source detection
$dataSource = new CsvDataSource($dataSource);
}
if (is_a($dataSource, 'frictionlessdata\\tableschema\\DataSources\\CsvDataSource')) {
$dataSource->setCsvDialect($this->csvDialect);
}
$this->dataSource = $dataSource;
if (!is_a($schema, 'frictionlessdata\\tableschema\\Schema')) {
if ($schema) {
$schema = new Schema($schema);
} else {
$schema = new InferSchema();
}
}
$this->schema = $schema;
$this->dataSource->open();
$this->uniqueFieldValues = [];
}
/**
* @param DataSources\DataSourceInterface $dataSource
* @param Schema $schema
* @param int $numPeekRows
*
* @return array of validation errors
*/
public static function validate($dataSource, $schema, $numPeekRows = 10, $csvDialect = null)
{
try {
$table = new static($dataSource, $schema, $csvDialect);
} catch (Exceptions\DataSourceException $e) {
return [new SchemaValidationError(SchemaValidationError::LOAD_FAILED, $e->getMessage())];
}
if ($numPeekRows > 0) {
$i = 0;
try {
foreach ($table as $row) {
if (++$i > $numPeekRows) {
break;
}
}
} catch (Exceptions\DataSourceException $e) {
// general error in getting the next row from the data source
return [new SchemaValidationError(SchemaValidationError::ROW_VALIDATION, [
'row' => $i,
'error' => $e->getMessage(),
])];
} catch (Exceptions\FieldValidationException $e) {
// validation error in one of the fields
return array_map(function ($validationError) use ($i) {
return new SchemaValidationError(SchemaValidationError::ROW_FIELD_VALIDATION, [
'row' => $i + 1,
'field' => $validationError->extraDetails['field'],
'error' => $validationError->extraDetails['error'],
'value' => $validationError->extraDetails['value'],
]);
}, $e->validationErrors);
}
}
return [];
}
public function schema($numPeekRows = 10)
{
$this->ensureInferredSchema($numPeekRows);
return $this->schema;
}
public function headers($numPeekRows = 10)
{
$this->ensureInferredSchema($numPeekRows);
return array_keys($this->schema->fields());
}
public function read($options = null)
{
$options = array_merge([
'keyed' => true,
'extended' => false,
'cast' => true,
'limit' => null,
], $options ? $options : []);
$rows = [];
$rowNum = 0;
if ($options['extended']) {
$headers = $this->headers($options['limit'] ? $options['limit'] : null);
}
if (!$options['cast']) {
$this->dataSource->open();
while (!$this->dataSource->isEof()) {
$row = $this->dataSource->getNextLine();
if ($options['extended']) {
$rows[] = [$rowNum, $headers, array_values($row)];
} else {
$rows[] = $row;
}
if ($options['limit'] && $options['limit'] > 0 && $rowNum + 1 >= $options['limit']) {
break;
}
++$rowNum;
}
} else {
foreach ($this as $row) {
if ($options['extended']) {
$rows[] = [$rowNum, $headers, array_values($row)];
} else {
$rows[] = $row;
}
if ($options['limit'] && $options['limit'] > 0 && $rowNum + 1 >= $options['limit']) {
break;
}
++$rowNum;
}
}
return $rows;
}
public function save($outputDataSource)
{
return $this->dataSource->save($outputDataSource);
}
/**
* called on each iteration to get the next row
* does validation and casting on the row.
*
* @return mixed[]
*
* @throws Exceptions\FieldValidationException
* @throws Exceptions\DataSourceException
*/
public function current(): array
{
if (count($this->castRows) > 0) {
$row = array_shift($this->castRows);
} else {
$row = $this->schema->castRow($this->dataSource->getNextLine());
foreach ($this->schema->fields() as $field) {
if ($field->unique()) {
$fieldName = $field->name();
$value = $row[$fieldName];
if (
array_key_exists($fieldName, $this->uniqueFieldValues)
&& in_array($value, $this->uniqueFieldValues[$fieldName], false)
) {
throw new DataSourceException('field must be unique', $this->currentLine);
}
$this->uniqueFieldValues[$fieldName][] = $value;
}
}
$pkRowValues = [];
foreach ($this->schema->primaryKey() as $key) {
$value = $row[$key];
if (null === $value) {
throw new DataSourceException('value for '.$key.' field cannot be null because it is part of the primary key', $this->currentLine);
}
$pkRowValues[$key] = $value;
}
if ([] !== $pkRowValues) {
if (in_array($pkRowValues, $this->primaryKeyValues, false)) {
throw new DataSourceException('duplicate row for the primary key '.implode('/', array_keys($pkRowValues)), $this->currentLine);
}
$this->primaryKeyValues[] = $pkRowValues;
}
}
return $row;
}
// not interesting, standard iterator functions
// to simplify we prevent rewinding - so you can only iterate once
public function __destruct()
{
$this->dataSource->close();
}
public function rewind(): void
{
if (0 == $this->currentLine) {
$this->currentLine = 1;
} elseif (0 == count($this->castRows)) {
$this->currentLine = 1;
$this->dataSource->open();
}
}
public function key(): int
{
return $this->currentLine - count($this->castRows);
}
public function next(): void
{
if (0 == count($this->castRows)) {
++$this->currentLine;
}
}
public function valid(): bool
{
return count($this->castRows) > 0 || !$this->dataSource->isEof();
}
protected $currentLine = 0;
protected $dataSource;
protected $schema;
protected $uniqueFieldValues;
protected $primaryKeyValues = [];
protected $castRows = [];
protected function isInferSchema()
{
return is_a($this->schema, 'frictionlessdata\\tableschema\\InferSchema');
}
protected function ensureInferredSchema($numPeekRows = 10)
{
if ($this->isInferSchema() && 0 == count($this->schema->fields())) {
// need to fetch some rows first
if ($numPeekRows > 0) {
$i = 0;
foreach ($this as $row) {
if (++$i > $numPeekRows) {
break;
}
}
// these rows will be returned by next current() call
$this->castRows = $this->schema->lock();
}
}
}
}