Failed Conditions
Push — master ( 5868f8...b1beaf )
by
unknown
21:24 queued 09:39
created

Calculation::getLocale()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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