Completed
Push — develop ( 8c5838...f74fde )
by Adrien
20:53
created

SYLK::canRead()   B

Complexity

Conditions 3
Paths 3

Size

Total Lines 24
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 3.054

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 12
nc 3
nop 1
dl 0
loc 24
ccs 9
cts 11
cp 0.8182
crap 3.054
rs 8.9713
c 1
b 0
f 0
1
<?php
2
3
namespace PhpOffice\PhpSpreadsheet\Reader;
4
5
/**
6
 * Copyright (c) 2006 - 2016 PhpSpreadsheet
7
 *
8
 * This library is free software; you can redistribute it and/or
9
 * modify it under the terms of the GNU Lesser General Public
10
 * License as published by the Free Software Foundation; either
11
 * version 2.1 of the License, or (at your option) any later version.
12
 *
13
 * This library is distributed in the hope that it will be useful,
14
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16
 * Lesser General Public License for more details.
17
 *
18
 * You should have received a copy of the GNU Lesser General Public
19
 * License along with this library; if not, write to the Free Software
20
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
21
 *
22
 * @category   PhpSpreadsheet
23
 * @copyright  Copyright (c) 2006 - 2016 PhpSpreadsheet (https://github.com/PHPOffice/PhpSpreadsheet)
24
 * @license    http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt    LGPL
25
 * @version    ##VERSION##, ##DATE##
26
 */
27
class SYLK extends BaseReader implements IReader
28
{
29
    /**
30
     * Input encoding
31
     *
32
     * @var string
33
     */
34
    private $inputEncoding = 'ANSI';
35
36
    /**
37
     * Sheet index to read
38
     *
39
     * @var int
40
     */
41
    private $sheetIndex = 0;
42
43
    /**
44
     * Formats
45
     *
46
     * @var array
47
     */
48
    private $formats = [];
49
50
    /**
51
     * Format Count
52
     *
53
     * @var int
54
     */
55
    private $format = 0;
56
57
    /**
58
     * Create a new SYLK Reader instance
59
     */
60 1
    public function __construct()
61
    {
62 1
        $this->readFilter = new DefaultReadFilter();
63 1
    }
64
65
    /**
66
     * Validate that the current file is a SYLK file
67
     *
68
     * @param     string         $pFilename
69
     * @throws Exception
70
     * @return bool
71
     */
72 1
    public function canRead($pFilename)
73
    {
74
        // Check if file exists
75
        try {
76 1
            $this->openFile($pFilename);
77
        } catch (Exception $e) {
78
            return false;
79
        }
80
81
        // Read sample data (first 2 KB will do)
82 1
        $data = fread($this->fileHandle, 2048);
83
84
        // Count delimiters in file
85 1
        $delimiterCount = substr_count($data, ';');
86 1
        $hasDelimiter = $delimiterCount > 0;
87
88
        // Analyze first line looking for ID; signature
89 1
        $lines = explode("\n", $data);
90 1
        $hasId = substr($lines[0], 0, 4) === 'ID;P';
91
92 1
        fclose($this->fileHandle);
93
94 1
        return $hasDelimiter && $hasId;
95
    }
96
97
    /**
98
     * Set input encoding
99
     *
100
     * @param string $pValue Input encoding
101
     */
102
    public function setInputEncoding($pValue = 'ANSI')
103
    {
104
        $this->inputEncoding = $pValue;
105
106
        return $this;
107
    }
108
109
    /**
110
     * Get input encoding
111
     *
112
     * @return string
113
     */
114
    public function getInputEncoding()
115
    {
116
        return $this->inputEncoding;
117
    }
118
119
    /**
120
     * Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns)
121
     *
122
     * @param    string     $pFilename
123
     * @throws   Exception
124
     */
125
    public function listWorksheetInfo($pFilename)
126
    {
127
        // Open file
128
        if (!$this->canRead($pFilename)) {
129
            throw new Exception($pFilename . ' is an Invalid Spreadsheet file.');
130
        }
131
        $this->openFile($pFilename);
132
        $fileHandle = $this->fileHandle;
133
        rewind($fileHandle);
134
135
        $worksheetInfo = [];
136
        $worksheetInfo[0]['worksheetName'] = 'Worksheet';
137
        $worksheetInfo[0]['lastColumnLetter'] = 'A';
138
        $worksheetInfo[0]['lastColumnIndex'] = 0;
139
        $worksheetInfo[0]['totalRows'] = 0;
140
        $worksheetInfo[0]['totalColumns'] = 0;
141
142
        // Loop through file
143
        $rowData = [];
0 ignored issues
show
Unused Code introduced by
$rowData is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
144
145
        // loop through one row (line) at a time in the file
146
        $rowIndex = 0;
147
        while (($rowData = fgets($fileHandle)) !== false) {
148
            $columnIndex = 0;
149
150
            // convert SYLK encoded $rowData to UTF-8
151
            $rowData = \PhpOffice\PhpSpreadsheet\Shared\StringHelper::SYLKtoUTF8($rowData);
152
153
            // explode each row at semicolons while taking into account that literal semicolon (;)
154
            // is escaped like this (;;)
155
            $rowData = explode("\t", str_replace('¤', ';', str_replace(';', "\t", str_replace(';;', '¤', rtrim($rowData)))));
156
157
            $dataType = array_shift($rowData);
158
            if ($dataType == 'C') {
159
                //  Read cell value data
160
                foreach ($rowData as $rowDatum) {
161 View Code Duplication
                    switch ($rowDatum{0}) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
162
                        case 'C':
163
                        case 'X':
164
                            $columnIndex = substr($rowDatum, 1) - 1;
165
                            break;
166
                        case 'R':
167
                        case 'Y':
168
                            $rowIndex = substr($rowDatum, 1);
169
                            break;
170
                    }
171
172
                    $worksheetInfo[0]['totalRows'] = max($worksheetInfo[0]['totalRows'], $rowIndex);
173
                    $worksheetInfo[0]['lastColumnIndex'] = max($worksheetInfo[0]['lastColumnIndex'], $columnIndex);
174
                }
175
            }
176
        }
177
178
        $worksheetInfo[0]['lastColumnLetter'] = \PhpOffice\PhpSpreadsheet\Cell::stringFromColumnIndex($worksheetInfo[0]['lastColumnIndex']);
179
        $worksheetInfo[0]['totalColumns'] = $worksheetInfo[0]['lastColumnIndex'] + 1;
180
181
        // Close file
182
        fclose($fileHandle);
183
184
        return $worksheetInfo;
185
    }
