Completed
Push — develop ( 39b55d...e2e982 )
by Adrien
19:14
created

Ods::loadIntoExisting()   F

Complexity

Conditions 81
Paths > 20000

Size

Total Lines 345
Code Lines 252

Duplication

Lines 19
Ratio 5.51 %

Code Coverage

Tests 197
CRAP Score 120.9459

Importance

Changes 0
Metric Value
cc 81
eloc 252
nc 429496.7295
nop 2
dl 19
loc 345
ccs 197
cts 241
cp 0.8174
crap 120.9459
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
8
/**
9
 * Copyright (c) 2006 - 2016 PhpSpreadsheet
10
 *
11
 * This library is free software; you can redistribute it and/or
12
 * modify it under the terms of the GNU Lesser General Public
13
 * License as published by the Free Software Foundation; either
14
 * version 2.1 of the License, or (at your option) any later version.
15
 *
16
 * This library is distributed in the hope that it will be useful,
17
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19
 * Lesser General Public License for more details.
20
 *
21
 * You should have received a copy of the GNU Lesser General Public
22
 * License along with this library; if not, write to the Free Software
23
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
24
 *
25
 * @category   PhpSpreadsheet
26
 * @copyright  Copyright (c) 2006 - 2016 PhpSpreadsheet (https://github.com/PHPOffice/PhpSpreadsheet)
27
 * @license    http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt    LGPL
28
 * @version    ##VERSION##, ##DATE##
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 1
    public function __construct()
43
    {
44 1
        $this->readFilter = new DefaultReadFilter();
45 1
    }
46
47
    /**
48
     * Can the current IReader read the file?
49
     *
50
     * @param     string         $pFilename
51
     * @throws Exception
52
     * @return     bool
53
     */
54 1
    public function canRead($pFilename)
55
    {
56
        // Check if file exists
57 1
        if (!file_exists($pFilename)) {
58
            throw new Exception('Could not open ' . $pFilename . ' for reading! File does not exist.');
59
        }
60
61 1
        $zipClass = \PhpOffice\PhpSpreadsheet\Settings::getZipClass();
62
63
        // Check if zip class exists
0 ignored issues
show
Unused Code Comprehensibility introduced by
46% 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...
64
//        if (!class_exists($zipClass, false)) {
65
//            throw new Exception($zipClass . " library is not enabled");
66
//        }
67
68 1
        $mimeType = 'UNKNOWN';
69
        // Load file
70 1
        $zip = new $zipClass();
71 1
        if ($zip->open($pFilename) === true) {
72
            // check if it is an OOXML archive
73 1
            $stat = $zip->statName('mimetype');
74 1
            if ($stat && ($stat['size'] <= 255)) {
75 1
                $mimeType = $zip->getFromName($stat['name']);
76
            } 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...
77
                $xml = simplexml_load_string(
78
                    $this->securityScan($zip->getFromName('META-INF/manifest.xml')),
79
                    'SimpleXMLElement',
80
                    \PhpOffice\PhpSpreadsheet\Settings::getLibXmlLoaderOptions()
81
                );
82
                $namespacesContent = $xml->getNamespaces(true);
83
                if (isset($namespacesContent['manifest'])) {
84
                    $manifest = $xml->children($namespacesContent['manifest']);
85
                    foreach ($manifest as $manifestDataSet) {
86
                        $manifestAttributes = $manifestDataSet->attributes($namespacesContent['manifest']);
87
                        if ($manifestAttributes->{'full-path'} == '/') {
88
                            $mimeType = (string) $manifestAttributes->{'media-type'};
89
                            break;
90
                        }
91
                    }
92
                }
93
            }
94
95 1
            $zip->close();
96
97 1
            return $mimeType === 'application/vnd.oasis.opendocument.spreadsheet';
98
        }
99
100
        return false;
101
    }
102
103
    /**
104
     * Reads names of the worksheets from a file, without parsing the whole file to a PhpSpreadsheet object
105
     *
106
     * @param     string         $pFilename
107
     * @throws     Exception
108
     */
109
    public function listWorksheetNames($pFilename)
