Passed
Push — master ( 3c7afe...11f0b5 )
by
unknown
14:12 queued 14s
created

Calculation   F

Complexity

Total Complexity 659

Size/Duplication

Total Lines 2777
Duplicated Lines 0 %

Test Coverage

Coverage 87.83%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 659
eloc 1470
dl 0
loc 2777
ccs 1212
cts 1380
cp 0.8783
rs 0.8
c 2
b 0
f 0

61 Methods

Rating   Name   Duplication   Size   Complexity  
A executeBinaryComparisonOperation() 0 15 3
F processTokenStack() 0 650 192
B convertMatrixReferences() 0 50 9
C extractCellRange() 0 53 14
A getDebugLog() 0 3 1
A disableCalculationCache() 0 3 1
A keyInExcelConstants() 0 3 1
A addDefaultArgumentValues() 0 23 6
A boolToString() 0 9 4
A getSpreadsheet() 0 3 1
A getArrayReturnType() 0 3 1
F internalParseFormula() 0 479 145
A disableBranchPruning() 0 3 1
A addCellReference() 0 18 4
A getBranchPruningEnabled() 0 3 1
A getMatrixDimensions() 0 16 3
A calculate() 0 6 2
A calculateFormula() 0 30 6
A getValueFromCache() 0 15 3
A parseFormula() 0 20 4
A setArrayReturnType() 0 13 4
B checkMatrixOperands() 0 40 9
A flushInstance() 0 4 1
A dataTestReference() 0 20 5
A getInstance() 0 14 4
A getInstanceArrayReturnType() 0 3 1
D _calculateFormulaValue() 0 67 20
C resizeMatricesExtend() 0 32 15
A swapOperands() 0 13 4
A __clone() 0 3 1
A __construct() 0 6 1
A clearCalculationCacheForWorksheet() 0 4 2
F calculateCellValue() 0 76 24
B executeArrayComparison() 0 42 11
A raiseFormulaError() 0 10 2
A enableBranchPruning() 0 3 1
C extractNamedRange() 0 52 16
A getExcelConstants() 0 3 1
A getSuppressFormulaErrors() 0 3 1
B validateBinaryOperand() 0 36 11
D executeNumericBinaryOperation() 0 131 34
A clearCalculationCache() 0 3 1
A setSuppressFormulaErrors() 0 5 1
A setInstanceArrayReturnType() 0 13 4
A getCalculationCacheEnabled() 0 3 1
C resizeMatricesShrink() 0 27 15
A getArgumentDefaultValue() 0 21 4
A isNumericOrBool() 0 3 2
A wrapResult() 0 17 6
A saveValueToCache() 0 4 2
A setCalculationCacheEnabled() 0 6 1
A enableCalculationCache() 0 3 1
B showTypeDetails() 0 32 10
A setBranchPruningEnabled() 0 6 1
B evaluateDefinedName() 0 53 10
A renameCalculationCacheForWorksheet() 0 5 2
B showValue() 0 31 11
A getImplementedFunctionNames() 0 11 3
B unwrapResult() 0 12 8
A makeError() 0 3 3
A isImplemented() 0 7 3

How to fix   Complexity   

Complex Class

