Reader   A
last analyzed

Complexity

Total Complexity 21

Size/Duplication

Total Lines 205
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 0
Metric Value
wmc 21
lcom 1
cbo 0
dl 0
loc 205
rs 10
c 0
b 0
f 0

8 Methods

Rating   Name   Duplication   Size   Complexity  
B __construct() 0 26 5
B next() 0 27 5
A readLine() 0 9 2
A current() 0 8 2
A key() 0 4 1
A rewind() 0 6 1
A valid() 0 8 3
A __destruct() 0 6 2
1
<?php
2
3
namespace SubjectivePHP\Csv;
4
5
/**
6
 * Simple class for reading delimited data files
7
 */
8
class Reader implements \Iterator
9
{
10
    /**
11
     * The column headers.
12
     *
13
     * @var array|null
14
     */
15
    private $headers;
16
17
    /**
18
     * The field delimiter (one character only).
19
     *
20
     * @var string
21
     */
22
    private $delimiter;
23
24
    /**
25
     *  The field enclosure character (one character only).
26
     *
27
     * @var string
28
     */
29
    private $enclosure;
30
31
    /**
32
     * The escape character (one character only).
33
     *
34
     * @var string
35
     */
36
    private $escapeChar;
37
38
    /**
39
     * File pointer to the csv file.
40
     *
41
     * @var resource
42
     */
43
    private $handle;
44
45
    /**
46
     * The current file pointer position.
47
     *
48
     * @var integer
49
     */
50
    private $position = 0;
51
52
    /**
53
     * The current row within the csv file.
54
     *
55
     * @var array|false|null
56
     */
57
    private $current = null;
58
59
    /**
60
     * Create a new Reader instance.
61
     *
62
     * @param string $file       The full path to the csv file.
63
     * @param array  $headers    The column headers. If null, the headers will be derived from the first line in the
64
     *                           file.
65
     * @param string $delimiter  The field delimiter (one character only).
66
     * @param string $enclosure  The field enclosure character (one character only).
67
     * @param string $escapeChar The escape character (one character only).
68
     *
69
     * @throws \InvalidArgumentException Thrown if $file is not readable.
70
     * @throws \InvalidArgumentException Thrown if $delimiter is a single character string.
71
     * @throws \InvalidArgumentException Thrown if $enclosure is a single character string.
72
     * @throws \InvalidArgumentException Thrown if $escapeChar is a single character string.
73
     */
74
    public function __construct($file, array $headers = null, $delimiter = ',', $enclosure = '"', $escapeChar = '\\')
75
    {
76
        if (!is_readable((string)$file)) {
77
            throw new \InvalidArgumentException(
78
                '$file must be a string containing a full path to a readable delimited file'
79
            );
80
        }
81
82
        if (strlen($delimiter) !== 1) {
83
            throw new \InvalidArgumentException('$delimiter must be a single character string');
84
        }
85
86
        if (strlen($enclosure) !== 1) {
87
            throw new \InvalidArgumentException('$enclosure must be a single character string');
88
        }
89
90
        if (strlen($escapeChar) !== 1) {
91
            throw new \InvalidArgumentException('$escapeChar must be a single character string');
92
        }
93
94
        $this->headers = $headers;
95
        $this->delimiter = $delimiter;
96
        $this->enclosure = $enclosure;
97
        $this->escapeChar = $escapeChar;
98
        $this->handle = fopen((string)$file, 'r');
99
    }
100
101
    /**
102
     * Advances to the next row in this csv reader
103
     *
104
     * @return mixed
105
     */
106
    public function next()
107
    {
108
        try {
109
            $raw = $this->readLine();
110
            if ($this->current !== null) {
111
                ++$this->position;
112
                $this->current = array_combine($this->headers, $raw);
113
            }
114
115
            if ($this->headers === null) {
116
                //No headers given, derive from first line of file
117
                $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...
118
                $this->current = array_combine($this->headers, $this->readLine());
119
                return;
120
            }
121
122
            //Headers given, skip first line if header line
123
            if ($raw === $this->headers) {
124
                $raw = $this->readLine();
125
            }
126
127
            $this->current = array_combine($this->headers, $raw);
128
        } catch (\Exception $e) {
129
            $this->current = false;
130
            return false;
131
        }
132
    }
133
134
    /**
135
     * Helper method to read the next line in the delimited file.
136
     *
137
     * @return array|false
138
     *
139
     * @throws \Exception Thrown if no data is returned when reading the file.
140
     */
141
    private function readLine()
142
    {
143
        $raw = fgetcsv($this->handle, 0, $this->delimiter, $this->enclosure, $this->escapeChar);
144
        if (empty($raw)) {
145
            throw new \Exception('Empty line read');
146
        }
147
148
        return $raw;
149
    }
150
151
    /**
152
     * Return the current element.
153
     *
154
     * @return array returns array containing values from the current row
155
     */
156
    public function current()
157
    {
158
        if ($this->current === null) {
159
            $this->next();
160
        }
161
162
        return $this->current;
163
    }
164
165
    /**
166
     * Return the key of the current element.
167
     *
168
     * @return integer
169
     */
170
    public function key()
171
    {
172
        return $this->position;
173
    }
174
175
    /**
176
     * Rewind the Iterator to the first element.
177
     *
178
     * @return void
179
     */
180
    public function rewind()
181
    {
182
        rewind($this->handle);
183
        $this->position = 0;
184
        $this->current = null;
185
    }
186
187
    /**
188
     * Check if there is a current element after calls to rewind() or next().
189
     *
190
     * @return bool true if there is a current element, false otherwise
191
     */
192
    public function valid()
193
    {
194
        if ($this->current === null) {
195
            $this->next();
196
        }
197
198
        return !feof($this->handle) && $this->current !== false;
199
    }
200
201
    /**
202
     * Ensure file handles are closed when all references to this reader are destroyed.
203
     *
204
     * @return void
205
     */
206
    public function __destruct()
207
    {
208
        if (is_resource($this->handle)) {
209
            fclose($this->handle);
210
        }
211
    }
212
}
213