110
    {
111
        // Check if file exists
112
        if (!file_exists($pFilename)) {
113
            throw new Exception('Could not open ' . $pFilename . ' for reading! File does not exist.');
114
        }
115
116
        $zipClass = \PhpOffice\PhpSpreadsheet\Settings::getZipClass();
117
118
        $zip = new $zipClass();
119
        if (!$zip->open($pFilename)) {
120
            throw new Exception('Could not open ' . $pFilename . ' for reading! Error opening file.');
121
        }
122
123
        $worksheetNames = [];
124
125
        $xml = new XMLReader();
126
        $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...
127
            $this->securityScanFile('zip://' . realpath($pFilename) . '#content.xml'),
128
            null,
129
            \PhpOffice\PhpSpreadsheet\Settings::getLibXmlLoaderOptions()
130
        );
131
        $xml->setParserProperty(2, true);
132
133
        //    Step into the first level of content of the XML
134
        $xml->read();
135
        while ($xml->read()) {
136
            //    Quickly jump through to the office:body node
137
            while ($xml->name !== 'office:body') {
138
                if ($xml->isEmptyElement) {
139
                    $xml->read();
140
                } else {
141
                    $xml->next();
142
                }
143
            }
144
            //    Now read each node until we find our first table:table node
145
            while ($xml->read()) {
146
                if ($xml->name == 'table:table' && $xml->nodeType == XMLReader::ELEMENT) {
147
                    //    Loop through each table:table node reading the table:name attribute for each worksheet name
148
                    do {
149
                        $worksheetNames[] = $xml->getAttribute('table:name');
150
                        $xml->next();
151
                    } while ($xml->name == 'table:table' && $xml->nodeType == XMLReader::ELEMENT);
152
                }
153
            }
154
        }
155
156
        return $worksheetNames;
157
    }
158
159
    /**
160
     * Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns)
161
     *
162
     * @param   string     $pFilename
163
     * @throws   Exception
164
     */
165
    public function listWorksheetInfo($pFilename)
166
    {
167
        // Check if file exists
168
        if (!file_exists($pFilename)) {
169
            throw new Exception('Could not open ' . $pFilename . ' for reading! File does not exist.');
170
        }
171
172
        $worksheetInfo = [];
173
174
        $zipClass = \PhpOffice\PhpSpreadsheet\Settings::getZipClass();
175
176
        $zip = new $zipClass();
177
        if (!$zip->open($pFilename)) {
178
            throw new Exception('Could not open ' . $pFilename . ' for reading! Error opening file.');
179
        }
180
181
        $xml = new XMLReader();
182
        $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...
183
            $this->securityScanFile('zip://' . realpath($pFilename) . '#content.xml'),
184
            null,
185
            \PhpOffice\PhpSpreadsheet\Settings::getLibXmlLoaderOptions()
186
        );
187
        $xml->setParserProperty(2, true);
188
189
        //    Step into the first level of content of the XML
190
        $xml->read();
191
        while ($xml->read()) {
192
            //    Quickly jump through to the office:body node
193
            while ($xml->name !== 'office:body') {
194
                if ($xml->isEmptyElement) {
195
                    $xml->read();
196
                } else {
197
                    $xml->next();
198
                }
199
            }
200
                //    Now read each node until we find our first table:table node
201
            while ($xml->read()) {
202
                if ($xml->name == 'table:table' && $xml->nodeType == XMLReader::ELEMENT) {
203
                    $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...
204
205
                    $tmpInfo = [
206
                        'worksheetName' => $xml->getAttribute('table:name'),
207
                        'lastColumnLetter' => 'A',
208
                        'lastColumnIndex' => 0,
209
                        'totalRows' => 0,
210
                        'totalColumns' => 0,
211
                    ];
212
213
                    //    Loop through each child node of the table:table element reading
214
                    $currCells = 0;
215
                    do {
216
                        $xml->read();
217
                        if ($xml->name == 'table:table-row' && $xml->nodeType == XMLReader::ELEMENT) {
218
                            $rowspan = $xml->getAttribute('table:number-rows-repeated');
219
                            $rowspan = empty($rowspan) ? 1 : $rowspan;
220
                            $tmpInfo['totalRows'] += $rowspan;
221
                            $tmpInfo['totalColumns'] = max($tmpInfo['totalColumns'], $currCells);
222
                            $currCells = 0;
223
                            //    Step into the row
224
                            $xml->read();
225
                            do {
226
                                if ($xml->name == 'table:table-cell' && $xml->nodeType == XMLReader::ELEMENT) {
227
                                    if (!$xml->isEmptyElement) {
228
                                        ++$currCells;
229
                                        $xml->next();
230
                                    } else {
231
                                        $xml->read();
232
                                    }
233
                                } elseif ($xml->name == 'table:covered-table-cell' && $xml->nodeType == XMLReader::ELEMENT) {
234
                                    $mergeSize = $xml->getAttribute('table:number-columns-repeated');
235
                                    $currCells += $mergeSize;
236
                                    $xml->read();
237
                                }
238
                            } while ($xml->name != 'table:table-row');
239
                        }
240
                    } while ($xml->name != 'table:table');
241
242
                    $tmpInfo['totalColumns'] = max($tmpInfo['totalColumns'], $currCells);
243
                    $tmpInfo['lastColumnIndex'] = $tmpInfo['totalColumns'] - 1;
244
                    $tmpInfo['lastColumnLetter'] = \PhpOffice\PhpSpreadsheet\Cell::stringFromColumnIndex($tmpInfo['lastColumnIndex']);
245
                    $worksheetInfo[] = $tmpInfo;
246
                }
247
            }
248
        }
