Passed
Pull Request — master (#4419)
by Owen
13:44
created

Calculation::renameCalculationCacheForWorksheet()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 3.1852

Importance

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