Completed
Push — develop ( 5e03e2...c8a8fd )
by Adrien
28:49
created

Ods::loadIntoExisting()   F

Complexity

Conditions 80
Paths > 20000

Size

Total Lines 342
Code Lines 251

Duplication

Lines 19
Ratio 5.56 %

Code Coverage

Tests 197
CRAP Score 116.8293

Importance

Changes 0
Metric Value
cc 80
eloc 251
nc 16570628
nop 2
dl 19
loc 342
ccs 197
cts 240
cp 0.8208
crap 116.8293
rs 2
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace PhpOffice\PhpSpreadsheet\Reader;
4
5
use DateTime;
6
use DateTimeZone;
7
use PhpOffice\PhpSpreadsheet\Shared\File;
8
9
/**
10
 * Copyright (c) 2006 - 2016 PhpSpreadsheet
11
 *
12
 * This library is free software; you can redistribute it and/or
13
 * modify it under the terms of the GNU Lesser General Public
14
 * License as published by the Free Software Foundation; either
15
 * version 2.1 of the License, or (at your option) any later version.
16
 *
17
 * This library is distributed in the hope that it will be useful,
18
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
20
 * Lesser General Public License for more details.
21
 *
22
 * You should have received a copy of the GNU Lesser General Public
23
 * License along with this library; if not, write to the Free Software
24
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
25
 *
26
 * @category   PhpSpreadsheet
27
 * @copyright  Copyright (c) 2006 - 2016 PhpSpreadsheet (https://github.com/PHPOffice/PhpSpreadsheet)
28
 * @license    http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt    LGPL
29
 */
