Passed
Push — master ( efa0c0...317477 )
by
unknown
19:26 queued 11:40
created

Coordinate   F

Complexity

Total Complexity 109

Size/Duplication

Total Lines 758
Duplicated Lines 0 %

Test Coverage

Coverage 96.55%

Importance

Changes 0
Metric Value
wmc 109
eloc 303
c 0
b 0
f 0
dl 0
loc 758
rs 2
ccs 308
cts 319
cp 0.9655

23 Methods

Rating   Name   Duplication   Size   Complexity  
A indexesFromString() 0 9 1
A absoluteCoordinate() 0 18 3
A absoluteReference() 0 22 5
A coordinateIsRange() 0 3 2
A coordinateFromString() 0 11 4
A sortCellReferenceArray() 0 15 2
A getCellBlocksFromRangeString() 0 11 2
B extractAllCellReferencesInRange() 0 40 9
C mergeRangesInCollection() 0 67 14
B getReferencesForCellBlock() 0 47 6
A getRangeBoundaries() 0 7 1
A rangeDimension() 0 6 1
A allRanges() 0 8 2
A buildRange() 0 17 4
A validateRange() 0 4 3
A validateReferenceAndGetData() 0 26 6
A stringFromColumnIndex() 0 17 4
C coordinateIsInsideRange() 0 45 15
B columnIndexFromString() 0 48 7
A processRangeSetOperators() 0 18 3
B rangeBoundaries() 0 38 7
A splitRange() 0 14 3
A resolveUnionAndIntersection() 0 27 5

How to fix   Complexity   

Complex Class

Complex classes like Coordinate often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Coordinate, and based on these observations, apply Extract Interface, too.

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