Passed
Pull Request — master (#4240)
by Owen
10:54
created

ReferenceHelper::cellReverseSort()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3

Importance

Changes 0
Metric Value
eloc 5
c 0
b 0
f 0
dl 0
loc 13
ccs 6
cts 6
cp 1
rs 10
cc 3
nc 3
nop 2
crap 3
1
<?php
2
3
namespace PhpOffice\PhpSpreadsheet;
4
5
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
6
use PhpOffice\PhpSpreadsheet\Cell\AddressRange;
7
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
8
use PhpOffice\PhpSpreadsheet\Cell\DataType;
9
use PhpOffice\PhpSpreadsheet\Style\Conditional;
10
use PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter;
11
use PhpOffice\PhpSpreadsheet\Worksheet\Table;
12
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
13
14
class ReferenceHelper
15
{
16
    /**    Constants                */
17
    /**    Regular Expressions      */
18
    private const SHEETNAME_PART = '((\w*|\'[^!]*\')!)';
19
    private const SHEETNAME_PART_WITH_SLASHES = '/' . self::SHEETNAME_PART . '/';
20
    const REFHELPER_REGEXP_CELLREF = self::SHEETNAME_PART . '?(?<![:a-z1-9_\.\$])(\$?[a-z]{1,3}\$?\d+)(?=[^:!\d\'])';
21
    const REFHELPER_REGEXP_CELLRANGE = self::SHEETNAME_PART . '?(\$?[a-z]{1,3}\$?\d+):(\$?[a-z]{1,3}\$?\d+)';
22
    const REFHELPER_REGEXP_ROWRANGE = self::SHEETNAME_PART . '?(\$?\d+):(\$?\d+)';
23
    const REFHELPER_REGEXP_COLRANGE = self::SHEETNAME_PART . '?(\$?[a-z]{1,3}):(\$?[a-z]{1,3})';
24
25
    /**
26
     * Instance of this class.
27
     */
28
    private static ?ReferenceHelper $instance = null;
29
30
    private ?CellReferenceHelper $cellReferenceHelper = null;
31
32
    /**
33
     * Get an instance of this class.
34
     */
35 10376
    public static function getInstance(): self
36
    {
37 10376
        if (self::$instance === null) {
38 277
            self::$instance = new self();
39
        }
40
41 10376
        return self::$instance;
42
    }
43
44
    /**
45
     * Create a new ReferenceHelper.
46
     */
47 277
    protected function __construct()
48
    {
49 277
    }
50
51
    /**
52
     * Compare two column addresses
53
     * Intended for use as a Callback function for sorting column addresses by column.
54
     *
55
     * @param string $a First column to test (e.g. 'AA')
56
     * @param string $b Second column to test (e.g. 'Z')
57
     */
58 1
    public static function columnSort(string $a, string $b): int
59
    {
60 1
        return strcasecmp(strlen($a) . $a, strlen($b) . $b);
61
    }
62
63
    /**
64
     * Compare two column addresses
65
     * Intended for use as a Callback function for reverse sorting column addresses by column.
66
     *
67
     * @param string $a First column to test (e.g. 'AA')
68
     * @param string $b Second column to test (e.g. 'Z')
69
     */
70 1
    public static function columnReverseSort(string $a, string $b): int
71
    {
72 1
        return -strcasecmp(strlen($a) . $a, strlen($b) . $b);
73
    }
74
75
    /**
76
     * Compare two cell addresses
77
     * Intended for use as a Callback function for sorting cell addresses by column and row.
78
     *
79
     * @param string $a First cell to test (e.g. 'AA1')
80
     * @param string $b Second cell to test (e.g. 'Z1')
81
     */
82 20
    public static function cellSort(string $a, string $b): int
83
    {
84 20
        sscanf($a, '%[A-Z]%d', $ac, $ar);
85
        /** @var int $ar */
86
        /** @var string $ac */
87 20
        sscanf($b, '%[A-Z]%d', $bc, $br);
88
        /** @var int $br */
89
        /** @var string $bc */
90 20
        if ($ar === $br) {
91 1
            return strcasecmp(strlen($ac) . $ac, strlen($bc) . $bc);
92
        }
93
94 20
        return ($ar < $br) ? -1 : 1;
95
    }
96
97
    /**
98
     * Compare two cell addresses
99
     * Intended for use as a Callback function for sorting cell addresses by column and row.
100
     *
101
     * @param string $a First cell to test (e.g. 'AA1')
102
     * @param string $b Second cell to test (e.g. 'Z1')
103
     */
104 23
    public static function cellReverseSort(string $a, string $b): int
105
    {
106 23
        sscanf($a, '%[A-Z]%d', $ac, $ar);
107
        /** @var int $ar */
108
        /** @var string $ac */
109 23
        sscanf($b, '%[A-Z]%d', $bc, $br);
110
        /** @var int $br */
111
        /** @var string $bc */
112 23
        if ($ar === $br) {
113 2
            return -strcasecmp(strlen($ac) . $ac, strlen($bc) . $bc);
114
        }
115
116 22
        return ($ar < $br) ? 1 : -1;
117
    }
118
119
    /**
120
     * Update page breaks when inserting/deleting rows/columns.
121
     *
122
     * @param Worksheet $worksheet The worksheet that we're editing
123
     * @param int $numberOfColumns Number of columns to insert/delete (negative values indicate deletion)
124
     * @param int $numberOfRows Number of rows to insert/delete (negative values indicate deletion)
125
     */
126 91
    protected function adjustPageBreaks(Worksheet $worksheet, int $numberOfColumns, int $numberOfRows): void
127
    {
128 91
        $aBreaks = $worksheet->getBreaks();
129 91
        ($numberOfColumns > 0 || $numberOfRows > 0)
130 57
            ? uksort($aBreaks, [self::class, 'cellReverseSort'])
131 55
            : uksort($aBreaks, [self::class, 'cellSort']);
132
133 91
        foreach ($aBreaks as $cellAddress => $value) {
134
            /** @var CellReferenceHelper */
135 4
            $cellReferenceHelper = $this->cellReferenceHelper;
136 4
            if ($cellReferenceHelper->cellAddressInDeleteRange($cellAddress) === true) {
137
                //    If we're deleting, then clear any defined breaks that are within the range
138
                //        of rows/columns that we're deleting
139 1
                $worksheet->setBreak($cellAddress, Worksheet::BREAK_NONE);
140
            } else {
141
                //    Otherwise update any affected breaks by inserting a new break at the appropriate point
142
                //        and removing the old affected break
143 4
                $newReference = $this->updateCellReference($cellAddress);
144 4
                if ($cellAddress !== $newReference) {
145 4
                    $worksheet->setBreak($newReference, $value)
146 4
                        ->setBreak($cellAddress, Worksheet::BREAK_NONE);
147
                }
148
            }
149
        }
150
    }
151
152
    /**
153
     * Update cell comments when inserting/deleting rows/columns.
154
     *
155
     * @param Worksheet $worksheet The worksheet that we're editing
156
     */
157 91
    protected function adjustComments(Worksheet $worksheet): void
158
    {
159 91
        $aComments = $worksheet->getComments();
160 91
        $aNewComments = []; // the new array of all comments
161
162 91
        foreach ($aComments as $cellAddress => &$value) {
163
            // Any comments inside a deleted range will be ignored
164
            /** @var CellReferenceHelper */
165 21
            $cellReferenceHelper = $this->cellReferenceHelper;
166 21
            if ($cellReferenceHelper->cellAddressInDeleteRange($cellAddress) === false) {
167
                // Otherwise build a new array of comments indexed by the adjusted cell reference
168 21
                $newReference = $this->updateCellReference($cellAddress);
169 21
                $aNewComments[$newReference] = $value;
170
            }
171
        }
172
        //    Replace the comments array with the new set of comments
173 91
        $worksheet->setComments($aNewComments);
174
    }
175
176
    /**
177
     * Update hyperlinks when inserting/deleting rows/columns.
178
     *
179
     * @param Worksheet $worksheet The worksheet that we're editing
180
     * @param int $numberOfColumns Number of columns to insert/delete (negative values indicate deletion)
181
     * @param int $numberOfRows Number of rows to insert/delete (negative values indicate deletion)
182
     */
183 91
    protected function adjustHyperlinks(Worksheet $worksheet, int $numberOfColumns, int $numberOfRows): void
184
    {
185 91
        $aHyperlinkCollection = $worksheet->getHyperlinkCollection();
186 91
        ($numberOfColumns > 0 || $numberOfRows > 0)
187 57
            ? uksort($aHyperlinkCollection, [self::class, 'cellReverseSort'])
188 55
            : uksort($aHyperlinkCollection, [self::class, 'cellSort']);
189
190 91
        foreach ($aHyperlinkCollection as $cellAddress => $value) {
191 20
            $newReference = $this->updateCellReference($cellAddress);
192
            /** @var CellReferenceHelper */
193 20
            $cellReferenceHelper = $this->cellReferenceHelper;
194 20
            if ($cellReferenceHelper->cellAddressInDeleteRange($cellAddress) === true) {
195
                $worksheet->setHyperlink($cellAddress, null);
196 20
            } elseif ($cellAddress !== $newReference) {
197 20
                $worksheet->setHyperlink($newReference, $value);
198 20
                $worksheet->setHyperlink($cellAddress, null);
199
            }
200
        }
201
    }
202
203
    /**
204
     * Update conditional formatting styles when inserting/deleting rows/columns.
205
     *
206
     * @param Worksheet $worksheet The worksheet that we're editing
207
     * @param int $numberOfColumns Number of columns to insert/delete (negative values indicate deletion)
208
     * @param int $numberOfRows Number of rows to insert/delete (negative values indicate deletion)
209
     */
210 91
    protected function adjustConditionalFormatting(Worksheet $worksheet, int $numberOfColumns, int $numberOfRows): void
211
    {
212 91
        $aStyles = $worksheet->getConditionalStylesCollection();
213 91
        ($numberOfColumns > 0 || $numberOfRows > 0)
214 57
            ? uksort($aStyles, [self::class, 'cellReverseSort'])
215 55
            : uksort($aStyles, [self::class, 'cellSort']);
216
217 91
        foreach ($aStyles as $cellAddress => $cfRules) {
218 4
            $worksheet->removeConditionalStyles($cellAddress);
219 4
            $newReference = $this->updateCellReference($cellAddress);
220
221 4
            foreach ($cfRules as &$cfRule) {
222
                /** @var Conditional $cfRule */
223 4
                $conditions = $cfRule->getConditions();
224 4
                foreach ($conditions as &$condition) {
225 4
                    if (is_string($condition)) {
226
                        /** @var CellReferenceHelper */
227 4
                        $cellReferenceHelper = $this->cellReferenceHelper;
228 4
                        $condition = $this->updateFormulaReferences(
229 4
                            $condition,
230 4
                            $cellReferenceHelper->beforeCellAddress(),
231 4
                            $numberOfColumns,
232 4
                            $numberOfRows,
233 4
                            $worksheet->getTitle(),
234 4
                            true
235 4
                        );
236
                    }
237
                }
238 4
                $cfRule->setConditions($conditions);
239
            }
240 4
            $worksheet->setConditionalStyles($newReference, $cfRules);
241
        }
242
    }
243
244
    /**
245
     * Update data validations when inserting/deleting rows/columns.
246
     *
247
     * @param Worksheet $worksheet The worksheet that we're editing
248
     * @param int $numberOfColumns Number of columns to insert/delete (negative values indicate deletion)
249
     * @param int $numberOfRows Number of rows to insert/delete (negative values indicate deletion)
250
     */
251 91
    protected function adjustDataValidations(Worksheet $worksheet, int $numberOfColumns, int $numberOfRows, string $beforeCellAddress): void
252
    {
253 91
        $aDataValidationCollection = $worksheet->getDataValidationCollection();
254 91
        ($numberOfColumns > 0 || $numberOfRows > 0)
255 57
            ? uksort($aDataValidationCollection, [self::class, 'cellReverseSort'])
256 55
            : uksort($aDataValidationCollection, [self::class, 'cellSort']);
257
258 91
        foreach ($aDataValidationCollection as $cellAddress => $dataValidation) {
259 4
            $formula = $dataValidation->getFormula1();
260 4
            if ($formula !== '') {
261 4
                $dataValidation->setFormula1(
262 4
                    $this->updateFormulaReferences(
263 4
                        $formula,
264
                        $beforeCellAddress,
265
                        $numberOfColumns,
266
                        $numberOfRows,
267
                        $worksheet->getTitle(),
268
                        true
269
                    )
270
                );
271
            }
272
            $formula = $dataValidation->getFormula2();
273 91
            if ($formula !== '') {
274
                $dataValidation->setFormula2(
275 91
                    $this->updateFormulaReferences(
276 91
                        $formula,
277 91
                        $beforeCellAddress,
278 21
                        $numberOfColumns,
279 21
                        $numberOfRows,
280
                        $worksheet->getTitle(),
281 91
                        true
282
                    )
283
                );
284
            }
285
            $addressParts = explode(' ', $cellAddress);
286
            $newReference = '';
287
            $separator = '';
288
            foreach ($addressParts as $addressPart) {
289
                $newReference .= $separator . $this->updateCellReference($addressPart);
290
                $separator = ' ';
291 91
            }
292
            if ($cellAddress !== $newReference) {
293 91
                $dataValidation->setSqref($newReference);
294 91
                $worksheet->setDataValidation($newReference, $dataValidation);
295 57
                $worksheet->setDataValidation($cellAddress, null);
296 55
            }
297 91
        }
298 17
    }
299 17
300 17
    /**
301 17
     * Update merged cells when inserting/deleting rows/columns.
302
     *
303
     * @param Worksheet $worksheet The worksheet that we're editing
304
     */
305
    protected function adjustMergeCells(Worksheet $worksheet): void
306
    {
307
        $aMergeCells = $worksheet->getMergeCells();
308
        $aNewMergeCells = []; // the new array of all merge cells
309
        foreach ($aMergeCells as $cellAddress => &$value) {
310
            $newReference = $this->updateCellReference($cellAddress);
311 91
            $aNewMergeCells[$newReference] = $newReference;
312
        }
313 91
        $worksheet->setMergeCells($aNewMergeCells); // replace the merge cells array
314 91
    }
315 25
316 25
    /**
317 25
     * Update protected cells when inserting/deleting rows/columns.
318 25
     *
319 19
     * @param Worksheet $worksheet The worksheet that we're editing
320
     * @param int $numberOfColumns Number of columns to insert/delete (negative values indicate deletion)
321
     * @param int $numberOfRows Number of rows to insert/delete (negative values indicate deletion)
322
     */
323 25
    protected function adjustProtectedCells(Worksheet $worksheet, int $numberOfColumns, int $numberOfRows): void
324
    {
325
        $aProtectedCells = $worksheet->getProtectedCells();
326
        ($numberOfColumns > 0 || $numberOfRows > 0)
327
            ? uksort($aProtectedCells, [self::class, 'cellReverseSort'])
328
            : uksort($aProtectedCells, [self::class, 'cellSort']);
329
        foreach ($aProtectedCells as $cellAddress => $value) {
330
            $newReference = $this->updateCellReference($cellAddress);
331
            if ($cellAddress !== $newReference) {
332
                $worksheet->protectCells($newReference, $value, true);
333
                $worksheet->unprotectCells($cellAddress);
334 91
            }
335
        }
336 91
    }
337 91
338 7
    /**
339 7
     * Update column dimensions when inserting/deleting rows/columns.
340 7
     *
341 7
     * @param Worksheet $worksheet The worksheet that we're editing
342 7
     */
343 7
    protected function adjustColumnDimensions(Worksheet $worksheet): void
344
    {
345
        $aColumnDimensions = array_reverse($worksheet->getColumnDimensions(), true);
346
        if (!empty($aColumnDimensions)) {
347 7
            foreach ($aColumnDimensions as $objColumnDimension) {
348
                $newReference = $this->updateCellReference($objColumnDimension->getColumnIndex() . '1');
349 7
                [$newReference] = Coordinate::coordinateFromString($newReference);
350 7
                if ($objColumnDimension->getColumnIndex() !== $newReference) {
351 5
                    $objColumnDimension->setColumnIndex($newReference);
352 5
                }
353 5
            }
354 5
355 5
            $worksheet->refreshColumnDimensions();
356
        }
357
    }
358
359
    /**
360
     * Update row dimensions when inserting/deleting rows/columns.
361
     *
362
     * @param Worksheet $worksheet The worksheet that we're editing
363
     * @param int $beforeRow Number of the row we're inserting/deleting before
364
     * @param int $numberOfRows Number of rows to insert/delete (negative values indicate deletion)
365
     */
366
    protected function adjustRowDimensions(Worksheet $worksheet, int $beforeRow, int $numberOfRows): void
367
    {
368 91
        $aRowDimensions = array_reverse($worksheet->getRowDimensions(), true);
369
        if (!empty($aRowDimensions)) {
370
            foreach ($aRowDimensions as $objRowDimension) {
371
                $newReference = $this->updateCellReference('A' . $objRowDimension->getRowIndex());
372
                [, $newReference] = Coordinate::coordinateFromString($newReference);
373
                $newRoweference = (int) $newReference;
374 91
                if ($objRowDimension->getRowIndex() !== $newRoweference) {
375
                    $objRowDimension->setRowIndex($newRoweference);
376
                }
377 91
            }
378 91
379
            $worksheet->refreshRowDimensions();
380 79
381
            $copyDimension = $worksheet->getRowDimension($beforeRow - 1);
382
            for ($i = $beforeRow; $i <= $beforeRow - 1 + $numberOfRows; ++$i) {
383
                $newDimension = $worksheet->getRowDimension($i);
384 91
                $newDimension->setRowHeight($copyDimension->getRowHeight());
385
                $newDimension->setVisible($copyDimension->getVisible());
386
                $newDimension->setOutlineLevel($copyDimension->getOutlineLevel());
387 91
                $newDimension->setCollapsed($copyDimension->getCollapsed());
388 91
            }
389 91
        }
390 91
    }
391
392
    /**
393 91
     * Insert a new column or row, updating all possible related data.
394 23
     *
395
     * @param string $beforeCellAddress Insert before this cell address (e.g. 'A1')
396
     * @param int $numberOfColumns Number of columns to insert/delete (negative values indicate deletion)
397
     * @param int $numberOfRows Number of rows to insert/delete (negative values indicate deletion)
398 91
     * @param Worksheet $worksheet The worksheet that we're editing
399 35
     */
400
    public function insertNewBefore(
401
        string $beforeCellAddress,
402
        int $numberOfColumns,
403 91
        int $numberOfRows,
404 91
        Worksheet $worksheet
405 91
    ): void {
406 56
        $remove = ($numberOfColumns < 0 || $numberOfRows < 0);
407 56
408 56
        if (
409 56
            $this->cellReferenceHelper === null
410
            || $this->cellReferenceHelper->refreshRequired($beforeCellAddress, $numberOfColumns, $numberOfRows)
411 91
        ) {
412 91
            $this->cellReferenceHelper = new CellReferenceHelper($beforeCellAddress, $numberOfColumns, $numberOfRows);
413 81
        }
414 75
415
        // Get coordinate of $beforeCellAddress
416
        [$beforeColumn, $beforeRow, $beforeColumnString] = Coordinate::indexesFromString($beforeCellAddress);
417
418 91
        // Clear cells if we are removing columns or rows
419 91
        $highestColumn = $worksheet->getHighestColumn();
420
        $highestDataColumn = $worksheet->getHighestDataColumn();
421 55
        $highestRow = $worksheet->getHighestRow();
422
        $highestDataRow = $worksheet->getHighestDataRow();
423
424
        // 1. Clear column strips if we are removing columns
425 91
        if ($numberOfColumns < 0 && $beforeColumn - 2 + $numberOfColumns > 0) {
426 86
            $this->clearColumnStrips($highestRow, $beforeColumn, $numberOfColumns, $worksheet);
427 86
        }
428
429 86
        // 2. Clear row strips if we are removing rows
430 26
        if ($numberOfRows < 0 && $beforeRow - 1 + $numberOfRows > 0) {
431
            $this->clearRowStrips($highestColumn, $beforeColumn, $beforeRow, $numberOfRows, $worksheet);
432
        }
433
434 85
        // Find missing coordinates. This is important when inserting or deleting column before the last column
435
        $startRow = $startCol = 1;
436
        $startColString = 'A';
437 85
        if ($numberOfRows === 0) {
438
            $startCol = $beforeColumn;
439 75
            $startColString = $beforeColumnString;
440
        } elseif ($numberOfColumns === 0) {
441
            $startRow = $beforeRow;
442 75
        }
443
        $highColumn = Coordinate::columnIndexFromString($highestDataColumn);
444 37
        for ($row = $startRow; $row <= $highestDataRow; ++$row) {
445 37
            for ($col = $startCol, $colString = $startColString; $col <= $highColumn; ++$col, ++$colString) {
446
                $worksheet->getCell("$colString$row"); // create cell if it doesn't exist
447
            }
448 75
        }
449
450
        $allCoordinates = $worksheet->getCoordinates();
451
        if ($remove) {
452 75
            // It's faster to reverse and pop than to use unshift, especially with large cell collections
453
            $allCoordinates = array_reverse($allCoordinates);
454
        }
455
456 58
        // Loop through cells, bottom-up, and change cell coordinate
457
        while ($coordinate = array_pop($allCoordinates)) {
458 20
            $cell = $worksheet->getCell($coordinate);
459
            $cellIndex = Coordinate::columnIndexFromString($cell->getColumn());
460
461
            if ($cellIndex - 1 + $numberOfColumns < 0) {
462
                continue;
463
            }
464 91
465 91
            // New coordinate
466
            $newCoordinate = Coordinate::stringFromColumnIndex($cellIndex + $numberOfColumns) . ($cell->getRow() + $numberOfRows);
467 91
468 23
            // Should the cell be updated? Move value and cellXf index from one cell to another.
469
            if (($cellIndex >= $beforeColumn) && ($cell->getRow() >= $beforeRow)) {
470
                // Update cell styles
471 91
                $worksheet->getCell($newCoordinate)->setXfIndex($cell->getXfIndex());
472 33
473
                // Insert this cell at its new location
474
                if ($cell->getDataType() === DataType::TYPE_FORMULA) {
475
                    // Formula should be adjusted
476 91
                    $worksheet->getCell($newCoordinate)
477
                        ->setValue($this->updateFormulaReferences($cell->getValueString(), $beforeCellAddress, $numberOfColumns, $numberOfRows, $worksheet->getTitle(), true));
478
                } else {
479 91
                    // Cell value should not be adjusted
480
                    $worksheet->getCell($newCoordinate)->setValueExplicit($cell->getValue(), $cell->getDataType());
481
                }
482 91
483
                // Clear the original cell
484
                $worksheet->getCellCollection()->delete($coordinate);
485 91
            } else {
486
                /*    We don't need to update styles for rows/columns before our insertion position,
487
                        but we do still need to adjust any formulae in those cells                    */
488 91
                if ($cell->getDataType() === DataType::TYPE_FORMULA) {
489
                    // Formula should be adjusted
490
                    $cell->setValue($this->updateFormulaReferences($cell->getValueString(), $beforeCellAddress, $numberOfColumns, $numberOfRows, $worksheet->getTitle(), true));
491 91
                }
492
            }
493
        }
494 91
495
        // Duplicate styles for the newly inserted cells
496
        $highestColumn = $worksheet->getHighestColumn();
497 91
        $highestRow = $worksheet->getHighestRow();
498
499
        if ($numberOfColumns > 0 && $beforeColumn - 2 > 0) {
500 91
            $this->duplicateStylesByColumn($worksheet, $beforeColumn, $beforeRow, $highestRow, $numberOfColumns);
501
        }
502
503 91
        if ($numberOfRows > 0 && $beforeRow - 1 > 0) {
504
            $this->duplicateStylesByRow($worksheet, $beforeColumn, $beforeRow, $highestColumn, $numberOfRows);
505
        }
506 91
507
        // Update worksheet: column dimensions
508
        $this->adjustColumnDimensions($worksheet);
509 91
510 1
        // Update worksheet: row dimensions
511 1
        $this->adjustRowDimensions($worksheet, $beforeRow, $numberOfRows);
512
513 1
        //    Update worksheet: page breaks
514 1
        $this->adjustPageBreaks($worksheet, $numberOfColumns, $numberOfRows);
515
516 1
        //    Update worksheet: comments
517
        $this->adjustComments($worksheet);
518
519
        // Update worksheet: hyperlinks
520 91
        $this->adjustHyperlinks($worksheet, $numberOfColumns, $numberOfRows);
521 6
522 6
        // Update worksheet: conditional formatting styles
523 6
        $this->adjustConditionalFormatting($worksheet, $numberOfColumns, $numberOfRows);
524
525
        // Update worksheet: data validations
526
        $this->adjustDataValidations($worksheet, $numberOfColumns, $numberOfRows, $beforeCellAddress);
527 91
528 91
        // Update worksheet: merge cells
529 19
        $this->adjustMergeCells($worksheet);
530 19
531 19
        // Update worksheet: protected cells
532
        $this->adjustProtectedCells($worksheet, $numberOfColumns, $numberOfRows);
533 19
534 1
        // Update worksheet: autofilter
535 1
        $this->adjustAutoFilter($worksheet, $beforeCellAddress, $numberOfColumns);
536 1
537
        // Update worksheet: table
538
        $this->adjustTable($worksheet, $beforeCellAddress, $numberOfColumns);
539
540
        // Update worksheet: freeze pane
541
        if ($worksheet->getFreezePane()) {
542 91
            $splitCell = $worksheet->getFreezePane();
543 7
            $topLeftCell = $worksheet->getTopLeftCell() ?? '';
544
545
            $splitCell = $this->updateCellReference($splitCell);
546
            $topLeftCell = $this->updateCellReference($topLeftCell);
547 91
548
            $worksheet->freezePane($splitCell, $topLeftCell);
549
        }
550 263
551
        // Page setup
552 263
        if ($worksheet->getPageSetup()->isPrintAreaSet()) {
553
            $worksheet->getPageSetup()->setPrintArea(
554
                $this->updateCellReference($worksheet->getPageSetup()->getPrintArea())
555 270
            );
556
        }
557 270
558
        // Update worksheet: drawings
559 270
        $aDrawings = $worksheet->getDrawingCollection();
560
        foreach ($aDrawings as $objDrawing) {
561
            $newReference = $this->updateCellReference($objDrawing->getCoordinates());
562
            if ($objDrawing->getCoordinates() != $newReference) {
563
                $objDrawing->setCoordinates($newReference);
564
            }
565
            if ($objDrawing->getCoordinates2() !== '') {
566
                $newReference = $this->updateCellReference($objDrawing->getCoordinates2());
567
                if ($objDrawing->getCoordinates2() != $newReference) {
568
                    $objDrawing->setCoordinates2($newReference);
569
                }
570
            }
571
        }
572
573 284
        // Update workbook: define names
574
        if (count($worksheet->getParentOrThrow()->getDefinedNames()) > 0) {
575
            $this->updateDefinedNames($worksheet, $beforeCellAddress, $numberOfColumns, $numberOfRows);
576
        }
577
578
        // Garbage collect
579
        $worksheet->garbageCollect();
580
    }
581
582 284
    private static function matchSheetName(?string $match, string $worksheetName): bool
583
    {
584 284
        return $match === null || $match === '' || $match === "'\u{fffc}'" || $match === "'\u{fffb}'" || strcasecmp(trim($match, "'"), $worksheetName) === 0;
585 284
    }
586
587 230
    private static function sheetnameBeforeCells(string $match, string $worksheetName, string $cells): string
588
    {
589
        $toString = ($match > '') ? "$match!" : '';
590
591 284
        return str_replace(["\u{fffc}", "'\u{fffb}'"], $worksheetName, $toString) . $cells;
592 284
    }
593 284
594
    /**
595 284
     * Update references within formulas.
596 284
     *
597 284
     * @param string $formula Formula to update
598 284
     * @param string $beforeCellAddress Insert before this one
599
     * @param int $numberOfColumns Number of columns to insert
600 284
     * @param int $numberOfRows Number of rows to insert
601 284
     * @param string $worksheetName Worksheet name/title
602 284
     *
603 3
     * @return string Updated formula
604 3
     */
605 3
    public function updateFormulaReferences(
606 3
        string $formula = '',
607
        string $beforeCellAddress = 'A1',
608 3
        int $numberOfColumns = 0,
609 3
        int $numberOfRows = 0,
610 3
        string $worksheetName = '',
611
        bool $includeAbsoluteReferences = false,
612 3
        bool $onlyAbsoluteReferences = false
613 3
    ): string {
614 3
        $callback = fn (array $matches): string => (strcasecmp(trim($matches[2], "'"), $worksheetName) === 0) ? (($matches[2][0] === "'") ? "'\u{fffc}'!" : "'\u{fffb}'!") : "'\u{fffd}'!";
615
        if (
616 3
            $this->cellReferenceHelper === null
617 3
            || $this->cellReferenceHelper->refreshRequired($beforeCellAddress, $numberOfColumns, $numberOfRows)
618 3
        ) {
619
            $this->cellReferenceHelper = new CellReferenceHelper($beforeCellAddress, $numberOfColumns, $numberOfRows);
620
        }
621
622
        //    Update cell references in the formula
623
        $formulaBlocks = explode('"', $formula);
624 284
        $i = false;
625 284
        foreach ($formulaBlocks as &$formulaBlock) {
626 284
            //    Ignore blocks that were enclosed in quotes (alternating entries in the $formulaBlocks array after the explode)
627 3
            $i = $i === false;
628 3
            if ($i) {
629 3
                $adjustCount = 0;
630 3
                $newCellTokens = $cellTokens = [];
631
                //    Search for row ranges (e.g. 'Sheet1'!3:5 or 3:5) with or without $ absolutes (e.g. $3:5)
632 3
                $formulaBlockx = ' ' . (preg_replace_callback(self::SHEETNAME_PART_WITH_SLASHES, $callback, $formulaBlock) ?? $formulaBlock) . ' ';
633 3
                $matchCount = preg_match_all('/' . self::REFHELPER_REGEXP_ROWRANGE . '/mui', $formulaBlockx, $matches, PREG_SET_ORDER);
634 3
                if ($matchCount > 0) {
635
                    foreach ($matches as $match) {
636 3
                        $fromString = self::sheetnameBeforeCells($match[2], $worksheetName, "{$match[3]}:{$match[4]}");
637 3
                        $modified3 = substr($this->updateCellReference('$A' . $match[3], $includeAbsoluteReferences, $onlyAbsoluteReferences), 2);
638 3
                        $modified4 = substr($this->updateCellReference('$A' . $match[4], $includeAbsoluteReferences, $onlyAbsoluteReferences), 2);
639
640 3
                        if ($match[3] . ':' . $match[4] !== $modified3 . ':' . $modified4) {
641 3
                            if (self::matchSheetName($match[2], $worksheetName)) {
642 3
                                $toString = self::sheetnameBeforeCells($match[2], $worksheetName, "$modified3:$modified4");
643
                                //    Max worksheet size is 1,048,576 rows by 16,384 columns in Excel 2007, so our adjustments need to be at least one digit more
644
                                $column = 100000;
645
                                $row = 10000000 + (int) trim($match[3], '$');
646
                                $cellIndex = "{$column}{$row}";
647
648 284
                                $newCellTokens[$cellIndex] = preg_quote($toString, '/');
649 284
                                $cellTokens[$cellIndex] = '/(?<!\d\$\!)' . preg_quote($fromString, '/') . '(?!\d)/i';
650 284
                                ++$adjustCount;
651 42
                            }
652 42
                        }
653 42
                    }
654 42
                }
655
                //    Search for column ranges (e.g. 'Sheet1'!C:E or C:E) with or without $ absolutes (e.g. $C:E)
656 42
                $formulaBlockx = ' ' . (preg_replace_callback(self::SHEETNAME_PART_WITH_SLASHES, $callback, $formulaBlock) ?? $formulaBlock) . ' ';
657 37
                $matchCount = preg_match_all('/' . self::REFHELPER_REGEXP_COLRANGE . '/mui', $formulaBlockx, $matches, PREG_SET_ORDER);
658 35
                if ($matchCount > 0) {
659 35
                    foreach ($matches as $match) {
660
                        $fromString = self::sheetnameBeforeCells($match[2], $worksheetName, "{$match[3]}:{$match[4]}");
661 35
                        $modified3 = substr($this->updateCellReference($match[3] . '$1', $includeAbsoluteReferences, $onlyAbsoluteReferences), 0, -2);
662 35
                        $modified4 = substr($this->updateCellReference($match[4] . '$1', $includeAbsoluteReferences, $onlyAbsoluteReferences), 0, -2);
663 35
664
                        if ($match[3] . ':' . $match[4] !== $modified3 . ':' . $modified4) {
665 35
                            if (self::matchSheetName($match[2], $worksheetName)) {
666 35
                                $toString = self::sheetnameBeforeCells($match[2], $worksheetName, "$modified3:$modified4");
667 35
                                //    Max worksheet size is 1,048,576 rows by 16,384 columns in Excel 2007, so our adjustments need to be at least one digit more
668
                                $column = Coordinate::columnIndexFromString(trim($match[3], '$')) + 100000;
669
                                $row = 10000000;
670
                                $cellIndex = "{$column}{$row}";
671
672
                                $newCellTokens[$cellIndex] = preg_quote($toString, '/');
673
                                $cellTokens[$cellIndex] = '/(?<![A-Z\$\!])' . preg_quote($fromString, '/') . '(?![A-Z])/i';
674 284
                                ++$adjustCount;
675 284
                            }
676
                        }
677 284
                    }
678 252
                }
679 252
                //    Search for cell ranges (e.g. 'Sheet1'!A3:C5 or A3:C5) with or without $ absolutes (e.g. $A1:C$5)
680
                $formulaBlockx = ' ' . (preg_replace_callback(self::SHEETNAME_PART_WITH_SLASHES, $callback, "$formulaBlock") ?? "$formulaBlock") . ' ';
681 252
                $matchCount = preg_match_all('/' . self::REFHELPER_REGEXP_CELLRANGE . '/mui', $formulaBlockx, $matches, PREG_SET_ORDER);
682 252
                if ($matchCount > 0) {
683 250
                    foreach ($matches as $match) {
684 250
                        $fromString = self::sheetnameBeforeCells($match[2], $worksheetName, "{$match[3]}:{$match[4]}");
685 250
                        $modified3 = $this->updateCellReference($match[3], $includeAbsoluteReferences, $onlyAbsoluteReferences);
686 250
                        $modified4 = $this->updateCellReference($match[4], $includeAbsoluteReferences, $onlyAbsoluteReferences);
687 250
688
                        if ($match[3] . $match[4] !== $modified3 . $modified4) {
689 250
                            if (self::matchSheetName($match[2], $worksheetName)) {
690 250
                                $toString = self::sheetnameBeforeCells($match[2], $worksheetName, "$modified3:$modified4");
691 250
                                [$column, $row] = Coordinate::coordinateFromString($match[3]);
692
                                //    Max worksheet size is 1,048,576 rows by 16,384 columns in Excel 2007, so our adjustments need to be at least one digit more
693 250
                                $column = Coordinate::columnIndexFromString(trim($column, '$')) + 100000;
694 250
                                $row = (int) trim($row, '$') + 10000000;
695 250
                                $cellIndex = "{$column}{$row}";
696
697
                                $newCellTokens[$cellIndex] = preg_quote($toString, '/');
698
                                $cellTokens[$cellIndex] = '/(?<![A-Z]\$\!)' . preg_quote($fromString, '/') . '(?!\d)/i';
699
                                ++$adjustCount;
700 284
                            }
701 263
                        }
702 257
                    }
703 257
                }
704
                //    Search for cell references (e.g. 'Sheet1'!A3 or C5) with or without $ absolutes (e.g. $A1 or C$5)
705 27
706 27
                $formulaBlockx = ' ' . (preg_replace_callback(self::SHEETNAME_PART_WITH_SLASHES, $callback, $formulaBlock) ?? $formulaBlock) . ' ';
707
                $matchCount = preg_match_all('/' . self::REFHELPER_REGEXP_CELLREF . '/mui', $formulaBlockx, $matches, PREG_SET_ORDER);
708 263
709
                if ($matchCount > 0) {
710
                    foreach ($matches as $match) {
711
                        $fromString = self::sheetnameBeforeCells($match[2], $worksheetName, "{$match[3]}");
712 284
713
                        $modified3 = $this->updateCellReference($match[3], $includeAbsoluteReferences, $onlyAbsoluteReferences);
714
                        if ($match[3] !== $modified3) {
715 284
                            if (self::matchSheetName($match[2], $worksheetName)) {
716
                                $toString = self::sheetnameBeforeCells($match[2], $worksheetName, "$modified3");
717
                                [$column, $row] = Coordinate::coordinateFromString($match[3]);
718
                                $columnAdditionalIndex = $column[0] === '$' ? 1 : 0;
719
                                $rowAdditionalIndex = $row[0] === '$' ? 1 : 0;
720
                                //    Max worksheet size is 1,048,576 rows by 16,384 columns in Excel 2007, so our adjustments need to be at least one digit more
721 125
                                $column = Coordinate::columnIndexFromString(trim($column, '$')) + 100000;
722
                                $row = (int) trim($row, '$') + 10000000;
723 125
                                $cellIndex = $row . $rowAdditionalIndex . $column . $columnAdditionalIndex;
724
725 125
                                $newCellTokens[$cellIndex] = preg_quote($toString, '/');
726 118
                                $cellTokens[$cellIndex] = '/(?<![A-Z\$\!])' . preg_quote($fromString, '/') . '(?!\d)/i';
727
                                ++$adjustCount;
728
                            }
729 125
                        }
730 102
                    }
731
                }
732
                if ($adjustCount > 0) {
733 125
                    if ($numberOfColumns > 0 || $numberOfRows > 0) {
734
                        krsort($cellTokens);
735
                        krsort($newCellTokens);
736 125
                    } else {
737
                        ksort($cellTokens);
738 125
                        ksort($newCellTokens);
739 125
                    }   //  Update cell references in the formula
740 125
                    $formulaBlock = str_replace('\\', '', (string) preg_replace($cellTokens, $newCellTokens, $formulaBlock));
741 125
                }
742 125
            }
743 125
        }
744
        unset($formulaBlock);
745 125
746 125
        //    Then rebuild the formula string
747 125
        return implode('"', $formulaBlocks);
748 125
    }
749
750 125
    /**
751 125
     * Update all cell references within a formula, irrespective of worksheet.
752
     */
753 125
    public function updateFormulaReferencesAnyWorksheet(string $formula = '', int $numberOfColumns = 0, int $numberOfRows = 0): string
754 119
    {
755 119
        $formula = $this->updateCellReferencesAllWorksheets($formula, $numberOfColumns, $numberOfRows);
756 119
757 119
        if ($numberOfColumns !== 0) {
758 119
            $formula = $this->updateColumnRangesAllWorksheets($formula, $numberOfColumns);
759 119
        }
760 119
761
        if ($numberOfRows !== 0) {
762 119
            $formula = $this->updateRowRangesAllWorksheets($formula, $numberOfRows);
763 22
        }
764 22
765 22
        return $formula;
766 22
    }
767
768 119
    private function updateCellReferencesAllWorksheets(string $formula, int $numberOfColumns, int $numberOfRows): string
769 42
    {
770 42
        $splitCount = preg_match_all(
771
            '/' . Calculation::CALCULATION_REGEXP_CELLREF_RELATIVE . '/mui',
772
            $formula,
773
            $splitRanges,
774 125
            PREG_OFFSET_CAPTURE
775
        );
776
777 118
        $columnLengths = array_map('strlen', array_column($splitRanges[6], 0));
778
        $rowLengths = array_map('strlen', array_column($splitRanges[7], 0));
779 118
        $columnOffsets = array_column($splitRanges[6], 1);
780 118
        $rowOffsets = array_column($splitRanges[7], 1);
781 118
782 118
        $columns = $splitRanges[6];
783 118
        $rows = $splitRanges[7];
784 118
785
        while ($splitCount > 0) {
786 118
            --$splitCount;
787 118
            $columnLength = $columnLengths[$splitCount];
788 118
            $rowLength = $rowLengths[$splitCount];
789 118
            $columnOffset = $columnOffsets[$splitCount];
790
            $rowOffset = $rowOffsets[$splitCount];
791 118
            $column = $columns[$splitCount][0];
792 118
            $row = $rows[$splitCount][0];
793
794 118
            if ($column[0] !== '$') {
795 3
                $column = ((Coordinate::columnIndexFromString($column) + $numberOfColumns) % AddressRange::MAX_COLUMN_INT) ?: AddressRange::MAX_COLUMN_INT;
796 3
                $column = Coordinate::stringFromColumnIndex($column);
797 3
                $rowOffset -= ($columnLength - strlen($column));
798 3
                $formula = substr($formula, 0, $columnOffset) . $column . substr($formula, $columnOffset + $columnLength);
799 3
            }
800 3
            if (!empty($row) && $row[0] !== '$') {
801 3
                $row = (((int) $row + $numberOfRows) % AddressRange::MAX_ROW) ?: AddressRange::MAX_ROW;
802
                $formula = substr($formula, 0, $rowOffset) . $row . substr($formula, $rowOffset + $rowLength);
803 3
            }
804 2
        }
805 2
806
        return $formula;
807 3
    }
808 2
809 2
    private function updateColumnRangesAllWorksheets(string $formula, int $numberOfColumns): string
810
    {
811
        $splitCount = preg_match_all(
812
            '/' . Calculation::CALCULATION_REGEXP_COLUMNRANGE_RELATIVE . '/mui',
813 118
            $formula,
814
            $splitRanges,
815
            PREG_OFFSET_CAPTURE
816 102
        );
817
818 102
        $fromColumnLengths = array_map('strlen', array_column($splitRanges[1], 0));
819 102
        $fromColumnOffsets = array_column($splitRanges[1], 1);
820 102
        $toColumnLengths = array_map('strlen', array_column($splitRanges[2], 0));
821 102
        $toColumnOffsets = array_column($splitRanges[2], 1);
822 102
823 102
        $fromColumns = $splitRanges[1];
824
        $toColumns = $splitRanges[2];
825 102
826 102
        while ($splitCount > 0) {
827 102
            --$splitCount;
828 102
            $fromColumnLength = $fromColumnLengths[$splitCount];
829
            $toColumnLength = $toColumnLengths[$splitCount];
830 102
            $fromColumnOffset = $fromColumnOffsets[$splitCount];
831 102
            $toColumnOffset = $toColumnOffsets[$splitCount];
832
            $fromColumn = $fromColumns[$splitCount][0];
833 102
            $toColumn = $toColumns[$splitCount][0];
834 3
835 3
            if (!empty($fromColumn) && $fromColumn[0] !== '$') {
836 3
                $fromColumn = Coordinate::stringFromColumnIndex(Coordinate::columnIndexFromString($fromColumn) + $numberOfColumns);
837 3
                $formula = substr($formula, 0, $fromColumnOffset) . $fromColumn . substr($formula, $fromColumnOffset + $fromColumnLength);
838 3
            }
839 3
            if (!empty($toColumn) && $toColumn[0] !== '$') {
840 3
                $toColumn = Coordinate::stringFromColumnIndex(Coordinate::columnIndexFromString($toColumn) + $numberOfColumns);
841
                $formula = substr($formula, 0, $toColumnOffset) . $toColumn . substr($formula, $toColumnOffset + $toColumnLength);
842 3
            }
843 2
        }
844 2
845
        return $formula;
846 3
    }
847 2
848 2
    private function updateRowRangesAllWorksheets(string $formula, int $numberOfRows): string
849
    {
850
        $splitCount = preg_match_all(
851
            '/' . Calculation::CALCULATION_REGEXP_ROWRANGE_RELATIVE . '/mui',
852 102
            $formula,
853
            $splitRanges,
854
            PREG_OFFSET_CAPTURE
855
        );
856
857
        $fromRowLengths = array_map('strlen', array_column($splitRanges[1], 0));
858
        $fromRowOffsets = array_column($splitRanges[1], 1);
859
        $toRowLengths = array_map('strlen', array_column($splitRanges[2], 0));
860
        $toRowOffsets = array_column($splitRanges[2], 1);
861
862 300
        $fromRows = $splitRanges[1];
863
        $toRows = $splitRanges[2];
864
865 300
        while ($splitCount > 0) {
866 1
            --$splitCount;
867
            $fromRowLength = $fromRowLengths[$splitCount];
868
            $toRowLength = $toRowLengths[$splitCount];
869 300
            $fromRowOffset = $fromRowOffsets[$splitCount];
870
            $toRowOffset = $toRowOffsets[$splitCount];
871
            $fromRow = $fromRows[$splitCount][0];
872 288
            $toRow = $toRows[$splitCount][0];
873
874 288
            if (!empty($fromRow) && $fromRow[0] !== '$') {
875
                $fromRow = (int) $fromRow + $numberOfRows;
876
                $formula = substr($formula, 0, $fromRowOffset) . $fromRow . substr($formula, $fromRowOffset + $fromRowLength);
877
            }
878 37
            if (!empty($toRow) && $toRow[0] !== '$') {
879
                $toRow = (int) $toRow + $numberOfRows;
880
                $formula = substr($formula, 0, $toRowOffset) . $toRow . substr($formula, $toRowOffset + $toRowLength);
881
            }
882
        }
883
884
        return $formula;
885
    }
886
887
    /**
888 794
     * Update cell reference.
889
     *
890 794
     * @param string $cellReference Cell address or range of addresses
891 1
     *
892
     * @return string Updated cell range
893
     */
894 794
    private function updateCellReference(string $cellReference = 'A1', bool $includeAbsoluteReferences = false, bool $onlyAbsoluteReferences = false): string
895 794
    {
896 136
        // Is it in another worksheet? Will not have to update anything.
897 136
        if (str_contains($cellReference, '!')) {
898 68
            return $cellReference;
899 68
        }
900 1
        // Is it a range or a single cell?
901 1
        if (!Coordinate::coordinateIsRange($cellReference)) {
902 1
            // Single cell
903
            /** @var CellReferenceHelper */
904
            $cellReferenceHelper = $this->cellReferenceHelper;
905
906
            return $cellReferenceHelper->updateCellReference($cellReference, $includeAbsoluteReferences, $onlyAbsoluteReferences);
907
        }
908
909 7
        // Range
910
        return $this->updateCellRange($cellReference, $includeAbsoluteReferences, $onlyAbsoluteReferences);
911 7
    }
912 7
913 7
    /**
914
     * Update named formulae (i.e. containing worksheet references / named ranges).
915 4
     *
916
     * @param Spreadsheet $spreadsheet Object to update
917
     * @param string $oldName Old name (name to replace)
918
     * @param string $newName New name
919
     */
920 7
    public function updateNamedFormulae(Spreadsheet $spreadsheet, string $oldName = '', string $newName = ''): void
921
    {
922 7
        if ($oldName == '') {
923 7
            return;
924 7
        }
925
926
        foreach ($spreadsheet->getWorksheetIterator() as $sheet) {
927
            foreach ($sheet->getCoordinates(false) as $coordinate) {
928
                $cell = $sheet->getCell($coordinate);
929
                if ($cell->getDataType() === DataType::TYPE_FORMULA) {
930
                    $formula = $cell->getValueString();
931
                    if (str_contains($formula, $oldName)) {
932 7
                        $formula = str_replace("'" . $oldName . "'!", "'" . $newName . "'!", $formula);
933 5
                        $formula = str_replace($oldName . '!', $newName . '!', $formula);
934 5
                        $cell->setValueExplicit($formula, DataType::TYPE_FORMULA);
935
                    }
936 2
                }
937
            }
938
        }
939
    }
940
941 4
    private function updateDefinedNames(Worksheet $worksheet, string $beforeCellAddress, int $numberOfColumns, int $numberOfRows): void
942
    {
943 4
        foreach ($worksheet->getParentOrThrow()->getDefinedNames() as $definedName) {
944
            if ($definedName->isFormula() === false) {
945
                $this->updateNamedRange($definedName, $worksheet, $beforeCellAddress, $numberOfColumns, $numberOfRows);
946
            } else {
947
                $this->updateNamedFormula($definedName, $worksheet, $beforeCellAddress, $numberOfColumns, $numberOfRows);
948
            }
949
        }
950
    }
951 3
952 3
    private function updateNamedRange(DefinedName $definedName, Worksheet $worksheet, string $beforeCellAddress, int $numberOfColumns, int $numberOfRows): void
953 3
    {
954
        $cellAddress = $definedName->getValue();
955
        $asFormula = ($cellAddress[0] === '=');
956
        if ($definedName->getWorksheet() !== null && $definedName->getWorksheet()->getHashInt() === $worksheet->getHashInt()) {
957
            /**
958
             * If we delete the entire range that is referenced by a Named Range, MS Excel sets the value to #REF!
959
             * PhpSpreadsheet still only does a basic adjustment, so the Named Range will still reference Cells.
960
             * Note that this applies only when deleting columns/rows; subsequent insertion won't fix the #REF!
961
             * TODO Can we work out a method to identify Named Ranges that cease to be valid, so that we can replace
962
             *      them with a #REF!
963
             */
964 37
            if ($asFormula === true) {
965
                $formula = $this->updateFormulaReferences($cellAddress, $beforeCellAddress, $numberOfColumns, $numberOfRows, $worksheet->getTitle(), true, true);
966 37
                $definedName->setValue($formula);
967
            } else {
968
                $definedName->setValue($this->updateCellReference(ltrim($cellAddress, '='), true));
969
            }
970
        }
971 37
    }
972 37
973 37
    private function updateNamedFormula(DefinedName $definedName, Worksheet $worksheet, string $beforeCellAddress, int $numberOfColumns, int $numberOfRows): void
974 37
    {
975 37
        if ($definedName->getWorksheet() !== null && $definedName->getWorksheet()->getHashInt() === $worksheet->getHashInt()) {
976
            /**
977 37
             * If we delete the entire range that is referenced by a Named Formula, MS Excel sets the value to #REF!
978 37
             * PhpSpreadsheet still only does a basic adjustment, so the Named Formula will still reference Cells.
979
             * Note that this applies only when deleting columns/rows; subsequent insertion won't fix the #REF!
980
             * TODO Can we work out a method to identify Named Ranges that cease to be valid, so that we can replace
981
             *      them with a #REF!
982 37
             */
983
            $formula = $definedName->getValue();
984
            $formula = $this->updateFormulaReferences($formula, $beforeCellAddress, $numberOfColumns, $numberOfRows, $worksheet->getTitle(), true);
985
            $definedName->setValue($formula);
986
        }
987 37
    }
988
989
    /**
990
     * Update cell range.
991
     *
992
     * @param string $cellRange Cell range    (e.g. 'B2:D4', 'B:C' or '2:3')
993 37
     *
994
     * @return string Updated cell range
995
     */
996 23
    private function updateCellRange(string $cellRange = 'A1:A1', bool $includeAbsoluteReferences = false, bool $onlyAbsoluteReferences = false): string
997
    {
998 23
        if (!Coordinate::coordinateIsRange($cellRange)) {
999 23
            throw new Exception('Only cell ranges may be passed to this method.');
1000
        }
1001 23
1002 22
        // Update range
1003 22
        $range = Coordinate::splitRange($cellRange);
1004 22
        $ic = count($range);
1005
        for ($i = 0; $i < $ic; ++$i) {
1006
            $jc = count($range[$i]);
1007
            for ($j = 0; $j < $jc; ++$j) {
1008
                /** @var CellReferenceHelper */
1009 35
                $cellReferenceHelper = $this->cellReferenceHelper;
1010
                if (ctype_alpha($range[$i][$j])) {
1011 35
                    $range[$i][$j] = Coordinate::coordinateFromString(
1012 35
                        $cellReferenceHelper->updateCellReference($range[$i][$j] . '1', $includeAbsoluteReferences, $onlyAbsoluteReferences)
1013
                    )[0];
1014 35
                } elseif (ctype_digit($range[$i][$j])) {
1015 35
                    $range[$i][$j] = Coordinate::coordinateFromString(
1016 35
                        $cellReferenceHelper->updateCellReference('A' . $range[$i][$j], $includeAbsoluteReferences, $onlyAbsoluteReferences)
1017 35
                    )[1];
1018
                } else {
1019
                    $range[$i][$j] = $cellReferenceHelper->updateCellReference($range[$i][$j], $includeAbsoluteReferences, $onlyAbsoluteReferences);
1020
                }
1021
            }
1022 40
        }
1023
1024 40
        // Recreate range string
1025 40
        return Coordinate::buildRange($range);
1026 40
    }
1027 40
1028
    private function clearColumnStrips(int $highestRow, int $beforeColumn, int $numberOfColumns, Worksheet $worksheet): void
1029 40
    {
1030 19
        $startColumnId = Coordinate::stringFromColumnIndex($beforeColumn + $numberOfColumns);
1031 19
        $endColumnId = Coordinate::stringFromColumnIndex($beforeColumn);
1032
1033
        for ($row = 1; $row <= $highestRow - 1; ++$row) {
1034
            for ($column = $startColumnId; $column !== $endColumnId; ++$column) {
1035 91
                $coordinate = $column . $row;
1036
                $this->clearStripCell($worksheet, $coordinate);
1037 91
            }
1038 91
        }
1039 91
    }
1040 4
1041 2
    private function clearRowStrips(string $highestColumn, int $beforeColumn, int $beforeRow, int $numberOfRows, Worksheet $worksheet): void
1042 2
    {
1043 2
        $startColumnId = Coordinate::stringFromColumnIndex($beforeColumn);
1044 2
        ++$highestColumn;
1045 2
1046 2
        for ($column = $startColumnId; $column !== $highestColumn; ++$column) {
1047 2
            for ($row = $beforeRow + $numberOfRows; $row <= $beforeRow - 1; ++$row) {
1048 2
                $coordinate = $column . $row;
1049 2
                $this->clearStripCell($worksheet, $coordinate);
1050 1
            }
1051
        }
1052 2
    }
1053
1054
    private function clearStripCell(Worksheet $worksheet, string $coordinate): void
1055 2
    {
1056 1
        $worksheet->removeConditionalStyles($coordinate);
1057
        $worksheet->setHyperlink($coordinate);
1058 1
        $worksheet->setDataValidation($coordinate);
1059
        $worksheet->removeComment($coordinate);
1060
1061
        if ($worksheet->cellExists($coordinate)) {
1062
            $worksheet->getCell($coordinate)->setValueExplicit(null, DataType::TYPE_NULL);
1063
            $worksheet->getCell($coordinate)->setXfIndex(0);
1064 4
        }
1065 4
    }
1066 4
1067
    private function adjustAutoFilter(Worksheet $worksheet, string $beforeCellAddress, int $numberOfColumns): void
1068
    {
1069
        $autoFilter = $worksheet->getAutoFilter();
1070 1
        $autoFilterRange = $autoFilter->getRange();
1071
        if (!empty($autoFilterRange)) {
1072
            if ($numberOfColumns !== 0) {
1073
                $autoFilterColumns = $autoFilter->getColumns();
1074 1
                if (count($autoFilterColumns) > 0) {
1075 1
                    $column = '';
1076
                    $row = 0;
1077 1
                    sscanf($beforeCellAddress, '%[A-Z]%d', $column, $row);
1078 1
                    $columnIndex = Coordinate::columnIndexFromString((string) $column);
1079 1
                    [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($autoFilterRange);
1080 1
                    if ($columnIndex <= $rangeEnd[0]) {
1081
                        if ($numberOfColumns < 0) {
1082 1
                            $this->adjustAutoFilterDeleteRules($columnIndex, $numberOfColumns, $autoFilterColumns, $autoFilter);
1083
                        }
1084
                        $startCol = ($columnIndex > $rangeStart[0]) ? $columnIndex : $rangeStart[0];
1085
1086 1
                        //    Shuffle columns in autofilter range
1087
                        if ($numberOfColumns > 0) {
1088 1
                            $this->adjustAutoFilterInsert($startCol, $numberOfColumns, $rangeEnd[0], $autoFilter);
1089 1
                        } else {
1090 1
                            $this->adjustAutoFilterDelete($startCol, $numberOfColumns, $rangeEnd[0], $autoFilter);
1091
                        }
1092
                    }
1093 1
                }
1094 1
            }
1095 1
1096 1
            $worksheet->setAutoFilter(
1097
                $this->updateCellReference($autoFilterRange)
1098
            );
1099 1
        }
1100
    }
1101
1102 1
    private function adjustAutoFilterDeleteRules(int $columnIndex, int $numberOfColumns, array $autoFilterColumns, AutoFilter $autoFilter): void
1103 1
    {
1104 1
        // If we're actually deleting any columns that fall within the autofilter range,
1105
        //    then we delete any rules for those columns
1106
        $deleteColumn = $columnIndex + $numberOfColumns - 1;
1107 1
        $deleteCount = abs($numberOfColumns);
1108 1
1109 1
        for ($i = 1; $i <= $deleteCount; ++$i) {
1110 1
            $columnName = Coordinate::stringFromColumnIndex($deleteColumn + 1);
1111
            if (isset($autoFilterColumns[$columnName])) {
1112
                $autoFilter->clearColumn($columnName);
1113 91
            }
1114
            ++$deleteColumn;
1115 91
        }
1116
    }
1117 91
1118 4
    private function adjustAutoFilterInsert(int $startCol, int $numberOfColumns, int $rangeEnd, AutoFilter $autoFilter): void
1119 4
    {
1120 4
        $startColRef = $startCol;
1121 2
        $endColRef = $rangeEnd;
1122 2
        $toColRef = $rangeEnd + $numberOfColumns;
1123 2
1124 2
        do {
1125 2
            $autoFilter->shiftColumn(Coordinate::stringFromColumnIndex($endColRef), Coordinate::stringFromColumnIndex($toColRef));
1126 2
            --$endColRef;
1127 2
            --$toColRef;
1128 2
        } while ($startColRef <= $endColRef);
1129 2
    }
1130 1
1131
    private function adjustAutoFilterDelete(int $startCol, int $numberOfColumns, int $rangeEnd, AutoFilter $autoFilter): void
1132 2
    {
1133
        // For delete, we shuffle from beginning to end to avoid overwriting
1134
        $startColID = Coordinate::stringFromColumnIndex($startCol);
1135 2
        $toColID = Coordinate::stringFromColumnIndex($startCol + $numberOfColumns);
1136 1
        $endColID = Coordinate::stringFromColumnIndex($rangeEnd + 1);
1137
1138 1
        do {
1139
            $autoFilter->shiftColumn($startColID, $toColID);
1140
            ++$startColID;
1141
            ++$toColID;
1142
        } while ($startColID !== $endColID);
1143
    }
1144 4
1145
    private function adjustTable(Worksheet $worksheet, string $beforeCellAddress, int $numberOfColumns): void
1146
    {
1147
        $tableCollection = $worksheet->getTableCollection();
1148
1149 1
        foreach ($tableCollection as $table) {
1150
            $tableRange = $table->getRange();
1151
            if (!empty($tableRange)) {
1152
                if ($numberOfColumns !== 0) {
1153 1
                    $tableColumns = $table->getColumns();
1154 1
                    if (count($tableColumns) > 0) {
1155
                        $column = '';
1156 1
                        $row = 0;
1157 1
                        sscanf($beforeCellAddress, '%[A-Z]%d', $column, $row);
1158 1
                        $columnIndex = Coordinate::columnIndexFromString((string) $column);
1159 1
                        [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($tableRange);
1160
                        if ($columnIndex <= $rangeEnd[0]) {
1161 1
                            if ($numberOfColumns < 0) {
1162
                                $this->adjustTableDeleteRules($columnIndex, $numberOfColumns, $tableColumns, $table);
1163
                            }
1164
                            $startCol = ($columnIndex > $rangeStart[0]) ? $columnIndex : $rangeStart[0];
1165 1
1166
                            //    Shuffle columns in table range
1167 1
                            if ($numberOfColumns > 0) {
1168 1
                                $this->adjustTableInsert($startCol, $numberOfColumns, $rangeEnd[0], $table);
1169 1
                            } else {
1170
                                $this->adjustTableDelete($startCol, $numberOfColumns, $rangeEnd[0], $table);
1171
                            }
1172 1
                        }
1173 1
                    }
1174 1
                }
1175 1
1176
                $table->setRange($this->updateCellReference($tableRange));
1177
            }
1178 1
        }
1179
    }
1180
1181 1
    private function adjustTableDeleteRules(int $columnIndex, int $numberOfColumns, array $tableColumns, Table $table): void
1182 1
    {
1183 1
        // If we're actually deleting any columns that fall within the table range,
1184
        //    then we delete any rules for those columns
1185
        $deleteColumn = $columnIndex + $numberOfColumns - 1;
1186 1
        $deleteCount = abs($numberOfColumns);
1187 1
1188 1
        for ($i = 1; $i <= $deleteCount; ++$i) {
1189 1
            $columnName = Coordinate::stringFromColumnIndex($deleteColumn + 1);
1190
            if (isset($tableColumns[$columnName])) {
1191
                $table->clearColumn($columnName);
1192 23
            }
1193
            ++$deleteColumn;
1194 23
        }
1195 23
    }
1196
1197 22
    private function adjustTableInsert(int $startCol, int $numberOfColumns, int $rangeEnd, Table $table): void
1198 22
    {
1199 18
        $startColRef = $startCol;
1200 18
        $endColRef = $rangeEnd;
1201 18
        $toColRef = $rangeEnd + $numberOfColumns;
1202 18
1203
        do {
1204
            $table->shiftColumn(Coordinate::stringFromColumnIndex($endColRef), Coordinate::stringFromColumnIndex($toColRef));
1205
            --$endColRef;
1206
            --$toColRef;
1207
        } while ($startColRef <= $endColRef);
1208
    }
1209 33
1210
    private function adjustTableDelete(int $startCol, int $numberOfColumns, int $rangeEnd, Table $table): void
1211 33
    {
1212 33
        // For delete, we shuffle from beginning to end to avoid overwriting
1213
        $startColID = Coordinate::stringFromColumnIndex($startCol);
1214 33
        $toColID = Coordinate::stringFromColumnIndex($startCol + $numberOfColumns);
1215 33
        $endColID = Coordinate::stringFromColumnIndex($rangeEnd + 1);
1216 31
1217 31
        do {
1218 31
            $table->shiftColumn($startColID, $toColID);
1219 23
            ++$startColID;
1220
            ++$toColID;
1221
        } while ($startColID !== $endColID);
1222
    }
1223
1224
    private function duplicateStylesByColumn(Worksheet $worksheet, int $beforeColumn, int $beforeRow, int $highestRow, int $numberOfColumns): void
1225
    {
1226
        $beforeColumnName = Coordinate::stringFromColumnIndex($beforeColumn - 1);
1227
        for ($i = $beforeRow; $i <= $highestRow - 1; ++$i) {
1228
            // Style
1229 1
            $coordinate = $beforeColumnName . $i;
1230
            if ($worksheet->cellExists($coordinate)) {
1231 1
                $xfIndex = $worksheet->getCell($coordinate)->getXfIndex();
1232
                for ($j = $beforeColumn; $j <= $beforeColumn - 1 + $numberOfColumns; ++$j) {
1233
                    if (!empty($xfIndex) || $worksheet->cellExists([$j, $i])) {
1234
                        $worksheet->getCell([$j, $i])->setXfIndex($xfIndex);
1235
                    }
1236
                }
1237
            }
1238
        }
1239
    }
1240
1241
    private function duplicateStylesByRow(Worksheet $worksheet, int $beforeColumn, int $beforeRow, string $highestColumn, int $numberOfRows): void
1242
    {
1243
        $highestColumnIndex = Coordinate::columnIndexFromString($highestColumn);
1244
        for ($i = $beforeColumn; $i <= $highestColumnIndex; ++$i) {
1245
            // Style
1246
            $coordinate = Coordinate::stringFromColumnIndex($i) . ($beforeRow - 1);
1247
            if ($worksheet->cellExists($coordinate)) {
1248
                $xfIndex = $worksheet->getCell($coordinate)->getXfIndex();
1249
                for ($j = $beforeRow; $j <= $beforeRow - 1 + $numberOfRows; ++$j) {
1250
                    if (!empty($xfIndex) || $worksheet->cellExists([$i, $j])) {
1251
                        $worksheet->getCell(Coordinate::stringFromColumnIndex($i) . $j)->setXfIndex($xfIndex);
1252
                    }
1253
                }
1254
            }
1255
        }
1256
    }
1257
1258
    /**
1259
     * __clone implementation. Cloning should not be allowed in a Singleton!
1260
     */
1261
    final public function __clone()
1262
    {
1263
        throw new Exception('Cloning a Singleton is not allowed!');
1264
    }
1265
}
1266