1 | <?php |
||
5 | class ReaderDataset implements \Iterator |
||
6 | { |
||
7 | const DATASETBR_STATE_FILE = 'https://raw.githubusercontent.com/datasets-br/state-codes/master/data/br-state-codes.csv'; |
||
8 | |||
9 | private $states; |
||
10 | |||
11 | private $separator = ','; |
||
12 | private $enclosure = '"'; |
||
13 | private $escape = '\\'; |
||
14 | /** |
||
15 | * @var string |
||
16 | */ |
||
17 | private $filepath; |
||
18 | |||
19 | 1 | public function __construct($filepath) |
|
20 | { |
||
21 | 1 | $this->states = new \ArrayIterator(); |
|
22 | |||
23 | 1 | if (empty($filepath)) { |
|
24 | $filepath = self::DATASETBR_STATE_FILE; |
||
25 | } |
||
26 | |||
27 | 1 | $this->filepath = $filepath; |
|
28 | 1 | } |
|
29 | |||
30 | 1 | public function read() |
|
31 | { |
||
32 | 1 | $resource = fopen($this->filepath, 'r'); |
|
33 | 1 | $states = []; |
|
34 | 1 | $skipFirst = true; |
|
35 | |||
36 | 1 | while (!feof($resource)) { |
|
37 | 1 | $state = $this->readLine($resource); |
|
38 | 1 | if ($state->isState() && !$skipFirst) { |
|
39 | 1 | $states[] = $state; |
|
40 | } |
||
41 | 1 | $skipFirst = false; |
|
42 | } |
||
43 | |||
44 | 1 | $this->states = new \ArrayIterator($states); |
|
45 | 1 | $this->rewind(); |
|
46 | 1 | } |
|
47 | |||
48 | /** |
||
49 | * @param $resource |
||
50 | * |
||
51 | * @return GenericState |
||
52 | */ |
||
53 | 1 | private function readLine($resource) |
|
54 | { |
||
55 | 1 | $line = fgetcsv($resource, null, $this->separator, $this->enclosure, $this->escape); |
|
56 | |||
57 | 1 | return new GenericState($line[4], $line[1], $line[0], $line[9]); |
|
58 | } |
||
59 | |||
60 | public function current() |
||
64 | |||
65 | 1 | public function next() |
|
66 | { |
||
67 | 1 | $this->states->next(); |
|
69 | |||
70 | 1 | public function key() |
|
74 | |||
75 | 1 | public function valid() |
|
79 | |||
80 | 1 | public function rewind() |
|
84 | } |
||
85 |