Complex classes like Calculation 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 Calculation, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace PhpOffice\PhpSpreadsheet\Calculation;
4
5
use PhpOffice\PhpSpreadsheet\Calculation\Engine\BranchPruner;
6
use PhpOffice\PhpSpreadsheet\Calculation\Engine\CyclicReferenceStack;
7
use PhpOffice\PhpSpreadsheet\Calculation\Engine\Logger;
8
use PhpOffice\PhpSpreadsheet\Calculation\Engine\Operands;
9
use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError;
10
use PhpOffice\PhpSpreadsheet\Calculation\Token\Stack;
11
use PhpOffice\PhpSpreadsheet\Cell\AddressRange;
12
use PhpOffice\PhpSpreadsheet\Cell\Cell;
13
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
14
use PhpOffice\PhpSpreadsheet\Cell\DataType;
15
use PhpOffice\PhpSpreadsheet\DefinedName;
16
use PhpOffice\PhpSpreadsheet\NamedRange;
17
use PhpOffice\PhpSpreadsheet\ReferenceHelper;
18
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
19
use PhpOffice\PhpSpreadsheet\Spreadsheet;
20
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
21
use ReflectionClassConstant;
22
use ReflectionMethod;
23
use ReflectionParameter;
24
use Throwable;
25
26
class Calculation extends CalculationLocale
27
{
28
    /** Constants                */
29
    /** Regular Expressions        */
30
    //    Numeric operand
31
    const CALCULATION_REGEXP_NUMBER = '[-+]?\d*\.?\d+(e[-+]?\d+)?';
32
    //    String operand
33
    const CALCULATION_REGEXP_STRING = '"(?:[^"]|"")*"';
34
    //    Opening bracket
35
    const CALCULATION_REGEXP_OPENBRACE = '\(';
36
    //    Function (allow for the old @ symbol that could be used to prefix a function, but we'll ignore it)
37
    const CALCULATION_REGEXP_FUNCTION = '@?(?:_xlfn\.)?(?:_xlws\.)?([\p{L}][\p{L}\p{N}\.]*)[\s]*\(';
38
    //    Cell reference (cell or range of cells, with or without a sheet reference)
39
    const CALCULATION_REGEXP_CELLREF = '((([^\s,!&%^\/\*\+<>=:`-]*)|(\'(?:[^\']|\'[^!])+?\')|(\"(?:[^\"]|\"[^!])+?\"))!)?\$?\b([a-z]{1,3})\$?(\d{1,7})(?![\w.])';
40
    // Used only to detect spill operator #
41
    const CALCULATION_REGEXP_CELLREF_SPILL = '/' . self::CALCULATION_REGEXP_CELLREF . '#/i';
42
    //    Cell reference (with or without a sheet reference) ensuring absolute/relative
43
    const CALCULATION_REGEXP_CELLREF_RELATIVE = '((([^\s\(,!&%^\/\*\+<>=:`-]*)|(\'(?:[^\']|\'[^!])+?\')|(\"(?:[^\"]|\"[^!])+?\"))!)?(\$?\b[a-z]{1,3})(\$?\d{1,7})(?![\w.])';
44
    const CALCULATION_REGEXP_COLUMN_RANGE = '(((([^\s\(,!&%^\/\*\+<>=:`-]*)|(\'(?:[^\']|\'[^!])+?\')|(\".(?:[^\"]|\"[^!])?\"))!)?(\$?[a-z]{1,3})):(?![.*])';
45
    const CALCULATION_REGEXP_ROW_RANGE = '(((([^\s\(,!&%^\/\*\+<>=:`-]*)|(\'(?:[^\']|\'[^!])+?\')|(\"(?:[^\"]|\"[^!])+?\"))!)?(\$?[1-9][0-9]{0,6})):(?![.*])';
46
    //    Cell reference (with or without a sheet reference) ensuring absolute/relative
47
    //    Cell ranges ensuring absolute/relative
48
    const CALCULATION_REGEXP_COLUMNRANGE_RELATIVE = '(\$?[a-z]{1,3}):(\$?[a-z]{1,3})';
49
    const CALCULATION_REGEXP_ROWRANGE_RELATIVE = '(\$?\d{1,7}):(\$?\d{1,7})';
50
    //    Defined Names: Named Range of cells, or Named Formulae
51
    const CALCULATION_REGEXP_DEFINEDNAME = '((([^\s,!&%^\/\*\+<>=-]*)|(\'(?:[^\']|\'[^!])+?\')|(\"(?:[^\"]|\"[^!])+?\"))!)?([_\p{L}][_\p{L}\p{N}\.]*)';
52
    // Structured Reference (Fully Qualified and Unqualified)
53
    const CALCULATION_REGEXP_STRUCTURED_REFERENCE = '([\p{L}_\\\][\p{L}\p{N}\._]+)?(\[(?:[^\d\]+-])?)';
54
    //    Error
55
    const CALCULATION_REGEXP_ERROR = '\#[A-Z][A-Z0_\/]*[!\?]?';
56
57
    /** constants */
58
    const RETURN_ARRAY_AS_ERROR = 'error';
59
    const RETURN_ARRAY_AS_VALUE = 'value';
60
    const RETURN_ARRAY_AS_ARRAY = 'array';
61
62
    /** Preferable to use instance variable instanceArrayReturnType rather than this static property. */
63
    private static string $returnArrayAsType = self::RETURN_ARRAY_AS_VALUE;
64
65
    /** Preferable to use this instance variable rather than static returnArrayAsType */
66
    private ?string $instanceArrayReturnType = null;
67
68
    /**
69
     * Instance of this class.
70
     */
71
    private static ?Calculation $instance = null;
72
73
    /**
74
     * Instance of the spreadsheet this Calculation Engine is using.
75
     */
76
    private ?Spreadsheet $spreadsheet;
77
78
    /**
79
     * Calculation cache.
80
     *
81
     * @var mixed[]
82
     */
83
    private array $calculationCache = [];
84
85
    /**
86
     * Calculation cache enabled.
87
     */
88
    private bool $calculationCacheEnabled = true;
89
90
    private BranchPruner $branchPruner;
91
92
    private bool $branchPruningEnabled = true;
93
94
    /**
95
     * List of operators that can be used within formulae
96
     * The true/false value indicates whether it is a binary operator or a unary operator.
97
     */
98
    private const CALCULATION_OPERATORS = [
99
        '+' => true, '-' => true, '*' => true, '/' => true,
100
        '^' => true, '&' => true, '%' => false, '~' => false,
101
        '>' => true, '<' => true, '=' => true, '>=' => true,
102
        '<=' => true, '<>' => true, '∩' => true, '∪' => true,
103
        ':' => true,
104
    ];
105
106
    /**
107
     * List of binary operators (those that expect two operands).
108
     */
109
    private const BINARY_OPERATORS = [
110
        '+' => true, '-' => true, '*' => true, '/' => true,
111
        '^' => true, '&' => true, '>' => true, '<' => true,
112
        '=' => true, '>=' => true, '<=' => true, '<>' => true,
113
        '∩' => true, '∪' => true, ':' => true,
114
    ];
115
116
    /**
117
     * The debug log generated by the calculation engine.
118
     */
119
    private Logger $debugLog;
120
121
    private bool $suppressFormulaErrors = false;
122
123
    private bool $processingAnchorArray = false;
124
125
    /**
126
     * Error message for any error that was raised/thrown by the calculation engine.
127
     */
128
    public ?string $formulaError = null;
129
130
    /**
131
     * An array of the nested cell references accessed by the calculation engine, used for the debug log.
132
     */
133
    private CyclicReferenceStack $cyclicReferenceStack;
134
135
    private array $cellStack = [];
136
137
    /**
138
     * Current iteration counter for cyclic formulae
139
     * If the value is 0 (or less) then cyclic formulae will throw an exception,
140
     * otherwise they will iterate to the limit defined here before returning a result.
141
     */
142
    private int $cyclicFormulaCounter = 1;
143
144
    private string $cyclicFormulaCell = '';
145
146
    /**
147
     * Number of iterations for cyclic formulae.
148
     */
149
    public int $cyclicFormulaCount = 1;
150
151
    /**
152
     * Excel constant string translations to their PHP equivalents
153
     * Constant conversion from text name/value to actual (datatyped) value.
154
     */
155
    private const EXCEL_CONSTANTS = [
156
        'TRUE' => true,
157
        'FALSE' => false,
158
        'NULL' => null,
159
    ];
160
161 20
    public static function keyInExcelConstants(string $key): bool
162
    {
163 20
        return array_key_exists($key, self::EXCEL_CONSTANTS);
164
    }
165
166 3
    public static function getExcelConstants(string $key): bool|null
167
    {
168 3
        return self::EXCEL_CONSTANTS[$key];
169
    }
170
171
    /**
172
     *    Internal functions used for special control purposes.
173
     *
174
     * @var array<string, array<string, array<string>|string>>
175
     */
176
    private static array $controlFunctions = [
177
        'MKMATRIX' => [
178
            'argumentCount' => '*',
179
            'functionCall' => [Internal\MakeMatrix::class, 'make'],
180
        ],
181
        'NAME.ERROR' => [
182
            'argumentCount' => '*',
183
            'functionCall' => [ExcelError::class, 'NAME'],
184
        ],
185
        'WILDCARDMATCH' => [
186
            'argumentCount' => '2',
187
            'functionCall' => [Internal\WildcardMatch::class, 'compare'],
188
        ],
189
    ];
190
191 10518
    public function __construct(?Spreadsheet $spreadsheet = null)
192
    {
193 10518
        $this->spreadsheet = $spreadsheet;
194 10518
        $this->cyclicReferenceStack = new CyclicReferenceStack();
195 10518
        $this->debugLog = new Logger($this->cyclicReferenceStack);
196 10518
        $this->branchPruner = new BranchPruner($this->branchPruningEnabled);
197
    }
198
199
    /**
200
     * Get an instance of this class.
201
     *
202
     * @param ?Spreadsheet $spreadsheet Injected spreadsheet for working with a PhpSpreadsheet Spreadsheet object,
203
     *                                    or NULL to create a standalone calculation engine
204
     */
205 13029
    public static function getInstance(?Spreadsheet $spreadsheet = null): self
206
    {
207 13029
        if ($spreadsheet !== null) {
208 9260
            $instance = $spreadsheet->getCalculationEngine();
209 9260
            if (isset($instance)) {
210 9260
                return $instance;
211
            }
212
        }
213
214 4643
        if (!self::$instance) {
215 19
            self::$instance = new self();
216
        }
217
218 4643
        return self::$instance;
219
    }
220
221
    /**
222
     * Flush the calculation cache for any existing instance of this class
223
     *        but only if a Calculation instance exists.
224
     */
225 209
    public function flushInstance(): void
226
    {
227 209
        $this->clearCalculationCache();
228 209
        $this->branchPruner->clearBranchStore();
229
    }
230
231
    /**
232
     * Get the Logger for this calculation engine instance.
233
     */
234 1108
    public function getDebugLog(): Logger
235
    {
236 1108
        return $this->debugLog;
237
    }
238
239
    /**
240
     * __clone implementation. Cloning should not be allowed in a Singleton!
241
     */
242
    final public function __clone()
243
    {
244
        throw new Exception('Cloning the calculation engine is not allowed!');
245
    }
246
247
    /**
248
     * Set the Array Return Type (Array or Value of first element in the array).
249
     *
250
     * @param string $returnType Array return type
251
     *
252
     * @return bool Success or failure
253
     */
254 546
    public static function setArrayReturnType(string $returnType): bool
255
    {
256
        if (
257 546
            ($returnType == self::RETURN_ARRAY_AS_VALUE)
258 546
            || ($returnType == self::RETURN_ARRAY_AS_ERROR)
259 546
            || ($returnType == self::RETURN_ARRAY_AS_ARRAY)
260
        ) {
261 546
            self::$returnArrayAsType = $returnType;
262
263 546
            return true;
264
        }
265
266 1
        return false;
267
    }
268
269
    /**
270
     * Return the Array Return Type (Array or Value of first element in the array).
271
     *
272
     * @return string $returnType Array return type
273
     */
274 546
    public static function getArrayReturnType(): string
275
    {
276 546
        return self::$returnArrayAsType;
277
    }
278
279
    /**
280
     * Set the Instance Array Return Type (Array or Value of first element in the array).
281
     *
282
     * @param string $returnType Array return type
283
     *
284
     * @return bool Success or failure
285
     */
286 309
    public function setInstanceArrayReturnType(string $returnType): bool
287
    {
288
        if (
289 309
            ($returnType == self::RETURN_ARRAY_AS_VALUE)
290 309
            || ($returnType == self::RETURN_ARRAY_AS_ERROR)
291 309
            || ($returnType == self::RETURN_ARRAY_AS_ARRAY)
292
        ) {
293 309
            $this->instanceArrayReturnType = $returnType;
294
295 309
            return true;
296
        }
297
298
        return false;
299
    }
300
301
    /**
302
     * Return the Array Return Type (Array or Value of first element in the array).
303
     *
304
     * @return string $returnType Array return type for instance if non-null, otherwise static property
305
     */
306 8772
    public function getInstanceArrayReturnType(): string
307
    {
308 8772
        return $this->instanceArrayReturnType ?? self::$returnArrayAsType;
309
    }
310
311
    /**
312
     * Is calculation caching enabled?
313
     */
314 263
    public function getCalculationCacheEnabled(): bool
315
    {
316 263
        return $this->calculationCacheEnabled;
317
    }
318
319
    /**
320
     * Enable/disable calculation cache.
321
     */
322 8
    public function setCalculationCacheEnabled(bool $calculationCacheEnabled): self
323
    {
324 8
        $this->calculationCacheEnabled = $calculationCacheEnabled;
325 8
        $this->clearCalculationCache();
326
327 8
        return $this;
328
    }
329
330
    /**
331
     * Enable calculation cache.
332
     */
333
    public function enableCalculationCache(): void
334
    {
335
        $this->setCalculationCacheEnabled(true);
336
    }
337
338
    /**
339
     * Disable calculation cache.
340
     */
341
    public function disableCalculationCache(): void
342
    {
343
        $this->setCalculationCacheEnabled(false);
344
    }
345
346
    /**
347
     * Clear calculation cache.
348
     */
349 219
    public function clearCalculationCache(): void
350
    {
351 219
        $this->calculationCache = [];
352
    }
353
354
    /**
355
     * Clear calculation cache for a specified worksheet.
356
     */
357 125
    public function clearCalculationCacheForWorksheet(string $worksheetName): void
358
    {
359 125
        if (isset($this->calculationCache[$worksheetName])) {
360
            unset($this->calculationCache[$worksheetName]);
361
        }
362
    }
363
364
    /**
365
     * Rename calculation cache for a specified worksheet.
366
     */
367 1403
    public function renameCalculationCacheForWorksheet(string $fromWorksheetName, string $toWorksheetName): void
368
    {
369 1403
        if (isset($this->calculationCache[$fromWorksheetName])) {
370
            $this->calculationCache[$toWorksheetName] = &$this->calculationCache[$fromWorksheetName];
371
            unset($this->calculationCache[$fromWorksheetName]);
372
        }
373
    }
374
375 8
    public function getBranchPruningEnabled(): bool
376
    {
377 8
        return $this->branchPruningEnabled;
378
    }
379
380 8031
    public function setBranchPruningEnabled(mixed $enabled): self
381
    {
382 8031
        $this->branchPruningEnabled = (bool) $enabled;
383 8031
        $this->branchPruner = new BranchPruner($this->branchPruningEnabled);
384
385 8031
        return $this;
386
    }
387
388
    public function enableBranchPruning(): void
389
    {
390
        $this->setBranchPruningEnabled(true);
391
    }
392
393 8023
    public function disableBranchPruning(): void
394
    {
395 8023
        $this->setBranchPruningEnabled(false);
396
    }
397
398
    /**
399
     * Wrap string values in quotes.
400
     */
401 11495
    public static function wrapResult(mixed $value): mixed
402
    {
403 11495
        if (is_string($value)) {
404
            //    Error values cannot be "wrapped"
405 3980
            if (preg_match('/^' . self::CALCULATION_REGEXP_ERROR . '$/i', $value, $match)) {
406
                //    Return Excel errors "as is"
407 1249
                return $value;
408
            }
409
410
            //    Return strings wrapped in quotes
411 3196
            return self::FORMULA_STRING_QUOTE . $value . self::FORMULA_STRING_QUOTE;
412 9145
        } elseif ((is_float($value)) && ((is_nan($value)) || (is_infinite($value)))) {
413
            //    Convert numeric errors to NaN error
414 4
            return ExcelError::NAN();
415
        }
416
417 9142
        return $value;
418
    }
419
420
    /**
421
     * Remove quotes used as a wrapper to identify string values.
422
     */
423 11693
    public static function unwrapResult(mixed $value): mixed
424
    {
425 11693
        if (is_string($value)) {
426 3685
            if ((isset($value[0])) && ($value[0] == self::FORMULA_STRING_QUOTE) && (substr($value, -1) == self::FORMULA_STRING_QUOTE)) {
427 2967
                return substr($value, 1, -1);
428
            }
429
            //    Convert numeric errors to NAN error
430 10488
        } elseif ((is_float($value)) && ((is_nan($value)) || (is_infinite($value)))) {
431
            return ExcelError::NAN();
432
        }
433
434 10564
        return $value;
435
    }
436
437
    /**
438
     * Calculate cell value (using formula from a cell ID)
439
     * Retained for backward compatibility.
440
     *
441
     * @param ?Cell $cell Cell to calculate
442
     */
443
    public function calculate(?Cell $cell = null): mixed
444
    {
445
        try {
446
            return $this->calculateCellValue($cell);
447
        } catch (\Exception $e) {
448
            throw new Exception($e->getMessage());
449
        }
450
    }
451
452
    /**
453
     * Calculate the value of a cell formula.
454
     *
455
     * @param ?Cell $cell Cell to calculate
456
     * @param bool $resetLog Flag indicating whether the debug log should be reset or not
457
     */
458 8092
    public function calculateCellValue(?Cell $cell = null, bool $resetLog = true): mixed
459
    {
460 8092
        if ($cell === null) {
461
            return null;
462
        }
463
464 8092
        if ($resetLog) {
465
            //    Initialise the logging settings if requested
466 8080
            $this->formulaError = null;
467 8080
            $this->debugLog->clearLog();
468 8080
            $this->cyclicReferenceStack->clear();
469 8080
            $this->cyclicFormulaCounter = 1;
470
        }
471
472
        //    Execute the calculation for the cell formula
473 8092
        $this->cellStack[] = [
474 8092
            'sheet' => $cell->getWorksheet()->getTitle(),
475 8092
            'cell' => $cell->getCoordinate(),
476 8092
        ];
477
478 8092
        $cellAddressAttempted = false;
479 8092
        $cellAddress = null;
480
481
        try {
482 8092
            $value = $cell->getValue();
483 8092
            if (is_string($value) && $cell->getDataType() === DataType::TYPE_FORMULA) {
484 8092
                $value = preg_replace_callback(
485 8092
                    self::CALCULATION_REGEXP_CELLREF_SPILL,
486 8092
                    fn (array $matches) => 'ANCHORARRAY(' . substr($matches[0], 0, -1) . ')',
487 8092
                    $value
488 8092
                );
489
            }
490 8092
            $result = self::unwrapResult($this->_calculateFormulaValue($value, $cell->getCoordinate(), $cell)); //* @phpstan-ignore-line
491 7844
            if ($this->spreadsheet === null) {
492
                throw new Exception('null spreadsheet in calculateCellValue');
493
            }
494 7844
            $cellAddressAttempted = true;
495 7844
            $cellAddress = array_pop($this->cellStack);
496 7844
            if ($cellAddress === null) {
497
                throw new Exception('null cellAddress in calculateCellValue');
498
            }
499 7844
            $testSheet = $this->spreadsheet->getSheetByName($cellAddress['sheet']);
500 7844
            if ($testSheet === null) {
501
                throw new Exception('worksheet not found in calculateCellValue');
502
            }
503 7844
            $testSheet->getCell($cellAddress['cell']);
504 269
        } catch (\Exception $e) {
505 269
            if (!$cellAddressAttempted) {
506 269
                $cellAddress = array_pop($this->cellStack);
507
            }
508 269
            if ($this->spreadsheet !== null && is_array($cellAddress) && array_key_exists('sheet', $cellAddress)) {
509 269
                $sheetName = $cellAddress['sheet'] ?? null;
510 269
                $testSheet = is_string($sheetName) ? $this->spreadsheet->getSheetByName($sheetName) : null;
511 269
                if ($testSheet !== null && array_key_exists('cell', $cellAddress)) {
512 269
                    $testSheet->getCell($cellAddress['cell']);
513
                }
514
            }
515
516 269
            throw new Exception($e->getMessage(), $e->getCode(), $e);
517
        }
518
519 7844
        if (is_array($result) && $this->getInstanceArrayReturnType() !== self::RETURN_ARRAY_AS_ARRAY) {
520 4812
            $testResult = Functions::flattenArray($result);
521 4812
            if ($this->getInstanceArrayReturnType() == self::RETURN_ARRAY_AS_ERROR) {
522 1
                return ExcelError::VALUE();
523
            }
524 4812
            $result = array_shift($testResult);
525
        }
526
527 7844
        if ($result === null && $cell->getWorksheet()->getSheetView()->getShowZeros()) {
528 17
            return 0;
529 7843
        } elseif ((is_float($result)) && ((is_nan($result)) || (is_infinite($result)))) {
530
            return ExcelError::NAN();
531
        }
532
533 7843
        return $result;
534
    }
535
536
    /**
537
     * Validate and parse a formula string.
538
     *
539
     * @param string $formula Formula to parse
540
     */
541 8067
    public function parseFormula(string $formula): array|bool
542
    {
543 8067
        $formula = preg_replace_callback(
544 8067
            self::CALCULATION_REGEXP_CELLREF_SPILL,
545 8067
            fn (array $matches) => 'ANCHORARRAY(' . substr($matches[0], 0, -1) . ')',
546 8067
            $formula
547 8067
        ) ?? $formula;
548
        //    Basic validation that this is indeed a formula
549
        //    We return an empty array if not
550 8067
        $formula = trim($formula);
551 8067
        if ((!isset($formula[0])) || ($formula[0] != '=')) {
552
            return [];
553
        }
554 8067
        $formula = ltrim(substr($formula, 1));
555 8067
        if (!isset($formula[0])) {
556
            return [];
557
        }
558
559
        //    Parse the formula and return the token stack
560 8067
        return $this->internalParseFormula($formula);
561
    }
562
563
    /**
564
     * Calculate the value of a formula.
565
     *
566
     * @param string $formula Formula to parse
567
     * @param ?string $cellID Address of the cell to calculate
568
     * @param ?Cell $cell Cell to calculate
569
     */
570 255
    public function calculateFormula(string $formula, ?string $cellID = null, ?Cell $cell = null): mixed
571
    {
572
        //    Initialise the logging settings
573 255
        $this->formulaError = null;
574 255
        $this->debugLog->clearLog();
575 255
        $this->cyclicReferenceStack->clear();
576
577 255
        $resetCache = $this->getCalculationCacheEnabled();
578 255
        if ($this->spreadsheet !== null && $cellID === null && $cell === null) {
579 173
            $cellID = 'A1';
580 173
            $cell = $this->spreadsheet->getActiveSheet()->getCell($cellID);
581
        } else {
582
            //    Disable calculation cacheing because it only applies to cell calculations, not straight formulae
583
            //    But don't actually flush any cache
584 82
            $this->calculationCacheEnabled = false;
585
        }
586
587
        //    Execute the calculation
588
        try {
589 255
            $result = self::unwrapResult($this->_calculateFormulaValue($formula, $cellID, $cell));
590 2
        } catch (\Exception $e) {
591 2
            throw new Exception($e->getMessage());
592
        }
593
594 254
        if ($this->spreadsheet === null) {
595
            //    Reset calculation cacheing to its previous state
596 70
            $this->calculationCacheEnabled = $resetCache;
597
        }
598
599 254
        return $result;
600
    }
601
602 8245
    public function getValueFromCache(string $cellReference, mixed &$cellValue): bool
603
    {
604 8245
        $this->debugLog->writeDebugLog('Testing cache value for cell %s', $cellReference);
605
        // Is calculation cacheing enabled?
606
        // If so, is the required value present in calculation cache?
607 8245
        if (($this->calculationCacheEnabled) && (isset($this->calculationCache[$cellReference]))) {
608 337
            $this->debugLog->writeDebugLog('Retrieving value for cell %s from cache', $cellReference);
609
            // Return the cached result
610
611 337
            $cellValue = $this->calculationCache[$cellReference];
612
613 337
            return true;
614
        }
615
616 8245
        return false;
617
    }
618
619 7995
    public function saveValueToCache(string $cellReference, mixed $cellValue): void
620
    {
621 7995
        if ($this->calculationCacheEnabled) {
622 7987
            $this->calculationCache[$cellReference] = $cellValue;
623
        }
624
    }
625
626
    /**
627
     * Parse a cell formula and calculate its value.
628
     *
629
     * @param string $formula The formula to parse and calculate
630
     * @param ?string $cellID The ID (e.g. A3) of the cell that we are calculating
631
     * @param ?Cell $cell Cell to calculate
632
     * @param bool $ignoreQuotePrefix If set to true, evaluate the formyla even if the referenced cell is quote prefixed
633
     */
634 11963
    public function _calculateFormulaValue(string $formula, ?string $cellID = null, ?Cell $cell = null, bool $ignoreQuotePrefix = false): mixed
635
    {
636 11963
        $cellValue = null;
637
638
        //  Quote-Prefixed cell values cannot be formulae, but are treated as strings
639 11963
        if ($cell !== null && $ignoreQuotePrefix === false && $cell->getStyle()->getQuotePrefix() === true) {
640 1
            return self::wrapResult((string) $formula);
641
        }
642
643 11963
        if (preg_match('/^=\s*cmd\s*\|/miu', $formula) !== 0) {
644
            return self::wrapResult($formula);
645
        }
646
647
        //    Basic validation that this is indeed a formula
648
        //    We simply return the cell value if not
649 11963
        $formula = trim($formula);
650 11963
        if ($formula === '' || $formula[0] !== '=') {
651 2
            return self::wrapResult($formula);
652
        }
653 11963
        $formula = ltrim(substr($formula, 1));
654 11963
        if (!isset($formula[0])) {
655 5
            return self::wrapResult($formula);
656
        }
657
658 11962
        $pCellParent = ($cell !== null) ? $cell->getWorksheet() : null;
659 11962
        $wsTitle = ($pCellParent !== null) ? $pCellParent->getTitle() : "\x00Wrk";
660 11962
        $wsCellReference = $wsTitle . '!' . $cellID;
661
662 11962
        if (($cellID !== null) && ($this->getValueFromCache($wsCellReference, $cellValue))) {
663 333
            return $cellValue;
664
        }
665 11962
        $this->debugLog->writeDebugLog('Evaluating formula for cell %s', $wsCellReference);
666
667 11962
        if (($wsTitle[0] !== "\x00") && ($this->cyclicReferenceStack->onStack($wsCellReference))) {
668 13
            if ($this->cyclicFormulaCount <= 0) {
669 1
                $this->cyclicFormulaCell = '';
670
671 1
                return $this->raiseFormulaError('Cyclic Reference in Formula');
672 12
            } elseif ($this->cyclicFormulaCell === $wsCellReference) {
673 1
                ++$this->cyclicFormulaCounter;
674 1
                if ($this->cyclicFormulaCounter >= $this->cyclicFormulaCount) {
675 1
                    $this->cyclicFormulaCell = '';
676
677 1
                    return $cellValue;
678
                }
679 12
            } elseif ($this->cyclicFormulaCell == '') {
680 12
                if ($this->cyclicFormulaCounter >= $this->cyclicFormulaCount) {
681 11
                    return $cellValue;
682
                }
683 1
                $this->cyclicFormulaCell = $wsCellReference;
684
            }
685
        }
686
687 11962
        $this->debugLog->writeDebugLog('Formula for cell %s is %s', $wsCellReference, $formula);
688
        //    Parse the formula onto the token stack and calculate the value
689 11962
        $this->cyclicReferenceStack->push($wsCellReference);
690
691 11962
        $cellValue = $this->processTokenStack($this->internalParseFormula($formula, $cell), $cellID, $cell);
692 11710
        $this->cyclicReferenceStack->pop();
693
694
        // Save to calculation cache
695 11710
        if ($cellID !== null) {
696 7995
            $this->saveValueToCache($wsCellReference, $cellValue);
697
        }
698
699
        //    Return the calculated value
700 11710
        return $cellValue;
701
    }
702
703
    /**
704
     * Ensure that paired matrix operands are both matrices and of the same size.
705
     *
706
     * @param mixed $operand1 First matrix operand
707
     *
708
     * @param-out array $operand1
709
     *
710
     * @param mixed $operand2 Second matrix operand
711
     *
712
     * @param-out array $operand2
713
     *
714
     * @param int $resize Flag indicating whether the matrices should be resized to match
715
     *                                        and (if so), whether the smaller dimension should grow or the
716
     *                                        larger should shrink.
717
     *                                            0 = no resize
718
     *                                            1 = shrink to fit
719
     *                                            2 = extend to fit
720
     *
721
     * @return mixed[]
722
     */
723 65
    public static function checkMatrixOperands(mixed &$operand1, mixed &$operand2, int $resize = 1): array
724
    {
725
        //    Examine each of the two operands, and turn them into an array if they aren't one already
726
        //    Note that this function should only be called if one or both of the operand is already an array
727 65
        if (!is_array($operand1)) {
728 19
            if (is_array($operand2)) {
729 19
                [$matrixRows, $matrixColumns] = self::getMatrixDimensions($operand2);
730 19
                $operand1 = array_fill(0, $matrixRows, array_fill(0, $matrixColumns, $operand1));
731 19
                $resize = 0;
732
            } else {
733
                $operand1 = [$operand1];
734
                $operand2 = [$operand2];
735
            }
736 52
        } elseif (!is_array($operand2)) {
737 16
            [$matrixRows, $matrixColumns] = self::getMatrixDimensions($operand1);
738 16
            $operand2 = array_fill(0, $matrixRows, array_fill(0, $matrixColumns, $operand2));
739 16
            $resize = 0;
740
        }
741
742 65
        [$matrix1Rows, $matrix1Columns] = self::getMatrixDimensions($operand1);
743 65
        [$matrix2Rows, $matrix2Columns] = self::getMatrixDimensions($operand2);
744 65
        if ($resize === 3) {
745 23
            $resize = 2;
746 45
        } elseif (($matrix1Rows == $matrix2Columns) && ($matrix2Rows == $matrix1Columns)) {
747 37
            $resize = 1;
748
        }
749
750 65
        if ($resize == 2) {
751
            //    Given two matrices of (potentially) unequal size, convert the smaller in each dimension to match the larger
752 25
            self::resizeMatricesExtend($operand1, $operand2, $matrix1Rows, $matrix1Columns, $matrix2Rows, $matrix2Columns);
753 44
        } elseif ($resize == 1) {
754
            //    Given two matrices of (potentially) unequal size, convert the larger in each dimension to match the smaller
755
            /** @var mixed[][] $operand1 */
756
            /** @var mixed[][] $operand2 */
757 37
            self::resizeMatricesShrink($operand1, $operand2, $matrix1Rows, $matrix1Columns, $matrix2Rows, $matrix2Columns);
758
        }
759 65
        [$matrix1Rows, $matrix1Columns] = self::getMatrixDimensions($operand1);
760 65
        [$matrix2Rows, $matrix2Columns] = self::getMatrixDimensions($operand2);
761
762 65
        return [$matrix1Rows, $matrix1Columns, $matrix2Rows, $matrix2Columns];
763
    }
764
765
    /**
766
     * Read the dimensions of a matrix, and re-index it with straight numeric keys starting from row 0, column 0.
767
     *
768
     * @param mixed[] $matrix matrix operand
769
     *
770
     * @return int[] An array comprising the number of rows, and number of columns
771
     */
772 101
    public static function getMatrixDimensions(array &$matrix): array
773
    {
774 101
        $matrixRows = count($matrix);
775 101
        $matrixColumns = 0;
776 101
        foreach ($matrix as $rowKey => $rowValue) {
777 99
            if (!is_array($rowValue)) {
778 4
                $matrix[$rowKey] = [$rowValue];
779 4
                $matrixColumns = max(1, $matrixColumns);
780
            } else {
781 95
                $matrix[$rowKey] = array_values($rowValue);
782 95
                $matrixColumns = max(count($rowValue), $matrixColumns);
783
            }
784
        }
785 101
        $matrix = array_values($matrix);
786
787 101
        return [$matrixRows, $matrixColumns];
788
    }
789
790
    /**
791
     * Ensure that paired matrix operands are both matrices of the same size.
792
     *
793
     * @param mixed[][] $matrix1 First matrix operand
794
     * @param mixed[][] $matrix2 Second matrix operand
795
     * @param int $matrix1Rows Row size of first matrix operand
796
     * @param int $matrix1Columns Column size of first matrix operand
797
     * @param int $matrix2Rows Row size of second matrix operand
798
     * @param int $matrix2Columns Column size of second matrix operand
799
     */
800 37
    private static function resizeMatricesShrink(array &$matrix1, array &$matrix2, int $matrix1Rows, int $matrix1Columns, int $matrix2Rows, int $matrix2Columns): void
801
    {
802 37
        if (($matrix2Columns < $matrix1Columns) || ($matrix2Rows < $matrix1Rows)) {
803
            if ($matrix2Rows < $matrix1Rows) {
804
                for ($i = $matrix2Rows; $i < $matrix1Rows; ++$i) {
805
                    unset($matrix1[$i]);
806
                }
807
            }
808
            if ($matrix2Columns < $matrix1Columns) {
809
                for ($i = 0; $i < $matrix1Rows; ++$i) {
810
                    for ($j = $matrix2Columns; $j < $matrix1Columns; ++$j) {
811
                        unset($matrix1[$i][$j]);
812
                    }
813
                }
814
            }
815
        }
816
817 37
        if (($matrix1Columns < $matrix2Columns) || ($matrix1Rows < $matrix2Rows)) {
818
            if ($matrix1Rows < $matrix2Rows) {
819
                for ($i = $matrix1Rows; $i < $matrix2Rows; ++$i) {
820
                    unset($matrix2[$i]);
821
                }
822
            }
823
            if ($matrix1Columns < $matrix2Columns) {
824
                for ($i = 0; $i < $matrix2Rows; ++$i) {
825
                    for ($j = $matrix1Columns; $j < $matrix2Columns; ++$j) {
826
                        unset($matrix2[$i][$j]);
827
                    }
828
                }
829
            }
830
        }
831
    }
832
833
    /**
834
     * Ensure that paired matrix operands are both matrices of the same size.
835
     *
836
     * @param mixed[] $matrix1 First matrix operand
837
     * @param mixed[] $matrix2 Second matrix operand
838
     * @param int $matrix1Rows Row size of first matrix operand
839
     * @param int $matrix1Columns Column size of first matrix operand
840
     * @param int $matrix2Rows Row size of second matrix operand
841
     * @param int $matrix2Columns Column size of second matrix operand
842
     */
843 25
    private static function resizeMatricesExtend(array &$matrix1, array &$matrix2, int $matrix1Rows, int $matrix1Columns, int $matrix2Rows, int $matrix2Columns): void
844
    {
845 25
        if (($matrix2Columns < $matrix1Columns) || ($matrix2Rows < $matrix1Rows)) {
846 16
            if ($matrix2Columns < $matrix1Columns) {
847 15
                for ($i = 0; $i < $matrix2Rows; ++$i) {
848 15
                    $x = $matrix2[$i][$matrix2Columns - 1];
849 15
                    for ($j = $matrix2Columns; $j < $matrix1Columns; ++$j) {
850 15
                        $matrix2[$i][$j] = $x;
851
                    }
852
                }
853
            }
854 16
            if ($matrix2Rows < $matrix1Rows) {
855 2
                $x = $matrix2[$matrix2Rows - 1];
856 2
                for ($i = 0; $i < $matrix1Rows; ++$i) {
857 2
                    $matrix2[$i] = $x;
858
                }
859
            }
860
        }
861
862 25
        if (($matrix1Columns < $matrix2Columns) || ($matrix1Rows < $matrix2Rows)) {
863 15
            if ($matrix1Columns < $matrix2Columns) {
864
                for ($i = 0; $i < $matrix1Rows; ++$i) {
865
                    $x = $matrix1[$i][$matrix1Columns - 1];
866
                    for ($j = $matrix1Columns; $j < $matrix2Columns; ++$j) {
867
                        $matrix1[$i][$j] = $x;
868
                    }
869
                }
870
            }
871 15
            if ($matrix1Rows < $matrix2Rows) {
872 15
                $x = $matrix1[$matrix1Rows - 1];
873 15
                for ($i = 0; $i < $matrix2Rows; ++$i) {
874 15
                    $matrix1[$i] = $x;
875
                }
876
            }
877
        }
878
    }
879
880
    /**
881
     * Format details of an operand for display in the log (based on operand type).
882
     *
883
     * @param mixed $value First matrix operand
884
     */
885 11690
    private function showValue(mixed $value): mixed
886
    {
887 11690
        if ($this->debugLog->getWriteDebugLog()) {
888 3
            $testArray = Functions::flattenArray($value);
889 3
            if (count($testArray) == 1) {
890 3
                $value = array_pop($testArray);
891
            }
892
893 3
            if (is_array($value)) {
894 2
                $returnMatrix = [];
895 2
                $pad = $rpad = ', ';
896 2
                foreach ($value as $row) {
897 2
                    if (is_array($row)) {
898 2
                        $returnMatrix[] = implode($pad, array_map([$this, 'showValue'], $row));
899 2
                        $rpad = '; ';
900
                    } else {
901
                        $returnMatrix[] = $this->showValue($row);
902
                    }
903
                }
904
905 2
                return '{ ' . implode($rpad, $returnMatrix) . ' }';
906 3
            } elseif (is_string($value) && (trim($value, self::FORMULA_STRING_QUOTE) == $value)) {
907 2
                return self::FORMULA_STRING_QUOTE . $value . self::FORMULA_STRING_QUOTE;
908 3
            } elseif (is_bool($value)) {
909
                return ($value) ? self::$localeBoolean['TRUE'] : self::$localeBoolean['FALSE'];
910 3
            } elseif ($value === null) {
911
                return self::$localeBoolean['NULL'];
912
            }
913
        }
914
915 11690
        return Functions::flattenSingleValue($value);
916
    }
917
918
    /**
919
     * Format type and details of an operand for display in the log (based on operand type).
920
     *
921
     * @param mixed $value First matrix operand
922
     */
923 11712
    private function showTypeDetails(mixed $value): ?string
924
    {
925 11712
        if ($this->debugLog->getWriteDebugLog()) {
926 3
            $testArray = Functions::flattenArray($value);
927 3
            if (count($testArray) == 1) {
928 3
                $value = array_pop($testArray);
929
            }
930
931 3
            if ($value === null) {
932
                return 'a NULL value';
933 3
            } elseif (is_float($value)) {
934 3
                $typeString = 'a floating point number';
935 3
            } elseif (is_int($value)) {
936 3
                $typeString = 'an integer number';
937 2
            } elseif (is_bool($value)) {
938
                $typeString = 'a boolean';
939 2
            } elseif (is_array($value)) {
940 2
                $typeString = 'a matrix';
941
            } else {
942
                /** @var string $value */
943
                if ($value == '') {
944
                    return 'an empty string';
945
                } elseif ($value[0] == '#') {
946
                    return 'a ' . $value . ' error';
947
                }
948
                $typeString = 'a string';
949
            }
950
951 3
            return $typeString . ' with a value of ' . StringHelper::convertToString($this->showValue($value));
952
        }
953
954 11709
        return null;
955
    }
956
957
    /**
958
     * @return false|string False indicates an error
959
     */
960 12103
    private function convertMatrixReferences(string $formula): false|string
961
    {
962 12103
        static $matrixReplaceFrom = [self::FORMULA_OPEN_MATRIX_BRACE, ';', self::FORMULA_CLOSE_MATRIX_BRACE];
963 12103
        static $matrixReplaceTo = ['MKMATRIX(MKMATRIX(', '),MKMATRIX(', '))'];
964
965
        //    Convert any Excel matrix references to the MKMATRIX() function
966 12103
        if (str_contains($formula, self::FORMULA_OPEN_MATRIX_BRACE)) {
967
            //    If there is the possibility of braces within a quoted string, then we don't treat those as matrix indicators
968 797
            if (str_contains($formula, self::FORMULA_STRING_QUOTE)) {
969
                //    So instead we skip replacing in any quoted strings by only replacing in every other array element after we've exploded
970
                //        the formula
971 246
                $temp = explode(self::FORMULA_STRING_QUOTE, $formula);
972
                //    Open and Closed counts used for trapping mismatched braces in the formula
973 246
                $openCount = $closeCount = 0;
974 246
                $notWithinQuotes = false;
975 246
                foreach ($temp as &$value) {
976
                    //    Only count/replace in alternating array entries
977 246
                    $notWithinQuotes = $notWithinQuotes === false;
978 246
                    if ($notWithinQuotes === true) {
979 246
                        $openCount += substr_count($value, self::FORMULA_OPEN_MATRIX_BRACE);
980 246
                        $closeCount += substr_count($value, self::FORMULA_CLOSE_MATRIX_BRACE);
981 246
                        $value = str_replace($matrixReplaceFrom, $matrixReplaceTo, $value);
982
                    }
983
                }
984 246
                unset($value);
985
                //    Then rebuild the formula string
986 246
                $formula = implode(self::FORMULA_STRING_QUOTE, $temp);
987
            } else {
988
                //    If there's no quoted strings, then we do a simple count/replace
989 553
                $openCount = substr_count($formula, self::FORMULA_OPEN_MATRIX_BRACE);
990 553
                $closeCount = substr_count($formula, self::FORMULA_CLOSE_MATRIX_BRACE);
991 553
                $formula = str_replace($matrixReplaceFrom, $matrixReplaceTo, $formula);
992
            }
993
            //    Trap for mismatched braces and trigger an appropriate error
994 797
            if ($openCount < $closeCount) {
995
                if ($openCount > 0) {
996
                    return $this->raiseFormulaError("Formula Error: Mismatched matrix braces '}'");
997
                }
998
999
                return $this->raiseFormulaError("Formula Error: Unexpected '}' encountered");
1000 797
            } elseif ($openCount > $closeCount) {
1001
                if ($closeCount > 0) {
1002
                    return $this->raiseFormulaError("Formula Error: Mismatched matrix braces '{'");
1003
                }
1004
1005
                return $this->raiseFormulaError("Formula Error: Unexpected '{' encountered");
1006
            }
1007
        }
1008
1009 12103
        return $formula;
1010
    }
1011
1012
    /**
1013
     *    Comparison (Boolean) Operators.
1014
     *    These operators work on two values, but always return a boolean result.
1015
     */
1016
    private const COMPARISON_OPERATORS = ['>' => true, '<' => true, '=' => true, '>=' => true, '<=' => true, '<>' => true];
1017
1018
    /**
1019
     *    Operator Precedence.
1020
     *    This list includes all valid operators, whether binary (including boolean) or unary (such as %).
1021
     *    Array key is the operator, the value is its precedence.
1022
     */
1023
    private const OPERATOR_PRECEDENCE = [
1024
        ':' => 9, //    Range
1025
        '∩' => 8, //    Intersect
1026
        '∪' => 7, //    Union
1027
        '~' => 6, //    Negation
1028
        '%' => 5, //    Percentage
1029
        '^' => 4, //    Exponentiation
1030
        '*' => 3, '/' => 3, //    Multiplication and Division
1031
        '+' => 2, '-' => 2, //    Addition and Subtraction
1032
        '&' => 1, //    Concatenation
1033
        '>' => 0, '<' => 0, '=' => 0, '>=' => 0, '<=' => 0, '<>' => 0, //    Comparison
1034
    ];
1035
1036
    /**
1037
     * @return array<int, mixed>|false
1038
     */
1039 12103
    private function internalParseFormula(string $formula, ?Cell $cell = null): bool|array
1040
    {
1041 12103
        if (($formula = $this->convertMatrixReferences(trim($formula))) === false) {
1042
            return false;
1043
        }
1044 12103
        $phpSpreadsheetFunctions = &self::getFunctionsAddress();
1045
1046
        //    If we're using cell caching, then $pCell may well be flushed back to the cache (which detaches the parent worksheet),
1047
        //        so we store the parent worksheet so that we can re-attach it when necessary
1048 12103
        $pCellParent = ($cell !== null) ? $cell->getWorksheet() : null;
1049
1050 12103
        $regexpMatchString = '/^((?<string>' . self::CALCULATION_REGEXP_STRING
1051 12103
                                . ')|(?<function>' . self::CALCULATION_REGEXP_FUNCTION
1052 12103
                                . ')|(?<cellRef>' . self::CALCULATION_REGEXP_CELLREF
1053 12103
                                . ')|(?<colRange>' . self::CALCULATION_REGEXP_COLUMN_RANGE
1054 12103
                                . ')|(?<rowRange>' . self::CALCULATION_REGEXP_ROW_RANGE
1055 12103
                                . ')|(?<number>' . self::CALCULATION_REGEXP_NUMBER
1056 12103
                                . ')|(?<openBrace>' . self::CALCULATION_REGEXP_OPENBRACE
1057 12103
                                . ')|(?<structuredReference>' . self::CALCULATION_REGEXP_STRUCTURED_REFERENCE
1058 12103
                                . ')|(?<definedName>' . self::CALCULATION_REGEXP_DEFINEDNAME
1059 12103
                                . ')|(?<error>' . self::CALCULATION_REGEXP_ERROR
1060 12103
                                . '))/sui';
1061
1062
        //    Start with initialisation
1063 12103
        $index = 0;
1064 12103
        $stack = new Stack($this->branchPruner);
1065 12103
        $output = [];
1066 12103
        $expectingOperator = false; //    We use this test in syntax-checking the expression to determine when a
1067
        //        - is a negation or + is a positive operator rather than an operation
1068 12103
        $expectingOperand = false; //    We use this test in syntax-checking the expression to determine whether an operand
1069
        //        should be null in a function call
1070
1071
        //    The guts of the lexical parser
1072
        //    Loop through the formula extracting each operator and operand in turn
1073 12103
        while (true) {
1074
            // Branch pruning: we adapt the output item to the context (it will
1075
            // be used to limit its computation)
1076 12103
            $this->branchPruner->initialiseForLoop();
1077
1078 12103
            $opCharacter = $formula[$index]; //    Get the first character of the value at the current index position
1079
1080
            // Check for two-character operators (e.g. >=, <=, <>)
1081 12103
            if ((isset(self::COMPARISON_OPERATORS[$opCharacter])) && (strlen($formula) > $index) && isset($formula[$index + 1], self::COMPARISON_OPERATORS[$formula[$index + 1]])) {
1082 85
                $opCharacter .= $formula[++$index];
1083
            }
1084
            //    Find out if we're currently at the beginning of a number, variable, cell/row/column reference,
1085
            //         function, defined name, structured reference, parenthesis, error or operand
1086 12103
            $isOperandOrFunction = (bool) preg_match($regexpMatchString, substr($formula, $index), $match);
1087
1088 12103
            $expectingOperatorCopy = $expectingOperator;
1089 12103
            if ($opCharacter === '-' && !$expectingOperator) {                //    Is it a negation instead of a minus?
1090
                //    Put a negation on the stack
1091 1149
                $stack->push('Unary Operator', '~');
1092 1149
                ++$index; //        and drop the negation symbol
1093 12103
            } elseif ($opCharacter === '%' && $expectingOperator) {
1094
                //    Put a percentage on the stack
1095 11
                $stack->push('Unary Operator', '%');
1096 11
                ++$index;
1097 12103
            } elseif ($opCharacter === '+' && !$expectingOperator) {            //    Positive (unary plus rather than binary operator plus) can be discarded?
1098 7
                ++$index; //    Drop the redundant plus symbol
1099 12103
            } elseif ((($opCharacter === '~') || ($opCharacter === '∩') || ($opCharacter === '∪')) && (!$isOperandOrFunction)) {
1100
                //    We have to explicitly deny a tilde, union or intersect because they are legal
1101
                return $this->raiseFormulaError("Formula Error: Illegal character '~'"); //        on the stack but not in the input expression
1102 12103
            } elseif ((isset(self::CALCULATION_OPERATORS[$opCharacter]) || $isOperandOrFunction) && $expectingOperator) {    //    Are we putting an operator on the stack?
1103 1795
                while (self::swapOperands($stack, $opCharacter)) {
1104 94
                    $output[] = $stack->pop(); //    Swap operands and higher precedence operators from the stack to the output
1105
                }
1106
1107
                //    Finally put our current operator onto the stack
1108 1795
                $stack->push('Binary Operator', $opCharacter);
1109
1110 1795
                ++$index;
1111 1795
                $expectingOperator = false;
1112 12103
            } elseif ($opCharacter === ')' && $expectingOperator) { //    Are we expecting to close a parenthesis?
1113 11722
                $expectingOperand = false;
1114 11722
                while (($o2 = $stack->pop()) && $o2['value'] !== '(') { //    Pop off the stack back to the last (
1115 1378
                    $output[] = $o2;
1116
                }
1117 11722
                $d = $stack->last(2);
1118
1119
                // Branch pruning we decrease the depth whether is it a function
1120
                // call or a parenthesis
1121 11722
                $this->branchPruner->decrementDepth();
1122
1123 11722
                if (is_array($d) && preg_match('/^' . self::CALCULATION_REGEXP_FUNCTION . '$/miu', $d['value'], $matches)) {
1124
                    //    Did this parenthesis just close a function?
1125
                    try {
1126 11717
                        $this->branchPruner->closingBrace($d['value']);
1127 4
                    } catch (Exception $e) {
1128 4
                        return $this->raiseFormulaError($e->getMessage(), $e->getCode(), $e);
1129
                    }
1130
1131 11717
                    $functionName = $matches[1]; //    Get the function name
1132 11717
                    $d = $stack->pop();
1133 11717
                    $argumentCount = $d['value'] ?? 0; //    See how many arguments there were (argument count is the next value stored on the stack)
1134 11717
                    $output[] = $d; //    Dump the argument count on the output
1135 11717
                    $output[] = $stack->pop(); //    Pop the function and push onto the output
1136 11717
                    if (isset(self::$controlFunctions[$functionName])) {
1137 817
                        $expectedArgumentCount = self::$controlFunctions[$functionName]['argumentCount'];
1138 11714
                    } elseif (isset($phpSpreadsheetFunctions[$functionName])) {
1139 11714
                        $expectedArgumentCount = $phpSpreadsheetFunctions[$functionName]['argumentCount'];
1140
                    } else {    // did we somehow push a non-function on the stack? this should never happen
1141
                        return $this->raiseFormulaError('Formula Error: Internal error, non-function on stack');
1142
                    }
1143
                    //    Check the argument count
1144 11717
                    $argumentCountError = false;
1145 11717
                    $expectedArgumentCountString = null;
1146 11717
                    if (is_numeric($expectedArgumentCount)) {
1147 5913
                        if ($expectedArgumentCount < 0) {
1148 37
                            if ($argumentCount > abs($expectedArgumentCount + 0)) {
1149
                                $argumentCountError = true;
1150
                                $expectedArgumentCountString = 'no more than ' . abs($expectedArgumentCount + 0);
1151
                            }
1152
                        } else {
1153 5878
                            if ($argumentCount != $expectedArgumentCount) {
1154 142
                                $argumentCountError = true;
1155 142
                                $expectedArgumentCountString = $expectedArgumentCount;
1156
                            }
1157
                        }
1158 6565
                    } elseif (is_string($expectedArgumentCount) && $expectedArgumentCount !== '*') {
1159 6089
                        if (1 !== preg_match('/(\d*)([-+,])(\d*)/', $expectedArgumentCount, $argMatch)) {
1160 1
                            $argMatch = ['', '', '', ''];
1161
                        }
1162 6089
                        switch ($argMatch[2]) {
1163 6089
                            case '+':
1164 1164
                                if ($argumentCount < $argMatch[1]) {
1165 27
                                    $argumentCountError = true;
1166 27
                                    $expectedArgumentCountString = $argMatch[1] . ' or more ';
1167
                                }
1168
1169 1164
                                break;
1170 5091
                            case '-':
1171 874
                                if (($argumentCount < $argMatch[1]) || ($argumentCount > $argMatch[3])) {
1172 15
                                    $argumentCountError = true;
1173 15
                                    $expectedArgumentCountString = 'between ' . $argMatch[1] . ' and ' . $argMatch[3];
1174
                                }
1175
1176 874
                                break;
1177 4256
                            case ',':
1178 4256
                                if (($argumentCount != $argMatch[1]) && ($argumentCount != $argMatch[3])) {
1179 39
                                    $argumentCountError = true;
1180 39
                                    $expectedArgumentCountString = 'either ' . $argMatch[1] . ' or ' . $argMatch[3];
1181
                                }
1182
1183 4256
                                break;
1184
                        }
1185
                    }
1186 11717
                    if ($argumentCountError) {
1187 223
                        return $this->raiseFormulaError("Formula Error: Wrong number of arguments for $functionName() function: $argumentCount given, " . $expectedArgumentCountString . ' expected');
1188
                    }
1189
                }
1190 11502
                ++$index;
1191 12103
            } elseif ($opCharacter === ',') { // Is this the separator for function arguments?
1192
                try {
1193 7986
                    $this->branchPruner->argumentSeparator();
1194
                } catch (Exception $e) {
1195
                    return $this->raiseFormulaError($e->getMessage(), $e->getCode(), $e);
1196
                }
1197
1198 7986
                while (($o2 = $stack->pop()) && $o2['value'] !== '(') {        //    Pop off the stack back to the last (
1199 1440
                    $output[] = $o2; // pop the argument expression stuff and push onto the output
1200
                }
1201
                //    If we've a comma when we're expecting an operand, then what we actually have is a null operand;
1202
                //        so push a null onto the stack
1203 7986
                if (($expectingOperand) || (!$expectingOperator)) {
1204 119
                    $output[] = $stack->getStackItem('Empty Argument', null, 'NULL');
1205
                }
1206
                // make sure there was a function
1207 7986
                $d = $stack->last(2);
1208 7986
                if (!preg_match('/^' . self::CALCULATION_REGEXP_FUNCTION . '$/miu', $d['value'] ?? '', $matches)) {
1209
                    // Can we inject a dummy function at this point so that the braces at least have some context
1210
                    //     because at least the braces are paired up (at this stage in the formula)
1211
                    // MS Excel allows this if the content is cell references; but doesn't allow actual values,
1212
                    //    but at this point, we can't differentiate (so allow both)
1213
                    return $this->raiseFormulaError('Formula Error: Unexpected ,');
1214
                }
1215
1216
                /** @var array<string, int> $d */
1217 7986
                $d = $stack->pop();
1218 7986
                ++$d['value']; // increment the argument count
1219
1220 7986
                $stack->pushStackItem($d);
1221 7986
                $stack->push('Brace', '('); // put the ( back on, we'll need to pop back to it again
1222
1223 7986
                $expectingOperator = false;
1224 7986
                $expectingOperand = true;
1225 7986
                ++$index;
1226 12103
            } elseif ($opCharacter === '(' && !$expectingOperator) {
1227
                // Branch pruning: we go deeper
1228 34
                $this->branchPruner->incrementDepth();
1229 34
                $stack->push('Brace', '(', null);
1230 34
                ++$index;
1231 12103
            } elseif ($isOperandOrFunction && !$expectingOperatorCopy) {
1232
                // do we now have a function/variable/number?
1233 12099
                $expectingOperator = true;
1234 12099
                $expectingOperand = false;
1235 12099
                $val = $match[1] ?? ''; //* @phpstan-ignore-line
1236 12099
                $length = strlen($val);
1237
1238 12099
                if (preg_match('/^' . self::CALCULATION_REGEXP_FUNCTION . '$/miu', $val, $matches)) {
1239 11723
                    $val = (string) preg_replace('/\s/u', '', $val);
1240 11723
                    if (isset($phpSpreadsheetFunctions[strtoupper($matches[1])]) || isset(self::$controlFunctions[strtoupper($matches[1])])) {    // it's a function
1241 11721
                        $valToUpper = strtoupper($val);
1242
                    } else {
1243 5
                        $valToUpper = 'NAME.ERROR(';
1244
                    }
1245
                    // here $matches[1] will contain values like "IF"
1246
                    // and $val "IF("
1247
1248 11723
                    $this->branchPruner->functionCall($valToUpper);
1249
1250 11723
                    $stack->push('Function', $valToUpper);
1251
                    // tests if the function is closed right after opening
1252 11723
                    $ax = preg_match('/^\s*\)/u', substr($formula, $index + $length));
1253 11723
                    if ($ax) {
1254 324
                        $stack->push('Operand Count for Function ' . $valToUpper . ')', 0);
1255 324
                        $expectingOperator = true;
1256
                    } else {
1257 11545
                        $stack->push('Operand Count for Function ' . $valToUpper . ')', 1);
1258 11545
                        $expectingOperator = false;
1259
                    }
1260 11723
                    $stack->push('Brace', '(');
1261 11898
                } elseif (preg_match('/^' . self::CALCULATION_REGEXP_CELLREF . '$/miu', $val, $matches)) {
1262
                    //    Watch for this case-change when modifying to allow cell references in different worksheets...
1263
                    //    Should only be applied to the actual cell column, not the worksheet name
1264
                    //    If the last entry on the stack was a : operator, then we have a cell range reference
1265 7009
                    $testPrevOp = $stack->last(1);
1266 7009
                    if ($testPrevOp !== null && $testPrevOp['value'] === ':') {
1267
                        //    If we have a worksheet reference, then we're playing with a 3D reference
1268 1214
                        if ($matches[2] === '') {
1269
                            //    Otherwise, we 'inherit' the worksheet reference from the start cell reference
1270
                            //    The start of the cell range reference should be the last entry in $output
1271 1210
                            $rangeStartCellRef = $output[count($output) - 1]['value'] ?? '';
1272 1210
                            if ($rangeStartCellRef === ':') {
1273
                                // Do we have chained range operators?
1274 5
                                $rangeStartCellRef = $output[count($output) - 2]['value'] ?? '';
1275
                            }
1276 1210
                            preg_match('/^' . self::CALCULATION_REGEXP_CELLREF . '$/miu', $rangeStartCellRef, $rangeStartMatches);
1277 1210
                            if (array_key_exists(2, $rangeStartMatches)) {
1278 1205
                                if ($rangeStartMatches[2] > '') {
1279 1188
                                    $val = $rangeStartMatches[2] . '!' . $val;
1280
                                }
1281
                            } else {
1282 5
                                $val = ExcelError::REF();
1283
                            }
1284
                        } else {
1285 4
                            $rangeStartCellRef = $output[count($output) - 1]['value'] ?? '';
1286 4
                            if ($rangeStartCellRef === ':') {
1287
                                // Do we have chained range operators?
1288
                                $rangeStartCellRef = $output[count($output) - 2]['value'] ?? '';
1289
                            }
1290 4
                            preg_match('/^' . self::CALCULATION_REGEXP_CELLREF . '$/miu', $rangeStartCellRef, $rangeStartMatches);
1291 4
                            if (isset($rangeStartMatches[2]) && $rangeStartMatches[2] !== $matches[2]) {
1292 2
                                return $this->raiseFormulaError('3D Range references are not yet supported');
1293
                            }
1294
                        }
1295 7004
                    } elseif (!str_contains($val, '!') && $pCellParent !== null) {
1296 6790
                        $worksheet = $pCellParent->getTitle();
1297 6790
                        $val = "'{$worksheet}'!{$val}";
1298
                    }
1299
                    // unescape any apostrophes or double quotes in worksheet name
1300 7009
                    $val = str_replace(["''", '""'], ["'", '"'], $val);
1301 7009
                    $outputItem = $stack->getStackItem('Cell Reference', $val, $val);
1302
1303 7009
                    $output[] = $outputItem;
1304 6332
                } elseif (preg_match('/^' . self::CALCULATION_REGEXP_STRUCTURED_REFERENCE . '$/miu', $val, $matches)) {
1305
                    try {
1306 75
                        $structuredReference = Operands\StructuredReference::fromParser($formula, $index, $matches);
1307
                    } catch (Exception $e) {
1308
                        return $this->raiseFormulaError($e->getMessage(), $e->getCode(), $e);
1309
                    }
1310
1311 75
                    $val = $structuredReference->value();
1312 75
                    $length = strlen($val);
1313 75
                    $outputItem = $stack->getStackItem(Operands\StructuredReference::NAME, $structuredReference, null);
1314
1315 75
                    $output[] = $outputItem;
1316 75
                    $expectingOperator = true;
1317
                } else {
1318
                    // it's a variable, constant, string, number or boolean
1319 6266
                    $localeConstant = false;
1320 6266
                    $stackItemType = 'Value';
1321 6266
                    $stackItemReference = null;
1322
1323
                    //    If the last entry on the stack was a : operator, then we may have a row or column range reference
1324 6266
                    $testPrevOp = $stack->last(1);
1325 6266
                    if ($testPrevOp !== null && $testPrevOp['value'] === ':') {
1326 38
                        $stackItemType = 'Cell Reference';
1327
1328
                        if (
1329 38
                            !is_numeric($val)
1330 38
                            && ((ctype_alpha($val) === false || strlen($val) > 3))
1331 38
                            && (preg_match('/^' . self::CALCULATION_REGEXP_DEFINEDNAME . '$/mui', $val) !== false)
1332 38
                            && ($this->spreadsheet === null || $this->spreadsheet->getNamedRange($val) !== null)
1333
                        ) {
1334 10
                            $namedRange = ($this->spreadsheet === null) ? null : $this->spreadsheet->getNamedRange($val);
1335 10
                            if ($namedRange !== null) {
1336 4
                                $stackItemType = 'Defined Name';
1337 4
                                $address = str_replace('$', '', $namedRange->getValue());
1338 4
                                $stackItemReference = $val;
1339 4
                                if (str_contains($address, ':')) {
1340
                                    // We'll need to manipulate the stack for an actual named range rather than a named cell
1341 3
                                    $fromTo = explode(':', $address);
1342 3
                                    $to = array_pop($fromTo);
1343 3
                                    foreach ($fromTo as $from) {
1344 3
                                        $output[] = $stack->getStackItem($stackItemType, $from, $stackItemReference);
1345 3
                                        $output[] = $stack->getStackItem('Binary Operator', ':');
1346
                                    }
1347 3
                                    $address = $to;
1348
                                }
1349 4
                                $val = $address;
1350
                            }
1351 34
                        } elseif ($val === ExcelError::REF()) {
1352 3
                            $stackItemReference = $val;
1353
                        } else {
1354
                            /** @var non-empty-string $startRowColRef */
1355 31
                            $startRowColRef = $output[count($output) - 1]['value'] ?? '';
1356 31
                            [$rangeWS1, $startRowColRef] = Worksheet::extractSheetTitle($startRowColRef, true);
1357 31
                            $rangeSheetRef = $rangeWS1;
1358 31
                            if ($rangeWS1 !== '') {
1359 19
                                $rangeWS1 .= '!';
1360
                            }
1361 31
                            if (str_starts_with($rangeSheetRef, "'")) {
1362 18
                                $rangeSheetRef = Worksheet::unApostrophizeTitle($rangeSheetRef);
1363
                            }
1364 31
                            [$rangeWS2, $val] = Worksheet::extractSheetTitle($val, true);
1365 31
                            if ($rangeWS2 !== '') {
1366
                                $rangeWS2 .= '!';
1367
                            } else {
1368 31
                                $rangeWS2 = $rangeWS1;
1369
                            }
1370
1371 31
                            $refSheet = $pCellParent;
1372 31
                            if ($pCellParent !== null && $rangeSheetRef !== '' && $rangeSheetRef !== $pCellParent->getTitle()) {
1373 4
                                $refSheet = $pCellParent->getParentOrThrow()->getSheetByName($rangeSheetRef);
1374
                            }
1375
1376 31
                            if (ctype_digit($val) && $val <= 1048576) {
1377
                                //    Row range
1378 10
                                $stackItemType = 'Row Reference';
1379 10
                                $valx = $val;
1380 10
                                $endRowColRef = ($refSheet !== null) ? $refSheet->getHighestDataColumn($valx) : AddressRange::MAX_COLUMN; //    Max 16,384 columns for Excel2007
1381 10
                                $val = "{$rangeWS2}{$endRowColRef}{$val}";
1382 21
                            } elseif (ctype_alpha($val) && strlen($val) <= 3) {
1383
                                //    Column range
1384 15
                                $stackItemType = 'Column Reference';
1385 15
                                $endRowColRef = ($refSheet !== null) ? $refSheet->getHighestDataRow($val) : AddressRange::MAX_ROW; //    Max 1,048,576 rows for Excel2007
1386 15
                                $val = "{$rangeWS2}{$val}{$endRowColRef}";
1387
                            }
1388 31
                            $stackItemReference = $val;
1389
                        }
1390 6261
                    } elseif ($opCharacter === self::FORMULA_STRING_QUOTE) {
1391
                        //    UnEscape any quotes within the string
1392 2818
                        $val = self::wrapResult(str_replace('""', self::FORMULA_STRING_QUOTE, StringHelper::convertToString(self::unwrapResult($val))));
1393 4649
                    } elseif (isset(self::EXCEL_CONSTANTS[trim(strtoupper($val))])) {
1394 555
                        $stackItemType = 'Constant';
1395 555
                        $excelConstant = trim(strtoupper($val));
1396 555
                        $val = self::EXCEL_CONSTANTS[$excelConstant];
1397 555
                        $stackItemReference = $excelConstant;
1398 4362
                    } elseif (($localeConstant = array_search(trim(strtoupper($val)), self::$localeBoolean)) !== false) {
1399 39
                        $stackItemType = 'Constant';
1400 39
                        $val = self::EXCEL_CONSTANTS[$localeConstant];
1401 39
                        $stackItemReference = $localeConstant;
1402
                    } elseif (
1403 4343
                        preg_match('/^' . self::CALCULATION_REGEXP_ROW_RANGE . '/miu', substr($formula, $index), $rowRangeReference)
1404
                    ) {
1405 10
                        $val = $rowRangeReference[1];
1406 10
                        $length = strlen($rowRangeReference[1]);
1407 10
                        $stackItemType = 'Row Reference';
1408
                        // unescape any apostrophes or double quotes in worksheet name
1409 10
                        $val = str_replace(["''", '""'], ["'", '"'], $val);
1410 10
                        $column = 'A';
1411 10
                        if (($testPrevOp !== null && $testPrevOp['value'] === ':') && $pCellParent !== null) {
1412
                            $column = $pCellParent->getHighestDataColumn($val);
1413
                        }
1414 10
                        $val = "{$rowRangeReference[2]}{$column}{$rowRangeReference[7]}";
1415 10
                        $stackItemReference = $val;
1416
                    } elseif (
1417 4336
                        preg_match('/^' . self::CALCULATION_REGEXP_COLUMN_RANGE . '/miu', substr($formula, $index), $columnRangeReference)
1418
                    ) {
1419 15
                        $val = $columnRangeReference[1];
1420 15
                        $length = strlen($val);
1421 15
                        $stackItemType = 'Column Reference';
1422
                        // unescape any apostrophes or double quotes in worksheet name
1423 15
                        $val = str_replace(["''", '""'], ["'", '"'], $val);
1424 15
                        $row = '1';
1425 15
                        if (($testPrevOp !== null && $testPrevOp['value'] === ':') && $pCellParent !== null) {
1426
                            $row = $pCellParent->getHighestDataRow($val);
1427
                        }
1428 15
                        $val = "{$val}{$row}";
1429 15
                        $stackItemReference = $val;
1430 4321
                    } elseif (preg_match('/^' . self::CALCULATION_REGEXP_DEFINEDNAME . '.*/miu', $val, $match)) {
1431 158
                        $stackItemType = 'Defined Name';
1432 158
                        $stackItemReference = $val;
1433 4192
                    } elseif (is_numeric($val)) {
1434 4186
                        if ((str_contains((string) $val, '.')) || (stripos((string) $val, 'e') !== false) || ($val > PHP_INT_MAX) || ($val < -PHP_INT_MAX)) {
1435 1671
                            $val = (float) $val;
1436
                        } else {
1437 3431
                            $val = (int) $val;
1438
                        }
1439
                    }
1440
1441 6266
                    $details = $stack->getStackItem($stackItemType, $val, $stackItemReference);
1442 6266
                    if ($localeConstant) {
1443 39
                        $details['localeValue'] = $localeConstant;
1444
                    }
1445 6266
                    $output[] = $details;
1446
                }
1447 12099
                $index += $length;
1448 95
            } elseif ($opCharacter === '$') { // absolute row or column range
1449 6
                ++$index;
1450 89
            } elseif ($opCharacter === ')') { // miscellaneous error checking
1451 83
                if ($expectingOperand) {
1452 83
                    $output[] = $stack->getStackItem('Empty Argument', null, 'NULL');
1453 83
                    $expectingOperand = false;
1454 83
                    $expectingOperator = true;
1455
                } else {
1456
                    return $this->raiseFormulaError("Formula Error: Unexpected ')'");
1457
                }
1458 6
            } elseif (isset(self::CALCULATION_OPERATORS[$opCharacter]) && !$expectingOperator) {
1459
                return $this->raiseFormulaError("Formula Error: Unexpected operator '$opCharacter'");
1460
            } else {    // I don't even want to know what you did to get here
1461 6
                return $this->raiseFormulaError('Formula Error: An unexpected error occurred');
1462
            }
1463
            //    Test for end of formula string
1464 12099
            if ($index == strlen($formula)) {
1465
                //    Did we end with an operator?.
1466
                //    Only valid for the % unary operator
1467 11875
                if ((isset(self::CALCULATION_OPERATORS[$opCharacter])) && ($opCharacter != '%')) {
1468 1
                    return $this->raiseFormulaError("Formula Error: Operator '$opCharacter' has no operands");
1469
                }
1470
1471 11874
                break;
1472
            }
1473
            //    Ignore white space
1474 12067
            while (($formula[$index] === "\n") || ($formula[$index] === "\r")) {
1475
                ++$index;
1476
            }
1477
1478 12067
            if ($formula[$index] === ' ') {
1479 2056
                while ($formula[$index] === ' ') {
1480 2056
                    ++$index;
1481
                }
1482
1483
                //    If we're expecting an operator, but only have a space between the previous and next operands (and both are
1484
                //        Cell References, Defined Names or Structured References) then we have an INTERSECTION operator
1485 2056
                $countOutputMinus1 = count($output) - 1;
1486
                if (
1487 2056
                    ($expectingOperator)
1488 2056
                    && array_key_exists($countOutputMinus1, $output)
1489 2056
                    && is_array($output[$countOutputMinus1])
1490 2056
                    && array_key_exists('type', $output[$countOutputMinus1])
1491
                    && (
1492 2056
                        (preg_match('/^' . self::CALCULATION_REGEXP_CELLREF . '.*/miu', substr($formula, $index), $match))
1493 2056
                            && ($output[$countOutputMinus1]['type'] === 'Cell Reference')
1494 2056
                        || (preg_match('/^' . self::CALCULATION_REGEXP_DEFINEDNAME . '.*/miu', substr($formula, $index), $match))
1495 2056
                            && ($output[$countOutputMinus1]['type'] === 'Defined Name' || $output[$countOutputMinus1]['type'] === 'Value')
1496 2056
                        || (preg_match('/^' . self::CALCULATION_REGEXP_STRUCTURED_REFERENCE . '.*/miu', substr($formula, $index), $match))
1497 2056
                            && ($output[$countOutputMinus1]['type'] === Operands\StructuredReference::NAME || $output[$countOutputMinus1]['type'] === 'Value')
1498
                    )
1499
                ) {
1500 19
                    while (self::swapOperands($stack, $opCharacter)) {
1501 12
                        $output[] = $stack->pop(); //    Swap operands and higher precedence operators from the stack to the output
1502
                    }
1503 19
                    $stack->push('Binary Operator', '∩'); //    Put an Intersect Operator on the stack
1504 19
                    $expectingOperator = false;
1505
                }
1506
            }
1507
        }
1508
1509 11874
        while (($op = $stack->pop()) !== null) {
1510
            // pop everything off the stack and push onto output
1511 725
            if ($op['value'] == '(') {
1512 4
                return $this->raiseFormulaError("Formula Error: Expecting ')'"); // if there are any opening braces on the stack, then braces were unbalanced
1513
            }
1514 723
            $output[] = $op;
1515
        }
1516
1517 11872
        return $output;
1518
    }
1519
1520
    /** @param mixed[] $operandData */
1521 1671
    private static function dataTestReference(array &$operandData): mixed
1522
    {
1523 1671
        $operand = $operandData['value'];
1524 1671
        if (($operandData['reference'] === null) && (is_array($operand))) {
1525 42
            $rKeys = array_keys($operand);
1526 42
            $rowKey = array_shift($rKeys);
1527 42
            if (is_array($operand[$rowKey]) === false) {
1528 6
                $operandData['value'] = $operand[$rowKey];
1529
1530 6
                return $operand[$rowKey];
1531
            }
1532
1533 40
            $cKeys = array_keys(array_keys($operand[$rowKey]));
1534 40
            $colKey = array_shift($cKeys);
1535 40
            if (ctype_upper("$colKey")) {
1536
                $operandData['reference'] = $colKey . $rowKey;
1537
            }
1538
        }
1539
1540 1671
        return $operand;
1541
    }
1542
1543
    private static int $matchIndex8 = 8;
1544
1545
    private static int $matchIndex9 = 9;
1546
1547
    private static int $matchIndex10 = 10;
1548
1549
    /**
1550
     * @return array<int, mixed>|false|string
1551
     */
1552 11739
    private function processTokenStack(false|array $tokens, ?string $cellID = null, ?Cell $cell = null)
1553
    {
1554 11739
        if ($tokens === false) {
1555 2
            return false;
1556
        }
1557 11738
        $phpSpreadsheetFunctions = &self::getFunctionsAddress();
1558
1559
        //    If we're using cell caching, then $pCell may well be flushed back to the cache (which detaches the parent cell collection),
1560
        //        so we store the parent cell collection so that we can re-attach it when necessary
1561 11738
        $pCellWorksheet = ($cell !== null) ? $cell->getWorksheet() : null;
1562 11738
        $originalCoordinate = $cell?->getCoordinate();
1563 11738
        $pCellParent = ($cell !== null) ? $cell->getParent() : null;
1564 11738
        $stack = new Stack($this->branchPruner);
1565
1566
        // Stores branches that have been pruned
1567 11738
        $fakedForBranchPruning = [];
1568
        // help us to know when pruning ['branchTestId' => true/false]
1569 11738
        $branchStore = [];
1570
        //    Loop through each token in turn
1571 11738
        foreach ($tokens as $tokenIdx => $tokenData) {
1572 11738
            $this->processingAnchorArray = false;
1573 11738
            if ($tokenData['type'] === 'Cell Reference' && isset($tokens[$tokenIdx + 1]) && $tokens[$tokenIdx + 1]['type'] === 'Operand Count for Function ANCHORARRAY()') {
1574 6
                $this->processingAnchorArray = true;
1575
            }
1576 11738
            $token = $tokenData['value'];
1577
            // Branch pruning: skip useless resolutions
1578 11738
            $storeKey = $tokenData['storeKey'] ?? null;
1579 11738
            if ($this->branchPruningEnabled && isset($tokenData['onlyIf'])) {
1580 83
                $onlyIfStoreKey = $tokenData['onlyIf'];
1581 83
                $storeValue = $branchStore[$onlyIfStoreKey] ?? null;
1582 83
                $storeValueAsBool = ($storeValue === null)
1583 83
                    ? true : (bool) Functions::flattenSingleValue($storeValue);
1584 83
                if (is_array($storeValue)) {
1585 56
                    $wrappedItem = end($storeValue);
1586 56
                    $storeValue = is_array($wrappedItem) ? end($wrappedItem) : $wrappedItem;
1587
                }
1588
1589
                if (
1590 83
                    (isset($storeValue) || $tokenData['reference'] === 'NULL')
1591 83
                    && (!$storeValueAsBool || Information\ErrorValue::isError($storeValue) || ($storeValue === 'Pruned branch'))
1592
                ) {
1593
                    // If branching value is not true, we don't need to compute
1594 60
                    if (!isset($fakedForBranchPruning['onlyIf-' . $onlyIfStoreKey])) {
1595 58
                        $stack->push('Value', 'Pruned branch (only if ' . $onlyIfStoreKey . ') ' . $token);
1596 58
                        $fakedForBranchPruning['onlyIf-' . $onlyIfStoreKey] = true;
1597
                    }
1598
1599 60
                    if (isset($storeKey)) {
1600
                        // We are processing an if condition
1601
                        // We cascade the pruning to the depending branches
1602 3
                        $branchStore[$storeKey] = 'Pruned branch';
1603 3
                        $fakedForBranchPruning['onlyIfNot-' . $storeKey] = true;
1604 3
                        $fakedForBranchPruning['onlyIf-' . $storeKey] = true;
1605
                    }
1606
1607 60
                    continue;
1608
                }
1609
            }
1610
1611 11738
            if ($this->branchPruningEnabled && isset($tokenData['onlyIfNot'])) {
1612 78
                $onlyIfNotStoreKey = $tokenData['onlyIfNot'];
1613 78
                $storeValue = $branchStore[$onlyIfNotStoreKey] ?? null;
1614 78
                $storeValueAsBool = ($storeValue === null)
1615 78
                    ? true : (bool) Functions::flattenSingleValue($storeValue);
1616 78
                if (is_array($storeValue)) {
1617 51
                    $wrappedItem = end($storeValue);
1618 51
                    $storeValue = is_array($wrappedItem) ? end($wrappedItem) : $wrappedItem;
1619
                }
1620
1621
                if (
1622 78
                    (isset($storeValue) || $tokenData['reference'] === 'NULL')
1623 78
                    && ($storeValueAsBool || Information\ErrorValue::isError($storeValue) || ($storeValue === 'Pruned branch'))
1624
                ) {
1625
                    // If branching value is true, we don't need to compute
1626 56
                    if (!isset($fakedForBranchPruning['onlyIfNot-' . $onlyIfNotStoreKey])) {
1627 56
                        $stack->push('Value', 'Pruned branch (only if not ' . $onlyIfNotStoreKey . ') ' . $token);
1628 56
                        $fakedForBranchPruning['onlyIfNot-' . $onlyIfNotStoreKey] = true;
1629
                    }
1630
1631 56
                    if (isset($storeKey)) {
1632
                        // We are processing an if condition
1633
                        // We cascade the pruning to the depending branches
1634 10
                        $branchStore[$storeKey] = 'Pruned branch';
1635 10
                        $fakedForBranchPruning['onlyIfNot-' . $storeKey] = true;
1636 10
                        $fakedForBranchPruning['onlyIf-' . $storeKey] = true;
1637
                    }
1638
1639 56
                    continue;
1640
                }
1641
            }
1642
1643 11738
            if ($token instanceof Operands\StructuredReference) {
1644 16
                if ($cell === null) {
1645
                    return $this->raiseFormulaError('Structured References must exist in a Cell context');
1646
                }
1647
1648
                try {
1649 16
                    $cellRange = $token->parse($cell);
1650 16
                    if (str_contains($cellRange, ':')) {
1651 7
                        $this->debugLog->writeDebugLog('Evaluating Structured Reference %s as Cell Range %s', $token->value(), $cellRange);
1652 7
                        $rangeValue = self::getInstance($cell->getWorksheet()->getParent())->_calculateFormulaValue("={$cellRange}", $cellRange, $cell);
1653 7
                        $stack->push('Value', $rangeValue);
1654 7
                        $this->debugLog->writeDebugLog('Evaluated Structured Reference %s as value %s', $token->value(), $this->showValue($rangeValue));
1655
                    } else {
1656 10
                        $this->debugLog->writeDebugLog('Evaluating Structured Reference %s as Cell %s', $token->value(), $cellRange);
1657 10
                        $cellValue = $cell->getWorksheet()->getCell($cellRange)->getCalculatedValue(false);
1658 10
                        $stack->push('Cell Reference', $cellValue, $cellRange);
1659 16
                        $this->debugLog->writeDebugLog('Evaluated Structured Reference %s as value %s', $token->value(), $this->showValue($cellValue));
1660
                    }
1661 2
                } catch (Exception $e) {
1662 2
                    if ($e->getCode() === Exception::CALCULATION_ENGINE_PUSH_TO_STACK) {
1663 2
                        $stack->push('Error', ExcelError::REF(), null);
1664 2
                        $this->debugLog->writeDebugLog('Evaluated Structured Reference %s as error value %s', $token->value(), ExcelError::REF());
1665
                    } else {
1666
                        return $this->raiseFormulaError($e->getMessage(), $e->getCode(), $e);
1667
                    }
1668
                }
1669 11737
            } elseif (!is_numeric($token) && !is_object($token) && isset(self::BINARY_OPERATORS[$token])) {
1670
                // if the token is a binary operator, pop the top two values off the stack, do the operation, and push the result back on the stack
1671
                //    We must have two operands, error if we don't
1672 1671
                $operand2Data = $stack->pop();
1673 1671
                if ($operand2Data === null) {
1674
                    return $this->raiseFormulaError('Internal error - Operand value missing from stack');
1675
                }
1676 1671
                $operand1Data = $stack->pop();
1677 1671
                if ($operand1Data === null) {
1678
                    return $this->raiseFormulaError('Internal error - Operand value missing from stack');
1679
                }
1680
1681 1671
                $operand1 = self::dataTestReference($operand1Data);
1682 1671
                $operand2 = self::dataTestReference($operand2Data);
1683
1684
                //    Log what we're doing
1685 1671
                if ($token == ':') {
1686 1193
                    $this->debugLog->writeDebugLog('Evaluating Range %s %s %s', $this->showValue($operand1Data['reference']), $token, $this->showValue($operand2Data['reference']));
1687
                } else {
1688 732
                    $this->debugLog->writeDebugLog('Evaluating %s %s %s', $this->showValue($operand1), $token, $this->showValue($operand2));
1689
                }
1690
1691
                //    Process the operation in the appropriate manner
1692
                switch ($token) {
1693
                    // Comparison (Boolean) Operators
1694 1671
                    case '>': // Greater than
1695 1656
                    case '<': // Less than
1696 1639
                    case '>=': // Greater than or Equal to
1697 1631
                    case '<=': // Less than or Equal to
1698 1613
                    case '=': // Equality
1699 1461
                    case '<>': // Inequality
1700 410
                        $result = $this->executeBinaryComparisonOperation($operand1, $operand2, (string) $token, $stack);
1701 410
                        if (isset($storeKey)) {
1702 70
                            $branchStore[$storeKey] = $result;
1703
                        }
1704
1705 410
                        break;
1706
                    // Binary Operators
1707 1451
                    case ':': // Range
1708 1193
                        if ($operand1Data['type'] === 'Defined Name') {
1709 3
                            if (preg_match('/$' . self::CALCULATION_REGEXP_DEFINEDNAME . '^/mui', $operand1Data['reference']) !== false && $this->spreadsheet !== null) {
1710 3
                                $definedName = $this->spreadsheet->getNamedRange($operand1Data['reference']);
1711 3
                                if ($definedName !== null) {
1712 3
                                    $operand1Data['reference'] = $operand1Data['value'] = str_replace('$', '', $definedName->getValue());
1713
                                }
1714
                            }
1715
                        }
1716 1193
                        if (str_contains($operand1Data['reference'] ?? '', '!')) {
1717 1184
                            [$sheet1, $operand1Data['reference']] = Worksheet::extractSheetTitle($operand1Data['reference'], true, true);
1718
                        } else {
1719 13
                            $sheet1 = ($pCellWorksheet !== null) ? $pCellWorksheet->getTitle() : '';
1720
                        }
1721 1193
                        $sheet1 ??= '';
1722
1723
                        /** @var string */
1724 1193
                        $op2ref = $operand2Data['reference'];
1725 1193
                        [$sheet2, $operand2Data['reference']] = Worksheet::extractSheetTitle($op2ref, true, true);
1726 1193
                        if (empty($sheet2)) {
1727 7
                            $sheet2 = $sheet1;
1728
                        }
1729
1730 1193
                        if ($sheet1 === $sheet2) {
1731 1190
                            if ($operand1Data['reference'] === null && $cell !== null) {
1732
                                if (is_array($operand1Data['value'])) {
1733
                                    $operand1Data['reference'] = $cell->getCoordinate();
1734
                                } elseif ((trim($operand1Data['value']) != '') && (is_numeric($operand1Data['value']))) {
1735
                                    $operand1Data['reference'] = $cell->getColumn() . $operand1Data['value'];
1736
                                } elseif (trim($operand1Data['value']) == '') {
1737
                                    $operand1Data['reference'] = $cell->getCoordinate();
1738
                                } else {
1739
                                    $operand1Data['reference'] = $operand1Data['value'] . $cell->getRow();
1740
                                }
1741
                            }
1742 1190
                            if ($operand2Data['reference'] === null && $cell !== null) {
1743 2
                                if (is_array($operand2Data['value'])) {
1744 1
                                    $operand2Data['reference'] = $cell->getCoordinate();
1745 1
                                } elseif ((trim($operand2Data['value']) != '') && (is_numeric($operand2Data['value']))) {
1746
                                    $operand2Data['reference'] = $cell->getColumn() . $operand2Data['value'];
1747 1
                                } elseif (trim($operand2Data['value']) == '') {
1748
                                    $operand2Data['reference'] = $cell->getCoordinate();
1749
                                } else {
1750 1
                                    $operand2Data['reference'] = $operand2Data['value'] . $cell->getRow();
1751
                                }
1752
                            }
1753
1754 1190
                            $oData = array_merge(explode(':', $operand1Data['reference'] ?? ''), explode(':', $operand2Data['reference'] ?? ''));
1755 1190
                            $oCol = $oRow = [];
1756 1190
                            $breakNeeded = false;
1757 1190
                            foreach ($oData as $oDatum) {
1758
                                try {
1759 1190
                                    $oCR = Coordinate::coordinateFromString($oDatum);
1760 1190
                                    $oCol[] = Coordinate::columnIndexFromString($oCR[0]) - 1;
1761 1190
                                    $oRow[] = $oCR[1];
1762 1
                                } catch (\Exception) {
1763 1
                                    $stack->push('Error', ExcelError::REF(), null);
1764 1
                                    $breakNeeded = true;
1765
1766 1
                                    break;
1767
                                }
1768
                            }
1769 1190
                            if ($breakNeeded) {
1770 1
                                break;
1771
                            }
1772 1189
                            $cellRef = Coordinate::stringFromColumnIndex(min($oCol) + 1) . min($oRow) . ':' . Coordinate::stringFromColumnIndex(max($oCol) + 1) . max($oRow); // @phpstan-ignore-line
1773 1189
                            if ($pCellParent !== null && $this->spreadsheet !== null) {
1774 1189
                                $cellValue = $this->extractCellRange($cellRef, $this->spreadsheet->getSheetByName($sheet1), false);
1775
                            } else {
1776
                                return $this->raiseFormulaError('Unable to access Cell Reference');
1777
                            }
1778
1779 1189
                            $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($cellValue));
1780 1189
                            $stack->push('Cell Reference', $cellValue, $cellRef);
1781
                        } else {
1782 4
                            $this->debugLog->writeDebugLog('Evaluation Result is a #REF! Error');
1783 4
                            $stack->push('Error', ExcelError::REF(), null);
1784
                        }
1785
1786 1192
                        break;
1787 388
                    case '+':            //    Addition
1788 308
                    case '-':            //    Subtraction
1789 268
                    case '*':            //    Multiplication
1790 141
                    case '/':            //    Division
1791 45
                    case '^':            //    Exponential
1792 360
                        $result = $this->executeNumericBinaryOperation($operand1, $operand2, $token, $stack);
1793 360
                        if (isset($storeKey)) {
1794 5
                            $branchStore[$storeKey] = $result;
1795
                        }
1796
1797 360
                        break;
1798 41
                    case '&':            //    Concatenation
1799
                        //    If either of the operands is a matrix, we need to treat them both as matrices
1800
                        //        (converting the other operand to a matrix if need be); then perform the required
1801
                        //        matrix operation
1802 26
                        $operand1 = self::boolToString($operand1);
1803 26
                        $operand2 = self::boolToString($operand2);
1804 26
                        if (is_array($operand1) || is_array($operand2)) {
1805 16
                            if (is_string($operand1)) {
1806 7
                                $operand1 = self::unwrapResult($operand1);
1807
                            }
1808 16
                            if (is_string($operand2)) {
1809 5
                                $operand2 = self::unwrapResult($operand2);
1810
                            }
1811
                            //    Ensure that both operands are arrays/matrices
1812 16
                            [$rows, $columns] = self::checkMatrixOperands($operand1, $operand2, 2);
1813
1814 16
                            for ($row = 0; $row < $rows; ++$row) {
1815 16
                                for ($column = 0; $column < $columns; ++$column) {
1816 16
                                    $op1x = self::boolToString($operand1[$row][$column]);
1817 16
                                    $op2x = self::boolToString($operand2[$row][$column]);
1818 16
                                    if (Information\ErrorValue::isError($op1x)) {
1819
                                        // no need to do anything
1820 16
                                    } elseif (Information\ErrorValue::isError($op2x)) {
1821 1
                                        $operand1[$row][$column] = $op2x;
1822
                                    } else {
1823
                                        /** @var string $op1x */
1824
                                        /** @var string $op2x */
1825 15
                                        $operand1[$row][$column]
1826 15
                                            = StringHelper::substring(
1827 15
                                                $op1x . $op2x,
1828 15
                                                0,
1829 15
                                                DataType::MAX_STRING_LENGTH
1830 15
                                            );
1831
                                    }
1832
                                }
1833
                            }
1834 16
                            $result = $operand1;
1835
                        } else {
1836 12
                            if (Information\ErrorValue::isError($operand1)) {
1837
                                $result = $operand1;
1838 12
                            } elseif (Information\ErrorValue::isError($operand2)) {
1839
                                $result = $operand2;
1840
                            } else {
1841 12
                                $result = str_replace('""', self::FORMULA_STRING_QUOTE, self::unwrapResult($operand1) . self::unwrapResult($operand2)); //* @phpstan-ignore-line
1842 12
                                $result = StringHelper::substring(
1843 12
                                    $result,
1844 12
                                    0,
1845 12
                                    DataType::MAX_STRING_LENGTH
1846 12
                                );
1847 12
                                $result = self::FORMULA_STRING_QUOTE . $result . self::FORMULA_STRING_QUOTE;
1848
                            }
1849
                        }
1850 26
                        $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($result));
1851 26
                        $stack->push('Value', $result);
1852
1853 26
                        if (isset($storeKey)) {
1854
                            $branchStore[$storeKey] = $result;
1855
                        }
1856
1857 26
                        break;
1858 15
                    case '∩':            //    Intersect
1859
                        /** @var mixed[][] $operand1 */
1860
                        /** @var mixed[][] $operand2 */
1861 15
                        $rowIntersect = array_intersect_key($operand1, $operand2);
1862 15
                        $cellIntersect = $oCol = $oRow = [];
1863 15
                        foreach (array_keys($rowIntersect) as $row) {
1864 15
                            $oRow[] = $row;
1865 15
                            foreach ($rowIntersect[$row] as $col => $data) {
1866 15
                                $oCol[] = Coordinate::columnIndexFromString($col) - 1;
1867 15
                                $cellIntersect[$row] = array_intersect_key($operand1[$row], $operand2[$row]);
1868
                            }
1869
                        }
1870 15
                        if (count(Functions::flattenArray($cellIntersect)) === 0) {
1871 2
                            $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($cellIntersect));
1872 2
                            $stack->push('Error', ExcelError::null(), null);
1873
                        } else {
1874 13
                            $cellRef = Coordinate::stringFromColumnIndex(min($oCol) + 1) . min($oRow) . ':' // @phpstan-ignore-line
1875 13
                                . Coordinate::stringFromColumnIndex(max($oCol) + 1) . max($oRow); // @phpstan-ignore-line
1876 13
                            $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($cellIntersect));
1877 13
                            $stack->push('Value', $cellIntersect, $cellRef);
1878
                        }
1879
1880 15
                        break;
1881
                }
