Passed
Pull Request — master (#4390)
by Owen
13:00
created

Calculation::getFunctions()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
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
    public function __construct(?Spreadsheet $spreadsheet = null)
236
    {
237
        $this->spreadsheet = $spreadsheet;
238
        $this->cyclicReferenceStack = new CyclicReferenceStack();
239
        $this->debugLog = new Logger($this->cyclicReferenceStack);
240
        $this->branchPruner = new BranchPruner($this->branchPruningEnabled);
241
    }
242
243
    private static function loadLocales(): void
244
    {
245
        $localeFileDirectory = __DIR__ . '/locale/';
246
        $localeFileNames = glob($localeFileDirectory . '*', GLOB_ONLYDIR) ?: [];
247
        foreach ($localeFileNames as $filename) {
248
            $filename = substr($filename, strlen($localeFileDirectory));
249
            if ($filename != 'en') {
250
                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
    public static function getInstance(?Spreadsheet $spreadsheet = null): self
262
    {
263
        if ($spreadsheet !== null) {
264
            $instance = $spreadsheet->getCalculationEngine();
265
            if (isset($instance)) {
266
                return $instance;
267
            }
268
        }
269
270
        if (!self::$instance) {
271
            self::$instance = new self();
272
        }
273
274
        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
    public function flushInstance(): void
282
    {
283
        $this->clearCalculationCache();
284
        $this->branchPruner->clearBranchStore();
285
    }
286
287
    /**
288
     * Get the Logger for this calculation engine instance.
289
     */
290
    public function getDebugLog(): Logger
291
    {
292
        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
    public static function getTRUE(): string
309
    {
310
        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
    public static function getFALSE(): string
319
    {
320
        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
    public static function setArrayReturnType(string $returnType): bool
331
    {
332
        if (
333
            ($returnType == self::RETURN_ARRAY_AS_VALUE)
334
            || ($returnType == self::RETURN_ARRAY_AS_ERROR)
335
            || ($returnType == self::RETURN_ARRAY_AS_ARRAY)
336
        ) {
337
            self::$returnArrayAsType = $returnType;
338
339
            return true;
340
        }
341
342
        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
    public static function getArrayReturnType(): string
351
    {
352
        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
    public function setInstanceArrayReturnType(string $returnType): bool
363
    {
364
        if (
365
            ($returnType == self::RETURN_ARRAY_AS_VALUE)
366
            || ($returnType == self::RETURN_ARRAY_AS_ERROR)
367
            || ($returnType == self::RETURN_ARRAY_AS_ARRAY)
368
        ) {
369
            $this->instanceArrayReturnType = $returnType;
370
371
            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
    public function getInstanceArrayReturnType(): string
383
    {
384
        return $this->instanceArrayReturnType ?? self::$returnArrayAsType;
385
    }
386
387
    /**
388
     * Is calculation caching enabled?
389
     */
390
    public function getCalculationCacheEnabled(): bool
391
    {
392
        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
    public function clearCalculationCache(): void
424
    {
425
        $this->calculationCache = [];
426
    }
427
428
    /**
429
     * Clear calculation cache for a specified worksheet.
430
     */
431
    public function clearCalculationCacheForWorksheet(string $worksheetName): void
432
    {
433
        if (isset($this->calculationCache[$worksheetName])) {
434
            unset($this->calculationCache[$worksheetName]);
435
        }
436
    }
437
438
    /**
439
     * Rename calculation cache for a specified worksheet.
440
     */
441
    public function renameCalculationCacheForWorksheet(string $fromWorksheetName, string $toWorksheetName): void
442
    {
443
        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
    public function setBranchPruningEnabled(mixed $enabled): void
453
    {
454
        $this->branchPruningEnabled = $enabled;
455
        $this->branchPruner = new BranchPruner($this->branchPruningEnabled);
456
    }
457
458
    public function enableBranchPruning(): void
459
    {
460
        $this->setBranchPruningEnabled(true);
461
    }
462
463
    public function disableBranchPruning(): void
464
    {
465
        $this->setBranchPruningEnabled(false);
466
    }
467
468
    /**
469
     * Get the currently defined locale code.
470
     */
471
    public function getLocale(): string
472
    {
473
        return self::$localeLanguage;
474
    }
475
476
    private function getLocaleFile(string $localeDir, string $locale, string $language, string $file): string
477
    {
478
        $localeFileName = $localeDir . str_replace('_', DIRECTORY_SEPARATOR, $locale)
479
            . DIRECTORY_SEPARATOR . $file;
480
        if (!file_exists($localeFileName)) {
481
            //    If there isn't a locale specific file, look for a language specific file
482
            $localeFileName = $localeDir . $language . DIRECTORY_SEPARATOR . $file;
483
            if (!file_exists($localeFileName)) {
484
                throw new Exception('Locale file not found');
485
            }
486
        }
487
488
        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
    public function getFalseTrueArray(): array
496
    {
497
        if (!empty(self::$falseTrueArray)) {
498
            return self::$falseTrueArray;
499
        }
500
        if (count(self::$validLocaleLanguages) == 1) {
501
            self::loadLocales();
502
        }
503
        $falseTrueArray = [['FALSE'], ['TRUE']];
504
        foreach (self::$validLocaleLanguages as $language) {
505
            if (str_starts_with($language, 'en')) {
506
                continue;
507
            }
508
            $locale = $language;
509
            if (str_contains($locale, '_')) {
510
                [$language] = explode('_', $locale);
511
            }
512
            $localeDir = implode(DIRECTORY_SEPARATOR, [__DIR__, 'locale', null]);
513
514
            try {
515
                $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
            $localeFunctions = file($functionNamesFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: [];
521
            foreach ($localeFunctions as $localeFunction) {
522
                [$localeFunction] = explode('##', $localeFunction); //    Strip out comments
523
                if (str_contains($localeFunction, '=')) {
524
                    [$fName, $lfName] = array_map('trim', explode('=', $localeFunction));
525
                    if ($fName === 'FALSE') {
526
                        $falseTrueArray[0][] = $lfName;
527
                    } elseif ($fName === 'TRUE') {
528
                        $falseTrueArray[1][] = $lfName;
529
                    }
530
                }
531
            }
532
        }
533
        self::$falseTrueArray = $falseTrueArray;
534
535
        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
    public function setLocale(string $locale): bool
544
    {
545
        //    Identify our locale and language
546
        $language = $locale = strtolower($locale);
547
        if (str_contains($locale, '_')) {
548
            [$language] = explode('_', $locale);
549
        }
550
        if (count(self::$validLocaleLanguages) == 1) {
551
            self::loadLocales();
552
        }
553
554
        //    Test whether we have any language data for this language (any locale)
555
        if (in_array($language, self::$validLocaleLanguages, true)) {
556
            //    initialise language/locale settings
557
            self::$localeFunctions = [];
558
            self::$localeArgumentSeparator = ',';
559
            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
            if ($locale !== 'en_us') {
563
                $localeDir = implode(DIRECTORY_SEPARATOR, [__DIR__, 'locale', null]);
564
565
                //    Search for a file with a list of function names for locale
566
                try {
567
                    $functionNamesFile = $this->getLocaleFile($localeDir, $locale, $language, 'functions');
568
                } catch (Exception $e) {
569
                    return false;
570
                }
571
572
                //    Retrieve the list of locale or language specific function names
573
                $localeFunctions = file($functionNamesFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: [];
574
                $phpSpreadsheetFunctions = &self::getFunctionsAddress();
575
                foreach ($localeFunctions as $localeFunction) {
576
                    [$localeFunction] = explode('##', $localeFunction); //    Strip out comments
577
                    if (str_contains($localeFunction, '=')) {
578
                        [$fName, $lfName] = array_map('trim', explode('=', $localeFunction));
579
                        if ((str_starts_with($fName, '*') || isset($phpSpreadsheetFunctions[$fName])) && ($lfName != '') && ($fName != $lfName)) {
580
                            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
                if (isset(self::$localeFunctions['TRUE'])) {
586
                    self::$localeBoolean['TRUE'] = self::$localeFunctions['TRUE'];
587
                }
588
                if (isset(self::$localeFunctions['FALSE'])) {
589
                    self::$localeBoolean['FALSE'] = self::$localeFunctions['FALSE'];
590
                }
591
592
                try {
593
                    $configFile = $this->getLocaleFile($localeDir, $locale, $language, 'config');
594
                } catch (Exception) {
595
                    return false;
596
                }
597
598
                $localeSettings = file($configFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: [];
599
                foreach ($localeSettings as $localeSetting) {
600
                    [$localeSetting] = explode('##', $localeSetting); //    Strip out comments
601
                    if (str_contains($localeSetting, '=')) {
602
                        [$settingName, $settingValue] = array_map('trim', explode('=', $localeSetting));
603
                        $settingName = strtoupper($settingName);
604
                        if ($settingValue !== '') {
605
                            switch ($settingName) {
606
                                case 'ARGUMENTSEPARATOR':
607
                                    self::$localeArgumentSeparator = $settingValue;
608
609
                                    break;
610
                            }
611
                        }
612
                    }
613
                }
614
            }
615
616
            self::$functionReplaceFromExcel = self::$functionReplaceToExcel
617
            = self::$functionReplaceFromLocale = self::$functionReplaceToLocale = null;
618
            self::$localeLanguage = $locale;
619
620
            return true;
621
        }
622
623
        return false;
624
    }
625
626
    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
        $strlen = mb_strlen($formula);
635
        for ($i = 0; $i < $strlen; ++$i) {
636
            $chr = mb_substr($formula, $i, 1);
637
            switch ($chr) {
638
                case $openBrace:
639
                    ++$inBracesLevel;
640
641
                    break;
642
                case $closeBrace:
643
                    --$inBracesLevel;
644
645
                    break;
646
                case $fromSeparator:
647
                    if ($inBracesLevel > 0) {
648
                        $formula = mb_substr($formula, 0, $i) . $toSeparator . mb_substr($formula, $i + 1);
649
                    }
650
            }
651
        }
652
653
        return $formula;
654
    }
655
656
    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
        $formula = (string) preg_replace($from, $to, $formula);
667
668
        // Temporarily adjust matrix separators so that they won't be confused with function arguments
669
        $formula = self::translateSeparator(';', '|', $formula, $inMatrixBracesLevel, self::FORMULA_OPEN_MATRIX_BRACE, self::FORMULA_CLOSE_MATRIX_BRACE);
670
        $formula = self::translateSeparator(',', '!', $formula, $inMatrixBracesLevel, self::FORMULA_OPEN_MATRIX_BRACE, self::FORMULA_CLOSE_MATRIX_BRACE);
671
        // Function Argument Separators
672
        $formula = self::translateSeparator($fromSeparator, $toSeparator, $formula, $inFunctionBracesLevel);
673
        // Restore matrix separators
674
        $formula = self::translateSeparator('|', ';', $formula, $inMatrixBracesLevel, self::FORMULA_OPEN_MATRIX_BRACE, self::FORMULA_CLOSE_MATRIX_BRACE);
675
        $formula = self::translateSeparator('!', ',', $formula, $inMatrixBracesLevel, self::FORMULA_OPEN_MATRIX_BRACE, self::FORMULA_CLOSE_MATRIX_BRACE);
676
677
        return $formula;
678
    }
679
680
    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
        if (self::$localeLanguage !== 'en_us') {
685
            $inFunctionBracesLevel = 0;
686
            $inMatrixBracesLevel = 0;
687
            //    If there is the possibility of separators within a quoted string, then we treat them as literals
688
            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
                $temp = explode(self::FORMULA_STRING_QUOTE, $formula);
692
                $notWithinQuotes = false;
693
                foreach ($temp as &$value) {
694
                    //    Only adjust in alternating array entries
695
                    $notWithinQuotes = $notWithinQuotes === false;
696
                    if ($notWithinQuotes === true) {
697
                        $value = self::translateFormulaBlock($from, $to, $value, $inFunctionBracesLevel, $inMatrixBracesLevel, $fromSeparator, $toSeparator);
698
                    }
699
                }
700
                unset($value);
701
                //    Then rebuild the formula string
702
                $formula = implode(self::FORMULA_STRING_QUOTE, $temp);
703
            } else {
704
                //    If there's no quoted strings, then we do a simple count/replace
705
                $formula = self::translateFormulaBlock($from, $to, $formula, $inFunctionBracesLevel, $inMatrixBracesLevel, $fromSeparator, $toSeparator);
706
            }
707
        }
708
709
        return $formula;
710
    }
711
712
    private static ?array $functionReplaceFromExcel;
713
714
    private static ?array $functionReplaceToLocale;
715
716
    public function translateFormulaToLocale(string $formula): string
717
    {
718
        $formula = preg_replace(self::CALCULATION_REGEXP_STRIP_XLFN_XLWS, '', $formula) ?? '';
719
        // Build list of function names and constants for translation
720
        if (self::$functionReplaceFromExcel === null) {
721
            self::$functionReplaceFromExcel = [];
722
            foreach (array_keys(self::$localeFunctions) as $excelFunctionName) {
723
                self::$functionReplaceFromExcel[] = '/(@?[^\w\.])' . preg_quote($excelFunctionName, '/') . '([\s]*\()/ui';
724
            }
725
            foreach (array_keys(self::$localeBoolean) as $excelBoolean) {
726
                self::$functionReplaceFromExcel[] = '/(@?[^\w\.])' . preg_quote($excelBoolean, '/') . '([^\w\.])/ui';
727
            }
728
        }
729
730
        if (self::$functionReplaceToLocale === null) {
731
            self::$functionReplaceToLocale = [];
732
            foreach (self::$localeFunctions as $localeFunctionName) {
733
                self::$functionReplaceToLocale[] = '$1' . trim($localeFunctionName) . '$2';
734
            }
735
            foreach (self::$localeBoolean as $localeBoolean) {
736
                self::$functionReplaceToLocale[] = '$1' . trim($localeBoolean) . '$2';
737
            }
738
        }
739
740
        return self::translateFormula(
741
            self::$functionReplaceFromExcel,
742
            self::$functionReplaceToLocale,
743
            $formula,
744
            ',',
745
            self::$localeArgumentSeparator
746
        );
747
    }
748
749
    private static ?array $functionReplaceFromLocale;
750
751
    private static ?array $functionReplaceToExcel;
752
753
    public function translateFormulaToEnglish(string $formula): string
754
    {
755
        if (self::$functionReplaceFromLocale === null) {
756
            self::$functionReplaceFromLocale = [];
757
            foreach (self::$localeFunctions as $localeFunctionName) {
758
                self::$functionReplaceFromLocale[] = '/(@?[^\w\.])' . preg_quote($localeFunctionName, '/') . '([\s]*\()/ui';
759
            }
760
            foreach (self::$localeBoolean as $excelBoolean) {
761
                self::$functionReplaceFromLocale[] = '/(@?[^\w\.])' . preg_quote($excelBoolean, '/') . '([^\w\.])/ui';
762
            }
763
        }
764
765
        if (self::$functionReplaceToExcel === null) {
766
            self::$functionReplaceToExcel = [];
767
            foreach (array_keys(self::$localeFunctions) as $excelFunctionName) {
768
                self::$functionReplaceToExcel[] = '$1' . trim($excelFunctionName) . '$2';
769
            }
770
            foreach (array_keys(self::$localeBoolean) as $excelBoolean) {
771
                self::$functionReplaceToExcel[] = '$1' . trim($excelBoolean) . '$2';
772
            }
773
        }
774
775
        return self::translateFormula(self::$functionReplaceFromLocale, self::$functionReplaceToExcel, $formula, self::$localeArgumentSeparator, ',');
776
    }
777
778
    public static function localeFunc(string $function): string
779
    {
780
        if (self::$localeLanguage !== 'en_us') {
781
            $functionName = trim($function, '(');
782
            if (isset(self::$localeFunctions[$functionName])) {
783
                $brace = ($functionName != $function);
784
                $function = self::$localeFunctions[$functionName];
785
                if ($brace) {
786
                    $function .= '(';
787
                }
788
            }
789
        }
790
791
        return $function;
792
    }
793
794
    /**
795
     * Wrap string values in quotes.
796
     */
797
    public static function wrapResult(mixed $value): mixed
798
    {
799
        if (is_string($value)) {
800
            //    Error values cannot be "wrapped"
801
            if (preg_match('/^' . self::CALCULATION_REGEXP_ERROR . '$/i', $value, $match)) {
802
                //    Return Excel errors "as is"
803
                return $value;
804
            }
805
806
            //    Return strings wrapped in quotes
807
            return self::FORMULA_STRING_QUOTE . $value . self::FORMULA_STRING_QUOTE;
808
        } elseif ((is_float($value)) && ((is_nan($value)) || (is_infinite($value)))) {
809
            //    Convert numeric errors to NaN error
810
            return ExcelError::NAN();
811
        }
812
813
        return $value;
814
    }
815
816
    /**
817
     * Remove quotes used as a wrapper to identify string values.
818
     */
819
    public static function unwrapResult(mixed $value): mixed
820
    {
821
        if (is_string($value)) {
822
            if ((isset($value[0])) && ($value[0] == self::FORMULA_STRING_QUOTE) && (substr($value, -1) == self::FORMULA_STRING_QUOTE)) {
823
                return substr($value, 1, -1);
824
            }
825
            //    Convert numeric errors to NAN error
826
        } elseif ((is_float($value)) && ((is_nan($value)) || (is_infinite($value)))) {
827
            return ExcelError::NAN();
828
        }
829
830
        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
    public function calculateCellValue(?Cell $cell = null, bool $resetLog = true): mixed
855
    {
856
        if ($cell === null) {
857
            return null;
858
        }
859
860
        if ($resetLog) {
861
            //    Initialise the logging settings if requested
862
            $this->formulaError = null;
863
            $this->debugLog->clearLog();
864
            $this->cyclicReferenceStack->clear();
865
            $this->cyclicFormulaCounter = 1;
866
        }
867
868
        //    Execute the calculation for the cell formula
869
        $this->cellStack[] = [
870
            'sheet' => $cell->getWorksheet()->getTitle(),
871
            'cell' => $cell->getCoordinate(),
872
        ];
873
874
        $cellAddressAttempted = false;
875
        $cellAddress = null;
876
877
        try {
878
            $value = $cell->getValue();
879
            if ($cell->getDataType() === DataType::TYPE_FORMULA) {
880
                $value = preg_replace_callback(
881
                    self::CALCULATION_REGEXP_CELLREF_SPILL,
882
                    fn (array $matches) => 'ANCHORARRAY(' . substr($matches[0], 0, -1) . ')',
883
                    $value
884
                );
885
            }
886
            $result = self::unwrapResult($this->_calculateFormulaValue($value, $cell->getCoordinate(), $cell));
887
            if ($this->spreadsheet === null) {
888
                throw new Exception('null spreadsheet in calculateCellValue');
889
            }
890
            $cellAddressAttempted = true;
891
            $cellAddress = array_pop($this->cellStack);
892
            if ($cellAddress === null) {
893
                throw new Exception('null cellAddress in calculateCellValue');
894
            }
895
            $testSheet = $this->spreadsheet->getSheetByName($cellAddress['sheet']);
896
            if ($testSheet === null) {
897
                throw new Exception('worksheet not found in calculateCellValue');
898
            }
899
            $testSheet->getCell($cellAddress['cell']);
900
        } catch (\Exception $e) {
901
            if (!$cellAddressAttempted) {
902
                $cellAddress = array_pop($this->cellStack);
903
            }
904
            if ($this->spreadsheet !== null && is_array($cellAddress) && array_key_exists('sheet', $cellAddress)) {
905
                $testSheet = $this->spreadsheet->getSheetByName($cellAddress['sheet']);
906
                if ($testSheet !== null && array_key_exists('cell', $cellAddress)) {
907
                    $testSheet->getCell($cellAddress['cell']);
908
                }
909
            }
910
911
            throw new Exception($e->getMessage(), $e->getCode(), $e);
912
        }
913
914
        if (is_array($result) && $this->getInstanceArrayReturnType() !== self::RETURN_ARRAY_AS_ARRAY) {
915
            $testResult = Functions::flattenArray($result);
916
            if ($this->getInstanceArrayReturnType() == self::RETURN_ARRAY_AS_ERROR) {
917
                return ExcelError::VALUE();
918
            }
919
            $result = array_shift($testResult);
920
        }
921
922
        if ($result === null && $cell->getWorksheet()->getSheetView()->getShowZeros()) {
923
            return 0;
924
        } elseif ((is_float($result)) && ((is_nan($result)) || (is_infinite($result)))) {
925
            return ExcelError::NAN();
926
        }
927
928
        return $result;
929
    }
930
931
    /**
932
     * Validate and parse a formula string.
933
     *
934
     * @param string $formula Formula to parse
935
     */
936
    public function parseFormula(string $formula): array|bool
937
    {
938
        $formula = preg_replace_callback(
939
            self::CALCULATION_REGEXP_CELLREF_SPILL,
940
            fn (array $matches) => 'ANCHORARRAY(' . substr($matches[0], 0, -1) . ')',
941
            $formula
942
        ) ?? $formula;
943
        //    Basic validation that this is indeed a formula
944
        //    We return an empty array if not
945
        $formula = trim($formula);
946
        if ((!isset($formula[0])) || ($formula[0] != '=')) {
947
            return [];
948
        }
949
        $formula = ltrim(substr($formula, 1));
950
        if (!isset($formula[0])) {
951
            return [];
952
        }
953
954
        //    Parse the formula and return the token stack
955
        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
    public function calculateFormula(string $formula, ?string $cellID = null, ?Cell $cell = null): mixed
966
    {
967
        //    Initialise the logging settings
968
        $this->formulaError = null;
969
        $this->debugLog->clearLog();
970
        $this->cyclicReferenceStack->clear();
971
972
        $resetCache = $this->getCalculationCacheEnabled();
973
        if ($this->spreadsheet !== null && $cellID === null && $cell === null) {
974
            $cellID = 'A1';
975
            $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
            $this->calculationCacheEnabled = false;
980
        }
981
982
        //    Execute the calculation
983
        try {
984
            $result = self::unwrapResult($this->_calculateFormulaValue($formula, $cellID, $cell));
985
        } catch (\Exception $e) {
986
            throw new Exception($e->getMessage());
987
        }
988
989
        if ($this->spreadsheet === null) {
990
            //    Reset calculation cacheing to its previous state
991
            $this->calculationCacheEnabled = $resetCache;
992
        }
993
994
        return $result;
995
    }
996
997
    public function getValueFromCache(string $cellReference, mixed &$cellValue): bool
998
    {
999
        $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
        if (($this->calculationCacheEnabled) && (isset($this->calculationCache[$cellReference]))) {
1003
            $this->debugLog->writeDebugLog('Retrieving value for cell %s from cache', $cellReference);
1004
            // Return the cached result
1005
1006
            $cellValue = $this->calculationCache[$cellReference];
1007
1008
            return true;
1009
        }
1010
1011
        return false;
1012
    }
1013
1014
    public function saveValueToCache(string $cellReference, mixed $cellValue): void
1015
    {
1016
        if ($this->calculationCacheEnabled) {
1017
            $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
    public function _calculateFormulaValue(string $formula, ?string $cellID = null, ?Cell $cell = null, bool $ignoreQuotePrefix = false): mixed
1030
    {
1031
        $cellValue = null;
1032
1033
        //  Quote-Prefixed cell values cannot be formulae, but are treated as strings
1034
        if ($cell !== null && $ignoreQuotePrefix === false && $cell->getStyle()->getQuotePrefix() === true) {
1035
            return self::wrapResult((string) $formula);
1036
        }
1037
1038
        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
        $formula = trim($formula);
1045
        if ($formula === '' || $formula[0] !== '=') {
1046
            return self::wrapResult($formula);
1047
        }
1048
        $formula = ltrim(substr($formula, 1));
1049
        if (!isset($formula[0])) {
1050
            return self::wrapResult($formula);
1051
        }
1052
1053
        $pCellParent = ($cell !== null) ? $cell->getWorksheet() : null;
1054
        $wsTitle = ($pCellParent !== null) ? $pCellParent->getTitle() : "\x00Wrk";
1055
        $wsCellReference = $wsTitle . '!' . $cellID;
1056
1057
        if (($cellID !== null) && ($this->getValueFromCache($wsCellReference, $cellValue))) {
1058
            return $cellValue;
1059
        }
1060
        $this->debugLog->writeDebugLog('Evaluating formula for cell %s', $wsCellReference);
1061
1062
        if (($wsTitle[0] !== "\x00") && ($this->cyclicReferenceStack->onStack($wsCellReference))) {
1063
            if ($this->cyclicFormulaCount <= 0) {
1064
                $this->cyclicFormulaCell = '';
1065
1066
                return $this->raiseFormulaError('Cyclic Reference in Formula');
1067
            } elseif ($this->cyclicFormulaCell === $wsCellReference) {
1068
                ++$this->cyclicFormulaCounter;
1069
                if ($this->cyclicFormulaCounter >= $this->cyclicFormulaCount) {
1070
                    $this->cyclicFormulaCell = '';
1071
1072
                    return $cellValue;
1073
                }
1074
            } elseif ($this->cyclicFormulaCell == '') {
1075
                if ($this->cyclicFormulaCounter >= $this->cyclicFormulaCount) {
1076
                    return $cellValue;
1077
                }
1078
                $this->cyclicFormulaCell = $wsCellReference;
1079
            }
1080
        }
1081
1082
        $this->debugLog->writeDebugLog('Formula for cell %s is %s', $wsCellReference, $formula);
1083
        //    Parse the formula onto the token stack and calculate the value
1084
        $this->cyclicReferenceStack->push($wsCellReference);
1085
1086
        $cellValue = $this->processTokenStack($this->internalParseFormula($formula, $cell), $cellID, $cell);
1087
        $this->cyclicReferenceStack->pop();
1088
1089
        // Save to calculation cache
1090
        if ($cellID !== null) {
1091
            $this->saveValueToCache($wsCellReference, $cellValue);
1092
        }
1093
1094
        //    Return the calculated value
1095
        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
    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
        if (!is_array($operand1)) {
1115
            [$matrixRows, $matrixColumns] = self::getMatrixDimensions($operand2);
1116
            $operand1 = array_fill(0, $matrixRows, array_fill(0, $matrixColumns, $operand1));
1117
            $resize = 0;
1118
        } elseif (!is_array($operand2)) {
1119
            [$matrixRows, $matrixColumns] = self::getMatrixDimensions($operand1);
1120
            $operand2 = array_fill(0, $matrixRows, array_fill(0, $matrixColumns, $operand2));
1121
            $resize = 0;
1122
        }
1123
1124
        [$matrix1Rows, $matrix1Columns] = self::getMatrixDimensions($operand1);
1125
        [$matrix2Rows, $matrix2Columns] = self::getMatrixDimensions($operand2);
1126
        if ($resize === 3) {
1127
            $resize = 2;
1128
        } elseif (($matrix1Rows == $matrix2Columns) && ($matrix2Rows == $matrix1Columns)) {
1129
            $resize = 1;
1130
        }
1131
1132
        if ($resize == 2) {
1133
            //    Given two matrices of (potentially) unequal size, convert the smaller in each dimension to match the larger
1134
            self::resizeMatricesExtend($operand1, $operand2, $matrix1Rows, $matrix1Columns, $matrix2Rows, $matrix2Columns);
1135
        } elseif ($resize == 1) {
1136
            //    Given two matrices of (potentially) unequal size, convert the larger in each dimension to match the smaller
1137
            self::resizeMatricesShrink($operand1, $operand2, $matrix1Rows, $matrix1Columns, $matrix2Rows, $matrix2Columns);
1138
        }
1139
        [$matrix1Rows, $matrix1Columns] = self::getMatrixDimensions($operand1);
1140
        [$matrix2Rows, $matrix2Columns] = self::getMatrixDimensions($operand2);
1141
1142
        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
    public static function getMatrixDimensions(array &$matrix): array
1153
    {
1154
        $matrixRows = count($matrix);
1155
        $matrixColumns = 0;
1156
        foreach ($matrix as $rowKey => $rowValue) {
1157
            if (!is_array($rowValue)) {
1158
                $matrix[$rowKey] = [$rowValue];
1159
                $matrixColumns = max(1, $matrixColumns);
1160
            } else {
1161
                $matrix[$rowKey] = array_values($rowValue);
1162
                $matrixColumns = max(count($rowValue), $matrixColumns);
1163
            }
1164
        }
1165
        $matrix = array_values($matrix);
1166
1167
        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
    private static function resizeMatricesShrink(array &$matrix1, array &$matrix2, int $matrix1Rows, int $matrix1Columns, int $matrix2Rows, int $matrix2Columns): void
1181
    {
1182
        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
        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
    private static function resizeMatricesExtend(array &$matrix1, array &$matrix2, int $matrix1Rows, int $matrix1Columns, int $matrix2Rows, int $matrix2Columns): void
1224
    {
1225
        if (($matrix2Columns < $matrix1Columns) || ($matrix2Rows < $matrix1Rows)) {
1226
            if ($matrix2Columns < $matrix1Columns) {
1227
                for ($i = 0; $i < $matrix2Rows; ++$i) {
1228
                    $x = $matrix2[$i][$matrix2Columns - 1];
1229
                    for ($j = $matrix2Columns; $j < $matrix1Columns; ++$j) {
1230
                        $matrix2[$i][$j] = $x;
1231
                    }
1232
                }
1233
            }
1234
            if ($matrix2Rows < $matrix1Rows) {
1235
                $x = $matrix2[$matrix2Rows - 1];
1236
                for ($i = 0; $i < $matrix1Rows; ++$i) {
1237
                    $matrix2[$i] = $x;
1238
                }
1239
            }
1240
        }
1241
1242
        if (($matrix1Columns < $matrix2Columns) || ($matrix1Rows < $matrix2Rows)) {
1243
            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
            if ($matrix1Rows < $matrix2Rows) {
1252
                $x = $matrix1[$matrix1Rows - 1];
1253
                for ($i = 0; $i < $matrix2Rows; ++$i) {
1254
                    $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
    private function showValue(mixed $value): mixed
1266
    {
1267
        if ($this->debugLog->getWriteDebugLog()) {
1268
            $testArray = Functions::flattenArray($value);
1269
            if (count($testArray) == 1) {
1270
                $value = array_pop($testArray);
1271
            }
1272
1273
            if (is_array($value)) {
1274
                $returnMatrix = [];
1275
                $pad = $rpad = ', ';
1276
                foreach ($value as $row) {
1277
                    if (is_array($row)) {
1278
                        $returnMatrix[] = implode($pad, array_map([$this, 'showValue'], $row));
1279
                        $rpad = '; ';
1280
                    } else {
1281
                        $returnMatrix[] = $this->showValue($row);
1282
                    }
1283
                }
1284
1285
                return '{ ' . implode($rpad, $returnMatrix) . ' }';
1286
            } elseif (is_string($value) && (trim($value, self::FORMULA_STRING_QUOTE) == $value)) {
1287
                return self::FORMULA_STRING_QUOTE . $value . self::FORMULA_STRING_QUOTE;
1288
            } elseif (is_bool($value)) {
1289
                return ($value) ? self::$localeBoolean['TRUE'] : self::$localeBoolean['FALSE'];
1290
            } elseif ($value === null) {
1291
                return self::$localeBoolean['NULL'];
1292
            }
1293
        }
1294
1295
        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
    private function showTypeDetails(mixed $value): ?string
1304
    {
1305
        if ($this->debugLog->getWriteDebugLog()) {
1306
            $testArray = Functions::flattenArray($value);
1307
            if (count($testArray) == 1) {
1308
                $value = array_pop($testArray);
1309
            }
1310
1311
            if ($value === null) {
1312
                return 'a NULL value';
1313
            } elseif (is_float($value)) {
1314
                $typeString = 'a floating point number';
1315
            } elseif (is_int($value)) {
1316
                $typeString = 'an integer number';
1317
            } elseif (is_bool($value)) {
1318
                $typeString = 'a boolean';
1319
            } elseif (is_array($value)) {
1320
                $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
            return $typeString . ' with a value of ' . $this->showValue($value);
1331
        }
1332
1333
        return null;
1334
    }
1335
1336
    /**
1337
     * @return false|string False indicates an error
1338
     */
1339
    private function convertMatrixReferences(string $formula): false|string
1340
    {
1341
        static $matrixReplaceFrom = [self::FORMULA_OPEN_MATRIX_BRACE, ';', self::FORMULA_CLOSE_MATRIX_BRACE];
1342
        static $matrixReplaceTo = ['MKMATRIX(MKMATRIX(', '),MKMATRIX(', '))'];
1343
1344
        //    Convert any Excel matrix references to the MKMATRIX() function
1345
        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
            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
                $temp = explode(self::FORMULA_STRING_QUOTE, $formula);
1351
                //    Open and Closed counts used for trapping mismatched braces in the formula
1352
                $openCount = $closeCount = 0;
1353
                $notWithinQuotes = false;
1354
                foreach ($temp as &$value) {
1355
                    //    Only count/replace in alternating array entries
1356
                    $notWithinQuotes = $notWithinQuotes === false;
1357
                    if ($notWithinQuotes === true) {
1358
                        $openCount += substr_count($value, self::FORMULA_OPEN_MATRIX_BRACE);
1359
                        $closeCount += substr_count($value, self::FORMULA_CLOSE_MATRIX_BRACE);
1360
                        $value = str_replace($matrixReplaceFrom, $matrixReplaceTo, $value);
1361
                    }
1362
                }
1363
                unset($value);
1364
                //    Then rebuild the formula string
1365
                $formula = implode(self::FORMULA_STRING_QUOTE, $temp);
1366
            } else {
1367
                //    If there's no quoted strings, then we do a simple count/replace
1368
                $openCount = substr_count($formula, self::FORMULA_OPEN_MATRIX_BRACE);
1369
                $closeCount = substr_count($formula, self::FORMULA_CLOSE_MATRIX_BRACE);
1370
                $formula = str_replace($matrixReplaceFrom, $matrixReplaceTo, $formula);
1371
            }
1372
            //    Trap for mismatched braces and trigger an appropriate error
1373
            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
            } 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
        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
    private function internalParseFormula(string $formula, ?Cell $cell = null): bool|array
1435
    {
1436
        if (($formula = $this->convertMatrixReferences(trim($formula))) === false) {
1437
            return false;
1438
        }
1439
        $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
        $pCellParent = ($cell !== null) ? $cell->getWorksheet() : null;
1444
1445
        $regexpMatchString = '/^((?<string>' . self::CALCULATION_REGEXP_STRING
1446
                                . ')|(?<function>' . self::CALCULATION_REGEXP_FUNCTION
1447
                                . ')|(?<cellRef>' . self::CALCULATION_REGEXP_CELLREF
1448
                                . ')|(?<colRange>' . self::CALCULATION_REGEXP_COLUMN_RANGE
1449
                                . ')|(?<rowRange>' . self::CALCULATION_REGEXP_ROW_RANGE
1450
                                . ')|(?<number>' . self::CALCULATION_REGEXP_NUMBER
1451
                                . ')|(?<openBrace>' . self::CALCULATION_REGEXP_OPENBRACE
1452
                                . ')|(?<structuredReference>' . self::CALCULATION_REGEXP_STRUCTURED_REFERENCE
1453
                                . ')|(?<definedName>' . self::CALCULATION_REGEXP_DEFINEDNAME
1454
                                . ')|(?<error>' . self::CALCULATION_REGEXP_ERROR
1455
                                . '))/sui';
1456
1457
        //    Start with initialisation
1458
        $index = 0;
1459
        $stack = new Stack($this->branchPruner);
1460
        $output = [];
1461
        $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
        $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
        while (true) {
1469
            // Branch pruning: we adapt the output item to the context (it will
1470
            // be used to limit its computation)
1471
            $this->branchPruner->initialiseForLoop();
1472
1473
            $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
            if ((isset(self::$comparisonOperators[$opCharacter])) && (strlen($formula) > $index) && isset($formula[$index + 1], self::$comparisonOperators[$formula[$index + 1]])) {
1477
                $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
            $isOperandOrFunction = (bool) preg_match($regexpMatchString, substr($formula, $index), $match);
1482
1483
            $expectingOperatorCopy = $expectingOperator;
1484
            if ($opCharacter === '-' && !$expectingOperator) {                //    Is it a negation instead of a minus?
1485
                //    Put a negation on the stack
1486
                $stack->push('Unary Operator', '~');
1487
                ++$index; //        and drop the negation symbol
1488
            } elseif ($opCharacter === '%' && $expectingOperator) {
1489
                //    Put a percentage on the stack
1490
                $stack->push('Unary Operator', '%');
1491
                ++$index;
1492
            } elseif ($opCharacter === '+' && !$expectingOperator) {            //    Positive (unary plus rather than binary operator plus) can be discarded?
1493
                ++$index; //    Drop the redundant plus symbol
1494
            } 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
            } elseif ((isset(self::CALCULATION_OPERATORS[$opCharacter]) || $isOperandOrFunction) && $expectingOperator) {    //    Are we putting an operator on the stack?
1498
                while (
1499
                    $stack->count() > 0
1500
                    && ($o2 = $stack->last())
1501
                    && isset(self::CALCULATION_OPERATORS[$o2['value']])
1502
                    && @(self::$operatorAssociativity[$opCharacter] ? self::$operatorPrecedence[$opCharacter] < self::$operatorPrecedence[$o2['value']] : self::$operatorPrecedence[$opCharacter] <= self::$operatorPrecedence[$o2['value']])
1503
                ) {
1504
                    $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
                $stack->push('Binary Operator', $opCharacter);
1509
1510
                ++$index;
1511
                $expectingOperator = false;
1512
            } elseif ($opCharacter === ')' && $expectingOperator) { //    Are we expecting to close a parenthesis?
1513
                $expectingOperand = false;
1514
                while (($o2 = $stack->pop()) && $o2['value'] !== '(') { //    Pop off the stack back to the last (
1515
                    $output[] = $o2;
1516
                }
1517
                $d = $stack->last(2);
1518
1519
                // Branch pruning we decrease the depth whether is it a function
1520
                // call or a parenthesis
1521
                $this->branchPruner->decrementDepth();
1522
1523
                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
                        $this->branchPruner->closingBrace($d['value']);
1527
                    } catch (Exception $e) {
1528
                        return $this->raiseFormulaError($e->getMessage(), $e->getCode(), $e);
1529
                    }
1530
1531
                    $functionName = $matches[1]; //    Get the function name
1532
                    $d = $stack->pop();
1533
                    $argumentCount = $d['value'] ?? 0; //    See how many arguments there were (argument count is the next value stored on the stack)
1534
                    $output[] = $d; //    Dump the argument count on the output
1535
                    $output[] = $stack->pop(); //    Pop the function and push onto the output
1536
                    if (isset(self::$controlFunctions[$functionName])) {
1537
                        $expectedArgumentCount = self::$controlFunctions[$functionName]['argumentCount'];
1538
                    } elseif (isset($phpSpreadsheetFunctions[$functionName])) {
1539
                        $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
                    $argumentCountError = false;
1545
                    $expectedArgumentCountString = null;
1546
                    if (is_numeric($expectedArgumentCount)) {
1547
                        if ($expectedArgumentCount < 0) {
1548
                            if ($argumentCount > abs($expectedArgumentCount + 0)) {
1549
                                $argumentCountError = true;
1550
                                $expectedArgumentCountString = 'no more than ' . abs($expectedArgumentCount + 0);
1551
                            }
1552
                        } else {
1553
                            if ($argumentCount != $expectedArgumentCount) {
1554
                                $argumentCountError = true;
1555
                                $expectedArgumentCountString = $expectedArgumentCount;
1556
                            }
1557
                        }
1558
                    } elseif ($expectedArgumentCount != '*') {
1559
                        if (1 !== preg_match('/(\d*)([-+,])(\d*)/', $expectedArgumentCount, $argMatch)) {
1560
                            $argMatch = ['', '', '', ''];
1561
                        }
1562
                        switch ($argMatch[2]) {
1563
                            case '+':
1564
                                if ($argumentCount < $argMatch[1]) {
1565
                                    $argumentCountError = true;
1566
                                    $expectedArgumentCountString = $argMatch[1] . ' or more ';
1567
                                }
1568
1569
                                break;
1570
                            case '-':
1571
                                if (($argumentCount < $argMatch[1]) || ($argumentCount > $argMatch[3])) {
1572
                                    $argumentCountError = true;
1573
                                    $expectedArgumentCountString = 'between ' . $argMatch[1] . ' and ' . $argMatch[3];
1574
                                }
1575
1576
                                break;
1577
                            case ',':
1578
                                if (($argumentCount != $argMatch[1]) && ($argumentCount != $argMatch[3])) {
1579
                                    $argumentCountError = true;
1580
                                    $expectedArgumentCountString = 'either ' . $argMatch[1] . ' or ' . $argMatch[3];
1581
                                }
1582
1583
                                break;
1584
                        }
1585
                    }
1586
                    if ($argumentCountError) {
1587
                        return $this->raiseFormulaError("Formula Error: Wrong number of arguments for $functionName() function: $argumentCount given, " . $expectedArgumentCountString . ' expected');
1588
                    }
1589
                }
1590
                ++$index;
1591
            } elseif ($opCharacter === ',') { // Is this the separator for function arguments?
1592
                try {
1593
                    $this->branchPruner->argumentSeparator();
1594
                } catch (Exception $e) {
1595
                    return $this->raiseFormulaError($e->getMessage(), $e->getCode(), $e);
1596
                }
1597
1598
                while (($o2 = $stack->pop()) && $o2['value'] !== '(') {        //    Pop off the stack back to the last (
1599
                    $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
                if (($expectingOperand) || (!$expectingOperator)) {
1604
                    $output[] = $stack->getStackItem('Empty Argument', null, 'NULL');
1605
                }
1606
                // make sure there was a function
1607
                $d = $stack->last(2);
1608
                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
                $d = $stack->pop();
1618
                ++$d['value']; // increment the argument count
1619
1620
                $stack->pushStackItem($d);
1621
                $stack->push('Brace', '('); // put the ( back on, we'll need to pop back to it again
1622
1623
                $expectingOperator = false;
1624
                $expectingOperand = true;
1625
                ++$index;
1626
            } elseif ($opCharacter === '(' && !$expectingOperator) {
1627
                // Branch pruning: we go deeper
1628
                $this->branchPruner->incrementDepth();
1629
                $stack->push('Brace', '(', null);
1630
                ++$index;
1631
            } elseif ($isOperandOrFunction && !$expectingOperatorCopy) {
1632
                // do we now have a function/variable/number?
1633
                $expectingOperator = true;
1634
                $expectingOperand = false;
1635
                $val = $match[1] ?? ''; //* @phpstan-ignore-line
1636
                $length = strlen($val);
1637
1638
                if (preg_match('/^' . self::CALCULATION_REGEXP_FUNCTION . '$/miu', $val, $matches)) {
1639
                    $val = (string) preg_replace('/\s/u', '', $val);
1640
                    if (isset($phpSpreadsheetFunctions[strtoupper($matches[1])]) || isset(self::$controlFunctions[strtoupper($matches[1])])) {    // it's a function
1641
                        $valToUpper = strtoupper($val);
1642
                    } else {
1643
                        $valToUpper = 'NAME.ERROR(';
1644
                    }
1645
                    // here $matches[1] will contain values like "IF"
1646
                    // and $val "IF("
1647
1648
                    $this->branchPruner->functionCall($valToUpper);
1649
1650
                    $stack->push('Function', $valToUpper);
1651
                    // tests if the function is closed right after opening
1652
                    $ax = preg_match('/^\s*\)/u', substr($formula, $index + $length));
1653
                    if ($ax) {
1654
                        $stack->push('Operand Count for Function ' . $valToUpper . ')', 0);
1655
                        $expectingOperator = true;
1656
                    } else {
1657
                        $stack->push('Operand Count for Function ' . $valToUpper . ')', 1);
1658
                        $expectingOperator = false;
1659
                    }
1660
                    $stack->push('Brace', '(');
1661
                } 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
                    $testPrevOp = $stack->last(1);
1666
                    if ($testPrevOp !== null && $testPrevOp['value'] === ':') {
1667
                        //    If we have a worksheet reference, then we're playing with a 3D reference
1668
                        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
                            $rangeStartCellRef = $output[count($output) - 1]['value'] ?? '';
1672
                            if ($rangeStartCellRef === ':') {
1673
                                // Do we have chained range operators?
1674
                                $rangeStartCellRef = $output[count($output) - 2]['value'] ?? '';
1675
                            }
1676
                            preg_match('/^' . self::CALCULATION_REGEXP_CELLREF . '$/miu', $rangeStartCellRef, $rangeStartMatches);
1677
                            if (array_key_exists(2, $rangeStartMatches)) {
1678
                                if ($rangeStartMatches[2] > '') {
1679
                                    $val = $rangeStartMatches[2] . '!' . $val;
1680
                                }
1681
                            } else {
1682
                                $val = ExcelError::REF();
1683
                            }
1684
                        } else {
1685
                            $rangeStartCellRef = $output[count($output) - 1]['value'] ?? '';
1686
                            if ($rangeStartCellRef === ':') {
1687
                                // Do we have chained range operators?
1688
                                $rangeStartCellRef = $output[count($output) - 2]['value'] ?? '';
1689
                            }
1690
                            preg_match('/^' . self::CALCULATION_REGEXP_CELLREF . '$/miu', $rangeStartCellRef, $rangeStartMatches);
1691
                            if (isset($rangeStartMatches[2]) && $rangeStartMatches[2] !== $matches[2]) {
1692
                                return $this->raiseFormulaError('3D Range references are not yet supported');
1693
                            }
1694
                        }
1695
                    } elseif (!str_contains($val, '!') && $pCellParent !== null) {
1696
                        $worksheet = $pCellParent->getTitle();
1697
                        $val = "'{$worksheet}'!{$val}";
1698
                    }
1699
                    // unescape any apostrophes or double quotes in worksheet name
1700
                    $val = str_replace(["''", '""'], ["'", '"'], $val);
1701
                    $outputItem = $stack->getStackItem('Cell Reference', $val, $val);
1702
1703
                    $output[] = $outputItem;
1704
                } elseif (preg_match('/^' . self::CALCULATION_REGEXP_STRUCTURED_REFERENCE . '$/miu', $val, $matches)) {
1705
                    try {
1706
                        $structuredReference = Operands\StructuredReference::fromParser($formula, $index, $matches);
1707
                    } catch (Exception $e) {
1708
                        return $this->raiseFormulaError($e->getMessage(), $e->getCode(), $e);
1709
                    }
1710
1711
                    $val = $structuredReference->value();
1712
                    $length = strlen($val);
1713
                    $outputItem = $stack->getStackItem(Operands\StructuredReference::NAME, $structuredReference, null);
1714
1715
                    $output[] = $outputItem;
1716
                    $expectingOperator = true;
1717
                } else {
1718
                    // it's a variable, constant, string, number or boolean
1719
                    $localeConstant = false;
1720
                    $stackItemType = 'Value';
1721
                    $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
                    $testPrevOp = $stack->last(1);
1725
                    if ($testPrevOp !== null && $testPrevOp['value'] === ':') {
1726
                        $stackItemType = 'Cell Reference';
1727
1728
                        if (
1729
                            !is_numeric($val)
1730
                            && ((ctype_alpha($val) === false || strlen($val) > 3))
1731
                            && (preg_match('/^' . self::CALCULATION_REGEXP_DEFINEDNAME . '$/mui', $val) !== false)
1732
                            && ($this->spreadsheet === null || $this->spreadsheet->getNamedRange($val) !== null)
1733
                        ) {
1734
                            $namedRange = ($this->spreadsheet === null) ? null : $this->spreadsheet->getNamedRange($val);
1735
                            if ($namedRange !== null) {
1736
                                $stackItemType = 'Defined Name';
1737
                                $address = str_replace('$', '', $namedRange->getValue());
1738
                                $stackItemReference = $val;
1739
                                if (str_contains($address, ':')) {
1740
                                    // We'll need to manipulate the stack for an actual named range rather than a named cell
1741
                                    $fromTo = explode(':', $address);
1742
                                    $to = array_pop($fromTo);
1743
                                    foreach ($fromTo as $from) {
1744
                                        $output[] = $stack->getStackItem($stackItemType, $from, $stackItemReference);
1745
                                        $output[] = $stack->getStackItem('Binary Operator', ':');
1746
                                    }
1747
                                    $address = $to;
1748
                                }
1749
                                $val = $address;
1750
                            }
1751
                        } elseif ($val === ExcelError::REF()) {
1752
                            $stackItemReference = $val;
1753
                        } else {
1754
                            /** @var non-empty-string $startRowColRef */
1755
                            $startRowColRef = $output[count($output) - 1]['value'] ?? '';
1756
                            [$rangeWS1, $startRowColRef] = Worksheet::extractSheetTitle($startRowColRef, true);
1757
                            $rangeSheetRef = $rangeWS1;
1758
                            if ($rangeWS1 !== '') {
1759
                                $rangeWS1 .= '!';
1760
                            }
1761
                            if (str_starts_with($rangeSheetRef, "'")) {
1762
                                $rangeSheetRef = Worksheet::unApostrophizeTitle($rangeSheetRef);
1763
                            }
1764
                            [$rangeWS2, $val] = Worksheet::extractSheetTitle($val, true);
1765
                            if ($rangeWS2 !== '') {
1766
                                $rangeWS2 .= '!';
1767
                            } else {
1768
                                $rangeWS2 = $rangeWS1;
1769
                            }
1770
1771
                            $refSheet = $pCellParent;
1772
                            if ($pCellParent !== null && $rangeSheetRef !== '' && $rangeSheetRef !== $pCellParent->getTitle()) {
1773
                                $refSheet = $pCellParent->getParentOrThrow()->getSheetByName($rangeSheetRef);
1774
                            }
1775
1776
                            if (ctype_digit($val) && $val <= 1048576) {
1777
                                //    Row range
1778
                                $stackItemType = 'Row Reference';
1779
                                $valx = $val;
1780
                                $endRowColRef = ($refSheet !== null) ? $refSheet->getHighestDataColumn($valx) : AddressRange::MAX_COLUMN; //    Max 16,384 columns for Excel2007
1781
                                $val = "{$rangeWS2}{$endRowColRef}{$val}";
1782
                            } elseif (ctype_alpha($val) && strlen($val) <= 3) {
1783
                                //    Column range
1784
                                $stackItemType = 'Column Reference';
1785
                                $endRowColRef = ($refSheet !== null) ? $refSheet->getHighestDataRow($val) : AddressRange::MAX_ROW; //    Max 1,048,576 rows for Excel2007
1786
                                $val = "{$rangeWS2}{$val}{$endRowColRef}";
1787
                            }
1788
                            $stackItemReference = $val;
1789
                        }
1790
                    } elseif ($opCharacter === self::FORMULA_STRING_QUOTE) {
1791
                        //    UnEscape any quotes within the string
1792
                        $val = self::wrapResult(str_replace('""', self::FORMULA_STRING_QUOTE, self::unwrapResult($val)));
1793
                    } elseif (isset(self::$excelConstants[trim(strtoupper($val))])) {
1794
                        $stackItemType = 'Constant';
1795
                        $excelConstant = trim(strtoupper($val));
1796
                        $val = self::$excelConstants[$excelConstant];
1797
                        $stackItemReference = $excelConstant;
1798
                    } elseif (($localeConstant = array_search(trim(strtoupper($val)), self::$localeBoolean)) !== false) {
1799
                        $stackItemType = 'Constant';
1800
                        $val = self::$excelConstants[$localeConstant];
1801
                        $stackItemReference = $localeConstant;
1802
                    } elseif (
1803
                        preg_match('/^' . self::CALCULATION_REGEXP_ROW_RANGE . '/miu', substr($formula, $index), $rowRangeReference)
1804
                    ) {
1805
                        $val = $rowRangeReference[1];
1806
                        $length = strlen($rowRangeReference[1]);
1807
                        $stackItemType = 'Row Reference';
1808
                        // unescape any apostrophes or double quotes in worksheet name
1809
                        $val = str_replace(["''", '""'], ["'", '"'], $val);
1810
                        $column = 'A';
1811
                        if (($testPrevOp !== null && $testPrevOp['value'] === ':') && $pCellParent !== null) {
1812
                            $column = $pCellParent->getHighestDataColumn($val);
1813
                        }
1814
                        $val = "{$rowRangeReference[2]}{$column}{$rowRangeReference[7]}";
1815
                        $stackItemReference = $val;
1816
                    } elseif (
1817
                        preg_match('/^' . self::CALCULATION_REGEXP_COLUMN_RANGE . '/miu', substr($formula, $index), $columnRangeReference)
1818
                    ) {
1819
                        $val = $columnRangeReference[1];
1820
                        $length = strlen($val);
1821
                        $stackItemType = 'Column Reference';
1822
                        // unescape any apostrophes or double quotes in worksheet name
1823
                        $val = str_replace(["''", '""'], ["'", '"'], $val);
1824
                        $row = '1';
1825
                        if (($testPrevOp !== null && $testPrevOp['value'] === ':') && $pCellParent !== null) {
1826
                            $row = $pCellParent->getHighestDataRow($val);
1827
                        }
1828
                        $val = "{$val}{$row}";
1829
                        $stackItemReference = $val;
1830
                    } elseif (preg_match('/^' . self::CALCULATION_REGEXP_DEFINEDNAME . '.*/miu', $val, $match)) {
1831
                        $stackItemType = 'Defined Name';
1832
                        $stackItemReference = $val;
1833
                    } elseif (is_numeric($val)) {
1834
                        if ((str_contains((string) $val, '.')) || (stripos((string) $val, 'e') !== false) || ($val > PHP_INT_MAX) || ($val < -PHP_INT_MAX)) {
1835
                            $val = (float) $val;
1836
                        } else {
1837
                            $val = (int) $val;
1838
                        }
1839
                    }
1840
1841
                    $details = $stack->getStackItem($stackItemType, $val, $stackItemReference);
1842
                    if ($localeConstant) {
1843
                        $details['localeValue'] = $localeConstant;
1844
                    }
1845
                    $output[] = $details;
1846
                }
1847
                $index += $length;
1848
            } elseif ($opCharacter === '$') { // absolute row or column range
1849
                ++$index;
1850
            } elseif ($opCharacter === ')') { // miscellaneous error checking
1851
                if ($expectingOperand) {
1852
                    $output[] = $stack->getStackItem('Empty Argument', null, 'NULL');
1853
                    $expectingOperand = false;
1854
                    $expectingOperator = true;
1855
                } else {
1856
                    return $this->raiseFormulaError("Formula Error: Unexpected ')'");
1857
                }
1858
            } 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
                return $this->raiseFormulaError('Formula Error: An unexpected error occurred');
1862
            }
1863
            //    Test for end of formula string
1864
            if ($index == strlen($formula)) {
1865
                //    Did we end with an operator?.
1866
                //    Only valid for the % unary operator
1867
                if ((isset(self::CALCULATION_OPERATORS[$opCharacter])) && ($opCharacter != '%')) {
1868
                    return $this->raiseFormulaError("Formula Error: Operator '$opCharacter' has no operands");
1869
                }
1870
1871
                break;
1872
            }
1873
            //    Ignore white space
1874
            while (($formula[$index] === "\n") || ($formula[$index] === "\r")) {
1875
                ++$index;
1876
            }
1877
1878
            if ($formula[$index] === ' ') {
1879
                while ($formula[$index] === ' ') {
1880
                    ++$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
                $countOutputMinus1 = count($output) - 1;
1886
                if (
1887
                    ($expectingOperator)
1888
                    && array_key_exists($countOutputMinus1, $output)
1889
                    && is_array($output[$countOutputMinus1])
1890
                    && array_key_exists('type', $output[$countOutputMinus1])
1891
                    && (
1892
                        (preg_match('/^' . self::CALCULATION_REGEXP_CELLREF . '.*/miu', substr($formula, $index), $match))
1893
                            && ($output[$countOutputMinus1]['type'] === 'Cell Reference')
1894
                        || (preg_match('/^' . self::CALCULATION_REGEXP_DEFINEDNAME . '.*/miu', substr($formula, $index), $match))
1895
                            && ($output[$countOutputMinus1]['type'] === 'Defined Name' || $output[$countOutputMinus1]['type'] === 'Value')
1896
                        || (preg_match('/^' . self::CALCULATION_REGEXP_STRUCTURED_REFERENCE . '.*/miu', substr($formula, $index), $match))
1897
                            && ($output[$countOutputMinus1]['type'] === Operands\StructuredReference::NAME || $output[$countOutputMinus1]['type'] === 'Value')
1898
                    )
1899
                ) {
1900
                    while (
1901
                        $stack->count() > 0
1902
                        && ($o2 = $stack->last())
1903
                        && isset(self::CALCULATION_OPERATORS[$o2['value']])
1904
                        && @(self::$operatorAssociativity[$opCharacter] ? self::$operatorPrecedence[$opCharacter] < self::$operatorPrecedence[$o2['value']] : self::$operatorPrecedence[$opCharacter] <= self::$operatorPrecedence[$o2['value']])
1905
                    ) {
1906
                        $output[] = $stack->pop(); //    Swap operands and higher precedence operators from the stack to the output
1907
                    }
1908
                    $stack->push('Binary Operator', '∩'); //    Put an Intersect Operator on the stack
1909
                    $expectingOperator = false;
1910
                }
1911
            }
1912
        }
1913
1914
        while (($op = $stack->pop()) !== null) {
1915
            // pop everything off the stack and push onto output
1916
            if ($op['value'] == '(') {
1917
                return $this->raiseFormulaError("Formula Error: Expecting ')'"); // if there are any opening braces on the stack, then braces were unbalanced
1918
            }
1919
            $output[] = $op;
1920
        }
1921
1922
        return $output;
1923
    }
1924
1925
    private static function dataTestReference(array &$operandData): mixed
1926
    {
1927
        $operand = $operandData['value'];
1928
        if (($operandData['reference'] === null) && (is_array($operand))) {
1929
            $rKeys = array_keys($operand);
1930
            $rowKey = array_shift($rKeys);
1931
            if (is_array($operand[$rowKey]) === false) {
1932
                $operandData['value'] = $operand[$rowKey];
1933
1934
                return $operand[$rowKey];
1935
            }
1936
1937
            $cKeys = array_keys(array_keys($operand[$rowKey]));
1938
            $colKey = array_shift($cKeys);
1939
            if (ctype_upper("$colKey")) {
1940
                $operandData['reference'] = $colKey . $rowKey;
1941
            }
1942
        }
1943
1944
        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
    private function processTokenStack(mixed $tokens, ?string $cellID = null, ?Cell $cell = null)
1957
    {
1958
        if ($tokens === false) {
1959
            return false;
1960
        }
1961
        $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
        $pCellWorksheet = ($cell !== null) ? $cell->getWorksheet() : null;
1966
        $originalCoordinate = $cell?->getCoordinate();
1967
        $pCellParent = ($cell !== null) ? $cell->getParent() : null;
1968
        $stack = new Stack($this->branchPruner);
1969
1970
        // Stores branches that have been pruned
1971
        $fakedForBranchPruning = [];
1972
        // help us to know when pruning ['branchTestId' => true/false]
1973
        $branchStore = [];
1974
        //    Loop through each token in turn
1975
        foreach ($tokens as $tokenIdx => $tokenData) {
1976
            $this->processingAnchorArray = false;
1977
            if ($tokenData['type'] === 'Cell Reference' && isset($tokens[$tokenIdx + 1]) && $tokens[$tokenIdx + 1]['type'] === 'Operand Count for Function ANCHORARRAY()') {
1978
                $this->processingAnchorArray = true;
1979
            }
1980
            $token = $tokenData['value'];
1981
            // Branch pruning: skip useless resolutions
1982
            $storeKey = $tokenData['storeKey'] ?? null;
1983
            if ($this->branchPruningEnabled && isset($tokenData['onlyIf'])) {
1984
                $onlyIfStoreKey = $tokenData['onlyIf'];
1985
                $storeValue = $branchStore[$onlyIfStoreKey] ?? null;
1986
                $storeValueAsBool = ($storeValue === null)
1987
                    ? true : (bool) Functions::flattenSingleValue($storeValue);
1988
                if (is_array($storeValue)) {
1989
                    $wrappedItem = end($storeValue);
1990
                    $storeValue = is_array($wrappedItem) ? end($wrappedItem) : $wrappedItem;
1991
                }
1992
1993
                if (
1994
                    (isset($storeValue) || $tokenData['reference'] === 'NULL')
1995
                    && (!$storeValueAsBool || Information\ErrorValue::isError($storeValue) || ($storeValue === 'Pruned branch'))
1996
                ) {
1997
                    // If branching value is not true, we don't need to compute
1998
                    if (!isset($fakedForBranchPruning['onlyIf-' . $onlyIfStoreKey])) {
1999
                        $stack->push('Value', 'Pruned branch (only if ' . $onlyIfStoreKey . ') ' . $token);
2000
                        $fakedForBranchPruning['onlyIf-' . $onlyIfStoreKey] = true;
2001
                    }
2002
2003
                    if (isset($storeKey)) {
2004
                        // We are processing an if condition
2005
                        // We cascade the pruning to the depending branches
2006
                        $branchStore[$storeKey] = 'Pruned branch';
2007
                        $fakedForBranchPruning['onlyIfNot-' . $storeKey] = true;
2008
                        $fakedForBranchPruning['onlyIf-' . $storeKey] = true;
2009
                    }
2010
2011
                    continue;
2012
                }
2013
            }
2014
2015
            if ($this->branchPruningEnabled && isset($tokenData['onlyIfNot'])) {
2016
                $onlyIfNotStoreKey = $tokenData['onlyIfNot'];
2017
                $storeValue = $branchStore[$onlyIfNotStoreKey] ?? null;
2018
                $storeValueAsBool = ($storeValue === null)
2019
                    ? true : (bool) Functions::flattenSingleValue($storeValue);
2020
                if (is_array($storeValue)) {
2021
                    $wrappedItem = end($storeValue);
2022
                    $storeValue = is_array($wrappedItem) ? end($wrappedItem) : $wrappedItem;
2023
                }
2024
2025
                if (
2026
                    (isset($storeValue) || $tokenData['reference'] === 'NULL')
2027
                    && ($storeValueAsBool || Information\ErrorValue::isError($storeValue) || ($storeValue === 'Pruned branch'))
2028
                ) {
2029
                    // If branching value is true, we don't need to compute
2030
                    if (!isset($fakedForBranchPruning['onlyIfNot-' . $onlyIfNotStoreKey])) {
2031
                        $stack->push('Value', 'Pruned branch (only if not ' . $onlyIfNotStoreKey . ') ' . $token);
2032
                        $fakedForBranchPruning['onlyIfNot-' . $onlyIfNotStoreKey] = true;
2033
                    }
2034
2035
                    if (isset($storeKey)) {
2036
                        // We are processing an if condition
2037
                        // We cascade the pruning to the depending branches
2038
                        $branchStore[$storeKey] = 'Pruned branch';
2039
                        $fakedForBranchPruning['onlyIfNot-' . $storeKey] = true;
2040
                        $fakedForBranchPruning['onlyIf-' . $storeKey] = true;
2041
                    }
2042
2043
                    continue;
2044
                }
2045
            }
2046
2047
            if ($token instanceof Operands\StructuredReference) {
2048
                if ($cell === null) {
2049
                    return $this->raiseFormulaError('Structured References must exist in a Cell context');
2050
                }
2051
2052
                try {
2053
                    $cellRange = $token->parse($cell);
2054
                    if (str_contains($cellRange, ':')) {
2055
                        $this->debugLog->writeDebugLog('Evaluating Structured Reference %s as Cell Range %s', $token->value(), $cellRange);
2056
                        $rangeValue = self::getInstance($cell->getWorksheet()->getParent())->_calculateFormulaValue("={$cellRange}", $cellRange, $cell);
2057
                        $stack->push('Value', $rangeValue);
2058
                        $this->debugLog->writeDebugLog('Evaluated Structured Reference %s as value %s', $token->value(), $this->showValue($rangeValue));
2059
                    } else {
2060
                        $this->debugLog->writeDebugLog('Evaluating Structured Reference %s as Cell %s', $token->value(), $cellRange);
2061
                        $cellValue = $cell->getWorksheet()->getCell($cellRange)->getCalculatedValue(false);
2062
                        $stack->push('Cell Reference', $cellValue, $cellRange);
2063
                        $this->debugLog->writeDebugLog('Evaluated Structured Reference %s as value %s', $token->value(), $this->showValue($cellValue));
2064
                    }
2065
                } catch (Exception $e) {
2066
                    if ($e->getCode() === Exception::CALCULATION_ENGINE_PUSH_TO_STACK) {
2067
                        $stack->push('Error', ExcelError::REF(), null);
2068
                        $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
            } 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
                $operand2Data = $stack->pop();
2077
                if ($operand2Data === null) {
2078
                    return $this->raiseFormulaError('Internal error - Operand value missing from stack');
2079
                }
2080
                $operand1Data = $stack->pop();
2081
                if ($operand1Data === null) {
2082
                    return $this->raiseFormulaError('Internal error - Operand value missing from stack');
2083
                }
2084
2085
                $operand1 = self::dataTestReference($operand1Data);
2086
                $operand2 = self::dataTestReference($operand2Data);
2087
2088
                //    Log what we're doing
2089
                if ($token == ':') {
2090
                    $this->debugLog->writeDebugLog('Evaluating Range %s %s %s', $this->showValue($operand1Data['reference']), $token, $this->showValue($operand2Data['reference']));
2091
                } else {
2092
                    $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
                    case '>': // Greater than
2099
                    case '<': // Less than
2100
                    case '>=': // Greater than or Equal to
2101
                    case '<=': // Less than or Equal to
2102
                    case '=': // Equality
2103
                    case '<>': // Inequality
2104
                        $result = $this->executeBinaryComparisonOperation($operand1, $operand2, (string) $token, $stack);
2105
                        if (isset($storeKey)) {
2106
                            $branchStore[$storeKey] = $result;
2107
                        }
2108
2109
                        break;
2110
                    // Binary Operators
2111
                    case ':': // Range
2112
                        if ($operand1Data['type'] === 'Defined Name') {
2113
                            if (preg_match('/$' . self::CALCULATION_REGEXP_DEFINEDNAME . '^/mui', $operand1Data['reference']) !== false && $this->spreadsheet !== null) {
2114
                                $definedName = $this->spreadsheet->getNamedRange($operand1Data['reference']);
2115
                                if ($definedName !== null) {
2116
                                    $operand1Data['reference'] = $operand1Data['value'] = str_replace('$', '', $definedName->getValue());
2117
                                }
2118
                            }
2119
                        }
2120
                        if (str_contains($operand1Data['reference'] ?? '', '!')) {
2121
                            [$sheet1, $operand1Data['reference']] = Worksheet::extractSheetTitle($operand1Data['reference'], true, true);
2122
                        } else {
2123
                            $sheet1 = ($pCellWorksheet !== null) ? $pCellWorksheet->getTitle() : '';
2124
                        }
2125
                        $sheet1 ??= '';
2126
2127
                        [$sheet2, $operand2Data['reference']] = Worksheet::extractSheetTitle($operand2Data['reference'], true, true);
2128
                        if (empty($sheet2)) {
2129
                            $sheet2 = $sheet1;
2130
                        }
2131
2132
                        if ($sheet1 === $sheet2) {
2133
                            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
                            if ($operand2Data['reference'] === null && $cell !== null) {
2145
                                if (is_array($operand2Data['value'])) {
2146
                                    $operand2Data['reference'] = $cell->getCoordinate();
2147
                                } elseif ((trim($operand2Data['value']) != '') && (is_numeric($operand2Data['value']))) {
2148
                                    $operand2Data['reference'] = $cell->getColumn() . $operand2Data['value'];
2149
                                } elseif (trim($operand2Data['value']) == '') {
2150
                                    $operand2Data['reference'] = $cell->getCoordinate();
2151
                                } else {
2152
                                    $operand2Data['reference'] = $operand2Data['value'] . $cell->getRow();
2153
                                }
2154
                            }
2155
2156
                            $oData = array_merge(explode(':', $operand1Data['reference'] ?? ''), explode(':', $operand2Data['reference'] ?? ''));
2157
                            $oCol = $oRow = [];
2158
                            $breakNeeded = false;
2159
                            foreach ($oData as $oDatum) {
2160
                                try {
2161
                                    $oCR = Coordinate::coordinateFromString($oDatum);
2162
                                    $oCol[] = Coordinate::columnIndexFromString($oCR[0]) - 1;
2163
                                    $oRow[] = $oCR[1];
2164
                                } catch (\Exception) {
2165
                                    $stack->push('Error', ExcelError::REF(), null);
2166
                                    $breakNeeded = true;
2167
2168
                                    break;
2169
                                }
2170
                            }
2171
                            if ($breakNeeded) {
2172
                                break;
2173
                            }
2174
                            $cellRef = Coordinate::stringFromColumnIndex(min($oCol) + 1) . min($oRow) . ':' . Coordinate::stringFromColumnIndex(max($oCol) + 1) . max($oRow); // @phpstan-ignore-line
2175
                            if ($pCellParent !== null && $this->spreadsheet !== null) {
2176
                                $cellValue = $this->extractCellRange($cellRef, $this->spreadsheet->getSheetByName($sheet1), false);
2177
                            } else {
2178
                                return $this->raiseFormulaError('Unable to access Cell Reference');
2179
                            }
2180
2181
                            $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($cellValue));
2182
                            $stack->push('Cell Reference', $cellValue, $cellRef);
2183
                        } else {
2184
                            $this->debugLog->writeDebugLog('Evaluation Result is a #REF! Error');
2185
                            $stack->push('Error', ExcelError::REF(), null);
2186
                        }
2187
2188
                        break;
2189
                    case '+':            //    Addition
2190
                    case '-':            //    Subtraction
2191
                    case '*':            //    Multiplication
2192
                    case '/':            //    Division
2193
                    case '^':            //    Exponential
2194
                        $result = $this->executeNumericBinaryOperation($operand1, $operand2, $token, $stack);
2195
                        if (isset($storeKey)) {
2196
                            $branchStore[$storeKey] = $result;
2197
                        }
2198
2199
                        break;
2200
                    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
                        $operand1 = self::boolToString($operand1);
2205
                        $operand2 = self::boolToString($operand2);
2206
                        if (is_array($operand1) || is_array($operand2)) {
2207
                            if (is_string($operand1)) {
2208
                                $operand1 = self::unwrapResult($operand1);
2209
                            }
2210
                            if (is_string($operand2)) {
2211
                                $operand2 = self::unwrapResult($operand2);
2212
                            }
2213
                            //    Ensure that both operands are arrays/matrices
2214
                            [$rows, $columns] = self::checkMatrixOperands($operand1, $operand2, 2);
2215
2216
                            for ($row = 0; $row < $rows; ++$row) {
2217
                                for ($column = 0; $column < $columns; ++$column) {
2218
                                    $op1x = self::boolToString($operand1[$row][$column]);
2219
                                    $op2x = self::boolToString($operand2[$row][$column]);
2220
                                    if (Information\ErrorValue::isError($op1x)) {
2221
                                        // no need to do anything
2222
                                    } elseif (Information\ErrorValue::isError($op2x)) {
2223
                                        $operand1[$row][$column] = $op2x;
2224
                                    } else {
2225
                                        $operand1[$row][$column]
2226
                                            = Shared\StringHelper::substring(
2227
                                                $op1x . $op2x,
2228
                                                0,
2229
                                                DataType::MAX_STRING_LENGTH
2230
                                            );
2231
                                    }
2232
                                }
2233
                            }
2234
                            $result = $operand1;
2235
                        } else {
2236
                            if (Information\ErrorValue::isError($operand1)) {
2237
                                $result = $operand1;
2238
                            } elseif (Information\ErrorValue::isError($operand2)) {
2239
                                $result = $operand2;
2240
                            } else {
2241
                                $result = str_replace('""', self::FORMULA_STRING_QUOTE, self::unwrapResult($operand1) . self::unwrapResult($operand2));
2242
                                $result = Shared\StringHelper::substring(
2243
                                    $result,
2244
                                    0,
2245
                                    DataType::MAX_STRING_LENGTH
2246
                                );
2247
                                $result = self::FORMULA_STRING_QUOTE . $result . self::FORMULA_STRING_QUOTE;
2248
                            }
2249
                        }
2250
                        $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($result));
2251
                        $stack->push('Value', $result);
2252
2253
                        if (isset($storeKey)) {
2254
                            $branchStore[$storeKey] = $result;
2255
                        }
2256
2257
                        break;
2258
                    case '∩':            //    Intersect
2259
                        $rowIntersect = array_intersect_key($operand1, $operand2);
2260
                        $cellIntersect = $oCol = $oRow = [];
2261
                        foreach (array_keys($rowIntersect) as $row) {
2262
                            $oRow[] = $row;
2263
                            foreach ($rowIntersect[$row] as $col => $data) {
2264
                                $oCol[] = Coordinate::columnIndexFromString($col) - 1;
2265
                                $cellIntersect[$row] = array_intersect_key($operand1[$row], $operand2[$row]);
2266
                            }
2267
                        }
2268
                        if (count(Functions::flattenArray($cellIntersect)) === 0) {
2269
                            $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($cellIntersect));
2270
                            $stack->push('Error', ExcelError::null(), null);
2271
                        } else {
2272
                            $cellRef = Coordinate::stringFromColumnIndex(min($oCol) + 1) . min($oRow) . ':' // @phpstan-ignore-line
2273
                                . Coordinate::stringFromColumnIndex(max($oCol) + 1) . max($oRow); // @phpstan-ignore-line
2274
                            $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($cellIntersect));
2275
                            $stack->push('Value', $cellIntersect, $cellRef);
2276
                        }
2277
2278
                        break;
2279
                }
2280
            } 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
                if (($arg = $stack->pop()) === null) {
2283
                    return $this->raiseFormulaError('Internal error - Operand value missing from stack');
2284
                }
2285
                $arg = $arg['value'];
2286
                if ($token === '~') {
2287
                    $this->debugLog->writeDebugLog('Evaluating Negation of %s', $this->showValue($arg));
2288
                    $multiplier = -1;
2289
                } else {
2290
                    $this->debugLog->writeDebugLog('Evaluating Percentile of %s', $this->showValue($arg));
2291
                    $multiplier = 0.01;
2292
                }
2293
                if (is_array($arg)) {
2294
                    $operand2 = $multiplier;
2295
                    $result = $arg;
2296
                    [$rows, $columns] = self::checkMatrixOperands($result, $operand2, 0);
2297
                    for ($row = 0; $row < $rows; ++$row) {
2298
                        for ($column = 0; $column < $columns; ++$column) {
2299
                            if (self::isNumericOrBool($result[$row][$column])) {
2300
                                $result[$row][$column] *= $multiplier;
2301
                            } else {
2302
                                $result[$row][$column] = self::makeError($result[$row][$column]);
2303
                            }
2304
                        }
2305
                    }
2306
2307
                    $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($result));
2308
                    $stack->push('Value', $result);
2309
                    if (isset($storeKey)) {
2310
                        $branchStore[$storeKey] = $result;
2311
                    }
2312
                } else {
2313
                    $this->executeNumericBinaryOperation($multiplier, $arg, '*', $stack);
2314
                }
2315
            } elseif (preg_match('/^' . self::CALCULATION_REGEXP_CELLREF . '$/i', $token ?? '', $matches)) {
2316
                $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
                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
                    if ($cell === null) {
2355
                        // We can't access the cell, so return a REF error
2356
                        $cellValue = ExcelError::REF();
2357
                    } else {
2358
                        $cellRef = $matches[6] . $matches[7];
2359
                        if ($matches[2] > '') {
2360
                            $matches[2] = trim($matches[2], "\"'");
2361
                            if ((str_contains($matches[2], '[')) || (str_contains($matches[2], ']'))) {
2362
                                //    It's a Reference to an external spreadsheet (not currently supported)
2363
                                return $this->raiseFormulaError('Unable to access External Workbook');
2364
                            }
2365
                            $this->debugLog->writeDebugLog('Evaluating Cell %s in worksheet %s', $cellRef, $matches[2]);
2366
                            if ($pCellParent !== null && $this->spreadsheet !== null) {
2367
                                $cellSheet = $this->spreadsheet->getSheetByName($matches[2]);
2368
                                if ($cellSheet && $cellSheet->cellExists($cellRef)) {
2369
                                    $cellValue = $this->extractCellRange($cellRef, $this->spreadsheet->getSheetByName($matches[2]), false);
2370
                                    $cell->attach($pCellParent);
2371
                                } else {
2372
                                    $cellRef = ($cellSheet !== null) ? "'{$matches[2]}'!{$cellRef}" : $cellRef;
2373
                                    $cellValue = ($cellSheet !== null) ? null : ExcelError::REF();
2374
                                }
2375
                            } else {
2376
                                return $this->raiseFormulaError('Unable to access Cell Reference');
2377
                            }
2378
                            $this->debugLog->writeDebugLog('Evaluation Result for cell %s in worksheet %s is %s', $cellRef, $matches[2], $this->showTypeDetails($cellValue));
2379
                        } else {
2380
                            $this->debugLog->writeDebugLog('Evaluating Cell %s in current worksheet', $cellRef);
2381
                            if ($pCellParent !== null && $pCellParent->has($cellRef)) {
2382
                                $cellValue = $this->extractCellRange($cellRef, $pCellWorksheet, false);
2383
                                $cell->attach($pCellParent);
2384
                            } else {
2385
                                $cellValue = null;
2386
                            }
2387
                            $this->debugLog->writeDebugLog('Evaluation Result for cell %s is %s', $cellRef, $this->showTypeDetails($cellValue));
2388
                        }
2389
                    }
2390
                }
2391
2392
                if ($this->getInstanceArrayReturnType() === self::RETURN_ARRAY_AS_ARRAY && !$this->processingAnchorArray && is_array($cellValue)) {
2393
                    while (is_array($cellValue)) {
2394
                        $cellValue = array_shift($cellValue);
2395
                    }
2396
                    if (is_string($cellValue)) {
2397
                        $cellValue = preg_replace('/"/', '""', $cellValue);
2398
                    }
2399
                    $this->debugLog->writeDebugLog('Scalar Result for cell %s is %s', $cellRef, $this->showTypeDetails($cellValue));
2400
                }
2401
                $this->processingAnchorArray = false;
2402
                $stack->push('Cell Value', $cellValue, $cellRef);
2403
                if (isset($storeKey)) {
2404
                    $branchStore[$storeKey] = $cellValue;
2405
                }
2406
            } 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
                if ($cell !== null && $pCellParent !== null) {
2409
                    $cell->attach($pCellParent);
2410
                }
2411
2412
                $functionName = $matches[1];
2413
                /** @var array $argCount */
2414
                $argCount = $stack->pop();
2415
                $argCount = $argCount['value'];
2416
                if ($functionName !== 'MKMATRIX') {
2417
                    $this->debugLog->writeDebugLog('Evaluating Function %s() with %s argument%s', self::localeFunc($functionName), (($argCount == 0) ? 'no' : $argCount), (($argCount == 1) ? '' : 's'));
2418
                }
2419
                if ((isset($phpSpreadsheetFunctions[$functionName])) || (isset(self::$controlFunctions[$functionName]))) {    // function
2420
                    $passByReference = false;
2421
                    $passCellReference = false;
2422
                    $functionCall = null;
2423
                    if (isset($phpSpreadsheetFunctions[$functionName])) {
2424
                        $functionCall = $phpSpreadsheetFunctions[$functionName]['functionCall'];
2425
                        $passByReference = isset($phpSpreadsheetFunctions[$functionName]['passByReference']);
2426
                        $passCellReference = isset($phpSpreadsheetFunctions[$functionName]['passCellReference']);
2427
                    } elseif (isset(self::$controlFunctions[$functionName])) {
2428
                        $functionCall = self::$controlFunctions[$functionName]['functionCall'];
2429
                        $passByReference = isset(self::$controlFunctions[$functionName]['passByReference']);
2430
                        $passCellReference = isset(self::$controlFunctions[$functionName]['passCellReference']);
2431
                    }
2432
2433
                    // get the arguments for this function
2434
                    $args = $argArrayVals = [];
2435
                    $emptyArguments = [];
2436
                    for ($i = 0; $i < $argCount; ++$i) {
2437
                        $arg = $stack->pop();
2438
                        $a = $argCount - $i - 1;
2439
                        if (
2440
                            ($passByReference)
2441
                            && (isset($phpSpreadsheetFunctions[$functionName]['passByReference'][$a]))
2442
                            && ($phpSpreadsheetFunctions[$functionName]['passByReference'][$a])
2443
                        ) {
2444
                            /** @var array $arg */
2445
                            if ($arg['reference'] === null) {
2446
                                $nextArg = $cellID;
2447
                                if ($functionName === 'ISREF' && ($arg['type'] ?? '') === 'Value') {
2448
                                    if (array_key_exists('value', $arg)) {
2449
                                        $argValue = $arg['value'];
2450
                                        if (is_scalar($argValue)) {
2451
                                            $nextArg = $argValue;
2452
                                        } elseif (empty($argValue)) {
2453
                                            $nextArg = '';
2454
                                        }
2455
                                    }
2456
                                }
2457
                                $args[] = $nextArg;
2458
                                if ($functionName !== 'MKMATRIX') {
2459
                                    $argArrayVals[] = $this->showValue($cellID);
2460
                                }
2461
                            } else {
2462
                                $args[] = $arg['reference'];
2463
                                if ($functionName !== 'MKMATRIX') {
2464
                                    $argArrayVals[] = $this->showValue($arg['reference']);
2465
                                }
2466
                            }
2467
                        } else {
2468
                            /** @var array $arg */
2469
                            if ($arg['type'] === 'Empty Argument' && in_array($functionName, ['MIN', 'MINA', 'MAX', 'MAXA', 'IF'], true)) {
2470
                                $emptyArguments[] = false;
2471
                                $args[] = $arg['value'] = 0;
2472
                                $this->debugLog->writeDebugLog('Empty Argument reevaluated as 0');
2473
                            } else {
2474
                                $emptyArguments[] = $arg['type'] === 'Empty Argument';
2475
                                $args[] = self::unwrapResult($arg['value']);
2476
                            }
2477
                            if ($functionName !== 'MKMATRIX') {
2478
                                $argArrayVals[] = $this->showValue($arg['value']);
2479
                            }
2480
                        }
2481
                    }
2482
2483
                    //    Reverse the order of the arguments
2484
                    krsort($args);
2485
                    krsort($emptyArguments);
2486
2487
                    if ($argCount > 0 && is_array($functionCall)) {
2488
                        $args = $this->addDefaultArgumentValues($functionCall, $args, $emptyArguments);
2489
                    }
2490
2491
                    if (($passByReference) && ($argCount == 0)) {
2492
                        $args[] = $cellID;
2493
                        $argArrayVals[] = $this->showValue($cellID);
2494
                    }
2495
2496
                    if ($functionName !== 'MKMATRIX') {
2497
                        if ($this->debugLog->getWriteDebugLog()) {
2498
                            krsort($argArrayVals);
2499
                            $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
                    if ($pCellWorksheet !== null && $originalCoordinate !== null) {
2505
                        $pCellWorksheet->getCell($originalCoordinate);
2506
                    }
2507
                    $args = $this->addCellReference($args, $passCellReference, $functionCall, $cell);
2508
2509
                    if (!is_array($functionCall)) {
2510
                        foreach ($args as &$arg) {
2511
                            $arg = Functions::flattenSingleValue($arg);
2512
                        }
2513
                        unset($arg);
2514
                    }
2515
2516
                    $result = call_user_func_array($functionCall, $args);
2517
2518
                    if ($functionName !== 'MKMATRIX') {
2519
                        $this->debugLog->writeDebugLog('Evaluation Result for %s() function call is %s', self::localeFunc($functionName), $this->showTypeDetails($result));
2520
                    }
2521
                    $stack->push('Value', self::wrapResult($result));
2522
                    if (isset($storeKey)) {
2523
                        $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
                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
                } elseif ((is_numeric($token)) || ($token === null) || (is_bool($token)) || ($token == '') || ($token[0] == self::FORMULA_STRING_QUOTE) || ($token[0] == '#')) {
2536
                    $stack->push($tokenData['type'], $token, $tokenData['reference']);
2537
                    if (isset($storeKey)) {
2538
                        $branchStore[$storeKey] = $token;
2539
                    }
2540
                } elseif (preg_match('/^' . self::CALCULATION_REGEXP_DEFINEDNAME . '$/miu', $token, $matches)) {
2541
                    // if the token is a named range or formula, evaluate it and push the result onto the stack
2542
                    $definedName = $matches[6];
2543
                    if (str_starts_with($definedName, '_xleta')) {
2544
                        return Functions::NOT_YET_IMPLEMENTED;
2545
                    }
2546
                    if ($cell === null || $pCellWorksheet === null) {
2547
                        return $this->raiseFormulaError("undefined name '$token'");
2548
                    }
2549
                    $specifiedWorksheet = trim($matches[2], "'");
2550
2551
                    $this->debugLog->writeDebugLog('Evaluating Defined Name %s', $definedName);
2552
                    $namedRange = DefinedName::resolveName($definedName, $pCellWorksheet, $specifiedWorksheet);
2553
                    // If not Defined Name, try as Table.
2554
                    if ($namedRange === null && $this->spreadsheet !== null) {
2555
                        $table = $this->spreadsheet->getTableByName($definedName);
2556
                        if ($table !== null) {
2557
                            $tableRange = Coordinate::getRangeBoundaries($table->getRange());
2558
                            if ($table->getShowHeaderRow()) {
2559
                                ++$tableRange[0][1];
2560
                            }
2561
                            if ($table->getShowTotalsRow()) {
2562
                                --$tableRange[1][1];
2563
                            }
2564
                            $tableRangeString
2565
                                = '$' . $tableRange[0][0]
2566
                                . '$' . $tableRange[0][1]
2567
                                . ':'
2568
                                . '$' . $tableRange[1][0]
2569
                                . '$' . $tableRange[1][1];
2570
                            $namedRange = new NamedRange($definedName, $table->getWorksheet(), $tableRangeString);
2571
                        }
2572
                    }
2573
                    if ($namedRange === null) {
2574
                        return $this->raiseFormulaError("undefined name '$definedName'");
2575
                    }
2576
2577
                    $result = $this->evaluateDefinedName($cell, $namedRange, $pCellWorksheet, $stack, $specifiedWorksheet !== '');
2578
2579
                    if (isset($storeKey)) {
2580
                        $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
        if ($stack->count() != 1) {
2589
            return $this->raiseFormulaError('internal error');
2590
        }
2591
        /** @var array $output */
2592
        $output = $stack->pop();
2593
        $output = $output['value'];
2594
2595
        return $output;
2596
    }
2597
2598
    private function validateBinaryOperand(mixed &$operand, mixed &$stack): bool
2599
    {
2600
        if (is_array($operand)) {
2601
            if ((count($operand, COUNT_RECURSIVE) - count($operand)) == 1) {
2602
                do {
2603
                    $operand = array_pop($operand);
2604
                } while (is_array($operand));
2605
            }
2606
        }
2607
        //    Numbers, matrices and booleans can pass straight through, as they're already valid
2608
        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
            if ($operand > '' && $operand[0] == self::FORMULA_STRING_QUOTE) {
2612
                $operand = self::unwrapResult($operand);
2613
            }
2614
            //    If the string is a numeric value, we treat it as a numeric, so no further testing
2615
            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
                if ($operand > '' && $operand[0] == '#') {
2618
                    $stack->push('Value', $operand);
2619
                    $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($operand));
2620
2621
                    return false;
2622
                } 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
                    $stack->push('Error', '#VALUE!');
2625
                    $this->debugLog->writeDebugLog('Evaluation Result is a %s', $this->showTypeDetails('#VALUE!'));
2626
2627
                    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
        return true;
2634
    }
2635
2636
    private function executeArrayComparison(mixed $operand1, mixed $operand2, string $operation, Stack &$stack, bool $recursingArrays): array
2637
    {
2638
        $result = [];
2639
        if (!is_array($operand2)) {
2640
            // Operand 1 is an array, Operand 2 is a scalar
2641
            foreach ($operand1 as $x => $operandData) {
2642
                $this->debugLog->writeDebugLog('Evaluating Comparison %s %s %s', $this->showValue($operandData), $operation, $this->showValue($operand2));
2643
                $this->executeBinaryComparisonOperation($operandData, $operand2, $operation, $stack);
2644
                /** @var array $r */
2645
                $r = $stack->pop();
2646
                $result[$x] = $r['value'];
2647
            }
2648
        } elseif (!is_array($operand1)) {
2649
            // Operand 1 is a scalar, Operand 2 is an array
2650
            foreach ($operand2 as $x => $operandData) {
2651
                $this->debugLog->writeDebugLog('Evaluating Comparison %s %s %s', $this->showValue($operand1), $operation, $this->showValue($operandData));
2652
                $this->executeBinaryComparisonOperation($operand1, $operandData, $operation, $stack);
2653
                /** @var array $r */
2654
                $r = $stack->pop();
2655
                $result[$x] = $r['value'];
2656
            }
2657
        } else {
2658
            // Operand 1 and Operand 2 are both arrays
2659
            if (!$recursingArrays) {
2660
                self::checkMatrixOperands($operand1, $operand2, 2);
2661
            }
2662
            foreach ($operand1 as $x => $operandData) {
2663
                $this->debugLog->writeDebugLog('Evaluating Comparison %s %s %s', $this->showValue($operandData), $operation, $this->showValue($operand2[$x]));
2664
                $this->executeBinaryComparisonOperation($operandData, $operand2[$x], $operation, $stack, true);
2665
                /** @var array $r */
2666
                $r = $stack->pop();
2667
                $result[$x] = $r['value'];
2668
            }
2669
        }
2670
        //    Log the result details
2671
        $this->debugLog->writeDebugLog('Comparison Evaluation Result is %s', $this->showTypeDetails($result));
2672
        //    And push the result onto the stack
2673
        $stack->push('Array', $result);
2674
2675
        return $result;
2676
    }
2677
2678
    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
        if ((is_array($operand1)) || (is_array($operand2))) {
2682
            return $this->executeArrayComparison($operand1, $operand2, $operation, $stack, $recursingArrays);
2683
        }
2684
2685
        $result = BinaryComparison::compare($operand1, $operand2, $operation);
2686
2687
        //    Log the result details
2688
        $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($result));
2689
        //    And push the result onto the stack
2690
        $stack->push('Value', $result);
2691
2692
        return $result;
2693
    }
2694
2695
    private function executeNumericBinaryOperation(mixed $operand1, mixed $operand2, string $operation, Stack &$stack): mixed
2696
    {
2697
        //    Validate the two operands
2698
        if (
2699
            ($this->validateBinaryOperand($operand1, $stack) === false)
2700
            || ($this->validateBinaryOperand($operand2, $stack) === false)
2701
        ) {
2702
            return false;
2703
        }
2704
2705
        if (
2706
            (Functions::getCompatibilityMode() != Functions::COMPATIBILITY_OPENOFFICE)
2707
            && ((is_string($operand1) && !is_numeric($operand1) && $operand1 !== '')
2708
                || (is_string($operand2) && !is_numeric($operand2) && $operand2 !== ''))
2709
        ) {
2710
            $result = ExcelError::VALUE();
2711
        } elseif (is_array($operand1) || is_array($operand2)) {
2712
            //    Ensure that both operands are arrays/matrices
2713
            if (is_array($operand1)) {
2714
                foreach ($operand1 as $key => $value) {
2715
                    $operand1[$key] = Functions::flattenArray($value);
2716
                }
2717
            }
2718
            if (is_array($operand2)) {
2719
                foreach ($operand2 as $key => $value) {
2720
                    $operand2[$key] = Functions::flattenArray($value);
2721
                }
2722
            }
2723
            [$rows, $columns] = self::checkMatrixOperands($operand1, $operand2, 3);
2724
2725
            for ($row = 0; $row < $rows; ++$row) {
2726
                for ($column = 0; $column < $columns; ++$column) {
2727
                    if ($operand1[$row][$column] === null) {
2728
                        $operand1[$row][$column] = 0;
2729
                    } elseif (!self::isNumericOrBool($operand1[$row][$column])) {
2730
                        $operand1[$row][$column] = self::makeError($operand1[$row][$column]);
2731
2732
                        continue;
2733
                    }
2734
                    if ($operand2[$row][$column] === null) {
2735
                        $operand2[$row][$column] = 0;
2736
                    } elseif (!self::isNumericOrBool($operand2[$row][$column])) {
2737
                        $operand1[$row][$column] = self::makeError($operand2[$row][$column]);
2738
2739
                        continue;
2740
                    }
2741
                    switch ($operation) {
2742
                        case '+':
2743
                            $operand1[$row][$column] += $operand2[$row][$column];
2744
2745
                            break;
2746
                        case '-':
2747
                            $operand1[$row][$column] -= $operand2[$row][$column];
2748
2749
                            break;
2750
                        case '*':
2751
                            $operand1[$row][$column] *= $operand2[$row][$column];
2752
2753
                            break;
2754
                        case '/':
2755
                            if ($operand2[$row][$column] == 0) {
2756
                                $operand1[$row][$column] = ExcelError::DIV0();
2757
                            } else {
2758
                                $operand1[$row][$column] /= $operand2[$row][$column];
2759
                            }
2760
2761
                            break;
2762
                        case '^':
2763
                            $operand1[$row][$column] = $operand1[$row][$column] ** $operand2[$row][$column];
2764
2765
                            break;
2766
2767
                        default:
2768
                            throw new Exception('Unsupported numeric binary operation');
2769
                    }
2770
                }
2771
            }
2772
            $result = $operand1;
2773
        } else {
2774
            //    If we're dealing with non-matrix operations, execute the necessary operation
2775
            switch ($operation) {
2776
                //    Addition
2777
                case '+':
2778
                    $result = $operand1 + $operand2;
2779
2780
                    break;
2781
                //    Subtraction
2782
                case '-':
2783
                    $result = $operand1 - $operand2;
2784
2785
                    break;
2786
                //    Multiplication
2787
                case '*':
2788
                    $result = $operand1 * $operand2;
2789
2790
                    break;
2791
                //    Division
2792
                case '/':
2793
                    if ($operand2 == 0) {
2794
                        //    Trap for Divide by Zero error
2795
                        $stack->push('Error', ExcelError::DIV0());
2796
                        $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails(ExcelError::DIV0()));
2797
2798
                        return false;
2799
                    }
2800
                    $result = $operand1 / $operand2;
2801
2802
                    break;
2803
                //    Power
2804
                case '^':
2805
                    $result = $operand1 ** $operand2;
2806
2807
                    break;
2808
2809
                default:
2810
                    throw new Exception('Unsupported numeric binary operation');
2811
            }
2812
        }
2813
2814
        //    Log the result details
2815
        $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($result));
2816
        //    And push the result onto the stack
2817
        $stack->push('Value', $result);
2818
2819
        return $result;
2820
    }
2821
2822
    /**
2823
     * Trigger an error, but nicely, if need be.
2824
     *
2825
     * @return false
2826
     */
2827
    protected function raiseFormulaError(string $errorMessage, int $code = 0, ?Throwable $exception = null): bool
2828
    {
2829
        $this->formulaError = $errorMessage;
2830
        $this->cyclicReferenceStack->clear();
2831
        $suppress = $this->suppressFormulaErrors;
2832
        if (!$suppress) {
2833
            throw new Exception($errorMessage, $code, $exception);
2834
        }
2835
2836
        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
    public function extractCellRange(string &$range = 'A1', ?Worksheet $worksheet = null, bool $resetLog = true): array
2849
    {
2850
        // Return value
2851
        $returnValue = [];
2852
2853
        if ($worksheet !== null) {
2854
            $worksheetName = $worksheet->getTitle();
2855
2856
            if (str_contains($range, '!')) {
2857
                [$worksheetName, $range] = Worksheet::extractSheetTitle($range, true, true);
2858
                $worksheet = ($this->spreadsheet === null) ? null : $this->spreadsheet->getSheetByName($worksheetName);
2859
            }
2860
2861
            // Extract range
2862
            $aReferences = Coordinate::extractAllCellReferencesInRange($range);
2863
            $range = "'" . $worksheetName . "'" . '!' . $range;
2864
            $currentCol = '';
2865
            $currentRow = 0;
2866
            if (!isset($aReferences[1])) {
2867
                //    Single cell in range
2868
                sscanf($aReferences[0], '%[A-Z]%d', $currentCol, $currentRow);
2869
                if ($worksheet !== null && $worksheet->cellExists($aReferences[0])) {
2870
                    $temp = $worksheet->getCell($aReferences[0])->getCalculatedValue($resetLog);
2871
                    if ($this->getInstanceArrayReturnType() === self::RETURN_ARRAY_AS_ARRAY) {
2872
                        while (is_array($temp)) {
2873
                            $temp = array_shift($temp);
2874
                        }
2875
                    }
2876
                    $returnValue[$currentRow][$currentCol] = $temp;
2877
                } else {
2878
                    $returnValue[$currentRow][$currentCol] = null;
2879
                }
2880
            } else {
2881
                // Extract cell data for all cells in the range
2882
                foreach ($aReferences as $reference) {
2883
                    // Extract range
2884
                    sscanf($reference, '%[A-Z]%d', $currentCol, $currentRow);
2885
                    if ($worksheet !== null && $worksheet->cellExists($reference)) {
2886
                        $temp = $worksheet->getCell($reference)->getCalculatedValue($resetLog);
2887 10482
                        if ($this->getInstanceArrayReturnType() === self::RETURN_ARRAY_AS_ARRAY) {
2888
                            while (is_array($temp)) {
2889 10482
                                $temp = array_shift($temp);
2890 10482
                            }
2891 10482
                        }
2892 10482
                        $returnValue[$currentRow][$currentCol] = $temp;
2893
                    } else {
2894
                        $returnValue[$currentRow][$currentCol] = null;
2895 3
                    }
2896
                }
2897 3
            }
2898 3
        }
2899 3
2900 3
        return $returnValue;
2901 3
    }
2902 3
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 12995
    {
2914
        // Return value
2915 12995
        $returnValue = [];
2916 9239
2917 9239
        if ($worksheet !== null) {
2918 9239
            if (str_contains($range, '!')) {
2919
                [$worksheetName, $range] = Worksheet::extractSheetTitle($range, true, true);
2920
                $worksheet = ($this->spreadsheet === null) ? null : $this->spreadsheet->getSheetByName($worksheetName);
2921
            }
2922 4622
2923 18
            // Named range?
2924
            $namedRange = ($worksheet === null) ? null : DefinedName::resolveName($range, $worksheet);
2925
            if ($namedRange === null) {
2926 4622
                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 203
            if ($worksheet !== null && ctype_alpha($splitRange[0][0])) {
2934
                $range = $splitRange[0][0] . '1:' . $splitRange[0][1] . $worksheet->getHighestRow();
2935 203
            } elseif ($worksheet !== null && ctype_digit($splitRange[0][0])) {
2936 203
                $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 1097
                //    Single cell (or single column or row) in range
2943
                [$currentCol, $currentRow] = Coordinate::coordinateFromString($aReferences[0]);
2944 1097
                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 979
            }
2961
        }
2962 979
2963
        return $returnValue;
2964
    }
2965
2966
    /**
2967
     * Is a specific function implemented?
2968
     *
2969
     * @param string $function Function Name
2970 963
     */
2971
    public function isImplemented(string $function): bool
2972 963
    {
2973
        $function = strtoupper($function);
2974
        $phpSpreadsheetFunctions = &self::getFunctionsAddress();
2975
        $notImplemented = !isset($phpSpreadsheetFunctions[$function]) || (is_array($phpSpreadsheetFunctions[$function]['functionCall']) && $phpSpreadsheetFunctions[$function]['functionCall'][1] === 'DUMMY');
2976
2977
        return !$notImplemented;
2978
    }
2979
2980
    /**
2981
     * Get a list of implemented Excel function names.
2982 546
     */
2983
    public function getImplementedFunctionNames(): array
2984
    {
2985 546
        $returnValue = [];
2986 546
        $phpSpreadsheetFunctions = &self::getFunctionsAddress();
2987 546
        foreach ($phpSpreadsheetFunctions as $functionName => $function) {
2988
            if ($this->isImplemented($functionName)) {
2989 546
                $returnValue[] = $functionName;
2990
            }
2991 546
        }
2992
2993
        return $returnValue;
2994 1
    }
2995
2996
    private function addDefaultArgumentValues(array $functionCall, array $args, array $emptyArguments): array
2997
    {
2998
        $reflector = new ReflectionMethod($functionCall[0], $functionCall[1]);
2999
        $methodArguments = $reflector->getParameters();
3000
3001
        if (count($methodArguments) > 0) {
3002 546
            // Apply any defaults for empty argument values
3003
            foreach ($emptyArguments as $argumentId => $isArgumentEmpty) {
3004 546
                if ($isArgumentEmpty === true) {
3005
                    $reflectedArgumentId = count($args) - (int) $argumentId - 1;
3006
                    if (
3007
                        !array_key_exists($reflectedArgumentId, $methodArguments)
3008
                        || $methodArguments[$reflectedArgumentId]->isVariadic()
3009
                    ) {
3010
                        break;
3011
                    }
3012
3013
                    $args[$argumentId] = $this->getArgumentDefaultValue($methodArguments[$reflectedArgumentId]);
3014 303
                }
3015
            }
3016
        }
3017 303
3018 303
        return $args;
3019 303
    }
3020
3021 303
    private function getArgumentDefaultValue(ReflectionParameter $methodArgument): mixed
3022
    {
3023 303
        $defaultValue = null;
3024
3025
        if ($methodArgument->isDefaultValueAvailable()) {
3026
            $defaultValue = $methodArgument->getDefaultValue();
3027
            if ($methodArgument->isDefaultValueConstant()) {
3028
                $constantName = $methodArgument->getDefaultValueConstantName() ?? '';
3029
                // read constant value
3030
                if (str_contains($constantName, '::')) {
3031
                    [$className, $constantName] = explode('::', $constantName);
3032
                    $constantReflector = new ReflectionClassConstant($className, $constantName);
3033
3034 8742
                    return $constantReflector->getValue();
3035
                }
3036 8742
3037
                return constant($constantName);
3038
            }
3039
        }
3040
3041
        return $defaultValue;
3042 242
    }
3043
3044 242
    /**
3045
     * Add cell reference if needed while making sure that it is the last argument.
3046
     */
3047
    private function addCellReference(array $args, bool $passCellReference, array|string $functionCall, ?Cell $cell = null): array
3048
    {
3049
        if ($passCellReference) {
3050
            if (is_array($functionCall)) {
3051
                $className = $functionCall[0];
3052
                $methodName = $functionCall[1];
3053
3054
                $reflectionMethod = new ReflectionMethod($className, $methodName);
3055
                $argumentCount = count($reflectionMethod->getParameters());
3056
                while (count($args) < $argumentCount - 1) {
3057
                    $args[] = null;
3058
                }
3059
            }
3060
3061
            $args[] = $cell;
3062
        }
3063
3064
        return $args;
3065
    }
3066
3067
    private function evaluateDefinedName(Cell $cell, DefinedName $namedRange, Worksheet $cellWorksheet, Stack $stack, bool $ignoreScope = false): mixed
3068
    {
3069
        $definedNameScope = $namedRange->getScope();
3070
        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 205
            return $result;
3076
        }
3077 205
3078
        $definedNameValue = $namedRange->getValue();
3079
        $definedNameType = $namedRange->isFormula() ? 'Formula' : 'Range';
3080
        $definedNameWorksheet = $namedRange->getWorksheet();
3081
3082
        if ($definedNameValue[0] !== '=') {
3083 119
            $definedNameValue = '=' . $definedNameValue;
3084
        }
3085 119
3086
        $this->debugLog->writeDebugLog('Defined Name is a %s with a value of %s', $definedNameType, $definedNameValue);
3087
3088
        $originalCoordinate = $cell->getCoordinate();
3089
        $recursiveCalculationCell = ($definedNameType !== 'Formula' && $definedNameWorksheet !== null && $definedNameWorksheet !== $cellWorksheet)
3090
            ? $definedNameWorksheet->getCell('A1')
3091
            : $cell;
3092
        $recursiveCalculationCellAddress = $recursiveCalculationCell->getCoordinate();
3093 1388
3094
        // Adjust relative references in ranges and formulae so that we execute the calculation for the correct rows and columns
3095 1388
        $definedNameValue = ReferenceHelper::getInstance()
3096
            ->updateFormulaReferencesAnyWorksheet(
3097
                $definedNameValue,
3098
                Coordinate::columnIndexFromString(
3099
                    $cell->getColumn()
3100
                ) - 1,
3101
                $cell->getRow() - 1
3102
            );
3103
3104 8011
        $this->debugLog->writeDebugLog('Value adjusted for relative references is %s', $definedNameValue);
3105
3106 8011
        $recursiveCalculator = new self($this->spreadsheet);
3107 8011
        $recursiveCalculator->getDebugLog()->setWriteDebugLog($this->getDebugLog()->getWriteDebugLog());
3108
        $recursiveCalculator->getDebugLog()->setEchoDebugLog($this->getDebugLog()->getEchoDebugLog());
3109
        $result = $recursiveCalculator->_calculateFormulaValue($definedNameValue, $recursiveCalculationCellAddress, $recursiveCalculationCell, true);
3110
        $cellWorksheet->getCell($originalCoordinate);
3111
3112
        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 8011
        }
3116
3117 8011
        $stack->push('Defined Name', $result, $namedRange->getName());
3118
3119
        return $result;
3120
    }
3121
3122
    public function setSuppressFormulaErrors(bool $suppressFormulaErrors): void
3123 784
    {
3124
        $this->suppressFormulaErrors = $suppressFormulaErrors;
3125 784
    }
3126
3127
    public function getSuppressFormulaErrors(): bool
3128 120
    {
3129
        return $this->suppressFormulaErrors;
3130 120
    }
3131 120
3132 120
    public static function boolToString(mixed $operand1): mixed
3133
    {
3134 29
        if (is_bool($operand1)) {
3135 29
            $operand1 = ($operand1) ? self::$localeBoolean['TRUE'] : self::$localeBoolean['FALSE'];
3136 3
        } elseif ($operand1 === null) {
3137
            $operand1 = '';
3138
        }
3139
3140 117
        return $operand1;
3141
    }
3142
3143
    private static function isNumericOrBool(mixed $operand): bool
3144
    {
3145
        return is_numeric($operand) || is_bool($operand);
3146
    }
3147 1
3148
    private static function makeError(mixed $operand = ''): string
3149 1
    {
3150
        return Information\ErrorValue::isError($operand) ? $operand : ExcelError::VALUE();
3151
    }
3152
}
3153