Passed
Push — master ( 6ec2cc...20aac0 )
by
unknown
20:38 queued 09:43
created

Calculation   F

Complexity

Total Complexity 726

Size/Duplication

Total Lines 3125
Duplicated Lines 0 %

Test Coverage

Coverage 88.61%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 726
eloc 1649
dl 0
loc 3125
ccs 1362
cts 1537
cp 0.8861
rs 0.8
c 1
b 0
f 0

72 Methods

Rating   Name   Duplication   Size   Complexity  
A getExcelConstants() 0 3 1
A keyInExcelConstants() 0 3 1
A getLocaleBoolean() 0 3 1
B convertMatrixReferences() 0 50 9
C extractCellRange() 0 53 14
A getLocale() 0 3 1
A getDebugLog() 0 3 1
A disableCalculationCache() 0 3 1
D setLocale() 0 81 21
A addDefaultArgumentValues() 0 23 6
A translateFormula() 0 30 5
A boolToString() 0 9 4
A getArrayReturnType() 0 3 1
F internalParseFormula() 0 489 152
A disableBranchPruning() 0 3 1
A translateFormulaBlock() 0 22 1
A getLocaleFile() 0 13 3
B translateFormulaToEnglish() 0 23 7
A addCellReference() 0 18 4
A translateSeparator() 0 28 6
A getMatrixDimensions() 0 16 3
A localeFunc() 0 14 4
A calculate() 0 6 2
A calculateFormula() 0 30 6
A getValueFromCache() 0 15 3
A setArrayReturnType() 0 13 4
A parseFormula() 0 20 4
B checkMatrixOperands() 0 33 8
A executeBinaryComparisonOperation() 0 15 3
B translateFormulaToLocale() 0 30 7
A flushInstance() 0 4 1
A dataTestReference() 0 20 5
A getInstance() 0 14 4
A getInstanceArrayReturnType() 0 3 1
D _calculateFormulaValue() 0 67 20
C resizeMatricesExtend() 0 32 15
A __clone() 0 3 1
A __construct() 0 6 1
A clearCalculationCacheForWorksheet() 0 4 2
F calculateCellValue() 0 75 22
A getTRUE() 0 3 1
B executeArrayComparison() 0 40 7
A raiseFormulaError() 0 10 2
A enableBranchPruning() 0 3 1
C extractNamedRange() 0 52 16
A getSuppressFormulaErrors() 0 3 1
B validateBinaryOperand() 0 36 11
D executeNumericBinaryOperation() 0 125 34
A clearCalculationCache() 0 3 1
A setSuppressFormulaErrors() 0 3 1
A setInstanceArrayReturnType() 0 13 4
A getCalculationCacheEnabled() 0 3 1
C resizeMatricesShrink() 0 27 15
A getFALSE() 0 3 1
A getArgumentDefaultValue() 0 21 4
A isNumericOrBool() 0 3 2
F processTokenStack() 0 640 192
A wrapResult() 0 17 6
A saveValueToCache() 0 4 2
A setCalculationCacheEnabled() 0 4 1
A enableCalculationCache() 0 3 1
B showTypeDetails() 0 31 10
A setBranchPruningEnabled() 0 4 1
B evaluateDefinedName() 0 53 10
A loadLocales() 0 8 4
B showValue() 0 31 11
A renameCalculationCacheForWorksheet() 0 5 2
A getImplementedFunctionNames() 0 11 3
B unwrapResult() 0 12 8
A makeError() 0 3 2
A isImplemented() 0 7 3
C getFalseTrueArray() 0 41 12

How to fix   Complexity   

Complex Class

Complex classes like Calculation often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Calculation, and based on these observations, apply Extract Interface, too.

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