Failed Conditions
Pull Request — master (#4474)
by Owen
12:47
created

Calculation::getImplementedFunctionNames()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3

Importance

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