Completed
Pull Request — master (#6)
by Chad
01:26
created

Reader::__destruct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
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).
0 ignored issues
show
Bug introduced by
There is no parameter named $delimiter. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
45
     * @param string $enclosure  The field enclosure character (one character only).
0 ignored issues
show
Bug introduced by
There is no parameter named $enclosure. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
46
     * @param string $escapeChar The escape character (one character only).
0 ignored issues
show
Bug introduced by
There is no parameter named $escapeChar. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
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(string $file, array $headers = null, CsvOptions $options = null)
54
    {
55
        if (!is_readable($file)) {
56
            throw new \InvalidArgumentException(
57
                '$file must be a string containing a full path to a readable delimited file'
58
            );
59
        }
60
61
        $this->headers = $headers;
62
        $options = $options ?? new CsvOptions();
63
        $this->fileObject = new SplFileObject($file);
64
        $this->fileObject->setFlags(SplFileObject::READ_CSV);
65
        $this->fileObject->setCsvControl($options->getDelimiter(), $options->getEnclosure(), $options->getEscapeChar());
66
    }
67
68
    public function getFilePath() : string
69
    {
70
        return $this->fileObject->getRealPath();
71
    }
72
73
    /**
74
     * Advances to the next row in this csv reader
75
     *
76
     * @return mixed
77
     */
78
    public function next()
79
    {
80
        try {
81
            $raw = $this->readLine();
82
            if ($this->current !== null) {
83
                ++$this->position;
84
                $this->current = array_combine($this->headers, $raw);
85
            }
86
87
            if ($this->headers === null) {
88
                //No headers given, derive from first line of file
89
                $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...
90
                $this->current = array_combine($this->headers, $this->readLine());
91
                return;
92
            }
93
94
            //Headers given, skip first line if header line
95
            if ($raw === $this->headers) {
96
                $raw = $this->readLine();
97
            }
98
99
            $this->current = array_combine($this->headers, $raw);
100
        } catch (\Exception $e) {
101
            $this->current = false;
102
            return false;
103
        }
104
    }
105
106
    /**
107
     * Helper method to read the next line in the delimited file.
108
     *
109
     * @return array|false
110
     *
111
     * @throws \Exception Thrown if no data is returned when reading the file.
112
     */
113
    private function readLine()
114
    {
115
        $raw = $this->fileObject->fgetcsv();
116
        if (empty($raw)) {
117
            throw new \Exception('Empty line read');
118
        }
119
120
        return $raw;
121
    }
122
123
    /**
124
     * Return the current element.
125
     *
126
     * @return array returns array containing values from the current row
127
     */
128
    public function current()
129
    {
130
        if ($this->current === null) {
131
            $this->next();
132
        }
133
134
        return $this->current;
135
    }
136
137
    /**
138
     * Return the key of the current element.
139
     *
140
     * @return integer
141
     */
142
    public function key()
143
    {
144
        return $this->position;
145
    }
146
147
    /**
148
     * Rewind the Iterator to the first element.
149
     *
150
     * @return void
151
     */
152
    public function rewind()
153
    {
154
        $this->fileObject->rewind();
155
        $this->position = 0;
156
        $this->current = null;
157
    }
158
159
    /**
160
     * Check if there is a current element after calls to rewind() or next().
161
     *
162
     * @return bool true if there is a current element, false otherwise
163
     */
164
    public function valid()
165
    {
166
        if ($this->current === null) {
167
            $this->next();
168
        }
169
170
        return !$this->fileObject->eof() && $this->current !== false;
171
    }
172
173
    /**
174
     * Ensure file handles are closed when all references to this reader are destroyed.
175
     *
176
     * @return void
177
     */
178
    public function __destruct()
179
    {
180
        $this->fileObject = null;
181
    }
182
}
183