1882 11730
            } elseif (($token === '~') || ($token === '%')) {
1883
                // if the token is a unary operator, pop one value off the stack, do the operation, and push it back on
1884 1144
                if (($arg = $stack->pop()) === null) {
1885
                    return $this->raiseFormulaError('Internal error - Operand value missing from stack');
1886
                }
1887 1144
                $arg = $arg['value'];
1888 1144
                if ($token === '~') {
1889 1140
                    $this->debugLog->writeDebugLog('Evaluating Negation of %s', $this->showValue($arg));
1890 1140
                    $multiplier = -1;
1891
                } else {
1892 6
                    $this->debugLog->writeDebugLog('Evaluating Percentile of %s', $this->showValue($arg));
1893 6
                    $multiplier = 0.01;
1894
                }
1895 1144
                if (is_array($arg)) {
1896 4
                    $operand2 = $multiplier;
1897 4
                    $result = $arg;
1898 4
                    [$rows, $columns] = self::checkMatrixOperands($result, $operand2, 0);
1899 4
                    for ($row = 0; $row < $rows; ++$row) {
1900 4
                        for ($column = 0; $column < $columns; ++$column) {
1901 4
                            if (self::isNumericOrBool($result[$row][$column])) {
1902 4
                                $result[$row][$column] *= $multiplier;
1903
                            } else {
1904 2
                                $result[$row][$column] = self::makeError($result[$row][$column]);
1905
                            }
1906
                        }
1907
                    }
1908
1909 4
                    $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($result));
1910 4
                    $stack->push('Value', $result);
1911 4
                    if (isset($storeKey)) {
1912
                        $branchStore[$storeKey] = $result;
1913
                    }
1914
                } else {
1915 1143
                    $this->executeNumericBinaryOperation($multiplier, $arg, '*', $stack);
1916
                }
