Passed
Pull Request — master (#4240)
by Owen
13:17
created

ReferenceHelper::adjustDataValidations()   B

Complexity

Conditions 8
Paths 68

Size

Total Lines 44
Code Lines 34

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 21
CRAP Score 8

Importance

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