Failed Conditions
Pull Request — master (#3528)
by Owen
13:22
created

ReferenceHelper::adjustProtectedCells()   A

Complexity

Conditions 6
Paths 16

Size

Total Lines 12
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 6

Importance

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