Failed Conditions
Pull Request — master (#4398)
by Owen
15:22
created

Calculation::setCalculationCacheEnabled()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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