30
class Ods extends BaseReader implements IReader
31
{
32
    /**
33
     * Formats
34
     *
35
     * @var array
36
     */
37
    private $styles = [];
0 ignored issues
show
Unused Code introduced by
The property $styles is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
38
39
    /**
40
     * Create a new Ods Reader instance
41
     */
42 2
    public function __construct()
43
    {
44 2
        $this->readFilter = new DefaultReadFilter();
45 2
    }
46
47
    /**
48
     * Can the current IReader read the file?
49
     *
50
     * @param     string         $pFilename
51
     * @throws Exception
52
     * @return     bool
53
     */
54 2
    public function canRead($pFilename)
55
    {
56 2
        File::assertFile($pFilename);
57
58 2
        $zipClass = \PhpOffice\PhpSpreadsheet\Settings::getZipClass();
59
60 2
        $mimeType = 'UNKNOWN';
61
        // Load file
62 2
        $zip = new $zipClass();
63 2
        if ($zip->open($pFilename) === true) {
64
            // check if it is an OOXML archive
65 2
            $stat = $zip->statName('mimetype');
66 2
            if ($stat && ($stat['size'] <= 255)) {
67 2
                $mimeType = $zip->getFromName($stat['name']);
68
            } elseif ($stat = $zip->statName('META-INF/manifest.xml')) {
0 ignored issues
show
Unused Code introduced by
$stat 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...
69
                $xml = simplexml_load_string(
70
                    $this->securityScan($zip->getFromName('META-INF/manifest.xml')),
71
                    'SimpleXMLElement',
72
                    \PhpOffice\PhpSpreadsheet\Settings::getLibXmlLoaderOptions()
73
                );
74
                $namespacesContent = $xml->getNamespaces(true);
75
                if (isset($namespacesContent['manifest'])) {
76
                    $manifest = $xml->children($namespacesContent['manifest']);
77
                    foreach ($manifest as $manifestDataSet) {
78
                        $manifestAttributes = $manifestDataSet->attributes($namespacesContent['manifest']);
79
                        if ($manifestAttributes->{'full-path'} == '/') {
80
                            $mimeType = (string) $manifestAttributes->{'media-type'};
81
                            break;
82
                        }
83
                    }
84
                }
85
            }
86
87 2
            $zip->close();
88
89 2
            return $mimeType === 'application/vnd.oasis.opendocument.spreadsheet';
90
        }
91
92
        return false;
93
    }
94
95
    /**
96
     * Reads names of the worksheets from a file, without parsing the whole file to a PhpSpreadsheet object
97
     *
98
     * @param     string         $pFilename
99
     * @throws     Exception
100
     */
101
    public function listWorksheetNames($pFilename)
102
    {
103
        File::assertFile($pFilename);
104
105
        $zipClass = \PhpOffice\PhpSpreadsheet\Settings::getZipClass();
106
107
        $zip = new $zipClass();
108
        if (!$zip->open($pFilename)) {
109
            throw new Exception('Could not open ' . $pFilename . ' for reading! Error opening file.');
110
        }
111
112
        $worksheetNames = [];
113
114
        $xml = new XMLReader();
115
        $res = $xml->xml(
0 ignored issues
show
Unused Code introduced by
$res 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...
116
            $this->securityScanFile('zip://' . realpath($pFilename) . '#content.xml'),
117
            null,
118
            \PhpOffice\PhpSpreadsheet\Settings::getLibXmlLoaderOptions()
119
        );
120
        $xml->setParserProperty(2, true);
121
122
        //    Step into the first level of content of the XML
123
        $xml->read();
124
        while ($xml->read()) {
125
            //    Quickly jump through to the office:body node
126
            while ($xml->name !== 'office:body') {
127
                if ($xml->isEmptyElement) {
128
                    $xml->read();
129
                } else {
130
                    $xml->next();
131
                }
132
            }
133
            //    Now read each node until we find our first table:table node
134
            while ($xml->read()) {
135
                if ($xml->name == 'table:table' && $xml->nodeType == XMLReader::ELEMENT) {
136
                    //    Loop through each table:table node reading the table:name attribute for each worksheet name
137
                    do {
138
                        $worksheetNames[] = $xml->getAttribute('table:name');
139
                        $xml->next();
140
                    } while ($xml->name == 'table:table' && $xml->nodeType == XMLReader::ELEMENT);
141
                }
142
            }
143
        }
144
145
        return $worksheetNames;
146
    }
147
148
    /**
149
     * Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns)
150
     *
151
     * @param   string     $pFilename
152
     * @throws   Exception
153
     */
154
    public function listWorksheetInfo($pFilename)
155
    {
156
        File::assertFile($pFilename);
157
158
        $worksheetInfo = [];
159
160
        $zipClass = \PhpOffice\PhpSpreadsheet\Settings::getZipClass();
161
162
        $zip = new $zipClass();
163
        if (!$zip->open($pFilename)) {
164
            throw new Exception('Could not open ' . $pFilename . ' for reading! Error opening file.');
165
        }
166
167
        $xml = new XMLReader();
168
        $res = $xml->xml(
0 ignored issues
show
Unused Code introduced by
$res 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...
169
            $this->securityScanFile('zip://' . realpath($pFilename) . '#content.xml'),
170
            null,
171
            \PhpOffice\PhpSpreadsheet\Settings::getLibXmlLoaderOptions()
172
        );
173
        $xml->setParserProperty(2, true);
174
175
        //    Step into the first level of content of the XML
176
        $xml->read();
177
        while ($xml->read()) {
178
            //    Quickly jump through to the office:body node
179
            while ($xml->name !== 'office:body') {
180
                if ($xml->isEmptyElement) {
181
                    $xml->read();
182
                } else {
183
                    $xml->next();
184
                }
185
            }
186
                //    Now read each node until we find our first table:table node
187
            while ($xml->read()) {
188
                if ($xml->name == 'table:table' && $xml->nodeType == XMLReader::ELEMENT) {
189
                    $worksheetNames[] = $xml->getAttribute('table:name');
0 ignored issues
show
Coding Style Comprehensibility introduced by
$worksheetNames was never initialized. Although not strictly required by PHP, it is generally a good practice to add $worksheetNames = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
190
191
                    $tmpInfo = [
192
                        'worksheetName' => $xml->getAttribute('table:name'),
193
                        'lastColumnLetter' => 'A',
194
                        'lastColumnIndex' => 0,
195
                        'totalRows' => 0,
196
                        'totalColumns' => 0,
197
                    ];
198
199
                    //    Loop through each child node of the table:table element reading
200
                    $currCells = 0;
201
                    do {
202
                        $xml->read();
203
                        if ($xml->name == 'table:table-row' && $xml->nodeType == XMLReader::ELEMENT) {
204
                            $rowspan = $xml->getAttribute('table:number-rows-repeated');
205
                            $rowspan = empty($rowspan) ? 1 : $rowspan;
206
                            $tmpInfo['totalRows'] += $rowspan;
207
                            $tmpInfo['totalColumns'] = max($tmpInfo['totalColumns'], $currCells);
208
                            $currCells = 0;
209
                            //    Step into the row
210
                            $xml->read();
211
                            do {
212
                                if ($xml->name == 'table:table-cell' && $xml->nodeType == XMLReader::ELEMENT) {
213
                                    if (!$xml->isEmptyElement) {
214
                                        ++$currCells;
215
                                        $xml->next();
216
                                    } else {
217
                                        $xml->read();
218
                                    }
219
                                } elseif ($xml->name == 'table:covered-table-cell' && $xml->nodeType == XMLReader::ELEMENT) {
220
                                    $mergeSize = $xml->getAttribute('table:number-columns-repeated');
221
                                    $currCells += $mergeSize;
222
                                    $xml->read();
223
                                }
224
                            } while ($xml->name != 'table:table-row');
225
                        }
226
                    } while ($xml->name != 'table:table');
227
228
                    $tmpInfo['totalColumns'] = max($tmpInfo['totalColumns'], $currCells);
229
                    $tmpInfo['lastColumnIndex'] = $tmpInfo['totalColumns'] - 1;
230
                    $tmpInfo['lastColumnLetter'] = \PhpOffice\PhpSpreadsheet\Cell::stringFromColumnIndex($tmpInfo['lastColumnIndex']);
231
                    $worksheetInfo[] = $tmpInfo;
232
                }
233
            }
234
        }
235
236
        return $worksheetInfo;
237
    }
238
239
    /**
240
     * Loads PhpSpreadsheet from file
241
     *
242
     * @param     string         $pFilename
243
     * @throws     Exception
244
     * @return     \PhpOffice\PhpSpreadsheet\Spreadsheet
245
     */
246 1
    public function load($pFilename)
247
    {
248
        // Create new Spreadsheet
249 1
        $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
250
251
        // Load into this instance
252 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...
253
    }
254
255 View Code Duplication
    private static function identifyFixedStyleValue($styleList, &$styleAttributeValue)
0 ignored issues
show
Unused Code introduced by
This method is not used, and could be removed.
Loading history...
Duplication introduced by
This method seems to be duplicated in 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...
256
    {
257
        $styleAttributeValue = strtolower($styleAttributeValue);
258
        foreach ($styleList as $style) {
259
            if ($styleAttributeValue == strtolower($style)) {
260
                $styleAttributeValue = $style;
261
262
                return true;
263
            }
264
        }
265
266
        return false;
267
    }
268
269
    /**
270
     * Loads PhpSpreadsheet from file into PhpSpreadsheet instance
271
     *
272
     * @param     string         $pFilename
273
     * @param    \PhpOffice\PhpSpreadsheet\Spreadsheet    $spreadsheet
274
     * @throws     Exception
275
     * @return     \PhpOffice\PhpSpreadsheet\Spreadsheet
276
     */
277 1
    public function loadIntoExisting($pFilename, \PhpOffice\PhpSpreadsheet\Spreadsheet $spreadsheet)
278
    {
279 1
        File::assertFile($pFilename);
280
281 1
        $timezoneObj = new DateTimeZone('Europe/London');
282 1
        $GMT = new \DateTimeZone('UTC');
283
284 1
        $zipClass = \PhpOffice\PhpSpreadsheet\Settings::getZipClass();
285
286 1
        $zip = new $zipClass();
287 1
        if (!$zip->open($pFilename)) {
288
            throw new Exception('Could not open ' . $pFilename . ' for reading! Error opening file.');
289
        }
290
291 1
        $xml = simplexml_load_string(
292 1
            $this->securityScan($zip->getFromName('meta.xml')),
293 1
            'SimpleXMLElement',
294 1
            \PhpOffice\PhpSpreadsheet\Settings::getLibXmlLoaderOptions()
295
        );
296 1
        $namespacesMeta = $xml->getNamespaces(true);
297
298 1
        $docProps = $spreadsheet->getProperties();
299 1
        $officeProperty = $xml->children($namespacesMeta['office']);
300 1
        foreach ($officeProperty as $officePropertyData) {
301 1
            $officePropertyDC = [];
302 1
            if (isset($namespacesMeta['dc'])) {
303 1
                $officePropertyDC = $officePropertyData->children($namespacesMeta['dc']);
304
            }
305 1
            foreach ($officePropertyDC as $propertyName => $propertyValue) {
306 1
                $propertyValue = (string) $propertyValue;
307
                switch ($propertyName) {
308 1
                    case 'title':
309 1
                        $docProps->setTitle($propertyValue);
310 1
                        break;
311 1
                    case 'subject':
312 1
                        $docProps->setSubject($propertyValue);
313 1
                        break;
314 1
                    case 'creator':
315
                        $docProps->setCreator($propertyValue);
316
                        $docProps->setLastModifiedBy($propertyValue);
317
                        break;
318 1
                    case 'date':
319 1
                        $creationDate = strtotime($propertyValue);
320 1
                        $docProps->setCreated($creationDate);
0 ignored issues
show
Documentation introduced by
$creationDate is of type integer, but the function expects a object<PhpOffice\PhpSpre...Document\datetime>|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
321 1
                        $docProps->setModified($creationDate);
0 ignored issues
show
Documentation introduced by
$creationDate is of type integer, but the function expects a object<PhpOffice\PhpSpre...Document\datetime>|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
322 1
                        break;
323 1
                    case 'description':
324 1
                        $docProps->setDescription($propertyValue);
325 1
                        break;
326
                }
327
            }
328 1
            $officePropertyMeta = [];
329 1
            if (isset($namespacesMeta['dc'])) {
330 1
                $officePropertyMeta = $officePropertyData->children($namespacesMeta['meta']);
331
            }
332 1
            foreach ($officePropertyMeta as $propertyName => $propertyValue) {
333 1
                $propertyValueAttributes = $propertyValue->attributes($namespacesMeta['meta']);
334 1
                $propertyValue = (string) $propertyValue;
335
                switch ($propertyName) {
336 1
                    case 'initial-creator':
337 1
                        $docProps->setCreator($propertyValue);
338 1
                        break;
339 1
                    case 'keyword':
340 1
                        $docProps->setKeywords($propertyValue);
341 1
                        break;
342 1
                    case 'creation-date':
343 1
                        $creationDate = strtotime($propertyValue);
344 1
                        $docProps->setCreated($creationDate);
0 ignored issues
show
Documentation introduced by
$creationDate is of type integer, but the function expects a object<PhpOffice\PhpSpre...Document\datetime>|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
345 1
                        break;
346 1
                    case 'user-defined':
347 1
                        $propertyValueType = \PhpOffice\PhpSpreadsheet\Document\Properties::PROPERTY_TYPE_STRING;
348 1
                        foreach ($propertyValueAttributes as $key => $value) {
349 1
                            if ($key == 'name') {
350 1
                                $propertyValueName = (string) $value;
351
                            } elseif ($key == 'value-type') {
352
                                switch ($value) {
353
                                    case 'date':
354
                                        $propertyValue = \PhpOffice\PhpSpreadsheet\Document\Properties::convertProperty($propertyValue, 'date');
355
                                        $propertyValueType = \PhpOffice\PhpSpreadsheet\Document\Properties::PROPERTY_TYPE_DATE;
356
                                        break;
357
                                    case 'boolean':
358
                                        $propertyValue = \PhpOffice\PhpSpreadsheet\Document\Properties::convertProperty($propertyValue, 'bool');
359
                                        $propertyValueType = \PhpOffice\PhpSpreadsheet\Document\Properties::PROPERTY_TYPE_BOOLEAN;
360
                                        break;
361
                                    case 'float':
362
                                        $propertyValue = \PhpOffice\PhpSpreadsheet\Document\Properties::convertProperty($propertyValue, 'r4');
363
                                        $propertyValueType = \PhpOffice\PhpSpreadsheet\Document\Properties::PROPERTY_TYPE_FLOAT;
364
                                        break;
365
                                    default:
366 1
                                        $propertyValueType = \PhpOffice\PhpSpreadsheet\Document\Properties::PROPERTY_TYPE_STRING;
367
                                }
368
                            }
369
                        }
370 1
                        $docProps->setCustomProperty($propertyValueName, $propertyValue, $propertyValueType);
0 ignored issues
show
Bug introduced by
The variable $propertyValueName 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...
371 1
                        break;
372
                }
373
            }
374
        }
375
376 1
        $xml = simplexml_load_string(
377 1
            $this->securityScan($zip->getFromName('content.xml')),
378 1
            'SimpleXMLElement',
379 1
            \PhpOffice\PhpSpreadsheet\Settings::getLibXmlLoaderOptions()
380
        );
381 1
        $namespacesContent = $xml->getNamespaces(true);
382
383 1
        $workbook = $xml->children($namespacesContent['office']);
384 1
        foreach ($workbook->body->spreadsheet as $workbookData) {
385 1
            $workbookData = $workbookData->children($namespacesContent['table']);
386 1
            $worksheetID = 0;
387 1
            foreach ($workbookData->table as $worksheetDataSet) {
388 1
                $worksheetData = $worksheetDataSet->children($namespacesContent['table']);
389 1
                $worksheetDataAttributes = $worksheetDataSet->attributes($namespacesContent['table']);
390 1
                if ((isset($this->loadSheetsOnly)) && (isset($worksheetDataAttributes['name'])) &&
391 1
                    (!in_array($worksheetDataAttributes['name'], $this->loadSheetsOnly))) {
392
                    continue;
393
                }
394
395
                // Create new Worksheet
396 1
                $spreadsheet->createSheet();
397 1
                $spreadsheet->setActiveSheetIndex($worksheetID);
398 1
                if (isset($worksheetDataAttributes['name'])) {
399 1
                    $worksheetName = (string) $worksheetDataAttributes['name'];
400
                    //    Use false for $updateFormulaCellReferences to prevent adjustment of worksheet references in
401
                    //        formula cells... during the load, all formulae should be correct, and we're simply
402
                    //        bringing the worksheet name in line with the formula, not the reverse
403 1
                    $spreadsheet->getActiveSheet()->setTitle($worksheetName, false);
404
                }
405
406 1
                $rowID = 1;
407 1
                foreach ($worksheetData as $key => $rowData) {
408
                    switch ($key) {
409 1
                        case 'table-header-rows':
410
                            foreach ($rowData as $keyRowData => $cellData) {
411
                                $rowData = $cellData;
412
                                break;
413
                            }
414
                            break;
415 1
                        case 'table-row':
416 1
                            $rowDataTableAttributes = $rowData->attributes($namespacesContent['table']);
417 1
                            $rowRepeats = (isset($rowDataTableAttributes['number-rows-repeated'])) ? $rowDataTableAttributes['number-rows-repeated'] : 1;
418 1
                            $columnID = 'A';
419 1
                            foreach ($rowData as $key => $cellData) {
420 1
                                if ($this->getReadFilter() !== null) {
421 1
                                    if (!$this->getReadFilter()->readCell($columnID, $rowID, $worksheetName)) {
0 ignored issues
show
Bug introduced by
The variable $worksheetName 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...
422
                                        continue;
423
                                    }
424
                                }
425
426 1
                                $cellDataText = (isset($namespacesContent['text'])) ? $cellData->children($namespacesContent['text']) : '';
427 1
                                $cellDataOffice = $cellData->children($namespacesContent['office']);
428 1
                                $cellDataOfficeAttributes = $cellData->attributes($namespacesContent['office']);
429 1
                                $cellDataTableAttributes = $cellData->attributes($namespacesContent['table']);
430
431 1
                                $type = $formatting = $hyperlink = null;
432 1
                                $hasCalculatedValue = false;
433 1
                                $cellDataFormula = '';
434 1
                                if (isset($cellDataTableAttributes['formula'])) {
435 1
                                    $cellDataFormula = $cellDataTableAttributes['formula'];
436 1
                                    $hasCalculatedValue = true;
437
                                }
438
439 1
                                if (isset($cellDataOffice->annotation)) {
440 1
                                    $annotationText = $cellDataOffice->annotation->children($namespacesContent['text']);
441 1
                                    $textArray = [];
442 1
                                    foreach ($annotationText as $t) {
443 1
                                        if (isset($t->span)) {
444
                                            foreach ($t->span as $text) {
445
                                                $textArray[] = (string) $text;
446
                                            }
447
                                        } else {
448 1
                                            $textArray[] = (string) $t;
449
                                        }
450
                                    }
451 1
                                    $text = implode("\n", $textArray);
452 1
                                    $spreadsheet->getActiveSheet()->getComment($columnID . $rowID)->setText($this->parseRichText($text));
453
//                                                                    ->setAuthor( $author )
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
454
                                }
455
456 1
                                if (isset($cellDataText->p)) {
457
                                    // Consolidate if there are multiple p records (maybe with spans as well)
458 1
                                    $dataArray = [];
459
                                    // Text can have multiple text:p and within those, multiple text:span.
460
                                    // text:p newlines, but text:span does not.
461
                                    // Also, here we assume there is no text data is span fields are specified, since
462
                                    // we have no way of knowing proper positioning anyway.
463 1
                                    foreach ($cellDataText->p as $pData) {
464 1
                                        if (isset($pData->span)) {
465
                                            // span sections do not newline, so we just create one large string here
466 1
                                            $spanSection = '';
467 1
                                            foreach ($pData->span as $spanData) {
468 1
                                                $spanSection .= $spanData;
469
                                            }
470 1
                                            array_push($dataArray, $spanSection);
471
                                        } elseif (isset($pData->a)) {
472
                                            //Reading the hyperlinks in p
473 1
                                            array_push($dataArray, $pData->a);
474
                                        } else {
475 1
                                            array_push($dataArray, $pData);
476
                                        }
477
                                    }
478 1
                                    $allCellDataText = implode($dataArray, "\n");
479
480 1
                                    switch ($cellDataOfficeAttributes['value-type']) {
481 1
                                        case 'string':
482 1
                                            $type = \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING;
483 1
                                            $dataValue = $allCellDataText;
484 1
                                            if (isset($dataValue->a)) {
485
                                                $dataValue = $dataValue->a;
486
                                                $cellXLinkAttributes = $dataValue->attributes($namespacesContent['xlink']);
487
                                                $hyperlink = $cellXLinkAttributes['href'];
488
                                            }
489 1
                                            break;
490 1
                                        case 'boolean':
491 1
                                            $type = \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_BOOL;
492 1
                                            $dataValue = ($allCellDataText == 'TRUE') ? true : false;
493 1
                                            break;
494 1 View Code Duplication
                                        case 'percentage':
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...
495
                                            $type = \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_NUMERIC;
496
                                            $dataValue = (float) $cellDataOfficeAttributes['value'];
497
                                            if (floor($dataValue) == $dataValue) {
498
                                                $dataValue = (integer) $dataValue;
499
                                            }
500
                                            $formatting = \PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_PERCENTAGE_00;
501
                                            break;
502 1 View Code Duplication
                                        case 'currency':
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...
503
                                            $type = \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_NUMERIC;
504
                                            $dataValue = (float) $cellDataOfficeAttributes['value'];
505
                                            if (floor($dataValue) == $dataValue) {
506
                                                $dataValue = (integer) $dataValue;
507
                                            }
508
                                            $formatting = \PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_CURRENCY_USD_SIMPLE;
509
                                            break;
510 1
                                        case 'float':
511 1
                                            $type = \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_NUMERIC;
512 1
                                            $dataValue = (float) $cellDataOfficeAttributes['value'];
513 1
                                            if (floor($dataValue) == $dataValue) {
514 1
                                                if ($dataValue == (integer) $dataValue) {
515 1
                                                    $dataValue = (integer) $dataValue;
516
                                                } else {
517
                                                    $dataValue = (float) $dataValue;
518
                                                }
519
                                            }
520 1
                                            break;
521 1
                                        case 'date':
522 1
                                            $type = \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_NUMERIC;
523 1
                                            $dateObj = new DateTime($cellDataOfficeAttributes['date-value'], $GMT);
524 1
                                            $dateObj->setTimeZone($timezoneObj);
525 1
                                            list($year, $month, $day, $hour, $minute, $second) = explode(' ', $dateObj->format('Y m d H i s'));
526 1
                                            $dataValue = \PhpOffice\PhpSpreadsheet\Shared\Date::formattedPHPToExcel($year, $month, $day, $hour, $minute, $second);
527 1
                                            if ($dataValue != floor($dataValue)) {
528 1
                                                $formatting = \PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_DATE_XLSX15 . ' ' . \PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_DATE_TIME4;
529
                                            } else {
530 1
                                                $formatting = \PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_DATE_XLSX15;
531
                                            }
532 1
                                            break;
533 1
                                        case 'time':
534 1
                                            $type = \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_NUMERIC;
535 1
                                            $dataValue = \PhpOffice\PhpSpreadsheet\Shared\Date::PHPToExcel(strtotime('01-01-1970 ' . implode(':', sscanf($cellDataOfficeAttributes['time-value'], 'PT%dH%dM%dS'))));
536 1
                                            $formatting = \PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_DATE_TIME4;
537 1
                                            break;
538
                                    }
539
                                } else {
540 1
                                    $type = \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_NULL;
541 1
                                    $dataValue = null;
542
                                }
543
544 1
                                if ($hasCalculatedValue) {
545 1
                                    $type = \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_FORMULA;
546 1
                                    $cellDataFormula = substr($cellDataFormula, strpos($cellDataFormula, ':=') + 1);
547 1
                                    $temp = explode('"', $cellDataFormula);
548 1
                                    $tKey = false;
549 1
                                    foreach ($temp as &$value) {
550
                                        //    Only replace in alternate array entries (i.e. non-quoted blocks)
551 1
                                        if ($tKey = !$tKey) {
552 1
                                            $value = preg_replace('/\[([^\.]+)\.([^\.]+):\.([^\.]+)\]/Ui', '$1!$2:$3', $value); //  Cell range reference in another sheet
553 1
                                            $value = preg_replace('/\[([^\.]+)\.([^\.]+)\]/Ui', '$1!$2', $value); //  Cell reference in another sheet
554 1
                                            $value = preg_replace('/\[\.([^\.]+):\.([^\.]+)\]/Ui', '$1:$2', $value); //  Cell range reference
555 1
                                            $value = preg_replace('/\[\.([^\.]+)\]/Ui', '$1', $value); //  Simple cell reference
556 1
                                            $value = \PhpOffice\PhpSpreadsheet\Calculation::translateSeparator(';', ',', $value, $inBraces);
557
                                        }
558
                                    }
559 1
                                    unset($value);
560
                                    //    Then rebuild the formula string
561 1
                                    $cellDataFormula = implode('"', $temp);
562
                                }
563
564 1
                                $colRepeats = (isset($cellDataTableAttributes['number-columns-repeated'])) ? $cellDataTableAttributes['number-columns-repeated'] : 1;
565 1
                                if ($type !== null) {
566 1
                                    for ($i = 0; $i < $colRepeats; ++$i) {
567 1
                                        if ($i > 0) {
568 1
                                            ++$columnID;
569
                                        }
570 1
                                        if ($type !== \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_NULL) {
571 1
                                            for ($rowAdjust = 0; $rowAdjust < $rowRepeats; ++$rowAdjust) {
572 1
                                                $rID = $rowID + $rowAdjust;
573 1
                                                $spreadsheet->getActiveSheet()->getCell($columnID . $rID)->setValueExplicit((($hasCalculatedValue) ? $cellDataFormula : $dataValue), $type);
0 ignored issues
show
Bug introduced by
The variable $dataValue 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...
574 1
                                                if ($hasCalculatedValue) {
575 1
                                                    $spreadsheet->getActiveSheet()->getCell($columnID . $rID)->setCalculatedValue($dataValue);
576
                                                }
577 1
                                                if ($formatting !== null) {
578 1
                                                    $spreadsheet->getActiveSheet()->getStyle($columnID . $rID)->getNumberFormat()->setFormatCode($formatting);
579
                                                } else {
580 1
                                                    $spreadsheet->getActiveSheet()->getStyle($columnID . $rID)->getNumberFormat()->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_GENERAL);
581
                                                }
582 1
                                                if ($hyperlink !== null) {
583
                                                    $spreadsheet->getActiveSheet()->getCell($columnID . $rID)->getHyperlink()->setUrl($hyperlink);
584
                                                }
585
                                            }
586
                                        }
587
                                    }
588
                                }
589
590
                                //    Merged cells
591 1
                                if ((isset($cellDataTableAttributes['number-columns-spanned'])) || (isset($cellDataTableAttributes['number-rows-spanned']))) {
592 1
                                    if (($type !== \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_NULL) || (!$this->readDataOnly)) {
593 1
                                        $columnTo = $columnID;
594 1 View Code Duplication
                                        if (isset($cellDataTableAttributes['number-columns-spanned'])) {
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...
595 1
                                            $columnTo = \PhpOffice\PhpSpreadsheet\Cell::stringFromColumnIndex(\PhpOffice\PhpSpreadsheet\Cell::columnIndexFromString($columnID) + $cellDataTableAttributes['number-columns-spanned'] - 2);
596
                                        }
597 1
                                        $rowTo = $rowID;
598 1
                                        if (isset($cellDataTableAttributes['number-rows-spanned'])) {
599 1
                                            $rowTo = $rowTo + $cellDataTableAttributes['number-rows-spanned'] - 1;
600
                                        }
601 1
                                        $cellRange = $columnID . $rowID . ':' . $columnTo . $rowTo;
602 1
                                        $spreadsheet->getActiveSheet()->mergeCells($cellRange);
603
                                    }
604
                                }
605
606 1
                                ++$columnID;
607
                            }
608 1
                            $rowID += $rowRepeats;
609 1
                            break;
610
                    }
611
                }
612 1
                ++$worksheetID;
613
            }
614
        }
615
616
        // Return
617 1
        return $spreadsheet;
618
    }
619
620 1
    private function parseRichText($is = '')
621
    {
622 1
        $value = new \PhpOffice\PhpSpreadsheet\RichText();
623
624 1
        $value->createText($is);
625
626 1
        return $value;
627
    }
628
}
629