Calculation::dataTestReference()   A
last analyzed

Complexity

Conditions 5
Paths 4

Size

Total Lines 20
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 5.0113

Importance

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