Completed
Push — develop ( 50ed76...6a48b5 )
by Adrien
63:50
created

Ods::load()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 7
ccs 3
cts 3
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace PhpOffice\PhpSpreadsheet\Reader;
4
5
use DateTime;
6
use DateTimeZone;
7
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
8
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
9
use PhpOffice\PhpSpreadsheet\Cell\DataType;
10
use PhpOffice\PhpSpreadsheet\Document\Properties;
11
use PhpOffice\PhpSpreadsheet\Reader\Security\XmlScanner;
12
use PhpOffice\PhpSpreadsheet\RichText\RichText;
13
use PhpOffice\PhpSpreadsheet\Settings;
14
use PhpOffice\PhpSpreadsheet\Shared\Date;
15
use PhpOffice\PhpSpreadsheet\Shared\File;
16
use PhpOffice\PhpSpreadsheet\Spreadsheet;
17
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
18
use XMLReader;
19
use ZipArchive;
20
21
class Ods extends BaseReader
22
{
23
    /**
24
     * Create a new Ods Reader instance.
25
     */
26 16
    public function __construct()
27
    {
28 16
        $this->readFilter = new DefaultReadFilter();
29 16
        $this->securityScanner = XmlScanner::getInstance($this);
30 16
    }
31
32
    /**
33
     * Can the current IReader read the file?
34
     *
35
     * @param string $pFilename
36
     *
37
     * @throws Exception
38
     *
39
     * @return bool
40
     */
41 3
    public function canRead($pFilename)
42
    {
43 3
        File::assertFile($pFilename);
44
45 3
        $mimeType = 'UNKNOWN';
46
47
        // Load file
48
49 3
        $zip = new ZipArchive();
50 3
        if ($zip->open($pFilename) === true) {
51
            // check if it is an OOXML archive
52 3
            $stat = $zip->statName('mimetype');
53 3
            if ($stat && ($stat['size'] <= 255)) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $stat of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
54 3
                $mimeType = $zip->getFromName($stat['name']);
55
            } elseif ($stat = $zip->statName('META-INF/manifest.xml')) {
0 ignored issues
show
Unused Code introduced by
The assignment to $stat is dead and can be removed.
Loading history...
56
                $xml = simplexml_load_string(
57
                    $this->securityScanner->scan($zip->getFromName('META-INF/manifest.xml')),
58
                    'SimpleXMLElement',
59
                    Settings::getLibXmlLoaderOptions()
60
                );
61
                $namespacesContent = $xml->getNamespaces(true);
62
                if (isset($namespacesContent['manifest'])) {
63
                    $manifest = $xml->children($namespacesContent['manifest']);
64
                    foreach ($manifest as $manifestDataSet) {
65
                        $manifestAttributes = $manifestDataSet->attributes($namespacesContent['manifest']);
66
                        if ($manifestAttributes->{'full-path'} == '/') {
67
                            $mimeType = (string) $manifestAttributes->{'media-type'};
68
69
                            break;
70
                        }
71
                    }
72
                }
73
            }
74
75 3
            $zip->close();
76
77 3
            return $mimeType === 'application/vnd.oasis.opendocument.spreadsheet';
78
        }
79
80
        return false;
81
    }
82
83
    /**
84
     * Reads names of the worksheets from a file, without parsing the whole file to a PhpSpreadsheet object.
85
     *
86
     * @param string $pFilename
87
     *
88
     * @throws Exception
89
     *
90
     * @return string[]
91
     */
92 1
    public function listWorksheetNames($pFilename)
