Failed Conditions
Pull Request — master (#3528)
by Owen
15:06 queued 35s
created

ReferenceHelper::adjustHyperlinks()   B

Complexity

Conditions 7
Paths 20

Size

Total Lines 17
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 7.0178

Importance

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