Calculation   F
last analyzed

Complexity

Total Complexity 661

Size/Duplication

Total Lines 2820
Duplicated Lines 0 %

Test Coverage

Coverage 87.64%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 661
eloc 1476
dl 0
loc 2820
ccs 1212
cts 1383
cp 0.8764
rs 0.8
c 2
b 0
f 0

61 Methods

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