Coordinate::stringFromColumnIndex()   A
last analyzed

Complexity

Conditions 4
Paths 2

Size

Total Lines 17
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 4

Importance

Changes 0
Metric Value
eloc 11
dl 0
loc 17
ccs 10
cts 10
cp 1
rs 9.9
c 0
b 0
f 0
cc 4
nc 2
nop 1
crap 4
1
<?php
2
3
namespace PhpOffice\PhpSpreadsheet\Cell;
4
5
use PhpOffice\PhpSpreadsheet\Exception;
6
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
7
use PhpOffice\PhpSpreadsheet\Worksheet\Validations;
8
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
9
10
/**
11
 * Helper class to manipulate cell coordinates.
12
 *
13
 * Columns indexes and rows are always based on 1, **not** on 0. This match the behavior
14
 * that Excel users are used to, and also match the Excel functions `COLUMN()` and `ROW()`.
15
 */
16
abstract class Coordinate
17
{
18
    public const A1_COORDINATE_REGEX = '/^(?<col>\$?[A-Z]{1,3})(?<row>\$?\d{1,7})$/i';
19
    public const FULL_REFERENCE_REGEX = '/^(?:(?<worksheet>[^!]*)!)?(?<localReference>(?<firstCoordinate>[$]?[A-Z]{1,3}[$]?\d{1,7})(?:\:(?<secondCoordinate>[$]?[A-Z]{1,3}[$]?\d{1,7}))?)$/i';
20
21
    /**
22
     * Default range variable constant.
23
     *
24
     * @var string
25
     */
26
    const DEFAULT_RANGE = 'A1:A1';
27
28
    /**
29
     * Convert string coordinate to [0 => int column index, 1 => int row index].
30
     *
31
     * @param string $cellAddress eg: 'A1'
32
     *
33
     * @return array{0: string, 1: string} Array containing column and row (indexes 0 and 1)
34
     */
35 10664
    public static function coordinateFromString(string $cellAddress): array
36
    {
37 10664
        if (preg_match(self::A1_COORDINATE_REGEX, $cellAddress, $matches)) {
38 10649
            return [$matches['col'], $matches['row']];
39 19
        } elseif (self::coordinateIsRange($cellAddress)) {
40 1
            throw new Exception('Cell coordinate string can not be a range of cells');
41 18
        } elseif ($cellAddress == '') {
42 2
            throw new Exception('Cell coordinate can not be zero-length string');
43
        }
44
45 16
        throw new Exception('Invalid cell coordinate ' . $cellAddress);
46
    }
47
48
    /**
49
     * Convert string coordinate to [0 => int column index, 1 => int row index, 2 => string column string].
50
     *
51
     * @param string $coordinates eg: 'A1', '$B$12'
52
     *
53
     * @return array{0: int, 1: int, 2: string} Array containing column and row index, and column string
54
     */
55 10365
    public static function indexesFromString(string $coordinates): array
56
    {
57 10365
        [$column, $row] = self::coordinateFromString($coordinates);
58 10361
        $column = ltrim($column, '$');
59
60 10361
        return [
61 10361
            self::columnIndexFromString($column),
62 10361
            (int) ltrim($row, '$'),
63 10361
            $column,
64 10361
        ];
65
    }
66
67
    /**
68
     * Checks if a Cell Address represents a range of cells.
69
     *
70
     * @param string $cellAddress eg: 'A1' or 'A1:A2' or 'A1:A2,C1:C2'
71
     *
72
     * @return bool Whether the coordinate represents a range of cells
73
     */
74 10451
    public static function coordinateIsRange(string $cellAddress): bool
75
    {
76 10451
        return str_contains($cellAddress, ':') || str_contains($cellAddress, ',');
77
    }
78
79
    /**
80
     * Make string row, column or cell coordinate absolute.
81
     *
82
     * @param int|string $cellAddress e.g. 'A' or '1' or 'A1'
83
     *                    Note that this value can be a row or column reference as well as a cell reference
84
     *
85
     * @return string Absolute coordinate        e.g. '$A' or '$1' or '$A$1'
86
     */
87 23
    public static function absoluteReference(int|string $cellAddress): string
88
    {
89 23
        $cellAddress = (string) $cellAddress;
90 23
        if (self::coordinateIsRange($cellAddress)) {
91 1
            throw new Exception('Cell coordinate string can not be a range of cells');
92
        }
93
94
        // Split out any worksheet name from the reference
95 22
        [$worksheet, $cellAddress] = Worksheet::extractSheetTitle($cellAddress, true);
96 22
        if ($worksheet > '') {
97 8
            $worksheet .= '!';
98
        }
99
100
        // Create absolute coordinate
101 22
        $cellAddress = "$cellAddress";
102 22
        if (ctype_digit($cellAddress)) {
103 2
            return $worksheet . '$' . $cellAddress;
104 20
        } elseif (ctype_alpha($cellAddress)) {
105 2
            return $worksheet . '$' . strtoupper($cellAddress);
106
        }
107
108 18
        return $worksheet . self::absoluteCoordinate($cellAddress);
109
    }
110
111
    /**
112
     * Make string coordinate absolute.
113
     *
114
     * @param string $cellAddress e.g. 'A1'
115
     *
116
     * @return string Absolute coordinate        e.g. '$A$1'
117
     */
118 217
    public static function absoluteCoordinate(string $cellAddress): string
119
    {
120 217
        if (self::coordinateIsRange($cellAddress)) {
121 1
            throw new Exception('Cell coordinate string can not be a range of cells');
122
        }
123
124
        // Split out any worksheet name from the coordinate
125 216
        [$worksheet, $cellAddress] = Worksheet::extractSheetTitle($cellAddress, true);
126 216
        if ($worksheet > '') {
127 6
            $worksheet .= '!';
128
        }
129
130
        // Create absolute coordinate
131 216
        [$column, $row] = self::coordinateFromString($cellAddress ?? 'A1');
132 216
        $column = ltrim($column, '$');
133 216
        $row = ltrim($row, '$');
134
135 216
        return $worksheet . '$' . $column . '$' . $row;
136
    }
137
138
    /**
139
     * Split range into coordinate strings.
140
     *
141
     * @param string $range e.g. 'B4:D9' or 'B4:D9,H2:O11' or 'B4'
142
     *
143
     * @return array<array<string>> Array containing one or more arrays containing one or two coordinate strings
144
     *                                e.g. ['B4','D9'] or [['B4','D9'], ['H2','O11']]
145
     *                                        or ['B4']
146
     */
147 1854
    public static function splitRange(string $range): array
148
    {
149
        // Ensure $pRange is a valid range
150 1854
        if (empty($range)) {
151
            $range = self::DEFAULT_RANGE;
152
        }
153
154 1854
        $exploded = explode(',', $range);
155 1854
        $outArray = [];
156 1854
        foreach ($exploded as $value) {
157 1854
            $outArray[] = explode(':', $value);
158
        }
159
160 1854
        return $outArray;
161
    }
162
163
    /**
164
     * Build range from coordinate strings.
165
     *
166
     * @param mixed[] $range Array containing one or more arrays containing one or two coordinate strings
167
     *
168
     * @return string String representation of $pRange
169
     */
170 41
    public static function buildRange(array $range): string
171
    {
172
        // Verify range
173 41
        if (empty($range)) {
174 1
            throw new Exception('Range does not contain any information');
175
        }
176
177
        // Build range
178 40
        $counter = count($range);
179 40
        for ($i = 0; $i < $counter; ++$i) {
180 40
            if (!is_array($range[$i])) {
181
                throw new Exception('Each array entry must be an array');
182
            }
183 40
            $range[$i] = implode(':', $range[$i]);
184
        }
185
186
        return implode(',', $range);
187
    }
188
189
    /**
190
     * Calculate range boundaries.
191
     *
192
     * @param string $range Cell range, Single Cell, Row/Column Range (e.g. A1:A1, B2, B:C, 2:3)
193
     *
194 869
     * @return array{array{int, int}, array{int, int}} Range coordinates [Start Cell, End Cell]
195
     *                    where Start Cell and End Cell are arrays (Column Number, Row Number)
196
     */
197 869
    public static function rangeBoundaries(string $range): array
198
    {
199
        // Ensure $pRange is a valid range
200
        if (empty($range)) {
201
            $range = self::DEFAULT_RANGE;
202 869
        }
203
204
        // Uppercase coordinate
205 869
        $range = strtoupper($range);
206 49
207
        // Extract range
208 862
        if (!str_contains($range, ':')) {
209
            $rangeA = $rangeB = $range;
210
        } else {
211 869
            [$rangeA, $rangeB] = explode(':', $range);
212 4
        }
213 4
214
        if (is_numeric($rangeA) && is_numeric($rangeB)) {
215
            $rangeA = 'A' . $rangeA;
216 869
            $rangeB = AddressRange::MAX_COLUMN . $rangeB;
217 4
        }
218 4
219
        if (ctype_alpha($rangeA) && ctype_alpha($rangeB)) {
220
            $rangeA = $rangeA . '1';
221
            $rangeB = $rangeB . AddressRange::MAX_ROW;
222 869
        }
223 869
224
        // Calculate range outer borders
225
        $rangeStart = self::coordinateFromString($rangeA);
226 869
        $rangeEnd = self::coordinateFromString($rangeB);
227 869
228 869
        // Translate column into index
229 869
        $rangeStart[0] = self::columnIndexFromString($rangeStart[0]);
230
        $rangeEnd[0] = self::columnIndexFromString($rangeEnd[0]);
231 869
        $rangeStart[1] = (int) $rangeStart[1];
232
        $rangeEnd[1] = (int) $rangeEnd[1];
233
234
        return [$rangeStart, $rangeEnd];
235
    }
236
237
    /**
238
     * Calculate range dimension.
239
     *
240
     * @param string $range Cell range, Single Cell, Row/Column Range (e.g. A1:A1, B2, B:C, 2:3)
241 238
     *
242
     * @return array{int, int} Range dimension (width, height)
243
     */
244 238
    public static function rangeDimension(string $range): array
245
    {
246 238
        // Calculate range outer borders
247
        [$rangeStart, $rangeEnd] = self::rangeBoundaries($range);
248
249
        return [($rangeEnd[0] - $rangeStart[0] + 1), ($rangeEnd[1] - $rangeStart[1] + 1)];
250
    }
251
252
    /**
253
     * Calculate range boundaries.
254
     *
255
     * @param string $range Cell range, Single Cell, Row/Column Range (e.g. A1:A1, B2, B:C, 2:3)
256
     *
257 105
     * @return array{array{string, int}, array{string, int}} Range coordinates [Start Cell, End Cell]
258
     *                    where Start Cell and End Cell are arrays [Column ID, Row Number]
259 105
     */
260
    public static function getRangeBoundaries(string $range): array
261 105
    {
262 105
        [$rangeA, $rangeB] = self::rangeBoundaries($range);
263 105
264 105
        return [
265
            [self::stringFromColumnIndex($rangeA[0]), $rangeA[1]],
266
            [self::stringFromColumnIndex($rangeB[0]), $rangeB[1]],
267
        ];
268
    }
269
270
    /**
271
     * Check if cell or range reference is valid and return an array with type of reference (cell or range), worksheet (if it was given)
272
     * and the coordinate or the first coordinate and second coordinate if it is a range.
273
     *
274
     * @param string $reference Coordinate or Range (e.g. A1:A1, B2, B:C, 2:3)
275 290
     *
276
     * @return array{type: string, firstCoordinate?: string, secondCoordinate?: string, coordinate?: string, worksheet?: string, localReference?: string} reference data
277 290
     */
278 290
    private static function validateReferenceAndGetData($reference): array
279 2
    {
280
        $data = [];
281
        if (1 !== preg_match(self::FULL_REFERENCE_REGEX, $reference, $matches)) {
282 289
            return ['type' => 'invalid'];
283 287
        }
284 287
285 287
        if (isset($matches['secondCoordinate'])) {
286
            $data['type'] = 'range';
287 288
            $data['firstCoordinate'] = str_replace('$', '', $matches['firstCoordinate']);
288 288
            $data['secondCoordinate'] = str_replace('$', '', $matches['secondCoordinate']);
289
        } else {
290
            $data['type'] = 'coordinate';
291 289
            $data['coordinate'] = str_replace('$', '', $matches['firstCoordinate']);
292 289
        }
293 19
294 6
        $worksheet = $matches['worksheet'];
295
        if ($worksheet !== '') {
296 19
            if (substr($worksheet, 0, 1) === "'" && substr($worksheet, -1, 1) === "'") {
297
                $worksheet = substr($worksheet, 1, -1);
298 289
            }
299
            $data['worksheet'] = strtolower($worksheet);
300 289
        }
301
        $data['localReference'] = str_replace('$', '', $matches['localReference']);
302
303
        return $data;
304
    }
305
306
    /**
307
     * Check if coordinate is inside a range.
308
     *
309
     * @param string $range Cell range, Single Cell, Row/Column Range (e.g. A1:A1, B2, B:C, 2:3)
310
     * @param string $coordinate Cell coordinate (e.g. A1)
311 290
     *
312
     * @return bool true if coordinate is inside range
313 290
     */
314 290
    public static function coordinateIsInsideRange(string $range, string $coordinate): bool
315 290
    {
316 1
        $range = Validations::convertWholeRowColumn($range);
317
        $rangeData = self::validateReferenceAndGetData($range);
318
        if ($rangeData['type'] === 'invalid') {
319 289
            throw new Exception('First argument needs to be a range');
320 289
        }
321 1
322
        $coordinateData = self::validateReferenceAndGetData($coordinate);
323
        if ($coordinateData['type'] === 'invalid') {
324 288
            throw new Exception('Second argument needs to be a single coordinate');
325 4
        }
326
327 284
        if (isset($coordinateData['worksheet']) && !isset($rangeData['worksheet'])) {
328 4
            return false;
329
        }
330
        if (!isset($coordinateData['worksheet']) && isset($rangeData['worksheet'])) {
331 280
            return false;
332 11
        }
333
334
        if (isset($coordinateData['worksheet'], $rangeData['worksheet'])) {
335
            if ($coordinateData['worksheet'] !== $rangeData['worksheet']) {
336
                return false;
337 280
            }
338
        }
339
340 280
        if (!isset($rangeData['localReference'])) {
341 280
            return false;
342
        }
343
        $boundaries = self::rangeBoundaries($rangeData['localReference']);
344 280
        if (!isset($coordinateData['localReference'])) {
345
            return false;
346 280
        }
347 280
        $coordinates = self::indexesFromString($coordinateData['localReference']);
348 92
349
        $columnIsInside = $boundaries[0][0] <= $coordinates[0] && $coordinates[0] <= $boundaries[1][0];
350 264
        if (!$columnIsInside) {
351 264
            return false;
352 117
        }
353
        $rowIsInside = $boundaries[0][1] <= $coordinates[1] && $coordinates[1] <= $boundaries[1][1];
354
        if (!$rowIsInside) {
355 256
            return false;
356
        }
357
358
        return true;
359
    }
360
361
    /**
362
     * Column index from string.
363
     *
364
     * @param ?string $columnAddress eg 'A'
365 10764
     *
366
     * @return int Column index (A = 1)
367
     */
368
    public static function columnIndexFromString(?string $columnAddress): int
369
    {
370
        //    Using a lookup cache adds a slight memory overhead, but boosts speed
371 10764
        //    caching using a static within the method is faster than a class static,
372 10764
        //        though it's additional memory overhead
373
        /** @var int[] */
374 10764
        static $indexCache = [];
375 10754
        $columnAddress = $columnAddress ?? '';
376
377
        if (isset($indexCache[$columnAddress])) {
378
            return $indexCache[$columnAddress];
379
        }
380
        //    It's surprising how costly the strtoupper() and ord() calls actually are, so we use a lookup array
381 313
        //        rather than use ord() and make it case insensitive to get rid of the strtoupper() as well.
382 313
        //        Because it's a static, there's no significant memory overhead either.
383 313
        /** @var array<string, int> */
384 313
        static $columnLookup = [
385 313
            'A' => 1, 'B' => 2, 'C' => 3, 'D' => 4, 'E' => 5, 'F' => 6, 'G' => 7, 'H' => 8, 'I' => 9, 'J' => 10,
386 313
            'K' => 11, 'L' => 12, 'M' => 13, 'N' => 14, 'O' => 15, 'P' => 16, 'Q' => 17, 'R' => 18, 'S' => 19,
387 313
            'T' => 20, 'U' => 21, 'V' => 22, 'W' => 23, 'X' => 24, 'Y' => 25, 'Z' => 26,
388 313
            'a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5, 'f' => 6, 'g' => 7, 'h' => 8, 'i' => 9, 'j' => 10,
389
            'k' => 11, 'l' => 12, 'm' => 13, 'n' => 14, 'o' => 15, 'p' => 16, 'q' => 17, 'r' => 18, 's' => 19,
390
            't' => 20, 'u' => 21, 'v' => 22, 'w' => 23, 'x' => 24, 'y' => 25, 'z' => 26,
391
        ];
392 313
393 312
        //    We also use the language construct isset() rather than the more costly strlen() function to match the
394 295
        //       length of $columnAddress for improved performance
395
        if (isset($columnAddress[0])) {
396 295
            if (!isset($columnAddress[1])) {
397 24
                $indexCache[$columnAddress] = $columnLookup[$columnAddress];
398 15
399 15
                return $indexCache[$columnAddress];
400
            } elseif (!isset($columnAddress[2])) {
401 15
                $indexCache[$columnAddress] = $columnLookup[$columnAddress[0]] * 26
402 12
                    + $columnLookup[$columnAddress[1]];
403 10
404 10
                return $indexCache[$columnAddress];
405 10
            } elseif (!isset($columnAddress[3])) {
406
                $indexCache[$columnAddress] = $columnLookup[$columnAddress[0]] * 676
407 10
                    + $columnLookup[$columnAddress[1]] * 26
408
                    + $columnLookup[$columnAddress[2]];
409
410
                return $indexCache[$columnAddress];
411 3
            }
412 3
        }
413 3
414
        throw new Exception(
415
            'Column string index can not be ' . ((isset($columnAddress[0])) ? 'longer than 3 characters' : 'empty')
416
        );
417
    }
418
419
    private const LOOKUP_CACHE = ' ABCDEFGHIJKLMNOPQRSTUVWXYZ';
420
421
    /**
422
     * String from column index.
423 6441
     *
424
     * @param int|numeric-string $columnIndex Column index (A = 1)
425
     */
426 6441
    public static function stringFromColumnIndex(int|string $columnIndex): string
427
    {
428 6441
        /** @var string[] */
429 248
        static $indexCache = [];
430 248
431
        if (!isset($indexCache[$columnIndex])) {
432 248
            $indexValue = $columnIndex;
433 248
            $base26 = '';
434 248
            do {
435 248
                $characterValue = ($indexValue % 26) ?: 26;
436 248
                $indexValue = ($indexValue - $characterValue) / 26;
437
                $base26 = self::LOOKUP_CACHE[$characterValue] . $base26;
438
            } while ($indexValue > 0);
439 6441
            $indexCache[$columnIndex] = $base26;
440
        }
441
442
        return $indexCache[$columnIndex];
443
    }
444
445
    /**
446
     * Extract all cell references in range, which may be comprised of multiple cell ranges.
447
     *
448
     * @param string $cellRange Range: e.g. 'A1' or 'A1:C10' or 'A1:E10,A20:E25' or 'A1:E5 C3:G7' or 'A1:C1,A3:C3 B1:C3'
449 6907
     *
450
     * @return string[] Array containing single cell references
451 6907
     */
452
    public static function extractAllCellReferencesInRange(string $cellRange): array
453
    {
454
        if (substr_count($cellRange, '!') > 1) {
455 6907
            throw new Exception('3-D Range References are not supported');
456 6907
        }
457 6907
458 4
        [$worksheet, $cellRange] = Worksheet::extractSheetTitle($cellRange, true);
459 4
        $quoted = '';
460 2
        if ($worksheet) {
461
            $quoted = Worksheet::nameRequiresQuotes($worksheet) ? "'" : '';
462 4
            if (str_starts_with($worksheet, "'") && str_ends_with($worksheet, "'")) {
463
                $worksheet = substr($worksheet, 1, -1);
464 6907
            }
465
            $worksheet = str_replace("'", "''", $worksheet);
466 6907
        }
467 6907
        [$ranges, $operators] = self::getCellBlocksFromRangeString($cellRange ?? 'A1');
468
469 6907
        $cells = [];
470
        foreach ($ranges as $range) {
471
            /** @var string $range */
472
            $cells[] = self::getReferencesForCellBlock($range);
473 6903
        }
474
475 6903
        /** @var mixed[] */
476
        $cells = self::processRangeSetOperators($operators, $cells);
477
478
        if (empty($cells)) {
479
            return [];
480 6903
        }
481
482
        /** @var string[] */
483 6903
        $cellList = array_merge(...$cells); //* @phpstan-ignore-line
484 6903
        // Unsure how to satisfy phpstan in line above
485 6903
486 6903
        $retVal = array_map(
487
            fn (string $cellAddress) => ($worksheet !== '') ? "{$quoted}{$worksheet}{$quoted}!{$cellAddress}" : $cellAddress,
488 6903
            self::sortCellReferenceArray($cellList)
489
        );
490
491
        return $retVal;
492
    }
493
494
    /**
495
     * @param mixed[] $operators
496
     * @param mixed[][] $cells
497 6903
     *
498
     * @return mixed[]
499 6903
     */
500 6903
    private static function processRangeSetOperators(array $operators, array $cells): array
501 7
    {
502 7
        $operatorCount = count($operators);
503 4
        for ($offset = 0; $offset < $operatorCount; ++$offset) {
504
            $operator = $operators[$offset];
505
            if ($operator !== ' ') {
506 3
                continue;
507 3
            }
508 3
509 3
            $cells[$offset] = array_intersect($cells[$offset], $cells[$offset + 1]);
510 3
            unset($operators[$offset], $cells[$offset + 1]);
511 3
            $operators = array_values($operators);
512
            $cells = array_values($cells);
513
            --$offset;
514 6903
            --$operatorCount;
515
        }
516
517
        return $cells;
518
    }
519
520
    /**
521
     * @param string[] $cellList
522 6903
     *
523
     * @return string[]
524
     */
525 6903
    private static function sortCellReferenceArray(array $cellList): array
526 6903
    {
527 6902
        //    Sort the result by column and row
528 6902
        $sortKeys = [];
529 6902
        foreach ($cellList as $coordinate) {
530
            $column = '';
531 6902
            $row = 0;
532 6902
            sscanf($coordinate, '%[A-Z]%d', $column, $row);
533
            /** @var int $row */
534 6903
            $key = (--$row * 16384) + self::columnIndexFromString((string) $column);
535
            $sortKeys[$key] = $coordinate;
536 6903
        }
537
        ksort($sortKeys);
538
539
        return array_values($sortKeys);
540
    }
541
542
    /**
543
     * Get all cell references applying union and intersection.
544
     *
545
     * @param string $cellBlock A cell range e.g. A1:B5,D1:E5 B2:C4
546
     *
547
     * @return string A string without intersection operator.
548 296
     *   If there was no intersection to begin with, return original argument.
549
     *   Otherwise, return cells and/or cell ranges in that range separated by comma.
550 296
     */
551 296
    public static function resolveUnionAndIntersection(string $cellBlock, string $implodeCharacter = ','): string
552 296
    {
553 296
        $cellBlock = preg_replace('/  +/', ' ', trim($cellBlock)) ?? $cellBlock;
554 296
        $cellBlock = preg_replace('/ ,/', ',', $cellBlock) ?? $cellBlock;
555 296
        $cellBlock = preg_replace('/, /', ',', $cellBlock) ?? $cellBlock;
556 296
        $array1 = [];
557 296
        $blocks = explode(',', $cellBlock);
558 293
        foreach ($blocks as $block) {
559
            $block0 = explode(' ', $block);
560 4
            if (count($block0) === 1) {
561 4
                $array1 = array_merge($array1, $block0);
562 4
            } else {
563 4
                $blockIdx = -1;
564 4
                $array2 = [];
565 4
                foreach ($block0 as $block00) {
566
                    ++$blockIdx;
567 4
                    if ($blockIdx === 0) {
568
                        $array2 = self::getReferencesForCellBlock($block00);
569
                    } else {
570 4
                        $array2 = array_intersect($array2, self::getReferencesForCellBlock($block00));
571
                    }
572
                }
573
                $array1 = array_merge($array1, $array2);
574 296
            }
575
        }
576
577
        return implode($implodeCharacter, $array1);
578
    }
579
580
    /**
581
     * Get all cell references for an individual cell block.
582
     *
583
     * @param string $cellBlock A cell range e.g. A4:B5
584 6911
     *
585
     * @return string[] All individual cells in that range
586 6911
     */
587
    private static function getReferencesForCellBlock(string $cellBlock): array
588
    {
589 6911
        $returnValue = [];
590 6848
591
        // Single cell?
592
        if (!self::coordinateIsRange($cellBlock)) {
593
            return (array) $cellBlock;
594 1236
        }
595 1236
596
        // Range...
597 1236
        $ranges = self::splitRange($cellBlock);
598
        foreach ($ranges as $range) {
599
            // Single cell?
600
            if (!isset($range[1])) {
601
                $returnValue[] = $range[0];
602
603
                continue;
604 1236
            }
605 1236
606 1236
            // Range...
607 1236
            [$rangeStart, $rangeEnd] = $range;
608 1236
            [$startColumn, $startRow] = self::coordinateFromString($rangeStart);
609 1236
            [$endColumn, $endRow] = self::coordinateFromString($rangeEnd);
610
            $startColumnIndex = self::columnIndexFromString($startColumn);
611
            $endColumnIndex = self::columnIndexFromString($endColumn);
612 1236
            ++$endColumnIndex;
613 1236
614
            // Current data
615 1236
            $currentColumnIndex = $startColumnIndex;
616
            $currentRow = $startRow;
617
618 1232
            self::validateRange($cellBlock, $startColumnIndex, $endColumnIndex, (int) $currentRow, (int) $endRow);
619
620
            // Loop cells
621 1232
            while ($currentColumnIndex < $endColumnIndex) {
622 1232
                /** @var int $currentRow */
623 1232
                /** @var int $endRow */
624
                while ($currentRow <= $endRow) {
625 1232
                    $returnValue[] = self::stringFromColumnIndex($currentColumnIndex) . $currentRow;
626 1232
                    ++$currentRow;
627
                }
628
                ++$currentColumnIndex;
629
                $currentRow = $startRow;
630 1232
            }
631
        }
632
633
        return $returnValue;
634
    }
635
636
    /**
637
     * Convert an associative array of single cell coordinates to values to an associative array
638
     * of cell ranges to values.  Only adjacent cell coordinates with the same
639
     * value will be merged.  If the value is an object, it must implement the method getHashCode().
640
     *
641
     * For example, this function converts:
642
     *
643
     *    [ 'A1' => 'x', 'A2' => 'x', 'A3' => 'x', 'A4' => 'y' ]
644
     *
645
     * to:
646
     *
647
     *    [ 'A1:A3' => 'x', 'A4' => 'y' ]
648
     *
649
     * @param array<string, mixed> $coordinateCollection associative array mapping coordinates to values
650 5
     *
651
     * @return array<string, mixed> associative array mapping coordinate ranges to valuea
652 5
     */
653 5
    public static function mergeRangesInCollection(array $coordinateCollection): array
654
    {
655 5
        $hashedValues = [];
656 5
        $mergedCoordCollection = [];
657 1
658
        foreach ($coordinateCollection as $coord => $value) {
659 1
            if (self::coordinateIsRange($coord)) {
660
                $mergedCoordCollection[$coord] = $value;
661
662 5
                continue;
663 5
            }
664 5
665
            [$column, $row] = self::coordinateFromString($coord);
666 5
            $row = (int) (ltrim($row, '$'));
667 5
            $hashCode = $column . '-' . StringHelper::convertToString((is_object($value) && method_exists($value, 'getHashCode')) ? $value->getHashCode() : $value);
668 5
669 5
            if (!isset($hashedValues[$hashCode])) {
670 5
                $hashedValues[$hashCode] = (object) [
671 5
                    'value' => $value,
672
                    'col' => $column,
673 3
                    'rows' => [$row],
674
                ];
675
            } else {
676
                $hashedValues[$hashCode]->rows[] = $row;
677 5
            }
678
        }
679 5
680 5
        ksort($hashedValues);
681 5
682 5
        foreach ($hashedValues as $hashedValue) {
683 5
            sort($hashedValue->rows);
684
            $rowStart = null;
685 5
            $rowEnd = null;
686 5
            $ranges = [];
687 5
688 5
            foreach ($hashedValue->rows as $row) {
689 3
                if ($rowStart === null) {
690 3
                    $rowStart = $row;
691
                    $rowEnd = $row;
692 1
                } elseif ($rowEnd === $row - 1) {
693
                    $rowEnd = $row;
694
                } else {
695 1
                    if ($rowStart == $rowEnd) {
696
                        $ranges[] = $hashedValue->col . $rowStart;
697
                    } else {
698 1
                        $ranges[] = $hashedValue->col . $rowStart . ':' . $hashedValue->col . $rowEnd;
699 1
                    }
700
701
                    $rowStart = $row;
702
                    $rowEnd = $row;
703 5
                }
704 5
            }
705 4
706
            if ($rowStart !== null) { // @phpstan-ignore-line
707 2
                if ($rowStart == $rowEnd) {
708
                    $ranges[] = $hashedValue->col . $rowStart;
709
                } else {
710
                    $ranges[] = $hashedValue->col . $rowStart . ':' . $hashedValue->col . $rowEnd;
711 5
                }
712 5
            }
713
714
            foreach ($ranges as $range) {
715
                $mergedCoordCollection[$range] = $hashedValue->value;
716 5
            }
717
        }
718
719
        return $mergedCoordCollection;
720
    }
721
722
    /**
723
     * Get the individual cell blocks from a range string, removing any $ characters.
724
     *      then splitting by operators and returning an array with ranges and operators.
725 6907
     *
726
     * @return mixed[][]
727 6907
     */
728
    private static function getCellBlocksFromRangeString(string $rangeString): array
729
    {
730 6907
        $rangeString = str_replace('$', '', strtoupper($rangeString));
731 6907
732 6907
        // split range sets on intersection (space) or union (,) operators
733 6907
        $tokens = preg_split('/([ ,])/', $rangeString, -1, PREG_SPLIT_DELIM_CAPTURE) ?: [];
734
        $split = array_chunk($tokens, 2);
735 6907
        $ranges = array_column($split, 0);
736
        $operators = array_column($split, 1);
737
738
        return [$ranges, $operators];
739
    }
740
741
    /**
742
     * Check that the given range is valid, i.e. that the start column and row are not greater than the end column and
743
     * row.
744 1236
     *
745
     * @param string $cellBlock The original range, for displaying a meaningful error message
746 1236
     */
747 4
    private static function validateRange(string $cellBlock, int $startColumnIndex, int $endColumnIndex, int $currentRow, int $endRow): void
748
    {
749
        if ($startColumnIndex >= $endColumnIndex || $currentRow > $endRow) {
750
            throw new Exception('Invalid range: "' . $cellBlock . '"');
751
        }
752
    }
753
}
754