Failed Conditions
Pull Request — master (#6)
by Chad
02:38
created

Reader::next()   B

Complexity

Conditions 5
Paths 16

Size

Total Lines 27
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 27
rs 8.439
c 0
b 0
f 0
cc 5
eloc 16
nc 16
nop 0
1
<?php
2
3
namespace SubjectivePHP\Csv;
4
5
use SplFileObject;
6
7
/**
8
 * Simple class for reading delimited data files
9
 */
10
class Reader implements \Iterator
11
{
12
    /**
13
     * The column headers.
14
     *
15
     * @var array|null
16
     */
17
    private $headers;
18
19
    /**
20
     * The current file pointer position.
21
     *
22
     * @var integer
23
     */
24
    private $position = 0;
25
26
    /**
27
     * The current row within the csv file.
28
     *
29
     * @var array|false|null
30
     */
31
    private $current = null;
32
33
    /**
34
     * @var SplFileObject
35
     */
36
    private $fileObject;
37
38
    /**
39
     * Create a new Reader instance.
40
     *
41
     * @param string $file       The full path to the csv file.
42
     * @param array  $headers    The column headers. If null, the headers will be derived from the first line in the
43
     *                           file.
44
     * @param string $delimiter  The field delimiter (one character only).
45
     * @param string $enclosure  The field enclosure character (one character only).
46
     * @param string $escapeChar The escape character (one character only).
47
     *
48
     * @throws \InvalidArgumentException Thrown if $file is not readable.
49
     * @throws \InvalidArgumentException Thrown if $delimiter is a single character string.
50
     * @throws \InvalidArgumentException Thrown if $enclosure is a single character string.
51
     * @throws \InvalidArgumentException Thrown if $escapeChar is a single character string.
52
     */
53
    public function __construct(
54
        string $file,
55
        array $headers = null,
56
        string $delimiter = ',',
57
        string $enclosure = '"',
58
        string $escapeChar = '\\'
59
    ) {
60
        if (!is_readable($file)) {
61
            throw new \InvalidArgumentException(
62
                '$file must be a string containing a full path to a readable delimited file'
63
            );
64
        }
65
66
        if (strlen($delimiter) !== 1) {
67
            throw new \InvalidArgumentException('$delimiter must be a single character string');
68
        }
69
70
        if (strlen($enclosure) !== 1) {
71
            throw new \InvalidArgumentException('$enclosure must be a single character string');
72
        }
73
74
        if (strlen($escapeChar) !== 1) {
75
            throw new \InvalidArgumentException('$escapeChar must be a single character string');
76
        }
77
78
        $this->headers = $headers;
79
        $this->fileObject = new SplFileObject($file);
80
        $this->fileObject->setFlags(SplFileObject::READ_CSV);
81
        $this->fileObject->setCsvControl($delimiter, $enclosure, $escapeChar);
82
    }
83
84
    public function getFilePath() : string
85
    {
86
        return $this->fileObject->getRealPath();
87
    }
88
89
    /**
90
     * Advances to the next row in this csv reader
91
     *
92
     * @return mixed
93
     */
94
    public function next()
95
    {
96
        try {
97
            $raw = $this->readLine();
98
            if ($this->current !== null) {
99
                ++$this->position;
100
                $this->current = array_combine($this->headers, $raw);
101
            }
102
103
            if ($this->headers === null) {
104
                //No headers given, derive from first line of file
105
                $this->headers = $raw;
0 ignored issues
show
Documentation Bug introduced by
It seems like $raw can also be of type false. However, the property $headers is declared as type array|null. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
106
                $this->current = array_combine($this->headers, $this->readLine());
107
                return;
108
            }
109
110
            //Headers given, skip first line if header line
111
            if ($raw === $this->headers) {
112
                $raw = $this->readLine();
113
            }
114
115
            $this->current = array_combine($this->headers, $raw);
116
        } catch (\Exception $e) {
117
            $this->current = false;
118
            return false;
119
        }
120
    }
121
122
    /**
123
     * Helper method to read the next line in the delimited file.
124
     *
125
     * @return array|false
126
     *
127
     * @throws \Exception Thrown if no data is returned when reading the file.
128
     */
129
    private function readLine()
130
    {
131
        $raw = $this->fileObject->fgetcsv();
132
        if (empty($raw)) {
133
            throw new \Exception('Empty line read');
134
        }
135
136
        return $raw;
137
    }
138
139
    /**
140
     * Return the current element.
141
     *
142
     * @return array returns array containing values from the current row
143
     */
144
    public function current()
145
    {
146
        if ($this->current === null) {
147
            $this->next();
148
        }
149
150
        return $this->current;
151
    }
152
153
    /**
154
     * Return the key of the current element.
155
     *
156
     * @return integer
157
     */
158
    public function key()
159
    {
160
        return $this->position;
161
    }
162
163
    /**
164
     * Rewind the Iterator to the first element.
165
     *
166
     * @return void
167
     */
168
    public function rewind()
169
    {
170
        $this->fileObject->rewind();
171
        $this->position = 0;
172
        $this->current = null;
173
    }
174
175
    /**
176
     * Check if there is a current element after calls to rewind() or next().
177
     *
178
     * @return bool true if there is a current element, false otherwise
179
     */
180
    public function valid()
181
    {
182
        if ($this->current === null) {
183
            $this->next();
184
        }
185
186
        return !$this->fileObject->eof() && $this->current !== false;
187
    }
188
189
    /**
190
     * Ensure file handles are closed when all references to this reader are destroyed.
191
     *
192
     * @return void
193
     */
194
    public function __destruct()
195
    {
196
        $this->fileObject = null;
197
    }
198
}
199