Passed
Push — master ( 3e93d4...2d1f4e )
by
unknown
24:41 queued 16:58
created

Calculation::_calculateFormulaValue()   D

Complexity

Conditions 20
Paths 52

Size

Total Lines 67
Code Lines 37

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 37
CRAP Score 20.0072

Importance

Changes 0
Metric Value
eloc 37
dl 0
loc 67
rs 4.1666
c 0
b 0
f 0
ccs 37
cts 38
cp 0.9737
cc 20
nc 52
nop 4
crap 20.0072

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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