chengkun
2025-09-12 b21e53f16f228d3192eb54178f081395878b2406
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
<?php
 
namespace PhpOffice\PhpSpreadsheet\Calculation\LookupRef;
 
use Exception;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PhpOffice\PhpSpreadsheet\Calculation\Functions;
use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError;
use PhpOffice\PhpSpreadsheet\Cell\AddressRange;
use PhpOffice\PhpSpreadsheet\Cell\Cell;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
 
class Indirect
{
    /**
     * Determine whether cell address is in A1 (true) or R1C1 (false) format.
     *
     * @param mixed $a1fmt Expect bool Helpers::CELLADDRESS_USE_A1 or CELLADDRESS_USE_R1C1,
     *                      but can be provided as numeric which is cast to bool
     */
    private static function a1Format(mixed $a1fmt): bool
    {
        $a1fmt = Functions::flattenSingleValue($a1fmt);
        if ($a1fmt === null) {
            return Helpers::CELLADDRESS_USE_A1;
        }
        if (is_string($a1fmt)) {
            throw new Exception(ExcelError::VALUE());
        }
 
        return (bool) $a1fmt;
    }
 
    /**
     * Convert cellAddress to string, verify not null string.
     */
    private static function validateAddress(array|string|null $cellAddress): string
    {
        $cellAddress = Functions::flattenSingleValue($cellAddress);
        if (!is_string($cellAddress) || !$cellAddress) {
            throw new Exception(ExcelError::REF());
        }
 
        return $cellAddress;
    }
 
    /**
     * INDIRECT.
     *
     * Returns the reference specified by a text string.
     * References are immediately evaluated to display their contents.
     *
     * Excel Function:
     *        =INDIRECT(cellAddress, bool) where the bool argument is optional
     *
     * @param array|string $cellAddress $cellAddress The cell address of the current cell (containing this formula)
     * @param mixed $a1fmt Expect bool Helpers::CELLADDRESS_USE_A1 or CELLADDRESS_USE_R1C1,
     *                      but can be provided as numeric which is cast to bool
     * @param Cell $cell The current cell (containing this formula)
     *
     * @return array|string An array containing a cell or range of cells, or a string on error
     */
    public static function INDIRECT($cellAddress, mixed $a1fmt, Cell $cell): string|array
    {
        [$baseCol, $baseRow] = Coordinate::indexesFromString($cell->getCoordinate());
 
        try {
            $a1 = self::a1Format($a1fmt);
            $cellAddress = self::validateAddress($cellAddress);
        } catch (Exception $e) {
            return $e->getMessage();
        }
 
        [$cellAddress, $worksheet, $sheetName] = Helpers::extractWorksheet($cellAddress, $cell);
 
        if (preg_match('/^' . Calculation::CALCULATION_REGEXP_COLUMNRANGE_RELATIVE . '$/miu', $cellAddress, $matches)) {
            $cellAddress = self::handleRowColumnRanges($worksheet, ...explode(':', $cellAddress));
        } elseif (preg_match('/^' . Calculation::CALCULATION_REGEXP_ROWRANGE_RELATIVE . '$/miu', $cellAddress, $matches)) {
            $cellAddress = self::handleRowColumnRanges($worksheet, ...explode(':', $cellAddress));
        }
 
        try {
            [$cellAddress1, $cellAddress2, $cellAddress] = Helpers::extractCellAddresses($cellAddress, $a1, $cell->getWorkSheet(), $sheetName, $baseRow, $baseCol);
        } catch (Exception) {
            return ExcelError::REF();
        }
 
        if (
            (!preg_match('/^' . Calculation::CALCULATION_REGEXP_CELLREF . '$/miu', $cellAddress1, $matches))
            || (($cellAddress2 !== null) && (!preg_match('/^' . Calculation::CALCULATION_REGEXP_CELLREF . '$/miu', $cellAddress2, $matches)))
        ) {
            return ExcelError::REF();
        }
 
        return self::extractRequiredCells($worksheet, $cellAddress);
    }
 
    /**
     * Extract range values.
     *
     * @return array Array of values in range if range contains more than one element.
     *                  Otherwise, a single value is returned.
     */
    private static function extractRequiredCells(?Worksheet $worksheet, string $cellAddress): array
    {
        return Calculation::getInstance($worksheet !== null ? $worksheet->getParent() : null)
            ->extractCellRange($cellAddress, $worksheet, false);
    }
 
    private static function handleRowColumnRanges(?Worksheet $worksheet, string $start, string $end): string
    {
        // Being lazy, we're only checking a single row/column to get the max
        if (ctype_digit($start) && $start <= 1048576) {
            // Max 16,384 columns for Excel2007
            $endColRef = ($worksheet !== null) ? $worksheet->getHighestDataColumn((int) $start) : AddressRange::MAX_COLUMN;
 
            return "A{$start}:{$endColRef}{$end}";
        } elseif (ctype_alpha($start) && strlen($start) <= 3) {
            // Max 1,048,576 rows for Excel2007
            $endRowRef = ($worksheet !== null) ? $worksheet->getHighestDataRow($start) : AddressRange::MAX_ROW;
 
            return "{$start}1:{$end}{$endRowRef}";
        }
 
        return "{$start}:{$end}";
    }
}