Passed
Push — master ( c54d55...902d4b )
by
unknown
18:58 queued 07:59
created

Calculation::getBranchPruningEnabled()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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