1917 11730
            } elseif (preg_match('/^' . self::CALCULATION_REGEXP_CELLREF . '$/i', $token ?? '', $matches)) {
1918 6905
                $cellRef = null;
1919
1920
                /* Phpstan says matches[8/9/10] is never set,
1921
                   and code coverage report seems to confirm.
1922
                   Appease PhpStan for now;
1923
                   probably delete this block later.
1924
                */
1925 6905
                if (isset($matches[self::$matchIndex8])) {
1926
                    if ($cell === null) {
1927
                        // We can't access the range, so return a REF error
1928
                        $cellValue = ExcelError::REF();
1929
                    } else {
1930
                        $cellRef = $matches[6] . $matches[7] . ':' . $matches[self::$matchIndex9] . $matches[self::$matchIndex10];
1931
                        if ($matches[2] > '') {
1932
                            $matches[2] = trim($matches[2], "\"'");
1933
                            if ((str_contains($matches[2], '[')) || (str_contains($matches[2], ']'))) {
1934
                                //    It's a Reference to an external spreadsheet (not currently supported)
1935
                                return $this->raiseFormulaError('Unable to access External Workbook');
1936
                            }
1937
                            $matches[2] = trim($matches[2], "\"'");
1938
                            $this->debugLog->writeDebugLog('Evaluating Cell Range %s in worksheet %s', $cellRef, $matches[2]);
1939
                            if ($pCellParent !== null && $this->spreadsheet !== null) {
1940
                                $cellValue = $this->extractCellRange($cellRef, $this->spreadsheet->getSheetByName($matches[2]), false);
1941
                            } else {
1942
                                return $this->raiseFormulaError('Unable to access Cell Reference');
1943
                            }
1944
                            $this->debugLog->writeDebugLog('Evaluation Result for cells %s in worksheet %s is %s', $cellRef, $matches[2], $this->showTypeDetails($cellValue));
1945
                        } else {
1946
                            $this->debugLog->writeDebugLog('Evaluating Cell Range %s in current worksheet', $cellRef);
1947
                            if ($pCellParent !== null) {
1948
                                $cellValue = $this->extractCellRange($cellRef, $pCellWorksheet, false);
1949
                            } else {
1950
                                return $this->raiseFormulaError('Unable to access Cell Reference');
1951
                            }
1952
                            $this->debugLog->writeDebugLog('Evaluation Result for cells %s is %s', $cellRef, $this->showTypeDetails($cellValue));
1953
                        }
1954
                    }
1955
                } else {
1956 6905
                    if ($cell === null) {
1957
                        // We can't access the cell, so return a REF error
1958
                        $cellValue = ExcelError::REF();
1959
                    } else {
1960 6905
                        $cellRef = $matches[6] . $matches[7];
1961 6905
                        if ($matches[2] > '') {
1962 6898
                            $matches[2] = trim($matches[2], "\"'");
1963 6898
                            if ((str_contains($matches[2], '[')) || (str_contains($matches[2], ']'))) {
1964
                                //    It's a Reference to an external spreadsheet (not currently supported)
1965 1
                                return $this->raiseFormulaError('Unable to access External Workbook');
1966
                            }
1967 6898
                            $this->debugLog->writeDebugLog('Evaluating Cell %s in worksheet %s', $cellRef, $matches[2]);
1968 6898
                            if ($pCellParent !== null && $this->spreadsheet !== null) {
1969 6898
                                $cellSheet = $this->spreadsheet->getSheetByName($matches[2]);
1970 6898
                                if ($cellSheet && $cellSheet->cellExists($cellRef)) {
1971 6773
                                    $cellValue = $this->extractCellRange($cellRef, $this->spreadsheet->getSheetByName($matches[2]), false);
1972 6773
                                    $cell->attach($pCellParent);
1973
                                } else {
1974 340
                                    $cellRef = ($cellSheet !== null) ? "'{$matches[2]}'!{$cellRef}" : $cellRef;
1975 340
                                    $cellValue = ($cellSheet !== null) ? null : ExcelError::REF();
1976
                                }
1977
                            } else {
1978
                                return $this->raiseFormulaError('Unable to access Cell Reference');
1979
                            }
1980 6898
                            $this->debugLog->writeDebugLog('Evaluation Result for cell %s in worksheet %s is %s', $cellRef, $matches[2], $this->showTypeDetails($cellValue));
1981
                        } else {
1982 11
                            $this->debugLog->writeDebugLog('Evaluating Cell %s in current worksheet', $cellRef);
1983 11
                            if ($pCellParent !== null && $pCellParent->has($cellRef)) {
1984 11
                                $cellValue = $this->extractCellRange($cellRef, $pCellWorksheet, false);
1985 11
                                $cell->attach($pCellParent);
1986
                            } else {
1987 2
                                $cellValue = null;
1988
                            }
1989 11
                            $this->debugLog->writeDebugLog('Evaluation Result for cell %s is %s', $cellRef, $this->showTypeDetails($cellValue));
1990
                        }
1991
                    }
1992
                }
1993
1994 6905
                if ($this->getInstanceArrayReturnType() === self::RETURN_ARRAY_AS_ARRAY && !$this->processingAnchorArray && is_array($cellValue)) {
1995 129
                    while (is_array($cellValue)) {
1996 129
                        $cellValue = array_shift($cellValue);
1997
                    }
1998 129
                    if (is_string($cellValue)) {
1999 94
                        $cellValue = preg_replace('/"/', '""', $cellValue);
2000
                    }
2001 129
                    $this->debugLog->writeDebugLog('Scalar Result for cell %s is %s', $cellRef, $this->showTypeDetails($cellValue));
2002
                }
2003 6905
                $this->processingAnchorArray = false;
2004 6905
                $stack->push('Cell Value', $cellValue, $cellRef);
2005 6905
                if (isset($storeKey)) {
2006 58
                    $branchStore[$storeKey] = $cellValue;
2007
                }
2008 11647
            } elseif (preg_match('/^' . self::CALCULATION_REGEXP_FUNCTION . '$/miu', $token ?? '', $matches)) {
2009
                // if the token is a function, pop arguments off the stack, hand them to the function, and push the result back on
2010 11426
                if ($cell !== null && $pCellParent !== null) {
2011 7848
                    $cell->attach($pCellParent);
2012
                }
2013
2014 11426
                $functionName = $matches[1];
2015
                /** @var array<string, int> $argCount */
2016 11426
                $argCount = $stack->pop();
2017 11426
                $argCount = $argCount['value'];
2018 11426
                if ($functionName !== 'MKMATRIX') {
2019 11425
                    $this->debugLog->writeDebugLog('Evaluating Function %s() with %s argument%s', self::localeFunc($functionName), (($argCount == 0) ? 'no' : $argCount), (($argCount == 1) ? '' : 's'));
2020
                }
2021 11426
                if ((isset($phpSpreadsheetFunctions[$functionName])) || (isset(self::$controlFunctions[$functionName]))) {    // function
2022 11426
                    $passByReference = false;
2023 11426
                    $passCellReference = false;
2024 11426
                    $functionCall = null;
2025 11426
                    if (isset($phpSpreadsheetFunctions[$functionName])) {
2026 11423
                        $functionCall = $phpSpreadsheetFunctions[$functionName]['functionCall'];
2027 11423
                        $passByReference = isset($phpSpreadsheetFunctions[$functionName]['passByReference']);
2028 11423
                        $passCellReference = isset($phpSpreadsheetFunctions[$functionName]['passCellReference']);
2029 816
                    } elseif (isset(self::$controlFunctions[$functionName])) {
2030 816
                        $functionCall = self::$controlFunctions[$functionName]['functionCall'];
2031 816
                        $passByReference = isset(self::$controlFunctions[$functionName]['passByReference']);
2032 816
                        $passCellReference = isset(self::$controlFunctions[$functionName]['passCellReference']);
2033
                    }
2034
2035
                    // get the arguments for this function
2036 11426
                    $args = $argArrayVals = [];
2037 11426
                    $emptyArguments = [];
2038 11426
                    for ($i = 0; $i < $argCount; ++$i) {
2039 11408
                        $arg = $stack->pop();
2040 11408
                        $a = $argCount - $i - 1;
2041
                        if (
2042 11408
                            ($passByReference)
2043 11408
                            && (isset($phpSpreadsheetFunctions[$functionName]['passByReference'][$a])) //* @phpstan-ignore-line
2044 11408
                            && ($phpSpreadsheetFunctions[$functionName]['passByReference'][$a])
2045
                        ) {
2046
                            /** @var mixed[] $arg */
2047 70
                            if ($arg['reference'] === null) {
2048 6
                                $nextArg = $cellID;
2049 6
                                if ($functionName === 'ISREF' && ($arg['type'] ?? '') === 'Value') {
2050 5
                                    if (array_key_exists('value', $arg)) {
2051 5
                                        $argValue = $arg['value'];
2052 5
                                        if (is_scalar($argValue)) {
2053 2
                                            $nextArg = $argValue;
2054 3
                                        } elseif (empty($argValue)) {
2055 1
                                            $nextArg = '';
2056
                                        }
2057
                                    }
2058
                                }
2059 6
                                $args[] = $nextArg;
2060 6
                                if ($functionName !== 'MKMATRIX') {
2061 6
                                    $argArrayVals[] = $this->showValue($cellID);
2062
                                }
2063
                            } else {
2064 64
                                $args[] = $arg['reference'];
2065 64
                                if ($functionName !== 'MKMATRIX') {
2066 64
                                    $argArrayVals[] = $this->showValue($arg['reference']);
2067
                                }
2068
                            }
2069
                        } else {
2070
                            /** @var mixed[] $arg */
2071 11363
                            if ($arg['type'] === 'Empty Argument' && in_array($functionName, ['MIN', 'MINA', 'MAX', 'MAXA', 'IF'], true)) {
2072 15
                                $emptyArguments[] = false;
2073 15
                                $args[] = $arg['value'] = 0;
2074 15
                                $this->debugLog->writeDebugLog('Empty Argument reevaluated as 0');
2075
                            } else {
2076 11363
                                $emptyArguments[] = $arg['type'] === 'Empty Argument';
2077 11363
                                $args[] = self::unwrapResult($arg['value']);
2078
                            }
2079 11363
                            if ($functionName !== 'MKMATRIX') {
2080 11362
                                $argArrayVals[] = $this->showValue($arg['value']);
2081
                            }
2082
                        }
2083
                    }
2084
2085
                    //    Reverse the order of the arguments
2086 11426
                    krsort($args);
2087 11426
                    krsort($emptyArguments);
2088
2089 11426
                    if ($argCount > 0 && is_array($functionCall)) {
2090
                        /** @var string[] */
2091 11408
                        $functionCallCopy = $functionCall;
2092 11408
                        $args = $this->addDefaultArgumentValues($functionCallCopy, $args, $emptyArguments);
2093
                    }
2094
2095 11426
                    if (($passByReference) && ($argCount == 0)) {
2096 9
                        $args[] = $cellID;
2097 9
                        $argArrayVals[] = $this->showValue($cellID);
2098
                    }
2099
2100 11426
                    if ($functionName !== 'MKMATRIX') {
2101 11425
                        if ($this->debugLog->getWriteDebugLog()) {
2102 2
                            krsort($argArrayVals);
2103 2
                            $this->debugLog->writeDebugLog('Evaluating %s ( %s )', self::localeFunc($functionName), implode(self::$localeArgumentSeparator . ' ', Functions::flattenArray($argArrayVals)));
2104
                        }
2105
                    }
2106
2107
                    //    Process the argument with the appropriate function call
2108 11426
                    if ($pCellWorksheet !== null && $originalCoordinate !== null) {
2109 7848
                        $pCellWorksheet->getCell($originalCoordinate);
2110
                    }
2111
                    /** @var array<string>|string $functionCall */
2112 11426
                    $args = $this->addCellReference($args, $passCellReference, $functionCall, $cell);
2113
2114 11426
                    if (!is_array($functionCall)) {
2115 53
                        foreach ($args as &$arg) {
2116
                            $arg = Functions::flattenSingleValue($arg);
2117
                        }
2118 53
                        unset($arg);
2119
                    }
2120
2121
                    /** @var callable $functionCall */
2122 11426
                    $result = call_user_func_array($functionCall, $args);
2123
2124 11420
                    if ($functionName !== 'MKMATRIX') {
2125 11417
                        $this->debugLog->writeDebugLog('Evaluation Result for %s() function call is %s', self::localeFunc($functionName), $this->showTypeDetails($result));
2126
                    }
2127 11420
                    $stack->push('Value', self::wrapResult($result));
2128 11420
                    if (isset($storeKey)) {
2129 22
                        $branchStore[$storeKey] = $result;
2130
                    }
2131
                }
2132
            } else {
2133
                // if the token is a number, boolean, string or an Excel error, push it onto the stack
2134 11647
                if (isset(self::EXCEL_CONSTANTS[strtoupper($token ?? '')])) {
2135
                    $excelConstant = strtoupper($token);
2136
                    $stack->push('Constant Value', self::EXCEL_CONSTANTS[$excelConstant]);
2137
                    if (isset($storeKey)) {
2138
                        $branchStore[$storeKey] = self::EXCEL_CONSTANTS[$excelConstant];
2139
                    }
2140
                    $this->debugLog->writeDebugLog('Evaluating Constant %s as %s', $excelConstant, $this->showTypeDetails(self::EXCEL_CONSTANTS[$excelConstant]));
2141 11647
                } elseif ((is_numeric($token)) || ($token === null) || (is_bool($token)) || ($token == '') || ($token[0] == self::FORMULA_STRING_QUOTE) || ($token[0] == '#')) {
2142 11590
                    $stack->push($tokenData['type'], $token, $tokenData['reference']);
2143 11590
                    if (isset($storeKey)) {
2144 73
                        $branchStore[$storeKey] = $token;
2145
                    }
2146 152
                } elseif (preg_match('/^' . self::CALCULATION_REGEXP_DEFINEDNAME . '$/miu', $token, $matches)) {
2147
                    // if the token is a named range or formula, evaluate it and push the result onto the stack
2148 152
                    $definedName = $matches[6];
2149 152
                    if (str_starts_with($definedName, '_xleta')) {
2150 1
                        return Functions::NOT_YET_IMPLEMENTED;
2151
                    }
2152 151
                    if ($cell === null || $pCellWorksheet === null) {
2153
                        return $this->raiseFormulaError("undefined name '$token'");
2154
                    }
2155 151
                    $specifiedWorksheet = trim($matches[2], "'");
2156
2157 151
                    $this->debugLog->writeDebugLog('Evaluating Defined Name %s', $definedName);
2158 151
                    $namedRange = DefinedName::resolveName($definedName, $pCellWorksheet, $specifiedWorksheet);
2159
                    // If not Defined Name, try as Table.
2160 151
                    if ($namedRange === null && $this->spreadsheet !== null) {
2161 36
                        $table = $this->spreadsheet->getTableByName($definedName);
2162 36
                        if ($table !== null) {
2163 3
                            $tableRange = Coordinate::getRangeBoundaries($table->getRange());
2164 3
                            if ($table->getShowHeaderRow()) {
2165 3
                                ++$tableRange[0][1];
2166
                            }
2167 3
                            if ($table->getShowTotalsRow()) {
2168
                                --$tableRange[1][1];
2169
                            }
2170 3
                            $tableRangeString
2171 3
                                = '$' . $tableRange[0][0]
2172 3
                                . '$' . $tableRange[0][1]
2173 3
                                . ':'
2174 3
                                . '$' . $tableRange[1][0]
2175 3
                                . '$' . $tableRange[1][1];
2176 3
                            $namedRange = new NamedRange($definedName, $table->getWorksheet(), $tableRangeString);
2177
                        }
2178
                    }
2179 151
                    if ($namedRange === null) {
2180 33
                        return $this->raiseFormulaError("undefined name '$definedName'");
2181
                    }
2182
2183 129
                    $result = $this->evaluateDefinedName($cell, $namedRange, $pCellWorksheet, $stack, $specifiedWorksheet !== '');
2184
2185 129
                    if (isset($storeKey)) {
2186 1
                        $branchStore[$storeKey] = $result;
2187
                    }
2188
                } else {
2189
                    return $this->raiseFormulaError("undefined name '$token'");
2190
                }
2191
            }
