-
Notifications
You must be signed in to change notification settings - Fork 111
Expand file tree
/
Copy pathCsvSource.php
More file actions
415 lines (369 loc) · 9.35 KB
/
CsvSource.php
File metadata and controls
415 lines (369 loc) · 9.35 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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
<?php
/**
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2009, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2009, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @since CakePHP Datasources v 0.3
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*
* A CakePHP datasource for interacting with files using comma separated value storage.
*
* Create a datasource in your config/database.php
* public $csvfile = array(
* 'datasource' => 'Datasources.CsvSource',
* 'path' => '/path/to/file', // Path
* 'extension' => 'csv', // File extension
* 'readonly' => true, // Mark for read only access
* 'recursive' => false // Only false is supported at the moment
* 'delimiter' => ',', // File delimiter
* 'encoding' => 'UTF8' // File convert to encode
* );
*/
App::uses('DataSource', 'Model/Datasource');
App::uses('Folder', 'Utility');
/**
* Comma Separated Values Datasource
*
*/
class CsvSource extends DataSource {
/**
* Description
*
* @var string
*/
public $description = 'CSV Data Source';
/**
* Column delimiter
*
* @var string
*/
public $delimiter = ';';
/**
* Maximum Columns
*
* @var integer
*/
public $maxCol = 0;
/**
* Field Names
*
* @var mixed
*/
public $fields = null;
/**
* File Handle
*
* @var mixed
*/
public $handle = false;
/**
* Page to start on
*
* @var integer
*/
public $page = 1;
/**
* Limit of records
*
* @var integer
*/
public $limit = 99999;
/**
* Default configuration.
*
* @var array
*/
protected $_baseConfig = array(
'datasource' => 'csv',
'path' => '.',
'extension' => 'csv',
'readonly' => true,
'recursive' => false
);
/**
* Constructor
*
* @param string $config Configuration array
* @param boolean $autoConnect Automatically connect to / open the file
*/
public function __construct($config = null, $autoConnect = true) {
$this->debug = Configure::read('debug') > 0;
$this->fullDebug = Configure::read('debug') > 1;
parent::__construct($config);
if ($autoConnect) {
$this->connect();
}
}
/**
* Connects to the mailbox using options in the given configuration array.
*
* @return boolean True if the file could be opened.
*/
public function connect() {
$this->connected = false;
if ($this->config['readonly']) {
$create = false;
$mode = 0;
} else {
$create = true;
$mode = 0777;
}
$this->connection = new Folder($this->config['path'], $create, $mode);
if ($this->connection) {
$this->handle = array();
$this->connected = true;
}
return $this->connected;
}
/**
* List available sources
*
* @return array of available CSV files
*/
public function listSources($data = null) {
$this->config['database'] = 'csv';
$cache = parent::listSources();
if ($cache !== null) {
return $cache;
}
$extPattern = '\.' . preg_quote($this->config['extension']);
if ($this->config['recursive']) {
$list = $this->connection->findRecursive('.*' . $extPattern, true);
foreach ($list as &$item) {
$item = mb_substr($item, mb_strlen($this->config['path'] . DS));
}
} else {
$list = $this->connection->find('.*' . $extPattern, true);
}
foreach ($list as &$item) {
$item = preg_replace('/' . $extPattern . '$/i', '', $item);
}
parent::listSources($list);
unset($this->config['database']);
return $list;
}
/**
* Returns a Model description (metadata) or null if none found.
*
* @return mixed
*/
public function describe($model) {
$this->_getDescriptionFromFirstLine($model);
return $this->fields;
}
/**
* Get Description from First Line, and store into class vars
*
* @param Model $model
* @return boolean True, Success
*/
protected function _getDescriptionFromFirstLine(Model $model) {
$filename = $model->table . '.' . $this->config['extension'];
$handle = fopen($this->config['path'] . DS . $filename, 'r');
$line = rtrim(fgets($handle));
$this->delimiter = isset($this->config['delimiter']) ? $this->config['delimiter'] : $this->delimiter;
$data = explode($this->delimiter, $line);
if (isset($this->config['encoding'])) {
mb_convert_variables($this->config['encoding'], "ASCII,UTF-8,SJIS-win", $data);
}
$this->fields = $data;
$this->maxCol = count($data);
fclose($handle);
return true;
}
/**
* Close file handle
*
* @return null
*/
public function close() {
if ($this->connected) {
if (!empty($this->handle)) {
foreach ($this->handle as $h) {
@fclose($h);
}
$this->handle = false;
}
$this->connected = false;
}
}
/**
* Read Data
*
* @param Model $model
* @param array $queryData
* @param integer $recursive Number of levels of association
* @return mixed
*/
public function read(Model $model, $queryData = array(), $recursive = null) {
$this->describe($model);
$config = $this->config;
$filename = $config['path'] . DS . $model->table . '.' . $config['extension'];
if (!Set::extract($this->handle, $model->table)) {
$this->handle[$model->table] = fopen($filename, 'r');
} else {
fseek($this->handle[$model->table], 0, SEEK_SET);
}
$queryData = $this->_scrubQueryData($queryData);
if (isset($queryData['limit']) && !empty($queryData['limit'])) {
$this->limit = $queryData['limit'];
}
if (isset($queryData['page']) && !empty($queryData['page'])) {
$this->page = $queryData['page'];
}
if (empty($queryData['fields'])) {
$fields = $this->fields;
$allFields = true;
} else {
$fields = $queryData['fields'];
$allFields = false;
$_fieldIndex = array();
$index = 0;
// generate an index array of all wanted fields
foreach ($this->fields as $field) {
if (in_array($field, $fields)) {
$_fieldIndex[] = $index;
}
$index++;
}
}
$lineCount = 0;
$recordCount = 0;
$findCount = 0;
$resultSet = array();
while (($data = fgetcsv($this->handle[$model->table], 8192, $this->delimiter)) !== false) {
if ($lineCount === 0) {
$lineCount++;
continue;
}
// Skip over records, that are not complete
if (count($data) < $this->maxCol) {
continue;
}
$record = array();
$i = 0;
foreach ((array)$this->fields as $field) {
$record[$model->alias][$field] = $data[$i++];
}
if ($this->_checkConditions($record, $queryData['conditions'], $model)) {
// Compute the virtual pagenumber
$page = floor($findCount / $this->limit) + 1;
if ($this->page <= $page) {
if (!$allFields) {
$record = array();
if (count($_fieldIndex) > 0) {
foreach ($_fieldIndex as $i) {
$record[$model->alias][$this->fields[$i]] = $data[$i];
}
}
}
$resultSet[] = $record;
$recordCount++;
}
}
unset($record);
$findCount++;
if ($recordCount >= $this->limit) {
break;
}
}
if ($model->findQueryType === 'count') {
return array(array(array('count' => count($resultSet))));
}
if (isset($this->config['encoding'])) {
mb_convert_variables($this->config['encoding'], "ASCII,UTF-8,SJIS-win", $resultSet);
return $resultSet;
}
return $resultSet;
}
/**
* Helper method to remove query metadata in given data array.
*
* @param array $data Data
* @return array Cleaned Data
*/
protected function _scrubQueryData($data) {
foreach (array('conditions', 'fields', 'joins', 'order', /*'limit', 'offset',*/ 'group') as $key) {
if (!isset($data[$key]) || empty($data[$key])) {
$data[$key] = array();
}
}
if (!isset($data['limit']) || empty($data['limit'])) {
$data['limit'] = PHP_INT_MAX;
}
if (!isset($data['offset']) || empty($data['offset'])) {
$data['offset'] = 0;
}
return $data;
}
/**
* Helper method to check conditions.
*
* @param array $record
* @param array $conditions
* @return boolean
*/
protected function _checkConditions($record, $conditions, $model) {
$result = true;
foreach ($conditions as $name => $value) {
$alias = $model->alias;
if (strpos($name, '.') !== false) {
list($alias, $name) = explode('.', $name);
}
if (strtolower($name) === 'or') {
$cond = $value;
$result = false;
foreach ($cond as $name => $value) {
list($condAlias, $name) = pluginSplit($name);
if (is_array($value)) {
foreach ($value as $val) {
if (Set::matches($this->_createRule($name, $val), $record[$alias])) {
$result = true;
}
}
} else {
if (Set::matches($this->_createRule($name, $value), $record[$alias])) {
$result = true;
}
}
}
} else {
if (!Set::matches($this->_createRule($name, $value), $record[$alias])) {
return false;
}
}
}
return $result;
}
/**
* Helper method to crete rule.
*
* @param string $name
* @param string $value
* @return string
*/
protected function _createRule($name, $value) {
if (strpos($name, ' ') !== false) {
return array(str_replace(' ', '', $name) . $value);
}
return array("{$name}={$value}");
}
/**
* Calculate
*
* @param Model $model
* @param mixed $func
* @param array $params
* @return array
*/
public function calculate(Model $model, $func, $params = array()) {
return array('count' => true);
}
}