Passed
Pull Request — master (#4240)
by Owen
27:46 queued 17:34
created

Coordinate::mergeRangesInCollection()   D

Complexity

Conditions 14
Paths 310

Size

Total Lines 67
Code Lines 43

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 40
CRAP Score 14.0028

Importance

Changes 0
Metric Value
eloc 43
dl 0
loc 67
ccs 40
cts 41
cp 0.9756
rs 4.0583
c 0
b 0
f 0
cc 14
nc 310
nop 1
crap 14.0028

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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