2192
        }
2193
        // when we're out of tokens, the stack should have a single element, the final result
2194 11708
        if ($stack->count() != 1) {
2195 1
            return $this->raiseFormulaError('internal error');
2196
        }
2197
        /** @var array<string, array<int, mixed>|false|string> */
2198 11708
        $output = $stack->pop();
2199 11708
        $output = $output['value'];
2200
2201 11708
        return $output;
2202
    }
2203
2204 1439
    private function validateBinaryOperand(mixed &$operand, Stack &$stack): bool
2205
    {
2206 1439
        if (is_array($operand)) {
2207 223
            if ((count($operand, COUNT_RECURSIVE) - count($operand)) == 1) {
2208
                do {
2209 190
                    $operand = array_pop($operand);
2210 190
                } while (is_array($operand));
2211
            }
2212
        }
2213
        //    Numbers, matrices and booleans can pass straight through, as they're already valid
2214 1439
        if (is_string($operand)) {
2215
            //    We only need special validations for the operand if it is a string
2216
            //    Start by stripping off the quotation marks we use to identify true excel string values internally
2217 16
            if ($operand > '' && $operand[0] == self::FORMULA_STRING_QUOTE) {
2218 5
                $operand = StringHelper::convertToString(self::unwrapResult($operand));
2219
            }
2220
            //    If the string is a numeric value, we treat it as a numeric, so no further testing
2221 16
            if (!is_numeric($operand)) {
2222
                //    If not a numeric, test to see if the value is an Excel error, and so can't be used in normal binary operations
2223 15
                if ($operand > '' && $operand[0] == '#') {
2224 6
                    $stack->push('Value', $operand);
2225 6
                    $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($operand));
2226
2227 6
                    return false;
2228 11
                } elseif (Engine\FormattedNumber::convertToNumberIfFormatted($operand) === false) {
2229
                    //    If not a numeric, a fraction or a percentage, then it's a text string, and so can't be used in mathematical binary operations
2230 6
                    $stack->push('Error', '#VALUE!');
2231 6
                    $this->debugLog->writeDebugLog('Evaluation Result is a %s', $this->showTypeDetails('#VALUE!'));
2232
2233 6
                    return false;
2234
                }
2235
            }
2236
        }