186
187
    /**
188
     * Loads PhpSpreadsheet from file
189
     *
190
     * @param     string         $pFilename
191
     * @throws     Exception
192
     * @return     \PhpOffice\PhpSpreadsheet\Spreadsheet
193
     */
194 1
    public function load($pFilename)
195
    {
196
        // Create new Spreadsheet
197 1
        $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
198
199
        // Load into this instance
200 1
        return $this->loadIntoExisting($pFilename, $spreadsheet);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->loadIntoEx...ilename, $spreadsheet); (PhpOffice\PhpSpreadsheet\Spreadsheet) is incompatible with the return type declared by the interface PhpOffice\PhpSpreadsheet\Reader\IReader::load of type PhpOffice\PhpSpreadsheet\Reader\PhpSpreadsheet.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

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

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
201
    }
202
203
    /**
204
     * Loads PhpSpreadsheet from file into PhpSpreadsheet instance
205
     *
206
     * @param     string         $pFilename
207
     * @param     \PhpOffice\PhpSpreadsheet\Spreadsheet    $spreadsheet
208
     * @throws    Exception
209
     * @return    \PhpOffice\PhpSpreadsheet\Spreadsheet
210
     */
211 1
    public function loadIntoExisting($pFilename, \PhpOffice\PhpSpreadsheet\Spreadsheet $spreadsheet)
