Failed Conditions
Pull Request — master (#3528)
by Owen
16:46 queued 06:04
created

ReferenceHelper::adjustHyperlinks()   B

Complexity

Conditions 7
Paths 20

Size

Total Lines 17
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 7.0178

Importance

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