2237
2238
        //    return a true if the value of the operand is one that we can use in normal binary mathematical operations
2239 1437
        return true;
2240
    }
2241
2242
    /** @return mixed[] */
2243 54
    private function executeArrayComparison(mixed $operand1, mixed $operand2, string $operation, Stack &$stack, bool $recursingArrays): array
2244
    {
2245 54
        $result = [];
2246 54
        if (!is_array($operand2) && is_array($operand1)) {
2247
            // Operand 1 is an array, Operand 2 is a scalar
2248 51
            foreach ($operand1 as $x => $operandData) {
2249 51
                $this->debugLog->writeDebugLog('Evaluating Comparison %s %s %s', $this->showValue($operandData), $operation, $this->showValue($operand2));
2250 51
                $this->executeBinaryComparisonOperation($operandData, $operand2, $operation, $stack);
2251
                /** @var array<string, mixed> $r */
2252 51
                $r = $stack->pop();
2253 51
                $result[$x] = $r['value'];
2254
            }
2255 10
        } elseif (is_array($operand2) && !is_array($operand1)) {
2256
            // Operand 1 is a scalar, Operand 2 is an array
2257 3
            foreach ($operand2 as $x => $operandData) {
2258 3
                $this->debugLog->writeDebugLog('Evaluating Comparison %s %s %s', $this->showValue($operand1), $operation, $this->showValue($operandData));
2259 3
                $this->executeBinaryComparisonOperation($operand1, $operandData, $operation, $stack);
2260
                /** @var array<string, mixed> $r */
2261 3
                $r = $stack->pop();
2262 3
                $result[$x] = $r['value'];
2263
            }
2264 9
        } elseif (is_array($operand2) && is_array($operand1)) {
2265
            // Operand 1 and Operand 2 are both arrays
2266 9
            if (!$recursingArrays) {
2267 9
                self::checkMatrixOperands($operand1, $operand2, 2);
2268
            }
2269 9
            foreach ($operand1 as $x => $operandData) {
2270 9
                $this->debugLog->writeDebugLog('Evaluating Comparison %s %s %s', $this->showValue($operandData), $operation, $this->showValue($operand2[$x]));
2271 9
                $this->executeBinaryComparisonOperation($operandData, $operand2[$x], $operation, $stack, true);
2272
                /** @var array<string, mixed> $r */
2273 9
                $r = $stack->pop();
2274 9
                $result[$x] = $r['value'];
2275
            }
2276
        } else {
2277
            throw new Exception('Neither operand is an arra');
2278
        }
2279
        //    Log the result details
2280 54
        $this->debugLog->writeDebugLog('Comparison Evaluation Result is %s', $this->showTypeDetails($result));
2281
        //    And push the result onto the stack
2282 54
        $stack->push('Array', $result);
2283
2284 54
        return $result;
2285
    }
