Passed
Push — master ( 41da84...3cb7b3 )
by
unknown
13:24 queued 13s
created

Calculation::executeBinaryComparisonOperation()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 15
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

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