93
    {
94 1
        File::assertFile($pFilename);
95
96 1
        $zip = new ZipArchive();
97 1
        if (!$zip->open($pFilename)) {
98
            throw new Exception('Could not open ' . $pFilename . ' for reading! Error opening file.');
99
        }
100
101 1
        $worksheetNames = [];
102
103 1
        $xml = new XMLReader();
104 1
        $xml->xml(
105 1
            $this->securityScanner->scanFile('zip://' . realpath($pFilename) . '#content.xml'),
106 1
            null,
107 1
            Settings::getLibXmlLoaderOptions()
108
        );
109 1
        $xml->setParserProperty(2, true);
110
111
        // Step into the first level of content of the XML
112 1
        $xml->read();
113 1
        while ($xml->read()) {
114
            // Quickly jump through to the office:body node
115 1
            while ($xml->name !== 'office:body') {
116 1
                if ($xml->isEmptyElement) {
117 1
                    $xml->read();
118
                } else {
119 1
                    $xml->next();
120
                }
121
            }
122
            // Now read each node until we find our first table:table node
123 1
            while ($xml->read()) {
124 1
                if ($xml->name == 'table:table' && $xml->nodeType == XMLReader::ELEMENT) {
125
                    // Loop through each table:table node reading the table:name attribute for each worksheet name
126
                    do {
127 1
                        $worksheetNames[] = $xml->getAttribute('table:name');
128 1
                        $xml->next();
129 1
                    } while ($xml->name == 'table:table' && $xml->nodeType == XMLReader::ELEMENT);
130
                }
131
            }
132
        }
133
134 1
        return $worksheetNames;
135
    }
136
137
    /**
138
     * Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns).
139
     *
140
     * @param string $pFilename
141
     *
142
     * @throws Exception
143
     *
144
     * @return array
145
     */
146
    public function listWorksheetInfo($pFilename)
147
    {
148
        File::assertFile($pFilename);
149
150
        $worksheetInfo = [];
151
152
        $zip = new ZipArchive();
153
        if (!$zip->open($pFilename)) {
154
            throw new Exception('Could not open ' . $pFilename . ' for reading! Error opening file.');
155
        }
156
157
        $xml = new XMLReader();
158
        $xml->xml(
159
            $this->securityScanner->scanFile('zip://' . realpath($pFilename) . '#content.xml'),
160
            null,
161
            Settings::getLibXmlLoaderOptions()
162
        );
163
        $xml->setParserProperty(2, true);
164
165
        // Step into the first level of content of the XML
166
        $xml->read();
167
        while ($xml->read()) {
168
            // Quickly jump through to the office:body node
169
            while ($xml->name !== 'office:body') {
170
                if ($xml->isEmptyElement) {
171
                    $xml->read();
172
                } else {
173
                    $xml->next();
174
                }
175
            }
176
            // Now read each node until we find our first table:table node
177
            while ($xml->read()) {
178
                if ($xml->name == 'table:table' && $xml->nodeType == XMLReader::ELEMENT) {
179
                    $worksheetNames[] = $xml->getAttribute('table:name');
180
181
                    $tmpInfo = [
182
                        'worksheetName' => $xml->getAttribute('table:name'),
183
                        'lastColumnLetter' => 'A',
184
                        'lastColumnIndex' => 0,
185
                        'totalRows' => 0,
186
                        'totalColumns' => 0,
187
                    ];
188
189
                    // Loop through each child node of the table:table element reading
190
                    $currCells = 0;
191
                    do {
192
                        $xml->read();
193
                        if ($xml->name == 'table:table-row' && $xml->nodeType == XMLReader::ELEMENT) {
194
                            $rowspan = $xml->getAttribute('table:number-rows-repeated');
195
                            $rowspan = empty($rowspan) ? 1 : $rowspan;
196
                            $tmpInfo['totalRows'] += $rowspan;
197
                            $tmpInfo['totalColumns'] = max($tmpInfo['totalColumns'], $currCells);
198
                            $currCells = 0;
199
                            // Step into the row
200
                            $xml->read();
201
                            do {
202
                                if ($xml->name == 'table:table-cell' && $xml->nodeType == XMLReader::ELEMENT) {
203
                                    if (!$xml->isEmptyElement) {
204
                                        ++$currCells;
205
                                        $xml->next();
206
                                    } else {
207
                                        $xml->read();
208
                                    }
209
                                } elseif ($xml->name == 'table:covered-table-cell' && $xml->nodeType == XMLReader::ELEMENT) {
210
                                    $mergeSize = $xml->getAttribute('table:number-columns-repeated');
211
                                    $currCells += (int) $mergeSize;
212
                                    $xml->read();
213
                                }
214
                            } while ($xml->name != 'table:table-row');
215
                        }
216
                    } while ($xml->name != 'table:table');
217
218
                    $tmpInfo['totalColumns'] = max($tmpInfo['totalColumns'], $currCells);
219
                    $tmpInfo['lastColumnIndex'] = $tmpInfo['totalColumns'] - 1;
220
                    $tmpInfo['lastColumnLetter'] = Coordinate::stringFromColumnIndex($tmpInfo['lastColumnIndex'] + 1);
221
                    $worksheetInfo[] = $tmpInfo;
222
                }
223
            }
224
        }
225
226
        return $worksheetInfo;
227
    }