2286
2287
    /** @return bool|mixed[] */
2288 410
    private function executeBinaryComparisonOperation(mixed $operand1, mixed $operand2, string $operation, Stack &$stack, bool $recursingArrays = false): array|bool
2289
    {
2290
        //    If we're dealing with matrix operations, we want a matrix result
2291 410
        if ((is_array($operand1)) || (is_array($operand2))) {
2292 54
            return $this->executeArrayComparison($operand1, $operand2, $operation, $stack, $recursingArrays);
2293
        }
2294
2295 410
        $result = BinaryComparison::compare($operand1, $operand2, $operation);
2296
2297
        //    Log the result details
2298 410
        $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($result));
2299
        //    And push the result onto the stack
2300 410
        $stack->push('Value', $result);
2301
2302 410
        return $result;
2303
    }
2304
2305 1439
    private function executeNumericBinaryOperation(mixed $operand1, mixed $operand2, string $operation, Stack &$stack): mixed
2306
    {
2307
        //    Validate the two operands
2308
        if (
2309 1439
            ($this->validateBinaryOperand($operand1, $stack) === false)
2310 1439
            || ($this->validateBinaryOperand($operand2, $stack) === false)
2311
        ) {
2312 10
            return false;
2313
        }
2314
2315
        if (
2316 1432
            (Functions::getCompatibilityMode() != Functions::COMPATIBILITY_OPENOFFICE)
2317 1432
            && ((is_string($operand1) && !is_numeric($operand1) && $operand1 !== '')
2318 1432
                || (is_string($operand2) && !is_numeric($operand2) && $operand2 !== ''))
2319
        ) {
2320
            $result = ExcelError::VALUE();
2321 1432
        } elseif (is_array($operand1) || is_array($operand2)) {
2322
            //    Ensure that both operands are arrays/matrices
2323 35
            if (is_array($operand1)) {
2324 29
                foreach ($operand1 as $key => $value) {
2325 29
                    $operand1[$key] = Functions::flattenArray($value);
2326
                }
2327
            }
2328 35
            if (is_array($operand2)) {
2329 29
                foreach ($operand2 as $key => $value) {
2330 29
                    $operand2[$key] = Functions::flattenArray($value);
2331
                }
2332
            }
2333 35
            [$rows, $columns] = self::checkMatrixOperands($operand1, $operand2, 3);
2334
2335 35
            for ($row = 0; $row < $rows; ++$row) {
2336 35
                for ($column = 0; $column < $columns; ++$column) {
2337 35
                    if ($operand1[$row][$column] === null) {
2338 1
                        $operand1[$row][$column] = 0;
2339 35
                    } elseif (!self::isNumericOrBool($operand1[$row][$column])) {
2340 1
                        $operand1[$row][$column] = self::makeError($operand1[$row][$column]);
2341
2342 1
                        continue;
2343
                    }
2344 35
                    if ($operand2[$row][$column] === null) {
2345 1
                        $operand2[$row][$column] = 0;
2346 35
                    } elseif (!self::isNumericOrBool($operand2[$row][$column])) {
2347
                        $operand1[$row][$column] = self::makeError($operand2[$row][$column]);
2348
2349
                        continue;
2350
                    }
2351
                    /** @var float|int */
2352 35
                    $operand1Val = $operand1[$row][$column];
2353
                    /** @var float|int */
2354 35
                    $operand2Val = $operand2[$row][$column];
2355
                    switch ($operation) {
2356 35
                        case '+':
2357 3
                            $operand1[$row][$column] = $operand1Val + $operand2Val;
2358
2359 3
                            break;
2360 32
                        case '-':
2361 3
                            $operand1[$row][$column] = $operand1Val - $operand2Val;
2362
2363 3
                            break;
2364 30
                        case '*':
2365 23
                            $operand1[$row][$column] = $operand1Val * $operand2Val;
2366
2367 23
                            break;
2368 7
                        case '/':
2369 5
                            if ($operand2Val == 0) {
2370 3
                                $operand1[$row][$column] = ExcelError::DIV0();
2371
                            } else {
2372 4
                                $operand1[$row][$column] = $operand1Val / $operand2Val;
2373
                            }
2374
2375 5
                            break;
2376 2
                        case '^':
2377 2
                            $operand1[$row][$column] = $operand1Val ** $operand2Val;
2378
2379 2
                            break;
2380
2381
                        default:
2382
                            throw new Exception('Unsupported numeric binary operation');
2383
                    }
2384
                }
2385
            }
2386 35
            $result = $operand1;
2387
        } else {
2388
            //    If we're dealing with non-matrix operations, execute the necessary operation
2389
            /** @var float|int $operand1 */
2390
            /** @var float|int $operand2 */
2391
            switch ($operation) {
2392
                //    Addition
2393 1416
                case '+':
2394 161
                    $result = $operand1 + $operand2;
2395
2396 161
                    break;
2397
                //    Subtraction
2398 1337
                case '-':
2399 51
                    $result = $operand1 - $operand2;
2400
2401 51
                    break;
2402
                //    Multiplication
2403 1302
                case '*':
2404 1240
                    $result = $operand1 * $operand2;
2405
2406 1240
                    break;
2407
                //    Division
2408 96
                case '/':
2409 94
                    if ($operand2 == 0) {
2410
                        //    Trap for Divide by Zero error
2411 43
                        $stack->push('Error', ExcelError::DIV0());
2412 43
                        $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails(ExcelError::DIV0()));
2413
2414 43
                        return false;
2415
                    }
2416 61
                    $result = $operand1 / $operand2;
2417
2418 61
                    break;
2419
                //    Power
2420 3
                case '^':
2421 3
                    $result = $operand1 ** $operand2;
2422
2423 3
                    break;
2424
2425
                default:
2426
                    throw new Exception('Unsupported numeric binary operation');
2427
            }
2428
        }