212
    {
213
        // Open file
214 1
        if (!$this->canRead($pFilename)) {
215
            throw new Exception($pFilename . ' is an Invalid Spreadsheet file.');
216
        }
217 1
        $this->openFile($pFilename);
218 1
        $fileHandle = $this->fileHandle;
219 1
        rewind($fileHandle);
220
221
        // Create new Worksheets
222 1
        while ($spreadsheet->getSheetCount() <= $this->sheetIndex) {
223
            $spreadsheet->createSheet();
224
        }
225 1
        $spreadsheet->setActiveSheetIndex($this->sheetIndex);
226
227 1
        $fromFormats = ['\-', '\ '];
228 1
        $toFormats = ['-', ' '];
229
230
        // Loop through file
231 1
        $rowData = [];
0 ignored issues
show
Unused Code introduced by
$rowData is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
232 1
        $column = $row = '';
233
234
        // loop through one row (line) at a time in the file
235 1
        while (($rowData = fgets($fileHandle)) !== false) {
236
            // convert SYLK encoded $rowData to UTF-8
237 1
            $rowData = \PhpOffice\PhpSpreadsheet\Shared\StringHelper::SYLKtoUTF8($rowData);
238
239
            // explode each row at semicolons while taking into account that literal semicolon (;)
240
            // is escaped like this (;;)
241 1
            $rowData = explode("\t", str_replace('¤', ';', str_replace(';', "\t", str_replace(';;', '¤', rtrim($rowData)))));
242
243 1
            $dataType = array_shift($rowData);
244
            //    Read shared styles
245 1
            if ($dataType == 'P') {
246 1
                $formatArray = [];
247 1
                foreach ($rowData as $rowDatum) {
248 1
                    switch ($rowDatum{0}) {
249 1
                        case 'P':
250 1
                            $formatArray['numberformat']['code'] = str_replace($fromFormats, $toFormats, substr($rowDatum, 1));
251 1
                            break;
252 1
                        case 'E':
253 1
                        case 'F':
254 1
                            $formatArray['font']['name'] = substr($rowDatum, 1);
255 1
                            break;
256 1
                        case 'L':
257 1
                            $formatArray['font']['size'] = substr($rowDatum, 1);
258 1
                            break;
259 1 View Code Duplication
                        case 'S':
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
260 1
                            $styleSettings = substr($rowDatum, 1);
261 1
                            for ($i = 0; $i < strlen($styleSettings); ++$i) {
262 1
                                switch ($styleSettings{$i}) {
263 1
                                    case 'I':
264 1
                                        $formatArray['font']['italic'] = true;
265 1
                                        break;
266 1
                                    case 'D':
267
                                        $formatArray['font']['bold'] = true;
268
                                        break;
269 1
                                    case 'T':
270
                                        $formatArray['borders']['top']['style'] = \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN;
271
                                        break;
272 1
                                    case 'B':
273 1
                                        $formatArray['borders']['bottom']['style'] = \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN;
274 1
                                        break;
275 1
                                    case 'L':
276
                                        $formatArray['borders']['left']['style'] = \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN;
277
                                        break;
278 1
                                    case 'R':
279
                                        $formatArray['borders']['right']['style'] = \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN;
280
                                        break;
281
                                }
282
                            }
283 1
                            break;
284
                    }
285
                }
286 1
                $this->formats['P' . $this->format++] = $formatArray;
287
            //    Read cell value data
288 1
            } elseif ($dataType == 'C') {
289 1
                $hasCalculatedValue = false;
290 1
                $cellData = $cellDataFormula = '';
291 1
                foreach ($rowData as $rowDatum) {
292 1
                    switch ($rowDatum{0}) {
293 1
                        case 'C':
294 1
                        case 'X':
295 1
                            $column = substr($rowDatum, 1);
296 1
                            break;
297 1
                        case 'R':
298 1
                        case 'Y':
299 1
                            $row = substr($rowDatum, 1);
300 1
                            break;
301 1
                        case 'K':
302 1
                            $cellData = substr($rowDatum, 1);
303 1
                            break;
304 1
                        case 'E':
305 1
                            $cellDataFormula = '=' . substr($rowDatum, 1);
306
                            //    Convert R1C1 style references to A1 style references (but only when not quoted)
307 1
                            $temp = explode('"', $cellDataFormula);
308 1
                            $key = false;
309 1 View Code Duplication
                            foreach ($temp as &$value) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
310
                                //    Only count/replace in alternate array entries
311 1
                                if ($key = !$key) {
312 1
                                    preg_match_all('/(R(\[?-?\d*\]?))(C(\[?-?\d*\]?))/', $value, $cellReferences, PREG_SET_ORDER + PREG_OFFSET_CAPTURE);
313
                                    //    Reverse the matches array, otherwise all our offsets will become incorrect if we modify our way
314
                                    //        through the formula from left to right. Reversing means that we work right to left.through
315
                                    //        the formula
316 1
                                    $cellReferences = array_reverse($cellReferences);
317
                                    //    Loop through each R1C1 style reference in turn, converting it to its A1 style equivalent,
318
                                    //        then modify the formula to use that new reference
319 1
                                    foreach ($cellReferences as $cellReference) {
320 1
                                        $rowReference = $cellReference[2][0];
321
                                        //    Empty R reference is the current row
322 1
                                        if ($rowReference == '') {
323 1
                                            $rowReference = $row;
324
                                        }
325
                                        //    Bracketed R references are relative to the current row
326 1
                                        if ($rowReference{0} == '[') {
327 1
                                            $rowReference = $row + trim($rowReference, '[]');
328
                                        }
329 1
                                        $columnReference = $cellReference[4][0];
330
                                        //    Empty C reference is the current column
331 1
                                        if ($columnReference == '') {
332
                                            $columnReference = $column;
333
                                        }
334
                                        //    Bracketed C references are relative to the current column
335 1
                                        if ($columnReference{0} == '[') {
336 1
                                            $columnReference = $column + trim($columnReference, '[]');
337
                                        }
338 1
                                        $A1CellReference = \PhpOffice\PhpSpreadsheet\Cell::stringFromColumnIndex($columnReference - 1) . $rowReference;
339
340 1
                                        $value = substr_replace($value, $A1CellReference, $cellReference[0][1], strlen($cellReference[0][0]));
341
                                    }
342
                                }
343
                            }
344 1
                            unset($value);
345
                            //    Then rebuild the formula string
346 1
                            $cellDataFormula = implode('"', $temp);
347 1
                            $hasCalculatedValue = true;
348 1
                            break;
349
                    }
350
                }
351 1
                $columnLetter = \PhpOffice\PhpSpreadsheet\Cell::stringFromColumnIndex($column - 1);
352 1
                $cellData = \PhpOffice\PhpSpreadsheet\Calculation::unwrapResult($cellData);
353
354
                // Set cell value
355 1
                $spreadsheet->getActiveSheet()->getCell($columnLetter . $row)->setValue(($hasCalculatedValue) ? $cellDataFormula : $cellData);
356 1
                if ($hasCalculatedValue) {
357 1
                    $cellData = \PhpOffice\PhpSpreadsheet\Calculation::unwrapResult($cellData);
358 1
                    $spreadsheet->getActiveSheet()->getCell($columnLetter . $row)->setCalculatedValue($cellData);
359
                }
360
            //    Read cell formatting
361 1
            } elseif ($dataType == 'F') {
362 1
                $formatStyle = $columnWidth = $styleSettings = '';
0 ignored issues
show
Unused Code introduced by
$styleSettings is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
363 1
                $styleData = [];
364 1
                foreach ($rowData as $rowDatum) {
365 1
                    switch ($rowDatum{0}) {
366 1
                        case 'C':
367 1
                        case 'X':
368 1
                            $column = substr($rowDatum, 1);
369 1
                            break;
370 1
                        case 'R':
371 1
                        case 'Y':
372 1
                            $row = substr($rowDatum, 1);
373 1
                            break;
374 1
                        case 'P':
375 1
                            $formatStyle = $rowDatum;
376 1
                            break;
377 1
                        case 'W':
378 1
                            list($startCol, $endCol, $columnWidth) = explode(' ', substr($rowDatum, 1));
379 1
                            break;
380 1 View Code Duplication
                        case 'S':
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
381 1
                            $styleSettings = substr($rowDatum, 1);
382 1
                            for ($i = 0; $i < strlen($styleSettings); ++$i) {
383 1
                                switch ($styleSettings{$i}) {
384 1
                                    case 'I':
385 1
                                        $styleData['font']['italic'] = true;
386 1
                                        break;
387 1
                                    case 'D':
388 1
                                        $styleData['font']['bold'] = true;
389 1
                                        break;
390 1
                                    case 'T':
391 1
                                        $styleData['borders']['top']['style'] = \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN;
392 1
                                        break;
393 1
                                    case 'B':
394 1
                                        $styleData['borders']['bottom']['style'] = \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN;
395 1
                                        break;
396 1
                                    case 'L':
397 1
                                        $styleData['borders']['left']['style'] = \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN;
398 1
                                        break;
399 1
                                    case 'R':
400 1
                                        $styleData['borders']['right']['style'] = \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN;
401 1
                                        break;
402
                                }
403
                            }
404 1
                            break;
405
                    }
406
                }
407 1
                if (($formatStyle > '') && ($column > '') && ($row > '')) {
408 1
                    $columnLetter = \PhpOffice\PhpSpreadsheet\Cell::stringFromColumnIndex($column - 1);
409 1 View Code Duplication
                    if (isset($this->formats[$formatStyle])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
410 1
                        $spreadsheet->getActiveSheet()->getStyle($columnLetter . $row)->applyFromArray($this->formats[$formatStyle]);
411
                    }
412
                }
413 1
                if ((!empty($styleData)) && ($column > '') && ($row > '')) {
414 1
                    $columnLetter = \PhpOffice\PhpSpreadsheet\Cell::stringFromColumnIndex($column - 1);
415 1
                    $spreadsheet->getActiveSheet()->getStyle($columnLetter . $row)->applyFromArray($styleData);
416
                }
417 1
                if ($columnWidth > '') {
418 1
                    if ($startCol == $endCol) {
419 1
                        $startCol = \PhpOffice\PhpSpreadsheet\Cell::stringFromColumnIndex($startCol - 1);
0 ignored issues
show
Bug introduced by
The variable $startCol does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
420 1
                        $spreadsheet->getActiveSheet()->getColumnDimension($startCol)->setWidth($columnWidth);
421
                    } else {
422 1
                        $startCol = \PhpOffice\PhpSpreadsheet\Cell::stringFromColumnIndex($startCol - 1);
423 1
                        $endCol = \PhpOffice\PhpSpreadsheet\Cell::stringFromColumnIndex($endCol - 1);
0 ignored issues
show
Bug introduced by
The variable $endCol does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
424 1
                        $spreadsheet->getActiveSheet()->getColumnDimension($startCol)->setWidth($columnWidth);
425
                        do {
426 1
                            $spreadsheet->getActiveSheet()->getColumnDimension(++$startCol)->setWidth($columnWidth);
427 1
                        } while ($startCol != $endCol);
428
                    }
429
                }
430
            } else {
431 1
                foreach ($rowData as $rowDatum) {
432 1 View Code Duplication
                    switch ($rowDatum{0}) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
433 1
                        case 'C':
434 1
                        case 'X':
435 1
                            $column = substr($rowDatum, 1);
436 1
                            break;
437 1
                        case 'R':
438 1
                        case 'Y':
439 1
                            $row = substr($rowDatum, 1);
440 1
                            break;
441
                    }
442
                }
443
            }
444
        }
445
446
        // Close file
447 1
        fclose($fileHandle);
448
449
        // Return
450 1
        return $spreadsheet;
451
    }
452
453
    /**
454
     * Get sheet index
455
     *
456
     * @return int
457
     */
458
    public function getSheetIndex()
459
    {
460
        return $this->sheetIndex;
461
    }
462
463
    /**
464
     * Set sheet index
465
     *
466
     * @param    int        $pValue        Sheet index
467
     * @return SYLK
468
     */
469
    public function setSheetIndex($pValue = 0)
470
    {
471
        $this->sheetIndex = $pValue;
472
473
        return $this;
474
    }
475
}
476