Completed
Pull Request — master (#8)
by Antonio Oertel
04:37 queued 01:48
created

ReaderDataset::readLine()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
ccs 0
cts 3
cp 0
cc 1
eloc 3
nc 1
nop 1
crap 2
1
<?php
2
3
namespace Brazanation\States\Console\Commands\Generate;
4
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
    public function __construct($filepath)
20
    {
21
        $this->states = new \ArrayIterator();
22
23
        if (empty($filepath)) {
24
            $filepath = self::DATASETBR_STATE_FILE;
25
        }
26
27
        $this->filepath = $filepath;
28
    }
29
30
    public function read()
31
    {
32
        $resource = fopen($this->filepath, 'r');
33
        $states = [];
34
        $skipFirst = true;
35
36
        while (!feof($resource)) {
37
            $state = $this->readLine($resource);
38
            if ($state->isState() && !$skipFirst) {
39
                $states[] = $state;
40
            }
41
            $skipFirst = false;
42
        }
43
44
        $this->states = new \ArrayIterator($states);
45
        $this->rewind();
46
    }
47
48
    /**
49
     * @param $resource
50
     *
51
     * @return GenericState
52
     */
53
    private function readLine($resource)
54
    {
55
        $line = fgetcsv($resource, null, $this->separator, $this->enclosure, $this->escape);
56
57
        return new GenericState($line[4], $line[1], $line[0], $line[9]);
58
    }
59
60
    public function current()
61
    {
62
        return $this->states->current();
63
    }
64
65
    public function next()
66
    {
67
        $this->states->next();
68
    }
69
70
    public function key()
71
    {
72
        return $this->states->key();
73
    }
74
75
    public function valid()
76
    {
77
        return $this->states->valid();
78
    }
79
80
    public function rewind()
81
    {
82
        $this->states->rewind();
83
    }
84
}
85