249
250
        return $worksheetInfo;
251
    }
252
253
    /**
254
     * Loads PhpSpreadsheet from file
255
     *
256
     * @param     string         $pFilename
257
     * @throws     Exception
258
     * @return     \PhpOffice\PhpSpreadsheet\Spreadsheet
259
     */
260 1
    public function load($pFilename)
261
    {
262
        // Create new Spreadsheet
263 1
        $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
264
265
        // Load into this instance
266 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...
267
    }
268
269 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...
270
    {
271
        $styleAttributeValue = strtolower($styleAttributeValue);
272
        foreach ($styleList as $style) {
273
            if ($styleAttributeValue == strtolower($style)) {
274
                $styleAttributeValue = $style;
275
276
                return true;
277
            }
278
        }
279
280
        return false;
281
    }
282
283
    /**
284
     * Loads PhpSpreadsheet from file into PhpSpreadsheet instance
285
     *
286
     * @param     string         $pFilename
287
     * @param    \PhpOffice\PhpSpreadsheet\Spreadsheet    $spreadsheet
288
     * @throws     Exception
289
     * @return     \PhpOffice\PhpSpreadsheet\Spreadsheet
290
     */
291 1
    public function loadIntoExisting($pFilename, \PhpOffice\PhpSpreadsheet\Spreadsheet $spreadsheet)
