Passed
Pull Request — master (#4240)
by Owen
15:00 queued 01:35
created

ReferenceHelper::adjustDataValidations()   B

Complexity

Conditions 7
Paths 36

Size

Total Lines 39
Code Lines 30

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 18
CRAP Score 7

Importance

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