1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace ByJG\AnyDataset\Dataset; |
4
|
|
|
|
5
|
|
|
use ByJG\AnyDataset\Exception\DatasetException; |
6
|
|
|
use ByJG\AnyDataset\Exception\NotFoundException; |
7
|
|
|
use Exception; |
8
|
|
|
use InvalidArgumentException; |
9
|
|
|
|
10
|
|
|
class TextFileDataset |
11
|
|
|
{ |
12
|
|
|
|
13
|
|
|
const CSVFILE = '/[|,;](?=(?:[^"]*"[^"]*")*(?![^"]*"))/'; |
14
|
|
|
const CSVFILE_SEMICOLON = '/[;](?=(?:[^"]*"[^"]*")*(?![^"]*"))/'; |
15
|
|
|
const CSVFILE_COMMA = '/[,](?=(?:[^"]*"[^"]*")*(?![^"]*"))/'; |
16
|
|
|
|
17
|
|
|
protected $source; |
18
|
|
|
protected $fields; |
19
|
|
|
protected $fieldexpression; |
20
|
|
|
protected $sourceType; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* Text File Data Set |
24
|
|
|
* |
25
|
|
|
* @param string $source |
26
|
|
|
* @param array $fields |
27
|
|
|
* @param string $fieldexpression |
28
|
|
|
* @throws NotFoundException |
29
|
|
|
*/ |
30
|
15 |
|
public function __construct($source, $fields, $fieldexpression = null) |
31
|
|
|
{ |
32
|
15 |
|
if (is_null($fieldexpression)) { |
33
|
|
|
$fieldexpression = TextFileDataset::CSVFILE; |
34
|
|
|
} |
35
|
|
|
|
36
|
15 |
|
if (!is_array($fields)) { |
37
|
|
|
throw new InvalidArgumentException("You must define an array of fields."); |
38
|
|
|
} |
39
|
15 |
|
if (!preg_match('~(http|https|ftp)://~', $source)) { |
40
|
9 |
|
$this->source = $source; |
41
|
|
|
|
42
|
9 |
|
if (!file_exists($this->source)) { |
43
|
1 |
|
throw new NotFoundException("The specified file " . $this->source . " does not exists"); |
44
|
|
|
} |
45
|
|
|
|
46
|
8 |
|
$this->sourceType = "FILE"; |
47
|
|
|
} else { |
48
|
6 |
|
$this->source = $source; |
49
|
6 |
|
$this->sourceType = "HTTP"; |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
|
53
|
14 |
|
$this->fields = $fields; |
54
|
|
|
|
55
|
14 |
|
if ($fieldexpression == 'CSVFILE') { |
56
|
|
|
$this->fieldexpression = TextFileDataset::CSVFILE; |
57
|
|
|
} else { |
58
|
14 |
|
$this->fieldexpression = $fieldexpression; |
59
|
|
|
} |
60
|
14 |
|
} |
61
|
|
|
|
62
|
|
|
/** |
63
|
|
|
* @access public |
64
|
|
|
* @return GenericIterator |
65
|
|
|
* @throws DatasetException |
66
|
|
|
* @throws Exception |
67
|
|
|
*/ |
68
|
14 |
|
public function getIterator() |
69
|
|
|
{ |
70
|
14 |
|
$old = ini_set('auto_detect_line_endings', true); |
71
|
14 |
|
$handle = @fopen($this->source, "r"); |
72
|
14 |
|
ini_set('auto_detect_line_endings', $old); |
73
|
14 |
|
if (!$handle) { |
74
|
2 |
|
throw new DatasetException("TextFileDataset failed to open resource"); |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
try { |
78
|
12 |
|
$iterator = new TextFileIterator($handle, $this->fields, $this->fieldexpression); |
79
|
12 |
|
return $iterator; |
80
|
|
|
} catch (Exception $ex) { |
81
|
|
|
fclose($handle); |
82
|
|
|
throw $ex; |
83
|
|
|
} |
84
|
|
|
} |
85
|
|
|
} |
86
|
|
|
|