228
229
    /**
230
     * Loads PhpSpreadsheet from file.
231
     *
232
     * @param string $pFilename
233
     *
234
     * @throws Exception
235
     *
236
     * @return Spreadsheet
237
     */
238 6
    public function load($pFilename)
239
    {
240
        // Create new Spreadsheet
241 6
        $spreadsheet = new Spreadsheet();
242
243
        // Load into this instance
244 6
        return $this->loadIntoExisting($pFilename, $spreadsheet);
245
    }
246
247
    /**
248
     * Loads PhpSpreadsheet from file into PhpSpreadsheet instance.
249
     *
250
     * @param string $pFilename
251
     * @param Spreadsheet $spreadsheet
252
     *
253
     * @throws Exception
254
     *
255
     * @return Spreadsheet
256
     */
257 12
    public function loadIntoExisting($pFilename, Spreadsheet $spreadsheet)
258
    {
259 12
        File::assertFile($pFilename);
260
261 12
        $timezoneObj = new DateTimeZone('Europe/London');
262 12
        $GMT = new \DateTimeZone('UTC');
263
264 12
        $zip = new ZipArchive();
265 12
        if (!$zip->open($pFilename)) {
266
            throw new Exception('Could not open ' . $pFilename . ' for reading! Error opening file.');
267
        }
268
269
        // Meta
270
271 12
        $xml = simplexml_load_string(
272 12
            $this->securityScanner->scan($zip->getFromName('meta.xml')),
273 12
            'SimpleXMLElement',
274 12
            Settings::getLibXmlLoaderOptions()
275
        );
276 12
        $namespacesMeta = $xml->getNamespaces(true);
277
278 12
        $docProps = $spreadsheet->getProperties();
279 12
        $officeProperty = $xml->children($namespacesMeta['office']);
280 12
        foreach ($officeProperty as $officePropertyData) {
281 12
            $officePropertyDC = [];
282 12
            if (isset($namespacesMeta['dc'])) {
283 12
                $officePropertyDC = $officePropertyData->children($namespacesMeta['dc']);
284
            }
285 12
            foreach ($officePropertyDC as $propertyName => $propertyValue) {
286 12
                $propertyValue = (string) $propertyValue;
287 12
                switch ($propertyName) {
288 12
                    case 'title':
289 10
                        $docProps->setTitle($propertyValue);
290
291 10
                        break;
292 12
                    case 'subject':
293 10
                        $docProps->setSubject($propertyValue);
294
295 10
                        break;
296 12
                    case 'creator':
297 5
                        $docProps->setCreator($propertyValue);
298 5
                        $docProps->setLastModifiedBy($propertyValue);
299
300 5
                        break;
301 12
                    case 'date':
302 12
                        $creationDate = strtotime($propertyValue);
303 12
                        $docProps->setCreated($creationDate);
304 12
                        $docProps->setModified($creationDate);
305
306 12
                        break;
307 10
                    case 'description':
308 10
                        $docProps->setDescription($propertyValue);
309
310 12
                        break;
311
                }
312
            }
313 12
            $officePropertyMeta = [];
314 12
            if (isset($namespacesMeta['dc'])) {
315 12
                $officePropertyMeta = $officePropertyData->children($namespacesMeta['meta']);
316
            }
317 12
            foreach ($officePropertyMeta as $propertyName => $propertyValue) {
318 12
                $propertyValueAttributes = $propertyValue->attributes($namespacesMeta['meta']);
319 12
                $propertyValue = (string) $propertyValue;
320 12
                switch ($propertyName) {
321 12
                    case 'initial-creator':
322 10
                        $docProps->setCreator($propertyValue);
323
324 10
                        break;
325 12
                    case 'keyword':
326 10
                        $docProps->setKeywords($propertyValue);
327
328 10
                        break;
329 12
                    case 'creation-date':
330 12
                        $creationDate = strtotime($propertyValue);
331 12
                        $docProps->setCreated($creationDate);
332
333 12
                        break;
334 12
                    case 'user-defined':
335 10
                        $propertyValueType = Properties::PROPERTY_TYPE_STRING;
336 10
                        foreach ($propertyValueAttributes as $key => $value) {
337 10
                            if ($key == 'name') {
338 10
                                $propertyValueName = (string) $value;
339
                            } elseif ($key == 'value-type') {
340
                                switch ($value) {
341
                                    case 'date':
342
                                        $propertyValue = Properties::convertProperty($propertyValue, 'date');
343
                                        $propertyValueType = Properties::PROPERTY_TYPE_DATE;
344
345
                                        break;
346
                                    case 'boolean':
347
                                        $propertyValue = Properties::convertProperty($propertyValue, 'bool');
348
                                        $propertyValueType = Properties::PROPERTY_TYPE_BOOLEAN;
349
350
                                        break;
351
                                    case 'float':
352
                                        $propertyValue = Properties::convertProperty($propertyValue, 'r4');
353
                                        $propertyValueType = Properties::PROPERTY_TYPE_FLOAT;
354
355
                                        break;
356
                                    default:
357 10
                                        $propertyValueType = Properties::PROPERTY_TYPE_STRING;
358
                                }
359
                            }
360
                        }
361 10
                        $docProps->setCustomProperty($propertyValueName, $propertyValue, $propertyValueType);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $propertyValueName does not seem to be defined for all execution paths leading up to this point.
Loading history...
362
363 12
                        break;
364
                }
365
            }
366
        }
367
368
        // Content
369
370 12
        $dom = new \DOMDocument('1.01', 'UTF-8');
371 12
        $dom->loadXML(
372 12
            $this->securityScanner->scan($zip->getFromName('content.xml')),
373 12
            Settings::getLibXmlLoaderOptions()
374
        );
375
376 12
        $officeNs = $dom->lookupNamespaceUri('office');
377 12
        $tableNs = $dom->lookupNamespaceUri('table');
378 12
        $textNs = $dom->lookupNamespaceUri('text');
379 12
        $xlinkNs = $dom->lookupNamespaceUri('xlink');
380
381 12
        $spreadsheets = $dom->getElementsByTagNameNS($officeNs, 'body')
382 12
            ->item(0)
383 12
            ->getElementsByTagNameNS($officeNs, 'spreadsheet');
384
385 12
        foreach ($spreadsheets as $workbookData) {
386
            /** @var \DOMElement $workbookData */
387 12
            $tables = $workbookData->getElementsByTagNameNS($tableNs, 'table');
388
389 12
            $worksheetID = 0;
390 12
            foreach ($tables as $worksheetDataSet) {
391
                /** @var \DOMElement $worksheetDataSet */
392 12
                $worksheetName = $worksheetDataSet->getAttributeNS($tableNs, 'name');
393
394
                // Check loadSheetsOnly
395 12
                if (isset($this->loadSheetsOnly)
396 12
                    && $worksheetName
397 12
                    && !in_array($worksheetName, $this->loadSheetsOnly)) {
398
                    continue;
399
                }
400
401
                // Create sheet
402 12
                if ($worksheetID > 0) {
403 7
                    $spreadsheet->createSheet(); // First sheet is added by default
404
                }
405 12
                $spreadsheet->setActiveSheetIndex($worksheetID);
406
407 12
                if ($worksheetName) {
408
                    // Use false for $updateFormulaCellReferences to prevent adjustment of worksheet references in
409
                    // formula cells... during the load, all formulae should be correct, and we're simply
410
                    // bringing the worksheet name in line with the formula, not the reverse
411 12
                    $spreadsheet->getActiveSheet()->setTitle($worksheetName, false, false);
412
                }
413
414
                // Go through every child of table element
415 12
                $rowID = 1;
416 12
                foreach ($worksheetDataSet->childNodes as $childNode) {
417
                    /** @var \DOMElement $childNode */
418
419
                    // Filter elements which are not under the "table" ns
420 12
                    if ($childNode->namespaceURI != $tableNs) {
421 10
                        continue;
422
                    }
423
424 12
                    $key = $childNode->nodeName;
425
426
                    // Remove ns from node name
427 12
                    if (strpos($key, ':') !== false) {
428 12
                        $keyChunks = explode(':', $key);
429 12
                        $key = array_pop($keyChunks);
430
                    }
431
432 12
                    switch ($key) {
433 12
                        case 'table-header-rows':
434
                            /// TODO :: Figure this out. This is only a partial implementation I guess.
435
                            //          ($rowData it's not used at all and I'm not sure that PHPExcel
436
                            //          has an API for this)
437
438
//                            foreach ($rowData as $keyRowData => $cellData) {
439
//                                $rowData = $cellData;
440
//                                break;
441
//                            }
442
                            break;
443 12
                        case 'table-row':
444 12
                            if ($childNode->hasAttributeNS($tableNs, 'number-rows-repeated')) {
445 7
                                $rowRepeats = $childNode->getAttributeNS($tableNs, 'number-rows-repeated');
446
                            } else {
447 12
                                $rowRepeats = 1;
448
                            }
449
450 12
                            $columnID = 'A';
451 12
                            foreach ($childNode->childNodes as $key => $cellData) {
452
                                // @var \DOMElement $cellData
453
454 12
                                if ($this->getReadFilter() !== null) {
455 12
                                    if (!$this->getReadFilter()->readCell($columnID, $rowID, $worksheetName)) {
456 1
                                        ++$columnID;
457
458 1
                                        continue;
459
                                    }
460
                                }
461
462
                                // Initialize variables
463 12
                                $formatting = $hyperlink = null;
464 12
                                $hasCalculatedValue = false;
465 12
                                $cellDataFormula = '';
466
467 12
                                if ($cellData->hasAttributeNS($tableNs, 'formula')) {
468 5
                                    $cellDataFormula = $cellData->getAttributeNS($tableNs, 'formula');
469 5
                                    $hasCalculatedValue = true;
470
                                }
471
472
                                // Annotations
473 12
                                $annotation = $cellData->getElementsByTagNameNS($officeNs, 'annotation');
474
475 12
                                if ($annotation->length > 0) {
476 6
                                    $textNode = $annotation->item(0)->getElementsByTagNameNS($textNs, 'p');
477
478 6
                                    if ($textNode->length > 0) {
479 6
                                        $text = $this->scanElementForText($textNode->item(0));
480
481 6
                                        $spreadsheet->getActiveSheet()
482 6
                                            ->getComment($columnID . $rowID)
483 6
                                            ->setText($this->parseRichText($text));
484
//                                                                    ->setAuthor( $author )
485
                                    }
486
                                }
487
488
                                // Content
489
490
                                /** @var \DOMElement[] $paragraphs */
491 12
                                $paragraphs = [];
492
493 12
                                foreach ($cellData->childNodes as $item) {
494
                                    /** @var \DOMElement $item */
495
496
                                    // Filter text:p elements
497 12
                                    if ($item->nodeName == 'text:p') {
498 12
                                        $paragraphs[] = $item;
499
                                    }
500
                                }
501
502 12
                                if (count($paragraphs) > 0) {
503
                                    // Consolidate if there are multiple p records (maybe with spans as well)
504 12
                                    $dataArray = [];
505
506
                                    // Text can have multiple text:p and within those, multiple text:span.
507
                                    // text:p newlines, but text:span does not.
508
                                    // Also, here we assume there is no text data is span fields are specified, since
509
                                    // we have no way of knowing proper positioning anyway.
510
511 12
                                    foreach ($paragraphs as $pData) {
512 12
                                        $dataArray[] = $this->scanElementForText($pData);
513
                                    }
514 12
                                    $allCellDataText = implode($dataArray, "\n");
0 ignored issues
show
Unused Code introduced by
The call to implode() has too many arguments starting with ' '. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

514
                                    $allCellDataText = /** @scrutinizer ignore-call */ implode($dataArray, "\n");

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
515
516 12
                                    $type = $cellData->getAttributeNS($officeNs, 'value-type');
517
518 12
                                    switch ($type) {
519 12
                                        case 'string':
520 11
                                            $type = DataType::TYPE_STRING;
521 11
                                            $dataValue = $allCellDataText;
522
523 11
                                            foreach ($paragraphs as $paragraph) {
524 11
                                                $link = $paragraph->getElementsByTagNameNS($textNs, 'a');
525 11
                                                if ($link->length > 0) {
526 11
                                                    $hyperlink = $link->item(0)->getAttributeNS($xlinkNs, 'href');
527
                                                }
528
                                            }
529
530 11
                                            break;
531 9
                                        case 'boolean':
532 5
                                            $type = DataType::TYPE_BOOL;
533 5
                                            $dataValue = ($allCellDataText == 'TRUE') ? true : false;
534
535 5
                                            break;
536 9
                                        case 'percentage':
537 3
                                            $type = DataType::TYPE_NUMERIC;
538 3
                                            $dataValue = (float) $cellData->getAttributeNS($officeNs, 'value');
539
540 3
                                            if (floor($dataValue) == $dataValue) {
541
                                                $dataValue = (int) $dataValue;
542
                                            }
543 3
                                            $formatting = NumberFormat::FORMAT_PERCENTAGE_00;
544
545 3
                                            break;
546 9
                                        case 'currency':
547 3
                                            $type = DataType::TYPE_NUMERIC;
548 3
                                            $dataValue = (float) $cellData->getAttributeNS($officeNs, 'value');
549
550 3
                                            if (floor($dataValue) == $dataValue) {
551 3
                                                $dataValue = (int) $dataValue;
552
                                            }
553 3
                                            $formatting = NumberFormat::FORMAT_CURRENCY_USD_SIMPLE;
554
555 3
                                            break;
556 7
                                        case 'float':
557 7
                                            $type = DataType::TYPE_NUMERIC;
558 7
                                            $dataValue = (float) $cellData->getAttributeNS($officeNs, 'value');
559
560 7
                                            if (floor($dataValue) == $dataValue) {
561 7
                                                if ($dataValue == (int) $dataValue) {
562 7
                                                    $dataValue = (int) $dataValue;
563
                                                } else {
564
                                                    $dataValue = (float) $dataValue;
565
                                                }
566
                                            }
567
568 7
                                            break;
569 5
                                        case 'date':
570 5
                                            $type = DataType::TYPE_NUMERIC;
571 5
                                            $value = $cellData->getAttributeNS($officeNs, 'date-value');
572
573 5
                                            $dateObj = new DateTime($value, $GMT);
574 5
                                            $dateObj->setTimeZone($timezoneObj);
575 5
                                            list($year, $month, $day, $hour, $minute, $second) = explode(
576 5
                                                ' ',
577 5
                                                $dateObj->format('Y m d H i s')
578
                                            );
579
580 5
                                            $dataValue = Date::formattedPHPToExcel(
581 5
                                                $year,
0 ignored issues
show
Bug introduced by
$year of type string is incompatible with the type integer expected by parameter $year of PhpOffice\PhpSpreadsheet...::formattedPHPToExcel(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

581
                                                /** @scrutinizer ignore-type */ $year,
Loading history...
582 5
                                                $month,
0 ignored issues
show
Bug introduced by
$month of type string is incompatible with the type integer expected by parameter $month of PhpOffice\PhpSpreadsheet...::formattedPHPToExcel(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

582
                                                /** @scrutinizer ignore-type */ $month,
Loading history...
583 5
                                                $day,
0 ignored issues
show
Bug introduced by
$day of type string is incompatible with the type integer expected by parameter $day of PhpOffice\PhpSpreadsheet...::formattedPHPToExcel(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

583
                                                /** @scrutinizer ignore-type */ $day,
Loading history...
584 5
                                                $hour,
0 ignored issues
show
Bug introduced by
$hour of type string is incompatible with the type integer expected by parameter $hours of PhpOffice\PhpSpreadsheet...::formattedPHPToExcel(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

584
                                                /** @scrutinizer ignore-type */ $hour,
Loading history...
585 5
                                                $minute,
0 ignored issues
show
Bug introduced by
$minute of type string is incompatible with the type integer expected by parameter $minutes of PhpOffice\PhpSpreadsheet...::formattedPHPToExcel(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

585
                                                /** @scrutinizer ignore-type */ $minute,
Loading history...
586 5
                                                $second
0 ignored issues
show
Bug introduced by
$second of type string is incompatible with the type integer expected by parameter $seconds of PhpOffice\PhpSpreadsheet...::formattedPHPToExcel(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

586
                                                /** @scrutinizer ignore-type */ $second
Loading history...
587
                                            );
588
589 5
                                            if ($dataValue != floor($dataValue)) {
590 1
                                                $formatting = NumberFormat::FORMAT_DATE_XLSX15
591 1
                                                    . ' '
592 5
                                                    . NumberFormat::FORMAT_DATE_TIME4;
593
                                            } else {
594 5
                                                $formatting = NumberFormat::FORMAT_DATE_XLSX15;
595
                                            }
596
597 5
                                            break;
598 5
                                        case 'time':
599 5
                                            $type = DataType::TYPE_NUMERIC;
600
601 5
                                            $timeValue = $cellData->getAttributeNS($officeNs, 'time-value');
602
603 5
                                            $dataValue = Date::PHPToExcel(
604 5
                                                strtotime(
605 5
                                                    '01-01-1970 ' . implode(':', sscanf($timeValue, 'PT%dH%dM%dS'))
606
                                                )
607
                                            );
608 5
                                            $formatting = NumberFormat::FORMAT_DATE_TIME4;
609
610 5
                                            break;
611
                                        default:
612 12
                                            $dataValue = null;
613
                                    }
614
                                } else {
615 11
                                    $type = DataType::TYPE_NULL;
616 11
                                    $dataValue = null;
617
                                }
618
619 12
                                if ($hasCalculatedValue) {
620 5
                                    $type = DataType::TYPE_FORMULA;
621 5
                                    $cellDataFormula = substr($cellDataFormula, strpos($cellDataFormula, ':=') + 1);
622 5
                                    $temp = explode('"', $cellDataFormula);
623 5
                                    $tKey = false;
624 5
                                    foreach ($temp as &$value) {
625
                                        // Only replace in alternate array entries (i.e. non-quoted blocks)
626 5
                                        if ($tKey = !$tKey) {
0 ignored issues
show
introduced by
The condition $tKey is always false.
Loading history...
627
                                            // Cell range reference in another sheet
628 5
                                            $value = preg_replace('/\[([^\.]+)\.([^\.]+):\.([^\.]+)\]/U', '$1!$2:$3', $value);
629
630
                                            // Cell reference in another sheet
631 5
                                            $value = preg_replace('/\[([^\.]+)\.([^\.]+)\]/U', '$1!$2', $value);
632
633
                                            // Cell range reference
634 5
                                            $value = preg_replace('/\[\.([^\.]+):\.([^\.]+)\]/U', '$1:$2', $value);
635
636
                                            // Simple cell reference
637 5
                                            $value = preg_replace('/\[\.([^\.]+)\]/U', '$1', $value);
638
639 5
                                            $value = Calculation::translateSeparator(';', ',', $value, $inBraces);
640
                                        }
641
                                    }
642 5
                                    unset($value);
643
644
                                    // Then rebuild the formula string
645 5
                                    $cellDataFormula = implode('"', $temp);
646
                                }
647
648 12
                                if ($cellData->hasAttributeNS($tableNs, 'number-columns-repeated')) {
649 11
                                    $colRepeats = (int) $cellData->getAttributeNS($tableNs, 'number-columns-repeated');
650
                                } else {
651 12
                                    $colRepeats = 1;
652
                                }
653
654 12
                                if ($type !== null) {
655 12
                                    for ($i = 0; $i < $colRepeats; ++$i) {
656 12
                                        if ($i > 0) {
657 11
                                            ++$columnID;
658
                                        }
659
660 12
                                        if ($type !== DataType::TYPE_NULL) {
661 12
                                            for ($rowAdjust = 0; $rowAdjust < $rowRepeats; ++$rowAdjust) {
662 12
                                                $rID = $rowID + $rowAdjust;
663
664 12
                                                $cell = $spreadsheet->getActiveSheet()
665 12
                                                    ->getCell($columnID . $rID);
666
667
                                                // Set value
668 12
                                                if ($hasCalculatedValue) {
669 5
                                                    $cell->setValueExplicit($cellDataFormula, $type);
670
                                                } else {
671 12
                                                    $cell->setValueExplicit($dataValue, $type);
672
                                                }
673
674 12
                                                if ($hasCalculatedValue) {
675 5
                                                    $cell->setCalculatedValue($dataValue);
676
                                                }
677
678
                                                // Set other properties
679 12
                                                if ($formatting !== null) {
680 7
                                                    $spreadsheet->getActiveSheet()
681 7
                                                        ->getStyle($columnID . $rID)
682 7
                                                        ->getNumberFormat()
683 7
                                                        ->setFormatCode($formatting);
684
                                                } else {
685 12
                                                    $spreadsheet->getActiveSheet()
686 12
                                                        ->getStyle($columnID . $rID)
687 12
                                                        ->getNumberFormat()
688 12
                                                        ->setFormatCode(NumberFormat::FORMAT_GENERAL);
689
                                                }
690
691 12
                                                if ($hyperlink !== null) {
692 5
                                                    $cell->getHyperlink()
693 5
                                                        ->setUrl($hyperlink);
694
                                                }
695
                                            }
696
                                        }
697
                                    }
698
                                }
699
700
                                // Merged cells
701 12
                                if ($cellData->hasAttributeNS($tableNs, 'number-columns-spanned')
702 12
                                    || $cellData->hasAttributeNS($tableNs, 'number-rows-spanned')
703
                                ) {
704 6
                                    if (($type !== DataType::TYPE_NULL) || (!$this->readDataOnly)) {
705 6
                                        $columnTo = $columnID;
706
707 6
                                        if ($cellData->hasAttributeNS($tableNs, 'number-columns-spanned')) {
708 6
                                            $columnIndex = Coordinate::columnIndexFromString($columnID);
709 6
                                            $columnIndex += (int) $cellData->getAttributeNS($tableNs, 'number-columns-spanned');
710 6
                                            $columnIndex -= 2;
711
712 6
                                            $columnTo = Coordinate::stringFromColumnIndex($columnIndex + 1);
713
                                        }
714
715 6
                                        $rowTo = $rowID;
716
717 6
                                        if ($cellData->hasAttributeNS($tableNs, 'number-rows-spanned')) {
718 6
                                            $rowTo = $rowTo + (int) $cellData->getAttributeNS($tableNs, 'number-rows-spanned') - 1;
719
                                        }
720
721 6
                                        $cellRange = $columnID . $rowID . ':' . $columnTo . $rowTo;
722 6
                                        $spreadsheet->getActiveSheet()->mergeCells($cellRange);
723
                                    }
724
                                }
725
726 12
                                ++$columnID;
727
                            }
728 12
                            $rowID += $rowRepeats;
729
730 12
                            break;
731
                    }
732
                }
733 12
                ++$worksheetID;
734
            }
735
        }
736
737
        // Return
738 12
        return $spreadsheet;
739
    }
740
741
    /**
742
     * Recursively scan element.
743
     *
744
     * @param \DOMNode $element
745
     *
746
     * @return string
747
     */
748 12
    protected function scanElementForText(\DOMNode $element)
749
    {
750 12
        $str = '';
751 12
        foreach ($element->childNodes as $child) {
752
            /** @var \DOMNode $child */
753 12
            if ($child->nodeType == XML_TEXT_NODE) {
754 12
                $str .= $child->nodeValue;
755 7
            } elseif ($child->nodeType == XML_ELEMENT_NODE && $child->nodeName == 'text:s') {
756
                // It's a space
757
758
                // Multiple spaces?
759
                /** @var \DOMAttr $cAttr */
760 3
                $cAttr = $child->attributes->getNamedItem('c');
761 3
                if ($cAttr) {
762 3
                    $multiplier = (int) $cAttr->nodeValue;
763
                } else {
764 3
                    $multiplier = 1;
765
                }
766
767 3
                $str .= str_repeat(' ', $multiplier);
768
            }
769
770 12
            if ($child->hasChildNodes()) {
771 12
                $str .= $this->scanElementForText($child);
772
            }
773
        }
774
775 12
        return $str;
776
    }
777
778
    /**
779
     * @param string $is
780
     *
781
     * @return RichText
782
     */
783 6
    private function parseRichText($is)
784
    {
785 6
        $value = new RichText();
786 6
        $value->createText($is);
787
788 6
        return $value;
789
    }
790
}
791