292
    {
293
        // Check if file exists
294 1
        if (!file_exists($pFilename)) {
295
            throw new Exception('Could not open ' . $pFilename . ' for reading! File does not exist.');
296
        }
297
298 1
        $timezoneObj = new DateTimeZone('Europe/London');
299 1
        $GMT = new \DateTimeZone('UTC');
300
301 1
        $zipClass = \PhpOffice\PhpSpreadsheet\Settings::getZipClass();
302
303 1
        $zip = new $zipClass();
304 1
        if (!$zip->open($pFilename)) {
305
            throw new Exception('Could not open ' . $pFilename . ' for reading! Error opening file.');
306
        }
307
308 1
        $xml = simplexml_load_string(
309 1
            $this->securityScan($zip->getFromName('meta.xml')),
310 1
            'SimpleXMLElement',
311 1
            \PhpOffice\PhpSpreadsheet\Settings::getLibXmlLoaderOptions()
312
        );
313 1
        $namespacesMeta = $xml->getNamespaces(true);
314
315 1
        $docProps = $spreadsheet->getProperties();
316 1
        $officeProperty = $xml->children($namespacesMeta['office']);
317 1
        foreach ($officeProperty as $officePropertyData) {
318 1
            $officePropertyDC = [];
319 1
            if (isset($namespacesMeta['dc'])) {
320 1
                $officePropertyDC = $officePropertyData->children($namespacesMeta['dc']);
321
            }
322 1
            foreach ($officePropertyDC as $propertyName => $propertyValue) {
323 1
                $propertyValue = (string) $propertyValue;
324
                switch ($propertyName) {
325 1
                    case 'title':
326 1
                        $docProps->setTitle($propertyValue);
327 1
                        break;
328 1
                    case 'subject':
329 1
                        $docProps->setSubject($propertyValue);
330 1
                        break;
331 1
                    case 'creator':
332
                        $docProps->setCreator($propertyValue);
333
                        $docProps->setLastModifiedBy($propertyValue);
334
                        break;
335 1
                    case 'date':
336 1
                        $creationDate = strtotime($propertyValue);
337 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...
338 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...
339 1
                        break;
340 1
                    case 'description':
341 1
                        $docProps->setDescription($propertyValue);
342 1
                        break;
343
                }
344
            }
345 1
            $officePropertyMeta = [];
346 1
            if (isset($namespacesMeta['dc'])) {
347 1
                $officePropertyMeta = $officePropertyData->children($namespacesMeta['meta']);
348
            }
349 1
            foreach ($officePropertyMeta as $propertyName => $propertyValue) {
350 1
                $propertyValueAttributes = $propertyValue->attributes($namespacesMeta['meta']);
351 1
                $propertyValue = (string) $propertyValue;
352
                switch ($propertyName) {
353 1
                    case 'initial-creator':
354 1
                        $docProps->setCreator($propertyValue);
355 1
                        break;
356 1
                    case 'keyword':
357 1
                        $docProps->setKeywords($propertyValue);
358 1
                        break;
359 1
                    case 'creation-date':
360 1
                        $creationDate = strtotime($propertyValue);
361 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...
362 1
                        break;
363 1
                    case 'user-defined':
364 1
                        $propertyValueType = \PhpOffice\PhpSpreadsheet\Document\Properties::PROPERTY_TYPE_STRING;
365 1
                        foreach ($propertyValueAttributes as $key => $value) {
366 1
                            if ($key == 'name') {
367 1
                                $propertyValueName = (string) $value;
368
                            } elseif ($key == 'value-type') {
369
                                switch ($value) {
370
                                    case 'date':
371
                                        $propertyValue = \PhpOffice\PhpSpreadsheet\Document\Properties::convertProperty($propertyValue, 'date');
372
                                        $propertyValueType = \PhpOffice\PhpSpreadsheet\Document\Properties::PROPERTY_TYPE_DATE;
373
                                        break;
374
                                    case 'boolean':
375
                                        $propertyValue = \PhpOffice\PhpSpreadsheet\Document\Properties::convertProperty($propertyValue, 'bool');
376
                                        $propertyValueType = \PhpOffice\PhpSpreadsheet\Document\Properties::PROPERTY_TYPE_BOOLEAN;
377
                                        break;
378
                                    case 'float':
379
                                        $propertyValue = \PhpOffice\PhpSpreadsheet\Document\Properties::convertProperty($propertyValue, 'r4');
380
                                        $propertyValueType = \PhpOffice\PhpSpreadsheet\Document\Properties::PROPERTY_TYPE_FLOAT;
381
                                        break;
382
                                    default:
383 1
                                        $propertyValueType = \PhpOffice\PhpSpreadsheet\Document\Properties::PROPERTY_TYPE_STRING;
384
                                }
385
                            }
386
                        }
387 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...
388 1
                        break;
389
                }
390
            }
391
        }
392
393 1
        $xml = simplexml_load_string(
394 1
            $this->securityScan($zip->getFromName('content.xml')),
395 1
            'SimpleXMLElement',
396 1
            \PhpOffice\PhpSpreadsheet\Settings::getLibXmlLoaderOptions()
397
        );
398 1
        $namespacesContent = $xml->getNamespaces(true);
399
400 1
        $workbook = $xml->children($namespacesContent['office']);
401 1
        foreach ($workbook->body->spreadsheet as $workbookData) {
402 1
            $workbookData = $workbookData->children($namespacesContent['table']);
403 1
            $worksheetID = 0;
404 1
            foreach ($workbookData->table as $worksheetDataSet) {
405 1
                $worksheetData = $worksheetDataSet->children($namespacesContent['table']);
406 1
                $worksheetDataAttributes = $worksheetDataSet->attributes($namespacesContent['table']);
407 1
                if ((isset($this->loadSheetsOnly)) && (isset($worksheetDataAttributes['name'])) &&
408 1
                    (!in_array($worksheetDataAttributes['name'], $this->loadSheetsOnly))) {
409
                    continue;
410
                }
411
412
                // Create new Worksheet
413 1
                $spreadsheet->createSheet();
414 1
                $spreadsheet->setActiveSheetIndex($worksheetID);
415 1
                if (isset($worksheetDataAttributes['name'])) {
416 1
                    $worksheetName = (string) $worksheetDataAttributes['name'];
417
                    //    Use false for $updateFormulaCellReferences to prevent adjustment of worksheet references in
418
                    //        formula cells... during the load, all formulae should be correct, and we're simply
419
                    //        bringing the worksheet name in line with the formula, not the reverse
420 1
                    $spreadsheet->getActiveSheet()->setTitle($worksheetName, false);
421
                }
422
423 1
                $rowID = 1;
424 1
                foreach ($worksheetData as $key => $rowData) {
425
                    switch ($key) {
426 1
                        case 'table-header-rows':
427
                            foreach ($rowData as $keyRowData => $cellData) {
428
                                $rowData = $cellData;
429
                                break;
430
                            }
431
                            break;
432 1
                        case 'table-row':
433 1
                            $rowDataTableAttributes = $rowData->attributes($namespacesContent['table']);
434 1
                            $rowRepeats = (isset($rowDataTableAttributes['number-rows-repeated'])) ? $rowDataTableAttributes['number-rows-repeated'] : 1;
435 1
                            $columnID = 'A';
436 1
                            foreach ($rowData as $key => $cellData) {
437 1
                                if ($this->getReadFilter() !== null) {
438 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...
439
                                        continue;
440
                                    }
441
                                }
442
443 1
                                $cellDataText = (isset($namespacesContent['text'])) ? $cellData->children($namespacesContent['text']) : '';
444 1
                                $cellDataOffice = $cellData->children($namespacesContent['office']);
445 1
                                $cellDataOfficeAttributes = $cellData->attributes($namespacesContent['office']);
446 1
                                $cellDataTableAttributes = $cellData->attributes($namespacesContent['table']);
447
448 1
                                $type = $formatting = $hyperlink = null;
449 1
                                $hasCalculatedValue = false;
450 1
                                $cellDataFormula = '';
451 1
                                if (isset($cellDataTableAttributes['formula'])) {
452 1
                                    $cellDataFormula = $cellDataTableAttributes['formula'];
453 1
                                    $hasCalculatedValue = true;
454
                                }
455
456 1
                                if (isset($cellDataOffice->annotation)) {
457 1
                                    $annotationText = $cellDataOffice->annotation->children($namespacesContent['text']);
458 1
                                    $textArray = [];
459 1
                                    foreach ($annotationText as $t) {
460 1
                                        if (isset($t->span)) {
461
                                            foreach ($t->span as $text) {
462
                                                $textArray[] = (string) $text;
463
                                            }
464
                                        } else {
465 1
                                            $textArray[] = (string) $t;
466
                                        }
467
                                    }
468 1
                                    $text = implode("\n", $textArray);
469 1
                                    $spreadsheet->getActiveSheet()->getComment($columnID . $rowID)->setText($this->parseRichText($text));
470
//                                                                    ->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...
471
                                }
472
473 1
                                if (isset($cellDataText->p)) {
474
                                    // Consolidate if there are multiple p records (maybe with spans as well)
475 1
                                    $dataArray = [];
476
                                    // Text can have multiple text:p and within those, multiple text:span.
477
                                    // text:p newlines, but text:span does not.
478
                                    // Also, here we assume there is no text data is span fields are specified, since
479
                                    // we have no way of knowing proper positioning anyway.
480 1
                                    foreach ($cellDataText->p as $pData) {
481 1
                                        if (isset($pData->span)) {
482
                                            // span sections do not newline, so we just create one large string here
483 1
                                            $spanSection = '';
484 1
                                            foreach ($pData->span as $spanData) {
485 1
                                                $spanSection .= $spanData;
486
                                            }
487 1
                                            array_push($dataArray, $spanSection);
488
                                        } elseif (isset($pData->a)) {
489
                                            //Reading the hyperlinks in p
490 1
                                            array_push($dataArray, $pData->a);
491
                                        } else {
492 1
                                            array_push($dataArray, $pData);
493
                                        }
494
                                    }
495 1
                                    $allCellDataText = implode($dataArray, "\n");
496
497 1
                                    switch ($cellDataOfficeAttributes['value-type']) {
498 1
                                        case 'string':
499 1
                                            $type = \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING;
500 1
                                            $dataValue = $allCellDataText;
501 1
                                            if (isset($dataValue->a)) {
502
                                                $dataValue = $dataValue->a;
503
                                                $cellXLinkAttributes = $dataValue->attributes($namespacesContent['xlink']);
504
                                                $hyperlink = $cellXLinkAttributes['href'];
505
                                            }
506 1
                                            break;
507 1
                                        case 'boolean':
508 1
                                            $type = \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_BOOL;
509 1
                                            $dataValue = ($allCellDataText == 'TRUE') ? true : false;
510 1
                                            break;
511 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...
512
                                            $type = \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_NUMERIC;
513
                                            $dataValue = (float) $cellDataOfficeAttributes['value'];
514
                                            if (floor($dataValue) == $dataValue) {
515
                                                $dataValue = (integer) $dataValue;
516
                                            }
517
                                            $formatting = \PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_PERCENTAGE_00;
518
                                            break;
519 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...
520
                                            $type = \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_NUMERIC;
521
                                            $dataValue = (float) $cellDataOfficeAttributes['value'];
522
                                            if (floor($dataValue) == $dataValue) {
523
                                                $dataValue = (integer) $dataValue;
524
                                            }
525
                                            $formatting = \PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_CURRENCY_USD_SIMPLE;
526
                                            break;
527 1
                                        case 'float':
528 1
                                            $type = \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_NUMERIC;
529 1
                                            $dataValue = (float) $cellDataOfficeAttributes['value'];
530 1
                                            if (floor($dataValue) == $dataValue) {
531 1
                                                if ($dataValue == (integer) $dataValue) {
532 1
                                                    $dataValue = (integer) $dataValue;
533
                                                } else {
534
                                                    $dataValue = (float) $dataValue;
535
                                                }
536
                                            }
537 1
                                            break;
538 1
                                        case 'date':
539 1
                                            $type = \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_NUMERIC;
540 1
                                            $dateObj = new DateTime($cellDataOfficeAttributes['date-value'], $GMT);
541 1
                                            $dateObj->setTimeZone($timezoneObj);
542 1
                                            list($year, $month, $day, $hour, $minute, $second) = explode(' ', $dateObj->format('Y m d H i s'));
543 1
                                            $dataValue = \PhpOffice\PhpSpreadsheet\Shared\Date::formattedPHPToExcel($year, $month, $day, $hour, $minute, $second);
544 1
                                            if ($dataValue != floor($dataValue)) {
545 1
                                                $formatting = \PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_DATE_XLSX15 . ' ' . \PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_DATE_TIME4;
546
                                            } else {
547 1
                                                $formatting = \PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_DATE_XLSX15;
548
                                            }
549 1
                                            break;
550 1
                                        case 'time':
551 1
                                            $type = \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_NUMERIC;
552 1
                                            $dataValue = \PhpOffice\PhpSpreadsheet\Shared\Date::PHPToExcel(strtotime('01-01-1970 ' . implode(':', sscanf($cellDataOfficeAttributes['time-value'], 'PT%dH%dM%dS'))));
553 1
                                            $formatting = \PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_DATE_TIME4;
554 1
                                            break;
555
                                    }
556
                                } else {
557 1
                                    $type = \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_NULL;
558 1
                                    $dataValue = null;
559
                                }
560
561 1
                                if ($hasCalculatedValue) {
562 1
                                    $type = \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_FORMULA;
563 1
                                    $cellDataFormula = substr($cellDataFormula, strpos($cellDataFormula, ':=') + 1);
564 1
                                    $temp = explode('"', $cellDataFormula);
565 1
                                    $tKey = false;
566 1
                                    foreach ($temp as &$value) {
567
                                        //    Only replace in alternate array entries (i.e. non-quoted blocks)
568 1
                                        if ($tKey = !$tKey) {
569 1
                                            $value = preg_replace('/\[([^\.]+)\.([^\.]+):\.([^\.]+)\]/Ui', '$1!$2:$3', $value); //  Cell range reference in another sheet
570 1
                                            $value = preg_replace('/\[([^\.]+)\.([^\.]+)\]/Ui', '$1!$2', $value); //  Cell reference in another sheet
571 1
                                            $value = preg_replace('/\[\.([^\.]+):\.([^\.]+)\]/Ui', '$1:$2', $value); //  Cell range reference
572 1
                                            $value = preg_replace('/\[\.([^\.]+)\]/Ui', '$1', $value); //  Simple cell reference
573 1
                                            $value = \PhpOffice\PhpSpreadsheet\Calculation::translateSeparator(';', ',', $value, $inBraces);
574
                                        }
575
                                    }
576 1
                                    unset($value);
577
                                    //    Then rebuild the formula string
578 1
                                    $cellDataFormula = implode('"', $temp);
579
                                }
580
581 1
                                $colRepeats = (isset($cellDataTableAttributes['number-columns-repeated'])) ? $cellDataTableAttributes['number-columns-repeated'] : 1;
582 1
                                if ($type !== null) {
583 1
                                    for ($i = 0; $i < $colRepeats; ++$i) {
584 1
                                        if ($i > 0) {
585 1
                                            ++$columnID;
586
                                        }
587 1
                                        if ($type !== \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_NULL) {
588 1
                                            for ($rowAdjust = 0; $rowAdjust < $rowRepeats; ++$rowAdjust) {
589 1
                                                $rID = $rowID + $rowAdjust;
590 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...
591 1
                                                if ($hasCalculatedValue) {
592 1
                                                    $spreadsheet->getActiveSheet()->getCell($columnID . $rID)->setCalculatedValue($dataValue);
593
                                                }
594 1
                                                if ($formatting !== null) {
595 1
                                                    $spreadsheet->getActiveSheet()->getStyle($columnID . $rID)->getNumberFormat()->setFormatCode($formatting);
596
                                                } else {
597 1
                                                    $spreadsheet->getActiveSheet()->getStyle($columnID . $rID)->getNumberFormat()->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_GENERAL);
598
                                                }
599 1
                                                if ($hyperlink !== null) {
600
                                                    $spreadsheet->getActiveSheet()->getCell($columnID . $rID)->getHyperlink()->setUrl($hyperlink);
601
                                                }
602
                                            }
603
                                        }
604
                                    }
605
                                }
606
607
                                //    Merged cells
608 1
                                if ((isset($cellDataTableAttributes['number-columns-spanned'])) || (isset($cellDataTableAttributes['number-rows-spanned']))) {
609 1
                                    if (($type !== \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_NULL) || (!$this->readDataOnly)) {
610 1
                                        $columnTo = $columnID;
611 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...
612 1
                                            $columnTo = \PhpOffice\PhpSpreadsheet\Cell::stringFromColumnIndex(\PhpOffice\PhpSpreadsheet\Cell::columnIndexFromString($columnID) + $cellDataTableAttributes['number-columns-spanned'] - 2);
613
                                        }
614 1
                                        $rowTo = $rowID;
615 1
                                        if (isset($cellDataTableAttributes['number-rows-spanned'])) {
616 1
                                            $rowTo = $rowTo + $cellDataTableAttributes['number-rows-spanned'] - 1;
617
                                        }
618 1
                                        $cellRange = $columnID . $rowID . ':' . $columnTo . $rowTo;
619 1
                                        $spreadsheet->getActiveSheet()->mergeCells($cellRange);
620
                                    }
621
                                }
622
623 1
                                ++$columnID;
624
                            }
625 1
                            $rowID += $rowRepeats;
626 1
                            break;
627
                    }
628
                }
629 1
                ++$worksheetID;
630
            }
631
        }
632
633
        // Return
634 1
        return $spreadsheet;
635
    }
636
637 1
    private function parseRichText($is = '')
638
    {
639 1
        $value = new \PhpOffice\PhpSpreadsheet\RichText();
640
641 1
        $value->createText($is);
642
643 1
        return $value;
644
    }
645
}
646