Completed
Push — master ( a907f1...ea97af )
by
unknown
36s queued 25s
created

Calculation::getSuppressFormulaErrors()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

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