2429
2430
        //    Log the result details
2431 1404
        $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($result));
2432
        //    And push the result onto the stack
2433 1404
        $stack->push('Value', $result);
2434
2435 1404
        return $result;
2436
    }
2437
2438
    /**
2439
     * Trigger an error, but nicely, if need be.
2440
     *
2441
     * @return false
2442
     */
2443 271
    protected function raiseFormulaError(string $errorMessage, int $code = 0, ?Throwable $exception = null): bool
2444
    {
2445 271
        $this->formulaError = $errorMessage;
2446 271
        $this->cyclicReferenceStack->clear();
2447 271
        $suppress = $this->suppressFormulaErrors;
2448 271
        if (!$suppress) {
2449 270
            throw new Exception($errorMessage, $code, $exception);
2450
        }
2451
2452 2
        return false;
2453
    }
2454
2455
    /**
2456
     * Extract range values.
2457
     *
2458
     * @param string $range String based range representation
2459
     * @param ?Worksheet $worksheet Worksheet
2460
     * @param bool $resetLog Flag indicating whether calculation log should be reset or not
2461
     *
2462
     * @return mixed[] Array of values in range if range contains more than one element. Otherwise, a single value is returned.
2463
     */
2464 6865
    public function extractCellRange(string &$range = 'A1', ?Worksheet $worksheet = null, bool $resetLog = true): array
2465
    {
2466
        // Return value
2467 6865
        $returnValue = [];
2468
2469 6865
        if ($worksheet !== null) {
2470 6864
            $worksheetName = $worksheet->getTitle();
2471
2472 6864
            if (str_contains($range, '!')) {
2473 10
                [$worksheetName, $range] = Worksheet::extractSheetTitle($range, true, true);
2474 10
                $worksheet = ($this->spreadsheet === null) ? null : $this->spreadsheet->getSheetByName($worksheetName);
2475
            }
2476
2477
            // Extract range
2478 6864
            $aReferences = Coordinate::extractAllCellReferencesInRange($range);
2479 6864
            $range = "'" . $worksheetName . "'" . '!' . $range;
2480 6864
            $currentCol = '';
2481 6864
            $currentRow = 0;
2482 6864
            if (!isset($aReferences[1])) {
2483
                //    Single cell in range
2484 6826
                sscanf($aReferences[0], '%[A-Z]%d', $currentCol, $currentRow);
2485 6826
                if ($worksheet !== null && $worksheet->cellExists($aReferences[0])) {
2486 6824
                    $temp = $worksheet->getCell($aReferences[0])->getCalculatedValue($resetLog);
2487 6824
                    if ($this->getInstanceArrayReturnType() === self::RETURN_ARRAY_AS_ARRAY) {
2488 131
                        while (is_array($temp)) {
2489 8
                            $temp = array_shift($temp);
2490
                        }
2491
                    }
2492 6824
                    $returnValue[$currentRow][$currentCol] = $temp;
2493
                } else {
2494 5
                    $returnValue[$currentRow][$currentCol] = null;
2495
                }
2496
            } else {
2497
                // Extract cell data for all cells in the range
2498 1192
                foreach ($aReferences as $reference) {
2499
                    // Extract range
2500 1192
                    sscanf($reference, '%[A-Z]%d', $currentCol, $currentRow);
2501 1192
                    if ($worksheet !== null && $worksheet->cellExists($reference)) {
2502 1153
                        $temp = $worksheet->getCell($reference)->getCalculatedValue($resetLog);
2503 1153
                        if ($this->getInstanceArrayReturnType() === self::RETURN_ARRAY_AS_ARRAY) {
2504 110
                            while (is_array($temp)) {
2505 1
                                $temp = array_shift($temp);
2506
                            }
2507
                        }
2508 1153
                        $returnValue[$currentRow][$currentCol] = $temp;
2509
                    } else {
2510 174
                        $returnValue[$currentRow][$currentCol] = null;
2511
                    }
2512
                }
2513
            }
2514
        }
2515
2516 6865
        return $returnValue;
2517
    }
2518
2519
    /**
2520
     * Extract range values.
2521
     *
2522
     * @param string $range String based range representation
2523
     * @param null|Worksheet $worksheet Worksheet
2524
     * @param bool $resetLog Flag indicating whether calculation log should be reset or not
2525
     *
2526
     * @return mixed[]|string Array of values in range if range contains more than one element. Otherwise, a single value is returned.
2527
     */
2528
    public function extractNamedRange(string &$range = 'A1', ?Worksheet $worksheet = null, bool $resetLog = true): string|array
2529
    {
2530
        // Return value
2531
        $returnValue = [];
2532
2533
        if ($worksheet !== null) {
2534
            if (str_contains($range, '!')) {
2535
                [$worksheetName, $range] = Worksheet::extractSheetTitle($range, true, true);
2536
                $worksheet = ($this->spreadsheet === null) ? null : $this->spreadsheet->getSheetByName($worksheetName);
2537
            }
2538
2539
            // Named range?
2540
            $namedRange = ($worksheet === null) ? null : DefinedName::resolveName($range, $worksheet);
2541
            if ($namedRange === null) {
2542
                return ExcelError::REF();
2543
            }
2544
2545
            $worksheet = $namedRange->getWorksheet();
2546
            $range = $namedRange->getValue();
2547
            $splitRange = Coordinate::splitRange($range);
2548
            //    Convert row and column references
2549
            if ($worksheet !== null && ctype_alpha($splitRange[0][0])) {
2550
                $range = $splitRange[0][0] . '1:' . $splitRange[0][1] . $worksheet->getHighestRow();
2551
            } elseif ($worksheet !== null && ctype_digit($splitRange[0][0])) {
2552
                $range = 'A' . $splitRange[0][0] . ':' . $worksheet->getHighestColumn() . $splitRange[0][1];
2553
            }
2554
2555
            // Extract range
2556
            $aReferences = Coordinate::extractAllCellReferencesInRange($range);
2557
            if (!isset($aReferences[1])) {
2558
                //    Single cell (or single column or row) in range
2559
                [$currentCol, $currentRow] = Coordinate::coordinateFromString($aReferences[0]);
2560
                if ($worksheet !== null && $worksheet->cellExists($aReferences[0])) {
2561
                    $returnValue[$currentRow][$currentCol] = $worksheet->getCell($aReferences[0])->getCalculatedValue($resetLog);
2562
                } else {
2563
                    $returnValue[$currentRow][$currentCol] = null;
2564
                }
2565
            } else {
2566
                // Extract cell data for all cells in the range
2567
                foreach ($aReferences as $reference) {
2568
                    // Extract range
2569
                    [$currentCol, $currentRow] = Coordinate::coordinateFromString($reference);
2570
                    if ($worksheet !== null && $worksheet->cellExists($reference)) {
2571
                        $returnValue[$currentRow][$currentCol] = $worksheet->getCell($reference)->getCalculatedValue($resetLog);
2572
                    } else {
2573
                        $returnValue[$currentRow][$currentCol] = null;
2574
                    }
2575
                }
2576
            }
2577
        }
2578
2579
        return $returnValue;
2580
    }
2581
2582
    /**
2583
     * Is a specific function implemented?
2584
     *
2585
     * @param string $function Function Name
2586
     */
2587 3
    public function isImplemented(string $function): bool
2588
    {
2589 3
        $function = strtoupper($function);
2590 3
        $phpSpreadsheetFunctions = &self::getFunctionsAddress();
2591 3
        $notImplemented = !isset($phpSpreadsheetFunctions[$function]) || (is_array($phpSpreadsheetFunctions[$function]['functionCall']) && $phpSpreadsheetFunctions[$function]['functionCall'][1] === 'DUMMY');
2592
2593 3
        return !$notImplemented;
2594
    }
2595
2596
    /**
2597
     * Get a list of implemented Excel function names.
2598
     *
2599
     * @return string[]
2600
     */
2601 2
    public function getImplementedFunctionNames(): array
2602
    {
2603 2
        $returnValue = [];
2604 2
        $phpSpreadsheetFunctions = &self::getFunctionsAddress();
2605 2
        foreach ($phpSpreadsheetFunctions as $functionName => $function) {
2606 2
            if ($this->isImplemented($functionName)) {
2607 2
                $returnValue[] = $functionName;
2608
            }
2609
        }
2610
2611 2
        return $returnValue;
2612
    }
2613
2614
    /**
2615
     * @param string[] $functionCall
2616
     * @param mixed[] $args
2617
     * @param mixed[] $emptyArguments
2618
     *
2619
     * @return mixed[]
2620
     */
2621 11408
    private function addDefaultArgumentValues(array $functionCall, array $args, array $emptyArguments): array
2622
    {
2623 11408
        $reflector = new ReflectionMethod($functionCall[0], $functionCall[1]);
2624 11408
        $methodArguments = $reflector->getParameters();
2625
2626 11408
        if (count($methodArguments) > 0) {
2627
            // Apply any defaults for empty argument values
2628 11401
            foreach ($emptyArguments as $argumentId => $isArgumentEmpty) {
2629 11356
                if ($isArgumentEmpty === true) {
2630 147
                    $reflectedArgumentId = count($args) - (int) $argumentId - 1;
2631
                    if (
2632 147
                        !array_key_exists($reflectedArgumentId, $methodArguments)
2633 147
                        || $methodArguments[$reflectedArgumentId]->isVariadic()
2634
                    ) {
2635 12
                        break;
2636
                    }
2637
2638 135
                    $args[$argumentId] = $this->getArgumentDefaultValue($methodArguments[$reflectedArgumentId]);
2639
                }
2640
            }
2641
        }
2642
2643 11408
        return $args;
2644
    }
2645
2646 135
    private function getArgumentDefaultValue(ReflectionParameter $methodArgument): mixed
2647
    {
2648 135
        $defaultValue = null;
2649
2650 135
        if ($methodArgument->isDefaultValueAvailable()) {
2651 63
            $defaultValue = $methodArgument->getDefaultValue();
2652 63
            if ($methodArgument->isDefaultValueConstant()) {
2653 2
                $constantName = $methodArgument->getDefaultValueConstantName() ?? '';
2654
                // read constant value
2655 2
                if (str_contains($constantName, '::')) {
2656 2
                    [$className, $constantName] = explode('::', $constantName);
2657 2
                    $constantReflector = new ReflectionClassConstant($className, $constantName);
2658
2659 2
                    return $constantReflector->getValue();
2660
                }
2661
2662
                return constant($constantName);
2663
            }
2664
        }
2665
2666 134
        return $defaultValue;
2667
    }
2668
2669
    /**
2670
     * Add cell reference if needed while making sure that it is the last argument.
2671
     *
2672
     * @param mixed[] $args
2673
     * @param string|string[] $functionCall
2674
     *
2675
     * @return mixed[]
2676
     */
2677 11426
    private function addCellReference(array $args, bool $passCellReference, array|string $functionCall, ?Cell $cell = null): array
2678
    {
2679 11426
        if ($passCellReference) {
2680 226
            if (is_array($functionCall)) {
2681 226
                $className = $functionCall[0];
2682 226
                $methodName = $functionCall[1];
2683
2684 226
                $reflectionMethod = new ReflectionMethod($className, $methodName);
2685 226
                $argumentCount = count($reflectionMethod->getParameters());
2686 226
                while (count($args) < $argumentCount - 1) {
2687 55
                    $args[] = null;
2688
                }
2689
            }
2690
2691 226
            $args[] = $cell;
2692
        }
2693
2694 11426
        return $args;
2695
    }
2696
2697 129
    private function evaluateDefinedName(Cell $cell, DefinedName $namedRange, Worksheet $cellWorksheet, Stack $stack, bool $ignoreScope = false): mixed
2698
    {
2699 129
        $definedNameScope = $namedRange->getScope();
2700 129
        if ($definedNameScope !== null && $definedNameScope !== $cellWorksheet && !$ignoreScope) {
2701
            // The defined name isn't in our current scope, so #REF
2702
            $result = ExcelError::REF();
2703
            $stack->push('Error', $result, $namedRange->getName());
2704
2705
            return $result;
2706
        }
2707
2708 129
        $definedNameValue = $namedRange->getValue();
2709 129
        $definedNameType = $namedRange->isFormula() ? 'Formula' : 'Range';
2710 129
        $definedNameWorksheet = $namedRange->getWorksheet();
2711
2712 129
        if ($definedNameValue[0] !== '=') {
2713 106
            $definedNameValue = '=' . $definedNameValue;
2714
        }
2715
2716 129
        $this->debugLog->writeDebugLog('Defined Name is a %s with a value of %s', $definedNameType, $definedNameValue);
2717
2718 129
        $originalCoordinate = $cell->getCoordinate();
2719 129
        $recursiveCalculationCell = ($definedNameType !== 'Formula' && $definedNameWorksheet !== null && $definedNameWorksheet !== $cellWorksheet)
2720 16
            ? $definedNameWorksheet->getCell('A1')
2721 122
            : $cell;
2722 129
        $recursiveCalculationCellAddress = $recursiveCalculationCell->getCoordinate();
2723
2724
        // Adjust relative references in ranges and formulae so that we execute the calculation for the correct rows and columns
2725 129
        $definedNameValue = ReferenceHelper::getInstance()
2726 129
            ->updateFormulaReferencesAnyWorksheet(
2727 129
                $definedNameValue,
2728 129
                Coordinate::columnIndexFromString(
2729 129
                    $cell->getColumn()
2730 129
                ) - 1,
2731 129
                $cell->getRow() - 1
2732 129
            );
2733
2734 129
        $this->debugLog->writeDebugLog('Value adjusted for relative references is %s', $definedNameValue);
2735
2736 129
        $recursiveCalculator = new self($this->spreadsheet);
2737 129
        $recursiveCalculator->getDebugLog()->setWriteDebugLog($this->getDebugLog()->getWriteDebugLog());
2738 129
        $recursiveCalculator->getDebugLog()->setEchoDebugLog($this->getDebugLog()->getEchoDebugLog());
2739 129
        $result = $recursiveCalculator->_calculateFormulaValue($definedNameValue, $recursiveCalculationCellAddress, $recursiveCalculationCell, true);
2740 129
        $cellWorksheet->getCell($originalCoordinate);
2741
2742 129
        if ($this->getDebugLog()->getWriteDebugLog()) {
2743
            $this->debugLog->mergeDebugLog(array_slice($recursiveCalculator->getDebugLog()->getLog(), 3));
2744
            $this->debugLog->writeDebugLog('Evaluation Result for Named %s %s is %s', $definedNameType, $namedRange->getName(), $this->showTypeDetails($result));
2745
        }
2746
2747 129
        $stack->push('Defined Name', $result, $namedRange->getName());
2748
2749 129
        return $result;
2750
    }
2751
2752 10
    public function setSuppressFormulaErrors(bool $suppressFormulaErrors): self
2753
    {
2754 10
        $this->suppressFormulaErrors = $suppressFormulaErrors;
2755
2756 10
        return $this;
2757
    }
2758
2759 12
    public function getSuppressFormulaErrors(): bool
2760
    {
2761 12
        return $this->suppressFormulaErrors;
2762
    }
2763
2764 30
    public static function boolToString(mixed $operand1): mixed
2765
    {
2766 30
        if (is_bool($operand1)) {
2767 1
            $operand1 = ($operand1) ? self::$localeBoolean['TRUE'] : self::$localeBoolean['FALSE'];
2768 30
        } elseif ($operand1 === null) {
2769
            $operand1 = '';
2770
        }
2771
2772 30
        return $operand1;
2773
    }
2774
2775 39
    private static function isNumericOrBool(mixed $operand): bool
2776
    {
2777 39
        return is_numeric($operand) || is_bool($operand);
2778
    }
2779
2780 3
    private static function makeError(mixed $operand = ''): string
2781
    {
2782 3
        return (is_string($operand) && Information\ErrorValue::isError($operand)) ? $operand : ExcelError::VALUE();
2783
    }
2784
2785 1798
    private static function swapOperands(Stack $stack, string $opCharacter): bool
2786
    {
2787 1798
        $retVal = false;
2788 1798
        if ($stack->count() > 0) {
2789 1321
            $o2 = $stack->last();
2790 1321
            if ($o2) {
2791 1321
                if (isset(self::CALCULATION_OPERATORS[$o2['value']])) {
2792 117
                    $retVal = (self::OPERATOR_PRECEDENCE[$opCharacter] ?? 0) <= self::OPERATOR_PRECEDENCE[$o2['value']];
2793
                }
2794
            }
2795
        }
2796
2797 1798
        return $retVal;
2798
    }
2799
2800 2
    public function getSpreadsheet(): ?Spreadsheet
2801
    {
2802 2
        return $this->spreadsheet;
2803
    }
2804
}
2805