Passed
Pull Request — master (#4240)
by Owen
27:46 queued 17:34
created

ReferenceHelper::__clone()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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