Completed
Pull Request — master (#2)
by
unknown
03:18
created

ExcelReader::rewind()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 6
cts 6
cp 1
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 0
crap 2
1
<?php
2
/*
3
The MIT License (MIT)
4
5
Copyright (c) 2015 PortPHP
6
7
Permission is hereby granted, free of charge, to any person obtaining a copy
8
of this software and associated documentation files (the "Software"), to deal
9
in the Software without restriction, including without limitation the rights
10
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
copies of the Software, and to permit persons to whom the Software is
12
furnished to do so, subject to the following conditions:
13
14
The above copyright notice and this permission notice shall be included in all
15
copies or substantial portions of the Software.
16
17
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23
SOFTWARE.
24
 */
25
namespace Port\Excel;
26
27
use PhpOffice\PhpSpreadsheet\IOFactory;
28
use PhpOffice\PhpSpreadsheet\Spreadsheet;
29
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
30
use Port\Reader\CountableReader;
31
32
/**
33
 * Reads Excel files with the help of PHPExcel
34
 *
35
 * PHPExcel must be installed.
36
 *
37
 * @author David de Boer <[email protected]>
38
 *
39
 * @see http://phpexcel.codeplex.com/
40
 * @see https://github.com/logiQ/PHPExcel
41
 */
42
class ExcelReader implements CountableReader, \SeekableIterator
43
{
44
    /**
45
     * @var array
46
     */
47
    protected $columnHeaders;
48
49
    /**
50
     * Total number of rows
51
     *
52
     * @var int
53
     */
54
    protected $count;
55
56
    /**
57
     * @var int
58
     */
59
    protected $headerRowNumber;
60
61
    /**
62
     * @var int
63
     */
64
    protected $pointer = 0;
65
66
    /**
67
     * @var array
68
     */
69
    protected $worksheet;
70
71
    // phpcs:disable Generic.Files.LineLength.MaxExceeded
72
    /**
73
     * @param \SplFileObject $file            Excel file
74
     * @param int            $headerRowNumber Optional number of header row
75
     * @param int            $activeSheet     Index of active sheet to read from
76
     * @param bool           $readOnly        If set to false, the reader take care of the excel formatting (slow)
77
     * @param int            $maxRows         Maximum number of rows to read
78
     */
79 11
    public function __construct(\SplFileObject $file, $headerRowNumber = null, $activeSheet = null, $readOnly = true, $maxRows = null)
80
    {
81
        // phpcs:enable Generic.Files.LineLength.MaxExceeded
82 11
        $reader = IOFactory::createReaderForFile($file->getPathName());
83 11
        $reader->setReadDataOnly($readOnly);
84
        /** @var Spreadsheet $excel */
85 11
        $excel = $reader->load($file->getPathname());
86
87 11
        if (null !== $activeSheet) {
88 1
            $excel->setActiveSheetIndex($activeSheet);
89 1
        }
90
91
        /** @var Worksheet $sheet */
92 11
        $sheet = $excel->getActiveSheet();
93
94 11
        if ($maxRows && $maxRows < $sheet->getHighestDataRow()) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $maxRows of type integer|null is loosely compared to true; this is ambiguous if the integer can be zero. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
95 1
            $maxColumn       = $sheet->getHighestDataColumn();
96 1
            $this->worksheet = $sheet->rangeToArray('A1:'.$maxColumn.$maxRows);
97 1
        } else {
98 11
            $this->worksheet = $excel->getActiveSheet()->toArray();
99
        }
100
101 11
        if (null !== $headerRowNumber) {
102 5
            $this->setHeaderRowNumber($headerRowNumber);
103 5
        }
104 11
    }
105
106
    /**
107
     * @return int
108
     */
109 5
    public function count()
110
    {
111 5
        $count = count($this->worksheet);
112 5
        if (null !== $this->headerRowNumber) {
113 2
            $count--;
114 2
        }
115
116 5
        return $count;
117
    }
118
119
    /**
120
     * Return the current row as an array
121
     *
122
     * If a header row has been set, an associative array will be returned
123
     *
124
     * @return array|null
125
     */
126 7
    public function current()
127
    {
128 7
        $row = $this->worksheet[$this->pointer];
129
130
        // If the excel file has column headers, use them to construct an associative
131
        // array for the columns in this line
132 6
        if (count($this->columnHeaders) === count($row)) {
133 4
            return array_combine(array_values($this->columnHeaders), $row);
134
        }
135
136
        // Else just return the column values
137 2
        return $row;
138
    }
139
140
    /**
141
     * Get column headers
142
     *
143
     * @return array
144
     */
145 1
    public function getColumnHeaders()
146
    {
147 1
        return $this->columnHeaders;
148
    }
149
150
    /**
151
     * Get a row
152
     *
153
     * @param int $number
154
     *
155
     * @return array
156
     */
157 4
    public function getRow($number)
158
    {
159 4
        $this->seek($number);
160
161 4
        return $this->current();
162
    }
163
164
    /**
165
     * Return the key of the current element
166
     *
167
     * @return int
168
     */
169 1
    public function key()
170
    {
171 1
        return $this->pointer;
172
    }
173
174
    /**
175
     * Move forward to next element
176
     *
177
     * @return void Any returned value is ignored.
178
     */
179 2
    public function next()
180
    {
181 2
        $this->pointer++;
182 2
    }
183
184
    /**
185
     * Rewind the file pointer
186
     *
187
     * If a header row has been set, the pointer is set just below the header
188
     * row. That way, when you iterate over the rows, that header row is
189
     * skipped.
190
     *
191
     * @return void Any returned value is ignored.
192
     */
193 2
    public function rewind()
194
    {
195 2
        if (null === $this->headerRowNumber) {
196 1
            $this->pointer = 0;
197 1
        } else {
198 1
            $this->pointer = $this->headerRowNumber + 1;
199
        }
200 2
    }
201
202
    /**
203
     * Seeks to a position
204
     *
205
     * @link http://php.net/manual/en/seekableiterator.seek.php
206
     *
207
     * @param int $pointer The position to seek to.
208
     *
209
     * @return void Any returned value is ignored.
210
     */
211 4
    public function seek($pointer)
212
    {
213 4
        $this->pointer = $pointer;
214 4
    }
215
216
    /**
217
     * Set column headers
218
     *
219
     * @param array $columnHeaders
220
     *
221
     * @return void Any returned value is ignored.
222
     */
223 2
    public function setColumnHeaders(array $columnHeaders)
224
    {
225 2
        $this->columnHeaders = $columnHeaders;
226 2
    }
227
228
    /**
229
     * Set header row number
230
     *
231
     * @param int $rowNumber Number of the row that contains column header names
232
     *
233
     * @return void Any returned value is ignored.
234
     */
235 5
    public function setHeaderRowNumber($rowNumber)
236
    {
237 5
        $this->headerRowNumber = $rowNumber;
238 5
        $this->columnHeaders   = $this->worksheet[$rowNumber];
239 5
    }
240
241
    /**
242
     * Checks if current position is valid
243
     *
244
     * @return bool The return value will be casted to boolean and then evaluated.
245
     * Returns true on success or false on failure.
246
     */
247 2
    public function valid()
248
    {
249 2
        return isset($this->worksheet[$this->pointer]);
250
    }
251
}
252