Passed
Pull Request — master (#4326)
by Owen
16:19 queued 04:29
created

Calculation::calculateCellValue()   F

Complexity

Conditions 22
Paths 233

Size

Total Lines 75
Code Lines 48

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 45
CRAP Score 22.4838

Importance

Changes 0
Metric Value
eloc 48
dl 0
loc 75
ccs 45
cts 50
cp 0.9
rs 2.9208
c 0
b 0
f 0
cc 22
nc 233
nop 2
crap 22.4838

How to fix   Long Method    Complexity   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
3
namespace PhpOffice\PhpSpreadsheet\Calculation;
4
5
use PhpOffice\PhpSpreadsheet\Calculation\Engine\BranchPruner;
6
use PhpOffice\PhpSpreadsheet\Calculation\Engine\CyclicReferenceStack;
7
use PhpOffice\PhpSpreadsheet\Calculation\Engine\Logger;
8
use PhpOffice\PhpSpreadsheet\Calculation\Engine\Operands;
9
use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError;
10
use PhpOffice\PhpSpreadsheet\Calculation\Token\Stack;
11
use PhpOffice\PhpSpreadsheet\Cell\AddressRange;
12
use PhpOffice\PhpSpreadsheet\Cell\Cell;
13
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
14
use PhpOffice\PhpSpreadsheet\Cell\DataType;
15
use PhpOffice\PhpSpreadsheet\DefinedName;
16
use PhpOffice\PhpSpreadsheet\NamedRange;
17
use PhpOffice\PhpSpreadsheet\ReferenceHelper;
18
use PhpOffice\PhpSpreadsheet\Shared;
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
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
     * Array of functions usable on Spreadsheet.
219
     * In theory, this could be const rather than static;
220
     *   however, Phpstan breaks trying to analyze it when attempted.
221
     */
222
    private static array $phpSpreadsheetFunctions = [
223
        'ABS' => [
224
            'category' => Category::CATEGORY_MATH_AND_TRIG,
225
            'functionCall' => [MathTrig\Absolute::class, 'evaluate'],
226
            'argumentCount' => '1',
227
        ],
228
        'ACCRINT' => [
229
            'category' => Category::CATEGORY_FINANCIAL,
230
            'functionCall' => [Financial\Securities\AccruedInterest::class, 'periodic'],
231
            'argumentCount' => '4-8',
232
        ],
233
        'ACCRINTM' => [
234
            'category' => Category::CATEGORY_FINANCIAL,
235
            'functionCall' => [Financial\Securities\AccruedInterest::class, 'atMaturity'],
236
            'argumentCount' => '3-5',
237
        ],
238
        'ACOS' => [
239
            'category' => Category::CATEGORY_MATH_AND_TRIG,
240
            'functionCall' => [MathTrig\Trig\Cosine::class, 'acos'],
241
            'argumentCount' => '1',
242
        ],
243
        'ACOSH' => [
244
            'category' => Category::CATEGORY_MATH_AND_TRIG,
245
            'functionCall' => [MathTrig\Trig\Cosine::class, 'acosh'],
246
            'argumentCount' => '1',
247
        ],
248
        'ACOT' => [
249
            'category' => Category::CATEGORY_MATH_AND_TRIG,
250
            'functionCall' => [MathTrig\Trig\Cotangent::class, 'acot'],
251
            'argumentCount' => '1',
252
        ],
253
        'ACOTH' => [
254
            'category' => Category::CATEGORY_MATH_AND_TRIG,
255
            'functionCall' => [MathTrig\Trig\Cotangent::class, 'acoth'],
256
            'argumentCount' => '1',
257
        ],
258
        'ADDRESS' => [
259
            'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE,
260
            'functionCall' => [LookupRef\Address::class, 'cell'],
261
            'argumentCount' => '2-5',
262
        ],
263
        'AGGREGATE' => [
264
            'category' => Category::CATEGORY_MATH_AND_TRIG,
265
            'functionCall' => [Functions::class, 'DUMMY'],
266
            'argumentCount' => '3+',
267
        ],
268
        'AMORDEGRC' => [
269
            'category' => Category::CATEGORY_FINANCIAL,
270
            'functionCall' => [Financial\Amortization::class, 'AMORDEGRC'],
271
            'argumentCount' => '6,7',
272
        ],
273
        'AMORLINC' => [
274
            'category' => Category::CATEGORY_FINANCIAL,
275
            'functionCall' => [Financial\Amortization::class, 'AMORLINC'],
276
            'argumentCount' => '6,7',
277
        ],
278
        'ANCHORARRAY' => [
279
            'category' => Category::CATEGORY_MICROSOFT_INTERNAL,
280
            'functionCall' => [Internal\ExcelArrayPseudoFunctions::class, 'anchorArray'],
281
            'argumentCount' => '1',
282
            'passCellReference' => true,
283
            'passByReference' => [true],
284
        ],
285
        'AND' => [
286
            'category' => Category::CATEGORY_LOGICAL,
287
            'functionCall' => [Logical\Operations::class, 'logicalAnd'],
288
            'argumentCount' => '1+',
289
        ],
290
        'ARABIC' => [
291
            'category' => Category::CATEGORY_MATH_AND_TRIG,
292
            'functionCall' => [MathTrig\Arabic::class, 'evaluate'],
293
            'argumentCount' => '1',
294
        ],
295
        'AREAS' => [
296
            'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE,
297
            'functionCall' => [Functions::class, 'DUMMY'],
298
            'argumentCount' => '1',
299
        ],
300
        'ARRAYTOTEXT' => [
301
            'category' => Category::CATEGORY_TEXT_AND_DATA,
302
            'functionCall' => [TextData\Text::class, 'fromArray'],
303
            'argumentCount' => '1,2',
304
        ],
305
        'ASC' => [
306
            'category' => Category::CATEGORY_TEXT_AND_DATA,
307
            'functionCall' => [Functions::class, 'DUMMY'],
308
            'argumentCount' => '1',
309
        ],
310
        'ASIN' => [
311
            'category' => Category::CATEGORY_MATH_AND_TRIG,
312
            'functionCall' => [MathTrig\Trig\Sine::class, 'asin'],
313
            'argumentCount' => '1',
314
        ],
315
        'ASINH' => [
316
            'category' => Category::CATEGORY_MATH_AND_TRIG,
317
            'functionCall' => [MathTrig\Trig\Sine::class, 'asinh'],
318
            'argumentCount' => '1',
319
        ],
320
        'ATAN' => [
321
            'category' => Category::CATEGORY_MATH_AND_TRIG,
322
            'functionCall' => [MathTrig\Trig\Tangent::class, 'atan'],
323
            'argumentCount' => '1',
324
        ],
325
        'ATAN2' => [
326
            'category' => Category::CATEGORY_MATH_AND_TRIG,
327
            'functionCall' => [MathTrig\Trig\Tangent::class, 'atan2'],
328
            'argumentCount' => '2',
329
        ],
330
        'ATANH' => [
331
            'category' => Category::CATEGORY_MATH_AND_TRIG,
332
            'functionCall' => [MathTrig\Trig\Tangent::class, 'atanh'],
333
            'argumentCount' => '1',
334
        ],
335
        'AVEDEV' => [
336
            'category' => Category::CATEGORY_STATISTICAL,
337
            'functionCall' => [Statistical\Averages::class, 'averageDeviations'],
338
            'argumentCount' => '1+',
339
        ],
340
        'AVERAGE' => [
341
            'category' => Category::CATEGORY_STATISTICAL,
342
            'functionCall' => [Statistical\Averages::class, 'average'],
343
            'argumentCount' => '1+',
344
        ],
345
        'AVERAGEA' => [
346
            'category' => Category::CATEGORY_STATISTICAL,
347
            'functionCall' => [Statistical\Averages::class, 'averageA'],
348
            'argumentCount' => '1+',
349
        ],
350
        'AVERAGEIF' => [
351
            'category' => Category::CATEGORY_STATISTICAL,
352
            'functionCall' => [Statistical\Conditional::class, 'AVERAGEIF'],
353
            'argumentCount' => '2,3',
354
        ],
355
        'AVERAGEIFS' => [
356
            'category' => Category::CATEGORY_STATISTICAL,
357
            'functionCall' => [Statistical\Conditional::class, 'AVERAGEIFS'],
358
            'argumentCount' => '3+',
359
        ],
360
        'BAHTTEXT' => [
361
            'category' => Category::CATEGORY_TEXT_AND_DATA,
362
            'functionCall' => [Functions::class, 'DUMMY'],
363
            'argumentCount' => '1',
364
        ],
365
        'BASE' => [
366
            'category' => Category::CATEGORY_MATH_AND_TRIG,
367
            'functionCall' => [MathTrig\Base::class, 'evaluate'],
368
            'argumentCount' => '2,3',
369
        ],
370
        'BESSELI' => [
371
            'category' => Category::CATEGORY_ENGINEERING,
372
            'functionCall' => [Engineering\BesselI::class, 'BESSELI'],
373
            'argumentCount' => '2',
374
        ],
375
        'BESSELJ' => [
376
            'category' => Category::CATEGORY_ENGINEERING,
377
            'functionCall' => [Engineering\BesselJ::class, 'BESSELJ'],
378
            'argumentCount' => '2',
379
        ],
380
        'BESSELK' => [
381
            'category' => Category::CATEGORY_ENGINEERING,
382
            'functionCall' => [Engineering\BesselK::class, 'BESSELK'],
383
            'argumentCount' => '2',
384
        ],
385
        'BESSELY' => [
386
            'category' => Category::CATEGORY_ENGINEERING,
387
            'functionCall' => [Engineering\BesselY::class, 'BESSELY'],
388
            'argumentCount' => '2',
389
        ],
390
        'BETADIST' => [
391
            'category' => Category::CATEGORY_STATISTICAL,
392
            'functionCall' => [Statistical\Distributions\Beta::class, 'distribution'],
393
            'argumentCount' => '3-5',
394
        ],
395
        'BETA.DIST' => [
396
            'category' => Category::CATEGORY_STATISTICAL,
397
            'functionCall' => [Functions::class, 'DUMMY'],
398
            'argumentCount' => '4-6',
399
        ],
400
        'BETAINV' => [
401
            'category' => Category::CATEGORY_STATISTICAL,
402
            'functionCall' => [Statistical\Distributions\Beta::class, 'inverse'],
403
            'argumentCount' => '3-5',
404
        ],
405
        'BETA.INV' => [
406
            'category' => Category::CATEGORY_STATISTICAL,
407
            'functionCall' => [Statistical\Distributions\Beta::class, 'inverse'],
408
            'argumentCount' => '3-5',
409
        ],
410
        'BIN2DEC' => [
411
            'category' => Category::CATEGORY_ENGINEERING,
412
            'functionCall' => [Engineering\ConvertBinary::class, 'toDecimal'],
413
            'argumentCount' => '1',
414
        ],
415
        'BIN2HEX' => [
416
            'category' => Category::CATEGORY_ENGINEERING,
417
            'functionCall' => [Engineering\ConvertBinary::class, 'toHex'],
418
            'argumentCount' => '1,2',
419
        ],
420
        'BIN2OCT' => [
421
            'category' => Category::CATEGORY_ENGINEERING,
422
            'functionCall' => [Engineering\ConvertBinary::class, 'toOctal'],
423
            'argumentCount' => '1,2',
424
        ],
425
        'BINOMDIST' => [
426
            'category' => Category::CATEGORY_STATISTICAL,
427
            'functionCall' => [Statistical\Distributions\Binomial::class, 'distribution'],
428
            'argumentCount' => '4',
429
        ],
430
        'BINOM.DIST' => [
431
            'category' => Category::CATEGORY_STATISTICAL,
432
            'functionCall' => [Statistical\Distributions\Binomial::class, 'distribution'],
433
            'argumentCount' => '4',
434
        ],
435
        'BINOM.DIST.RANGE' => [
436
            'category' => Category::CATEGORY_STATISTICAL,
437
            'functionCall' => [Statistical\Distributions\Binomial::class, 'range'],
438
            'argumentCount' => '3,4',
439
        ],
440
        'BINOM.INV' => [
441
            'category' => Category::CATEGORY_STATISTICAL,
442
            'functionCall' => [Statistical\Distributions\Binomial::class, 'inverse'],
443
            'argumentCount' => '3',
444
        ],
445
        'BITAND' => [
446
            'category' => Category::CATEGORY_ENGINEERING,
447
            'functionCall' => [Engineering\BitWise::class, 'BITAND'],
448
            'argumentCount' => '2',
449
        ],
450
        'BITOR' => [
451
            'category' => Category::CATEGORY_ENGINEERING,
452
            'functionCall' => [Engineering\BitWise::class, 'BITOR'],
453
            'argumentCount' => '2',
454
        ],
455
        'BITXOR' => [
456
            'category' => Category::CATEGORY_ENGINEERING,
457
            'functionCall' => [Engineering\BitWise::class, 'BITXOR'],
458
            'argumentCount' => '2',
459
        ],
460
        'BITLSHIFT' => [
461
            'category' => Category::CATEGORY_ENGINEERING,
462
            'functionCall' => [Engineering\BitWise::class, 'BITLSHIFT'],
463
            'argumentCount' => '2',
464
        ],
465
        'BITRSHIFT' => [
466
            'category' => Category::CATEGORY_ENGINEERING,
467
            'functionCall' => [Engineering\BitWise::class, 'BITRSHIFT'],
468
            'argumentCount' => '2',
469
        ],
470
        'BYCOL' => [
471
            'category' => Category::CATEGORY_LOGICAL,
472
            'functionCall' => [Functions::class, 'DUMMY'],
473
            'argumentCount' => '*',
474
        ],
475
        'BYROW' => [
476
            'category' => Category::CATEGORY_LOGICAL,
477
            'functionCall' => [Functions::class, 'DUMMY'],
478
            'argumentCount' => '*',
479
        ],
480
        'CEILING' => [
481
            'category' => Category::CATEGORY_MATH_AND_TRIG,
482
            'functionCall' => [MathTrig\Ceiling::class, 'ceiling'],
483
            'argumentCount' => '1-2', // 2 for Excel, 1-2 for Ods/Gnumeric
484
        ],
485
        'CEILING.MATH' => [
486
            'category' => Category::CATEGORY_MATH_AND_TRIG,
487
            'functionCall' => [MathTrig\Ceiling::class, 'math'],
488
            'argumentCount' => '1-3',
489
        ],
490
        'CEILING.PRECISE' => [
491
            'category' => Category::CATEGORY_MATH_AND_TRIG,
492
            'functionCall' => [MathTrig\Ceiling::class, 'precise'],
493
            'argumentCount' => '1,2',
494
        ],
495
        'CELL' => [
496
            'category' => Category::CATEGORY_INFORMATION,
497
            'functionCall' => [Functions::class, 'DUMMY'],
498
            'argumentCount' => '1,2',
499
        ],
500
        'CHAR' => [
501
            'category' => Category::CATEGORY_TEXT_AND_DATA,
502
            'functionCall' => [TextData\CharacterConvert::class, 'character'],
503
            'argumentCount' => '1',
504
        ],
505
        'CHIDIST' => [
506
            'category' => Category::CATEGORY_STATISTICAL,
507
            'functionCall' => [Statistical\Distributions\ChiSquared::class, 'distributionRightTail'],
508
            'argumentCount' => '2',
509
        ],
510
        'CHISQ.DIST' => [
511
            'category' => Category::CATEGORY_STATISTICAL,
512
            'functionCall' => [Statistical\Distributions\ChiSquared::class, 'distributionLeftTail'],
513
            'argumentCount' => '3',
514
        ],
515
        'CHISQ.DIST.RT' => [
516
            'category' => Category::CATEGORY_STATISTICAL,
517
            'functionCall' => [Statistical\Distributions\ChiSquared::class, 'distributionRightTail'],
518
            'argumentCount' => '2',
519
        ],
520
        'CHIINV' => [
521
            'category' => Category::CATEGORY_STATISTICAL,
522
            'functionCall' => [Statistical\Distributions\ChiSquared::class, 'inverseRightTail'],
523
            'argumentCount' => '2',
524
        ],
525
        'CHISQ.INV' => [
526
            'category' => Category::CATEGORY_STATISTICAL,
527
            'functionCall' => [Statistical\Distributions\ChiSquared::class, 'inverseLeftTail'],
528
            'argumentCount' => '2',
529
        ],
530
        'CHISQ.INV.RT' => [
531
            'category' => Category::CATEGORY_STATISTICAL,
532
            'functionCall' => [Statistical\Distributions\ChiSquared::class, 'inverseRightTail'],
533
            'argumentCount' => '2',
534
        ],
535
        'CHITEST' => [
536
            'category' => Category::CATEGORY_STATISTICAL,
537
            'functionCall' => [Statistical\Distributions\ChiSquared::class, 'test'],
538
            'argumentCount' => '2',
539
        ],
540
        'CHISQ.TEST' => [
541
            'category' => Category::CATEGORY_STATISTICAL,
542
            'functionCall' => [Statistical\Distributions\ChiSquared::class, 'test'],
543
            'argumentCount' => '2',
544
        ],
545
        'CHOOSE' => [
546
            'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE,
547
            'functionCall' => [LookupRef\Selection::class, 'CHOOSE'],
548
            'argumentCount' => '2+',
549
        ],
550
        'CHOOSECOLS' => [
551
            'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE,
552
            'functionCall' => [LookupRef\ChooseRowsEtc::class, 'chooseCols'],
553
            'argumentCount' => '2+',
554
        ],
555
        'CHOOSEROWS' => [
556
            'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE,
557
            'functionCall' => [LookupRef\ChooseRowsEtc::class, 'chooseRows'],
558
            'argumentCount' => '2+',
559
        ],
560
        'CLEAN' => [
561
            'category' => Category::CATEGORY_TEXT_AND_DATA,
562
            'functionCall' => [TextData\Trim::class, 'nonPrintable'],
563
            'argumentCount' => '1',
564
        ],
565
        'CODE' => [
566
            'category' => Category::CATEGORY_TEXT_AND_DATA,
567
            'functionCall' => [TextData\CharacterConvert::class, 'code'],
568
            'argumentCount' => '1',
569
        ],
570
        'COLUMN' => [
571
            'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE,
572
            'functionCall' => [LookupRef\RowColumnInformation::class, 'COLUMN'],
573
            'argumentCount' => '-1',
574
            'passCellReference' => true,
575
            'passByReference' => [true],
576
        ],
577
        'COLUMNS' => [
578
            'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE,
579
            'functionCall' => [LookupRef\RowColumnInformation::class, 'COLUMNS'],
580
            'argumentCount' => '1',
581
        ],
582
        'COMBIN' => [
583
            'category' => Category::CATEGORY_MATH_AND_TRIG,
584
            'functionCall' => [MathTrig\Combinations::class, 'withoutRepetition'],
585
            'argumentCount' => '2',
586
        ],
587
        'COMBINA' => [
588
            'category' => Category::CATEGORY_MATH_AND_TRIG,
589
            'functionCall' => [MathTrig\Combinations::class, 'withRepetition'],
590
            'argumentCount' => '2',
591
        ],
592
        'COMPLEX' => [
593
            'category' => Category::CATEGORY_ENGINEERING,
594
            'functionCall' => [Engineering\Complex::class, 'COMPLEX'],
595
            'argumentCount' => '2,3',
596
        ],
597
        'CONCAT' => [
598
            'category' => Category::CATEGORY_TEXT_AND_DATA,
599
            'functionCall' => [TextData\Concatenate::class, 'CONCATENATE'],
600
            'argumentCount' => '1+',
601
        ],
602
        'CONCATENATE' => [
603
            'category' => Category::CATEGORY_TEXT_AND_DATA,
604
            'functionCall' => [TextData\Concatenate::class, 'actualCONCATENATE'],
605
            'argumentCount' => '1+',
606
        ],
607
        'CONFIDENCE' => [
608
            'category' => Category::CATEGORY_STATISTICAL,
609
            'functionCall' => [Statistical\Confidence::class, 'CONFIDENCE'],
610
            'argumentCount' => '3',
611
        ],
612
        'CONFIDENCE.NORM' => [
613
            'category' => Category::CATEGORY_STATISTICAL,
614
            'functionCall' => [Statistical\Confidence::class, 'CONFIDENCE'],
615
            'argumentCount' => '3',
616
        ],
617
        'CONFIDENCE.T' => [
618
            'category' => Category::CATEGORY_STATISTICAL,
619
            'functionCall' => [Functions::class, 'DUMMY'],
620
            'argumentCount' => '3',
621
        ],
622
        'CONVERT' => [
623
            'category' => Category::CATEGORY_ENGINEERING,
624
            'functionCall' => [Engineering\ConvertUOM::class, 'CONVERT'],
625
            'argumentCount' => '3',
626
        ],
627
        'CORREL' => [
628
            'category' => Category::CATEGORY_STATISTICAL,
629
            'functionCall' => [Statistical\Trends::class, 'CORREL'],
630
            'argumentCount' => '2',
631
        ],
632
        'COS' => [
633
            'category' => Category::CATEGORY_MATH_AND_TRIG,
634
            'functionCall' => [MathTrig\Trig\Cosine::class, 'cos'],
635
            'argumentCount' => '1',
636
        ],
637
        'COSH' => [
638
            'category' => Category::CATEGORY_MATH_AND_TRIG,
639
            'functionCall' => [MathTrig\Trig\Cosine::class, 'cosh'],
640
            'argumentCount' => '1',
641
        ],
642
        'COT' => [
643
            'category' => Category::CATEGORY_MATH_AND_TRIG,
644
            'functionCall' => [MathTrig\Trig\Cotangent::class, 'cot'],
645
            'argumentCount' => '1',
646
        ],
647
        'COTH' => [
648
            'category' => Category::CATEGORY_MATH_AND_TRIG,
649
            'functionCall' => [MathTrig\Trig\Cotangent::class, 'coth'],
650
            'argumentCount' => '1',
651
        ],
652
        'COUNT' => [
653
            'category' => Category::CATEGORY_STATISTICAL,
654
            'functionCall' => [Statistical\Counts::class, 'COUNT'],
655
            'argumentCount' => '1+',
656
        ],
657
        'COUNTA' => [
658
            'category' => Category::CATEGORY_STATISTICAL,
659
            'functionCall' => [Statistical\Counts::class, 'COUNTA'],
660
            'argumentCount' => '1+',
661
        ],
662
        'COUNTBLANK' => [
663
            'category' => Category::CATEGORY_STATISTICAL,
664
            'functionCall' => [Statistical\Counts::class, 'COUNTBLANK'],
665
            'argumentCount' => '1',
666
        ],
667
        'COUNTIF' => [
668
            'category' => Category::CATEGORY_STATISTICAL,
669
            'functionCall' => [Statistical\Conditional::class, 'COUNTIF'],
670
            'argumentCount' => '2',
671
        ],
672
        'COUNTIFS' => [
673
            'category' => Category::CATEGORY_STATISTICAL,
674
            'functionCall' => [Statistical\Conditional::class, 'COUNTIFS'],
675
            'argumentCount' => '2+',
676
        ],
677
        'COUPDAYBS' => [
678
            'category' => Category::CATEGORY_FINANCIAL,
679
            'functionCall' => [Financial\Coupons::class, 'COUPDAYBS'],
680
            'argumentCount' => '3,4',
681
        ],
682
        'COUPDAYS' => [
683
            'category' => Category::CATEGORY_FINANCIAL,
684
            'functionCall' => [Financial\Coupons::class, 'COUPDAYS'],
685
            'argumentCount' => '3,4',
686
        ],
687
        'COUPDAYSNC' => [
688
            'category' => Category::CATEGORY_FINANCIAL,
689
            'functionCall' => [Financial\Coupons::class, 'COUPDAYSNC'],
690
            'argumentCount' => '3,4',
691
        ],
692
        'COUPNCD' => [
693
            'category' => Category::CATEGORY_FINANCIAL,
694
            'functionCall' => [Financial\Coupons::class, 'COUPNCD'],
695
            'argumentCount' => '3,4',
696
        ],
697
        'COUPNUM' => [
698
            'category' => Category::CATEGORY_FINANCIAL,
699
            'functionCall' => [Financial\Coupons::class, 'COUPNUM'],
700
            'argumentCount' => '3,4',
701
        ],
702
        'COUPPCD' => [
703
            'category' => Category::CATEGORY_FINANCIAL,
704
            'functionCall' => [Financial\Coupons::class, 'COUPPCD'],
705
            'argumentCount' => '3,4',
706
        ],
707
        'COVAR' => [
708
            'category' => Category::CATEGORY_STATISTICAL,
709
            'functionCall' => [Statistical\Trends::class, 'COVAR'],
710
            'argumentCount' => '2',
711
        ],
712
        'COVARIANCE.P' => [
713
            'category' => Category::CATEGORY_STATISTICAL,
714
            'functionCall' => [Statistical\Trends::class, 'COVAR'],
715
            'argumentCount' => '2',
716
        ],
717
        'COVARIANCE.S' => [
718
            'category' => Category::CATEGORY_STATISTICAL,
719
            'functionCall' => [Functions::class, 'DUMMY'],
720
            'argumentCount' => '2',
721
        ],
722
        'CRITBINOM' => [
723
            'category' => Category::CATEGORY_STATISTICAL,
724
            'functionCall' => [Statistical\Distributions\Binomial::class, 'inverse'],
725
            'argumentCount' => '3',
726
        ],
727
        'CSC' => [
728
            'category' => Category::CATEGORY_MATH_AND_TRIG,
729
            'functionCall' => [MathTrig\Trig\Cosecant::class, 'csc'],
730
            'argumentCount' => '1',
731
        ],
732
        'CSCH' => [
733
            'category' => Category::CATEGORY_MATH_AND_TRIG,
734
            'functionCall' => [MathTrig\Trig\Cosecant::class, 'csch'],
735
            'argumentCount' => '1',
736
        ],
737
        'CUBEKPIMEMBER' => [
738
            'category' => Category::CATEGORY_CUBE,
739
            'functionCall' => [Functions::class, 'DUMMY'],
740
            'argumentCount' => '?',
741
        ],
742
        'CUBEMEMBER' => [
743
            'category' => Category::CATEGORY_CUBE,
744
            'functionCall' => [Functions::class, 'DUMMY'],
745
            'argumentCount' => '?',
746
        ],
747
        'CUBEMEMBERPROPERTY' => [
748
            'category' => Category::CATEGORY_CUBE,
749
            'functionCall' => [Functions::class, 'DUMMY'],
750
            'argumentCount' => '?',
751
        ],
752
        'CUBERANKEDMEMBER' => [
753
            'category' => Category::CATEGORY_CUBE,
754
            'functionCall' => [Functions::class, 'DUMMY'],
755
            'argumentCount' => '?',
756
        ],
757
        'CUBESET' => [
758
            'category' => Category::CATEGORY_CUBE,
759
            'functionCall' => [Functions::class, 'DUMMY'],
760
            'argumentCount' => '?',
761
        ],
762
        'CUBESETCOUNT' => [
763
            'category' => Category::CATEGORY_CUBE,
764
            'functionCall' => [Functions::class, 'DUMMY'],
765
            'argumentCount' => '?',
766
        ],
767
        'CUBEVALUE' => [
768
            'category' => Category::CATEGORY_CUBE,
769
            'functionCall' => [Functions::class, 'DUMMY'],
770
            'argumentCount' => '?',
771
        ],
772
        'CUMIPMT' => [
773
            'category' => Category::CATEGORY_FINANCIAL,
774
            'functionCall' => [Financial\CashFlow\Constant\Periodic\Cumulative::class, 'interest'],
775
            'argumentCount' => '6',
776
        ],
777
        'CUMPRINC' => [
778
            'category' => Category::CATEGORY_FINANCIAL,
779
            'functionCall' => [Financial\CashFlow\Constant\Periodic\Cumulative::class, 'principal'],
780
            'argumentCount' => '6',
781
        ],
782
        'DATE' => [
783
            'category' => Category::CATEGORY_DATE_AND_TIME,
784
            'functionCall' => [DateTimeExcel\Date::class, 'fromYMD'],
785
            'argumentCount' => '3',
786
        ],
787
        'DATEDIF' => [
788
            'category' => Category::CATEGORY_DATE_AND_TIME,
789
            'functionCall' => [DateTimeExcel\Difference::class, 'interval'],
790
            'argumentCount' => '2,3',
791
        ],
792
        'DATESTRING' => [
793
            'category' => Category::CATEGORY_DATE_AND_TIME,
794
            'functionCall' => [Functions::class, 'DUMMY'],
795
            'argumentCount' => '?',
796
        ],
797
        'DATEVALUE' => [
798
            'category' => Category::CATEGORY_DATE_AND_TIME,
799
            'functionCall' => [DateTimeExcel\DateValue::class, 'fromString'],
800
            'argumentCount' => '1',
801
        ],
802
        'DAVERAGE' => [
803
            'category' => Category::CATEGORY_DATABASE,
804
            'functionCall' => [Database\DAverage::class, 'evaluate'],
805
            'argumentCount' => '3',
806
        ],
807
        'DAY' => [
808
            'category' => Category::CATEGORY_DATE_AND_TIME,
809
            'functionCall' => [DateTimeExcel\DateParts::class, 'day'],
810
            'argumentCount' => '1',
811
        ],
812
        'DAYS' => [
813
            'category' => Category::CATEGORY_DATE_AND_TIME,
814
            'functionCall' => [DateTimeExcel\Days::class, 'between'],
815
            'argumentCount' => '2',
816
        ],
817
        'DAYS360' => [
818
            'category' => Category::CATEGORY_DATE_AND_TIME,
819
            'functionCall' => [DateTimeExcel\Days360::class, 'between'],
820
            'argumentCount' => '2,3',
821
        ],
822
        'DB' => [
823
            'category' => Category::CATEGORY_FINANCIAL,
824
            'functionCall' => [Financial\Depreciation::class, 'DB'],
825
            'argumentCount' => '4,5',
826
        ],
827
        'DBCS' => [
828
            'category' => Category::CATEGORY_TEXT_AND_DATA,
829
            'functionCall' => [Functions::class, 'DUMMY'],
830
            'argumentCount' => '1',
831
        ],
832
        'DCOUNT' => [
833
            'category' => Category::CATEGORY_DATABASE,
834
            'functionCall' => [Database\DCount::class, 'evaluate'],
835
            'argumentCount' => '3',
836
        ],
837
        'DCOUNTA' => [
838
            'category' => Category::CATEGORY_DATABASE,
839
            'functionCall' => [Database\DCountA::class, 'evaluate'],
840
            'argumentCount' => '3',
841
        ],
842
        'DDB' => [
843
            'category' => Category::CATEGORY_FINANCIAL,
844
            'functionCall' => [Financial\Depreciation::class, 'DDB'],
845
            'argumentCount' => '4,5',
846
        ],
847
        'DEC2BIN' => [
848
            'category' => Category::CATEGORY_ENGINEERING,
849
            'functionCall' => [Engineering\ConvertDecimal::class, 'toBinary'],
850
            'argumentCount' => '1,2',
851
        ],
852
        'DEC2HEX' => [
853
            'category' => Category::CATEGORY_ENGINEERING,
854
            'functionCall' => [Engineering\ConvertDecimal::class, 'toHex'],
855
            'argumentCount' => '1,2',
856
        ],
857
        'DEC2OCT' => [
858
            'category' => Category::CATEGORY_ENGINEERING,
859
            'functionCall' => [Engineering\ConvertDecimal::class, 'toOctal'],
860
            'argumentCount' => '1,2',
861
        ],
862
        'DECIMAL' => [
863
            'category' => Category::CATEGORY_MATH_AND_TRIG,
864
            'functionCall' => [Functions::class, 'DUMMY'],
865
            'argumentCount' => '2',
866
        ],
867
        'DEGREES' => [
868
            'category' => Category::CATEGORY_MATH_AND_TRIG,
869
            'functionCall' => [MathTrig\Angle::class, 'toDegrees'],
870
            'argumentCount' => '1',
871
        ],
872
        'DELTA' => [
873
            'category' => Category::CATEGORY_ENGINEERING,
874
            'functionCall' => [Engineering\Compare::class, 'DELTA'],
875
            'argumentCount' => '1,2',
876
        ],
877
        'DEVSQ' => [
878
            'category' => Category::CATEGORY_STATISTICAL,
879
            'functionCall' => [Statistical\Deviations::class, 'sumSquares'],
880
            'argumentCount' => '1+',
881
        ],
882
        'DGET' => [
883
            'category' => Category::CATEGORY_DATABASE,
884
            'functionCall' => [Database\DGet::class, 'evaluate'],
885
            'argumentCount' => '3',
886
        ],
887
        'DISC' => [
888
            'category' => Category::CATEGORY_FINANCIAL,
889
            'functionCall' => [Financial\Securities\Rates::class, 'discount'],
890
            'argumentCount' => '4,5',
891
        ],
892
        'DMAX' => [
893
            'category' => Category::CATEGORY_DATABASE,
894
            'functionCall' => [Database\DMax::class, 'evaluate'],
895
            'argumentCount' => '3',
896
        ],
897
        'DMIN' => [
898
            'category' => Category::CATEGORY_DATABASE,
899
            'functionCall' => [Database\DMin::class, 'evaluate'],
900
            'argumentCount' => '3',
901
        ],
902
        'DOLLAR' => [
903
            'category' => Category::CATEGORY_TEXT_AND_DATA,
904
            'functionCall' => [TextData\Format::class, 'DOLLAR'],
905
            'argumentCount' => '1,2',
906
        ],
907
        'DOLLARDE' => [
908
            'category' => Category::CATEGORY_FINANCIAL,
909
            'functionCall' => [Financial\Dollar::class, 'decimal'],
910
            'argumentCount' => '2',
911
        ],
912
        'DOLLARFR' => [
913
            'category' => Category::CATEGORY_FINANCIAL,
914
            'functionCall' => [Financial\Dollar::class, 'fractional'],
915
            'argumentCount' => '2',
916
        ],
917
        'DPRODUCT' => [
918
            'category' => Category::CATEGORY_DATABASE,
919
            'functionCall' => [Database\DProduct::class, 'evaluate'],
920
            'argumentCount' => '3',
921
        ],
922
        'DROP' => [
923
            'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE,
924
            'functionCall' => [LookupRef\ChooseRowsEtc::class, 'drop'],
925
            'argumentCount' => '2-3',
926
        ],
927
        'DSTDEV' => [
928
            'category' => Category::CATEGORY_DATABASE,
929
            'functionCall' => [Database\DStDev::class, 'evaluate'],
930
            'argumentCount' => '3',
931
        ],
932
        'DSTDEVP' => [
933
            'category' => Category::CATEGORY_DATABASE,
934
            'functionCall' => [Database\DStDevP::class, 'evaluate'],
935
            'argumentCount' => '3',
936
        ],
937
        'DSUM' => [
938
            'category' => Category::CATEGORY_DATABASE,
939
            'functionCall' => [Database\DSum::class, 'evaluate'],
940
            'argumentCount' => '3',
941
        ],
942
        'DURATION' => [
943
            'category' => Category::CATEGORY_FINANCIAL,
944
            'functionCall' => [Functions::class, 'DUMMY'],
945
            'argumentCount' => '5,6',
946
        ],
947
        'DVAR' => [
948
            'category' => Category::CATEGORY_DATABASE,
949
            'functionCall' => [Database\DVar::class, 'evaluate'],
950
            'argumentCount' => '3',
951
        ],
952
        'DVARP' => [
953
            'category' => Category::CATEGORY_DATABASE,
954
            'functionCall' => [Database\DVarP::class, 'evaluate'],
955
            'argumentCount' => '3',
956
        ],
957
        'ECMA.CEILING' => [
958
            'category' => Category::CATEGORY_MATH_AND_TRIG,
959
            'functionCall' => [Functions::class, 'DUMMY'],
960
            'argumentCount' => '1,2',
961
        ],
962
        'EDATE' => [
963
            'category' => Category::CATEGORY_DATE_AND_TIME,
964
            'functionCall' => [DateTimeExcel\Month::class, 'adjust'],
965
            'argumentCount' => '2',
966
        ],
967
        'EFFECT' => [
968
            'category' => Category::CATEGORY_FINANCIAL,
969
            'functionCall' => [Financial\InterestRate::class, 'effective'],
970
            'argumentCount' => '2',
971
        ],
972
        'ENCODEURL' => [
973
            'category' => Category::CATEGORY_WEB,
974
            'functionCall' => [Web\Service::class, 'urlEncode'],
975
            'argumentCount' => '1',
976
        ],
977
        'EOMONTH' => [
978
            'category' => Category::CATEGORY_DATE_AND_TIME,
979
            'functionCall' => [DateTimeExcel\Month::class, 'lastDay'],
980
            'argumentCount' => '2',
981
        ],
982
        'ERF' => [
983
            'category' => Category::CATEGORY_ENGINEERING,
984
            'functionCall' => [Engineering\Erf::class, 'ERF'],
985
            'argumentCount' => '1,2',
986
        ],
987
        'ERF.PRECISE' => [
988
            'category' => Category::CATEGORY_ENGINEERING,
989
            'functionCall' => [Engineering\Erf::class, 'ERFPRECISE'],
990
            'argumentCount' => '1',
991
        ],
992
        'ERFC' => [
993
            'category' => Category::CATEGORY_ENGINEERING,
994
            'functionCall' => [Engineering\ErfC::class, 'ERFC'],
995
            'argumentCount' => '1',
996
        ],
997
        'ERFC.PRECISE' => [
998
            'category' => Category::CATEGORY_ENGINEERING,
999
            'functionCall' => [Engineering\ErfC::class, 'ERFC'],
1000
            'argumentCount' => '1',
1001
        ],
1002
        'ERROR.TYPE' => [
1003
            'category' => Category::CATEGORY_INFORMATION,
1004
            'functionCall' => [ExcelError::class, 'type'],
1005
            'argumentCount' => '1',
1006
        ],
1007
        'EVEN' => [
1008
            'category' => Category::CATEGORY_MATH_AND_TRIG,
1009
            'functionCall' => [MathTrig\Round::class, 'even'],
1010
            'argumentCount' => '1',
1011
        ],
1012
        'EXACT' => [
1013
            'category' => Category::CATEGORY_TEXT_AND_DATA,
1014
            'functionCall' => [TextData\Text::class, 'exact'],
1015
            'argumentCount' => '2',
1016
        ],
1017
        'EXP' => [
1018
            'category' => Category::CATEGORY_MATH_AND_TRIG,
1019
            'functionCall' => [MathTrig\Exp::class, 'evaluate'],
1020
            'argumentCount' => '1',
1021
        ],
1022
        'EXPAND' => [
1023
            'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE,
1024
            'functionCall' => [LookupRef\ChooseRowsEtc::class, 'expand'],
1025
            'argumentCount' => '2-4',
1026
        ],
1027
        'EXPONDIST' => [
1028
            'category' => Category::CATEGORY_STATISTICAL,
1029
            'functionCall' => [Statistical\Distributions\Exponential::class, 'distribution'],
1030
            'argumentCount' => '3',
1031
        ],
1032
        'EXPON.DIST' => [
1033
            'category' => Category::CATEGORY_STATISTICAL,
1034
            'functionCall' => [Statistical\Distributions\Exponential::class, 'distribution'],
1035
            'argumentCount' => '3',
1036
        ],
1037
        'FACT' => [
1038
            'category' => Category::CATEGORY_MATH_AND_TRIG,
1039
            'functionCall' => [MathTrig\Factorial::class, 'fact'],
1040
            'argumentCount' => '1',
1041
        ],
1042
        'FACTDOUBLE' => [
1043
            'category' => Category::CATEGORY_MATH_AND_TRIG,
1044
            'functionCall' => [MathTrig\Factorial::class, 'factDouble'],
1045
            'argumentCount' => '1',
1046
        ],
1047
        'FALSE' => [
1048
            'category' => Category::CATEGORY_LOGICAL,
1049
            'functionCall' => [Logical\Boolean::class, 'FALSE'],
1050
            'argumentCount' => '0',
1051
        ],
1052
        'FDIST' => [
1053
            'category' => Category::CATEGORY_STATISTICAL,
1054
            'functionCall' => [Functions::class, 'DUMMY'],
1055
            'argumentCount' => '3',
1056
        ],
1057
        'F.DIST' => [
1058
            'category' => Category::CATEGORY_STATISTICAL,
1059
            'functionCall' => [Statistical\Distributions\F::class, 'distribution'],
1060
            'argumentCount' => '4',
1061
        ],
1062
        'F.DIST.RT' => [
1063
            'category' => Category::CATEGORY_STATISTICAL,
1064
            'functionCall' => [Functions::class, 'DUMMY'],
1065
            'argumentCount' => '3',
1066
        ],
1067
        'FILTER' => [
1068
            'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE,
1069
            'functionCall' => [LookupRef\Filter::class, 'filter'],
1070
            'argumentCount' => '2-3',
1071
        ],
1072
        'FILTERXML' => [
1073
            'category' => Category::CATEGORY_WEB,
1074
            'functionCall' => [Functions::class, 'DUMMY'],
1075
            'argumentCount' => '2',
1076
        ],
1077
        'FIND' => [
1078
            'category' => Category::CATEGORY_TEXT_AND_DATA,
1079
            'functionCall' => [TextData\Search::class, 'sensitive'],
1080
            'argumentCount' => '2,3',
1081
        ],
1082
        'FINDB' => [
1083
            'category' => Category::CATEGORY_TEXT_AND_DATA,
1084
            'functionCall' => [TextData\Search::class, 'sensitive'],
1085
            'argumentCount' => '2,3',
1086
        ],
1087
        'FINV' => [
1088
            'category' => Category::CATEGORY_STATISTICAL,
1089
            'functionCall' => [Functions::class, 'DUMMY'],
1090
            'argumentCount' => '3',
1091
        ],
1092
        'F.INV' => [
1093
            'category' => Category::CATEGORY_STATISTICAL,
1094
            'functionCall' => [Functions::class, 'DUMMY'],
1095
            'argumentCount' => '3',
1096
        ],
1097
        'F.INV.RT' => [
1098
            'category' => Category::CATEGORY_STATISTICAL,
1099
            'functionCall' => [Functions::class, 'DUMMY'],
1100
            'argumentCount' => '3',
1101
        ],
1102
        'FISHER' => [
1103
            'category' => Category::CATEGORY_STATISTICAL,
1104
            'functionCall' => [Statistical\Distributions\Fisher::class, 'distribution'],
1105
            'argumentCount' => '1',
1106
        ],
1107
        'FISHERINV' => [
1108
            'category' => Category::CATEGORY_STATISTICAL,
1109
            'functionCall' => [Statistical\Distributions\Fisher::class, 'inverse'],
1110
            'argumentCount' => '1',
1111
        ],
1112
        'FIXED' => [
1113
            'category' => Category::CATEGORY_TEXT_AND_DATA,
1114
            'functionCall' => [TextData\Format::class, 'FIXEDFORMAT'],
1115
            'argumentCount' => '1-3',
1116
        ],
1117
        'FLOOR' => [
1118
            'category' => Category::CATEGORY_MATH_AND_TRIG,
1119
            'functionCall' => [MathTrig\Floor::class, 'floor'],
1120
            'argumentCount' => '1-2', // Excel requries 2, Ods/Gnumeric 1-2
1121
        ],
1122
        'FLOOR.MATH' => [
1123
            'category' => Category::CATEGORY_MATH_AND_TRIG,
1124
            'functionCall' => [MathTrig\Floor::class, 'math'],
1125
            'argumentCount' => '1-3',
1126
        ],
1127
        'FLOOR.PRECISE' => [
1128
            'category' => Category::CATEGORY_MATH_AND_TRIG,
1129
            'functionCall' => [MathTrig\Floor::class, 'precise'],
1130
            'argumentCount' => '1-2',
1131
        ],
1132
        'FORECAST' => [
1133
            'category' => Category::CATEGORY_STATISTICAL,
1134
            'functionCall' => [Statistical\Trends::class, 'FORECAST'],
1135
            'argumentCount' => '3',
1136
        ],
1137
        'FORECAST.ETS' => [
1138
            'category' => Category::CATEGORY_STATISTICAL,
1139
            'functionCall' => [Functions::class, 'DUMMY'],
1140
            'argumentCount' => '3-6',
1141
        ],
1142
        'FORECAST.ETS.CONFINT' => [
1143
            'category' => Category::CATEGORY_STATISTICAL,
1144
            'functionCall' => [Functions::class, 'DUMMY'],
1145
            'argumentCount' => '3-6',
1146
        ],
1147
        'FORECAST.ETS.SEASONALITY' => [
1148
            'category' => Category::CATEGORY_STATISTICAL,
1149
            'functionCall' => [Functions::class, 'DUMMY'],
1150
            'argumentCount' => '2-4',
1151
        ],
1152
        'FORECAST.ETS.STAT' => [
1153
            'category' => Category::CATEGORY_STATISTICAL,
1154
            'functionCall' => [Functions::class, 'DUMMY'],
1155
            'argumentCount' => '3-6',
1156
        ],
1157
        'FORECAST.LINEAR' => [
1158
            'category' => Category::CATEGORY_STATISTICAL,
1159
            'functionCall' => [Statistical\Trends::class, 'FORECAST'],
1160
            'argumentCount' => '3',
1161
        ],
1162
        'FORMULATEXT' => [
1163
            'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE,
1164
            'functionCall' => [LookupRef\Formula::class, 'text'],
1165
            'argumentCount' => '1',
1166
            'passCellReference' => true,
1167
            'passByReference' => [true],
1168
        ],
1169
        'FREQUENCY' => [
1170
            'category' => Category::CATEGORY_STATISTICAL,
1171
            'functionCall' => [Functions::class, 'DUMMY'],
1172
            'argumentCount' => '2',
1173
        ],
1174
        'FTEST' => [
1175
            'category' => Category::CATEGORY_STATISTICAL,
1176
            'functionCall' => [Functions::class, 'DUMMY'],
1177
            'argumentCount' => '2',
1178
        ],
1179
        'F.TEST' => [
1180
            'category' => Category::CATEGORY_STATISTICAL,
1181
            'functionCall' => [Functions::class, 'DUMMY'],
1182
            'argumentCount' => '2',
1183
        ],
1184
        'FV' => [
1185
            'category' => Category::CATEGORY_FINANCIAL,
1186
            'functionCall' => [Financial\CashFlow\Constant\Periodic::class, 'futureValue'],
1187
            'argumentCount' => '3-5',
1188
        ],
1189
        'FVSCHEDULE' => [
1190
            'category' => Category::CATEGORY_FINANCIAL,
1191
            'functionCall' => [Financial\CashFlow\Single::class, 'futureValue'],
1192
            'argumentCount' => '2',
1193
        ],
1194
        'GAMMA' => [
1195
            'category' => Category::CATEGORY_STATISTICAL,
1196
            'functionCall' => [Statistical\Distributions\Gamma::class, 'gamma'],
1197
            'argumentCount' => '1',
1198
        ],
1199
        'GAMMADIST' => [
1200
            'category' => Category::CATEGORY_STATISTICAL,
1201
            'functionCall' => [Statistical\Distributions\Gamma::class, 'distribution'],
1202
            'argumentCount' => '4',
1203
        ],
1204
        'GAMMA.DIST' => [
1205
            'category' => Category::CATEGORY_STATISTICAL,
1206
            'functionCall' => [Statistical\Distributions\Gamma::class, 'distribution'],
1207
            'argumentCount' => '4',
1208
        ],
1209
        'GAMMAINV' => [
1210
            'category' => Category::CATEGORY_STATISTICAL,
1211
            'functionCall' => [Statistical\Distributions\Gamma::class, 'inverse'],
1212
            'argumentCount' => '3',
1213
        ],
1214
        'GAMMA.INV' => [
1215
            'category' => Category::CATEGORY_STATISTICAL,
1216
            'functionCall' => [Statistical\Distributions\Gamma::class, 'inverse'],
1217
            'argumentCount' => '3',
1218
        ],
1219
        'GAMMALN' => [
1220
            'category' => Category::CATEGORY_STATISTICAL,
1221
            'functionCall' => [Statistical\Distributions\Gamma::class, 'ln'],
1222
            'argumentCount' => '1',
1223
        ],
1224
        'GAMMALN.PRECISE' => [
1225
            'category' => Category::CATEGORY_STATISTICAL,
1226
            'functionCall' => [Statistical\Distributions\Gamma::class, 'ln'],
1227
            'argumentCount' => '1',
1228
        ],
1229
        'GAUSS' => [
1230
            'category' => Category::CATEGORY_STATISTICAL,
1231
            'functionCall' => [Statistical\Distributions\StandardNormal::class, 'gauss'],
1232
            'argumentCount' => '1',
1233
        ],
1234
        'GCD' => [
1235
            'category' => Category::CATEGORY_MATH_AND_TRIG,
1236
            'functionCall' => [MathTrig\Gcd::class, 'evaluate'],
1237
            'argumentCount' => '1+',
1238
        ],
1239
        'GEOMEAN' => [
1240
            'category' => Category::CATEGORY_STATISTICAL,
1241
            'functionCall' => [Statistical\Averages\Mean::class, 'geometric'],
1242
            'argumentCount' => '1+',
1243
        ],
1244
        'GESTEP' => [
1245
            'category' => Category::CATEGORY_ENGINEERING,
1246
            'functionCall' => [Engineering\Compare::class, 'GESTEP'],
1247
            'argumentCount' => '1,2',
1248
        ],
1249
        'GETPIVOTDATA' => [
1250
            'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE,
1251
            'functionCall' => [Functions::class, 'DUMMY'],
1252
            'argumentCount' => '2+',
1253
        ],
1254
        'GROUPBY' => [
1255
            'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE,
1256
            'functionCall' => [Functions::class, 'DUMMY'],
1257
            'argumentCount' => '3-7',
1258
        ],
1259
        'GROWTH' => [
1260
            'category' => Category::CATEGORY_STATISTICAL,
1261
            'functionCall' => [Statistical\Trends::class, 'GROWTH'],
1262
            'argumentCount' => '1-4',
1263
        ],
1264
        'HARMEAN' => [
1265
            'category' => Category::CATEGORY_STATISTICAL,
1266
            'functionCall' => [Statistical\Averages\Mean::class, 'harmonic'],
1267
            'argumentCount' => '1+',
1268
        ],
1269
        'HEX2BIN' => [
1270
            'category' => Category::CATEGORY_ENGINEERING,
1271
            'functionCall' => [Engineering\ConvertHex::class, 'toBinary'],
1272
            'argumentCount' => '1,2',
1273
        ],
1274
        'HEX2DEC' => [
1275
            'category' => Category::CATEGORY_ENGINEERING,
1276
            'functionCall' => [Engineering\ConvertHex::class, 'toDecimal'],
1277
            'argumentCount' => '1',
1278
        ],
1279
        'HEX2OCT' => [
1280
            'category' => Category::CATEGORY_ENGINEERING,
1281
            'functionCall' => [Engineering\ConvertHex::class, 'toOctal'],
1282
            'argumentCount' => '1,2',
1283
        ],
1284
        'HLOOKUP' => [
1285
            'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE,
1286
            'functionCall' => [LookupRef\HLookup::class, 'lookup'],
1287
            'argumentCount' => '3,4',
1288
        ],
1289
        'HOUR' => [
1290
            'category' => Category::CATEGORY_DATE_AND_TIME,
1291
            'functionCall' => [DateTimeExcel\TimeParts::class, 'hour'],
1292
            'argumentCount' => '1',
1293
        ],
1294
        'HSTACK' => [
1295
            'category' => Category::CATEGORY_MATH_AND_TRIG,
1296
            'functionCall' => [Functions::class, 'DUMMY'],
1297
            'argumentCount' => '1+',
1298
        ],
1299
        'HYPERLINK' => [
1300
            'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE,
1301
            'functionCall' => [LookupRef\Hyperlink::class, 'set'],
1302
            'argumentCount' => '1,2',
1303
            'passCellReference' => true,
1304
        ],
1305
        'HYPGEOMDIST' => [
1306
            'category' => Category::CATEGORY_STATISTICAL,
1307
            'functionCall' => [Statistical\Distributions\HyperGeometric::class, 'distribution'],
1308
            'argumentCount' => '4',
1309
        ],
1310
        'HYPGEOM.DIST' => [
1311
            'category' => Category::CATEGORY_STATISTICAL,
1312
            'functionCall' => [Functions::class, 'DUMMY'],
1313
            'argumentCount' => '5',
1314
        ],
1315
        'IF' => [
1316
            'category' => Category::CATEGORY_LOGICAL,
1317
            'functionCall' => [Logical\Conditional::class, 'statementIf'],
1318
            'argumentCount' => '2-3',
1319
        ],
1320
        'IFERROR' => [
1321
            'category' => Category::CATEGORY_LOGICAL,
1322
            'functionCall' => [Logical\Conditional::class, 'IFERROR'],
1323
            'argumentCount' => '2',
1324
        ],
1325
        'IFNA' => [
1326
            'category' => Category::CATEGORY_LOGICAL,
1327
            'functionCall' => [Logical\Conditional::class, 'IFNA'],
1328
            'argumentCount' => '2',
1329
        ],
1330
        'IFS' => [
1331
            'category' => Category::CATEGORY_LOGICAL,
1332
            'functionCall' => [Logical\Conditional::class, 'IFS'],
1333
            'argumentCount' => '2+',
1334
        ],
1335
        'IMABS' => [
1336
            'category' => Category::CATEGORY_ENGINEERING,
1337
            'functionCall' => [Engineering\ComplexFunctions::class, 'IMABS'],
1338
            'argumentCount' => '1',
1339
        ],
1340
        'IMAGINARY' => [
1341
            'category' => Category::CATEGORY_ENGINEERING,
1342
            'functionCall' => [Engineering\Complex::class, 'IMAGINARY'],
1343
            'argumentCount' => '1',
1344
        ],
1345
        'IMARGUMENT' => [
1346
            'category' => Category::CATEGORY_ENGINEERING,
1347
            'functionCall' => [Engineering\ComplexFunctions::class, 'IMARGUMENT'],
1348
            'argumentCount' => '1',
1349
        ],
1350
        'IMCONJUGATE' => [
1351
            'category' => Category::CATEGORY_ENGINEERING,
1352
            'functionCall' => [Engineering\ComplexFunctions::class, 'IMCONJUGATE'],
1353
            'argumentCount' => '1',
1354
        ],
1355
        'IMCOS' => [
1356
            'category' => Category::CATEGORY_ENGINEERING,
1357
            'functionCall' => [Engineering\ComplexFunctions::class, 'IMCOS'],
1358
            'argumentCount' => '1',
1359
        ],
1360
        'IMCOSH' => [
1361
            'category' => Category::CATEGORY_ENGINEERING,
1362
            'functionCall' => [Engineering\ComplexFunctions::class, 'IMCOSH'],
1363
            'argumentCount' => '1',
1364
        ],
1365
        'IMCOT' => [
1366
            'category' => Category::CATEGORY_ENGINEERING,
1367
            'functionCall' => [Engineering\ComplexFunctions::class, 'IMCOT'],
1368
            'argumentCount' => '1',
1369
        ],
1370
        'IMCSC' => [
1371
            'category' => Category::CATEGORY_ENGINEERING,
1372
            'functionCall' => [Engineering\ComplexFunctions::class, 'IMCSC'],
1373
            'argumentCount' => '1',
1374
        ],
1375
        'IMCSCH' => [
1376
            'category' => Category::CATEGORY_ENGINEERING,
1377
            'functionCall' => [Engineering\ComplexFunctions::class, 'IMCSCH'],
1378
            'argumentCount' => '1',
1379
        ],
1380
        'IMDIV' => [
1381
            'category' => Category::CATEGORY_ENGINEERING,
1382
            'functionCall' => [Engineering\ComplexOperations::class, 'IMDIV'],
1383
            'argumentCount' => '2',
1384
        ],
1385
        'IMEXP' => [
1386
            'category' => Category::CATEGORY_ENGINEERING,
1387
            'functionCall' => [Engineering\ComplexFunctions::class, 'IMEXP'],
1388
            'argumentCount' => '1',
1389
        ],
1390
        'IMLN' => [
1391
            'category' => Category::CATEGORY_ENGINEERING,
1392
            'functionCall' => [Engineering\ComplexFunctions::class, 'IMLN'],
1393
            'argumentCount' => '1',
1394
        ],
1395
        'IMLOG10' => [
1396
            'category' => Category::CATEGORY_ENGINEERING,
1397
            'functionCall' => [Engineering\ComplexFunctions::class, 'IMLOG10'],
1398
            'argumentCount' => '1',
1399
        ],
1400
        'IMLOG2' => [
1401
            'category' => Category::CATEGORY_ENGINEERING,
1402
            'functionCall' => [Engineering\ComplexFunctions::class, 'IMLOG2'],
1403
            'argumentCount' => '1',
1404
        ],
1405
        'IMPOWER' => [
1406
            'category' => Category::CATEGORY_ENGINEERING,
1407
            'functionCall' => [Engineering\ComplexFunctions::class, 'IMPOWER'],
1408
            'argumentCount' => '2',
1409
        ],
1410
        'IMPRODUCT' => [
1411
            'category' => Category::CATEGORY_ENGINEERING,
1412
            'functionCall' => [Engineering\ComplexOperations::class, 'IMPRODUCT'],
1413
            'argumentCount' => '1+',
1414
        ],
1415
        'IMREAL' => [
1416
            'category' => Category::CATEGORY_ENGINEERING,
1417
            'functionCall' => [Engineering\Complex::class, 'IMREAL'],
1418
            'argumentCount' => '1',
1419
        ],
1420
        'IMSEC' => [
1421
            'category' => Category::CATEGORY_ENGINEERING,
1422
            'functionCall' => [Engineering\ComplexFunctions::class, 'IMSEC'],
1423
            'argumentCount' => '1',
1424
        ],
1425
        'IMSECH' => [
1426
            'category' => Category::CATEGORY_ENGINEERING,
1427
            'functionCall' => [Engineering\ComplexFunctions::class, 'IMSECH'],
1428
            'argumentCount' => '1',
1429
        ],
1430
        'IMSIN' => [
1431
            'category' => Category::CATEGORY_ENGINEERING,
1432
            'functionCall' => [Engineering\ComplexFunctions::class, 'IMSIN'],
1433
            'argumentCount' => '1',
1434
        ],
1435
        'IMSINH' => [
1436
            'category' => Category::CATEGORY_ENGINEERING,
1437
            'functionCall' => [Engineering\ComplexFunctions::class, 'IMSINH'],
1438
            'argumentCount' => '1',
1439
        ],
1440
        'IMSQRT' => [
1441
            'category' => Category::CATEGORY_ENGINEERING,
1442
            'functionCall' => [Engineering\ComplexFunctions::class, 'IMSQRT'],
1443
            'argumentCount' => '1',
1444
        ],
1445
        'IMSUB' => [
1446
            'category' => Category::CATEGORY_ENGINEERING,
1447
            'functionCall' => [Engineering\ComplexOperations::class, 'IMSUB'],
1448
            'argumentCount' => '2',
1449
        ],
1450
        'IMSUM' => [
1451
            'category' => Category::CATEGORY_ENGINEERING,
1452
            'functionCall' => [Engineering\ComplexOperations::class, 'IMSUM'],
1453
            'argumentCount' => '1+',
1454
        ],
1455
        'IMTAN' => [
1456
            'category' => Category::CATEGORY_ENGINEERING,
1457
            'functionCall' => [Engineering\ComplexFunctions::class, 'IMTAN'],
1458
            'argumentCount' => '1',
1459
        ],
1460
        'INDEX' => [
1461
            'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE,
1462
            'functionCall' => [LookupRef\Matrix::class, 'index'],
1463
            'argumentCount' => '2-4',
1464
        ],
1465
        'INDIRECT' => [
1466
            'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE,
1467
            'functionCall' => [LookupRef\Indirect::class, 'INDIRECT'],
1468
            'argumentCount' => '1,2',
1469
            'passCellReference' => true,
1470
        ],
1471
        'INFO' => [
1472
            'category' => Category::CATEGORY_INFORMATION,
1473
            'functionCall' => [Functions::class, 'DUMMY'],
1474
            'argumentCount' => '1',
1475
        ],
1476
        'INT' => [
1477
            'category' => Category::CATEGORY_MATH_AND_TRIG,
1478
            'functionCall' => [MathTrig\IntClass::class, 'evaluate'],
1479
            'argumentCount' => '1',
1480
        ],
1481
        'INTERCEPT' => [
1482
            'category' => Category::CATEGORY_STATISTICAL,
1483
            'functionCall' => [Statistical\Trends::class, 'INTERCEPT'],
1484
            'argumentCount' => '2',
1485
        ],
1486
        'INTRATE' => [
1487
            'category' => Category::CATEGORY_FINANCIAL,
1488
            'functionCall' => [Financial\Securities\Rates::class, 'interest'],
1489
            'argumentCount' => '4,5',
1490
        ],
1491
        'IPMT' => [
1492
            'category' => Category::CATEGORY_FINANCIAL,
1493
            'functionCall' => [Financial\CashFlow\Constant\Periodic\Interest::class, 'payment'],
1494
            'argumentCount' => '4-6',
1495
        ],
1496
        'IRR' => [
1497
            'category' => Category::CATEGORY_FINANCIAL,
1498
            'functionCall' => [Financial\CashFlow\Variable\Periodic::class, 'rate'],
1499
            'argumentCount' => '1,2',
1500
        ],
1501
        'ISBLANK' => [
1502
            'category' => Category::CATEGORY_INFORMATION,
1503
            'functionCall' => [Information\Value::class, 'isBlank'],
1504
            'argumentCount' => '1',
1505
        ],
1506
        'ISERR' => [
1507
            'category' => Category::CATEGORY_INFORMATION,
1508
            'functionCall' => [Information\ErrorValue::class, 'isErr'],
1509
            'argumentCount' => '1',
1510
        ],
1511
        'ISERROR' => [
1512
            'category' => Category::CATEGORY_INFORMATION,
1513
            'functionCall' => [Information\ErrorValue::class, 'isError'],
1514
            'argumentCount' => '1',
1515
        ],
1516
        'ISEVEN' => [
1517
            'category' => Category::CATEGORY_INFORMATION,
1518
            'functionCall' => [Information\Value::class, 'isEven'],
1519
            'argumentCount' => '1',
1520
        ],
1521
        'ISFORMULA' => [
1522
            'category' => Category::CATEGORY_INFORMATION,
1523
            'functionCall' => [Information\Value::class, 'isFormula'],
1524
            'argumentCount' => '1',
1525
            'passCellReference' => true,
1526
            'passByReference' => [true],
1527
        ],
1528
        'ISLOGICAL' => [
1529
            'category' => Category::CATEGORY_INFORMATION,
1530
            'functionCall' => [Information\Value::class, 'isLogical'],
1531
            'argumentCount' => '1',
1532
        ],
1533
        'ISNA' => [
1534
            'category' => Category::CATEGORY_INFORMATION,
1535
            'functionCall' => [Information\ErrorValue::class, 'isNa'],
1536
            'argumentCount' => '1',
1537
        ],
1538
        'ISNONTEXT' => [
1539
            'category' => Category::CATEGORY_INFORMATION,
1540
            'functionCall' => [Information\Value::class, 'isNonText'],
1541
            'argumentCount' => '1',
1542
        ],
1543
        'ISNUMBER' => [
1544
            'category' => Category::CATEGORY_INFORMATION,
1545
            'functionCall' => [Information\Value::class, 'isNumber'],
1546
            'argumentCount' => '1',
1547
        ],
1548
        'ISO.CEILING' => [
1549
            'category' => Category::CATEGORY_MATH_AND_TRIG,
1550
            'functionCall' => [Functions::class, 'DUMMY'],
1551
            'argumentCount' => '1,2',
1552
        ],
1553
        'ISODD' => [
1554
            'category' => Category::CATEGORY_INFORMATION,
1555
            'functionCall' => [Information\Value::class, 'isOdd'],
1556
            'argumentCount' => '1',
1557
        ],
1558
        'ISOMITTED' => [
1559
            'category' => Category::CATEGORY_INFORMATION,
1560
            'functionCall' => [Functions::class, 'DUMMY'],
1561
            'argumentCount' => '*',
1562
        ],
1563
        'ISOWEEKNUM' => [
1564
            'category' => Category::CATEGORY_DATE_AND_TIME,
1565
            'functionCall' => [DateTimeExcel\Week::class, 'isoWeekNumber'],
1566
            'argumentCount' => '1',
1567
        ],
1568
        'ISPMT' => [
1569
            'category' => Category::CATEGORY_FINANCIAL,
1570
            'functionCall' => [Financial\CashFlow\Constant\Periodic\Interest::class, 'schedulePayment'],
1571
            'argumentCount' => '4',
1572
        ],
1573
        'ISREF' => [
1574
            'category' => Category::CATEGORY_INFORMATION,
1575
            'functionCall' => [Information\Value::class, 'isRef'],
1576
            'argumentCount' => '1',
1577
            'passCellReference' => true,
1578
            'passByReference' => [true],
1579
        ],
1580
        'ISTEXT' => [
1581
            'category' => Category::CATEGORY_INFORMATION,
1582
            'functionCall' => [Information\Value::class, 'isText'],
1583
            'argumentCount' => '1',
1584
        ],
1585
        'ISTHAIDIGIT' => [
1586
            'category' => Category::CATEGORY_TEXT_AND_DATA,
1587
            'functionCall' => [Functions::class, 'DUMMY'],
1588
            'argumentCount' => '?',
1589
        ],
1590
        'JIS' => [
1591
            'category' => Category::CATEGORY_TEXT_AND_DATA,
1592
            'functionCall' => [Functions::class, 'DUMMY'],
1593
            'argumentCount' => '1',
1594
        ],
1595
        'KURT' => [
1596
            'category' => Category::CATEGORY_STATISTICAL,
1597
            'functionCall' => [Statistical\Deviations::class, 'kurtosis'],
1598
            'argumentCount' => '1+',
1599
        ],
1600
        'LAMBDA' => [
1601
            'category' => Category::CATEGORY_LOGICAL,
1602
            'functionCall' => [Functions::class, 'DUMMY'],
1603
            'argumentCount' => '*',
1604
        ],
1605
        'LARGE' => [
1606
            'category' => Category::CATEGORY_STATISTICAL,
1607
            'functionCall' => [Statistical\Size::class, 'large'],
1608
            'argumentCount' => '2',
1609
        ],
1610
        'LCM' => [
1611
            'category' => Category::CATEGORY_MATH_AND_TRIG,
1612
            'functionCall' => [MathTrig\Lcm::class, 'evaluate'],
1613
            'argumentCount' => '1+',
1614
        ],
1615
        'LEFT' => [
1616
            'category' => Category::CATEGORY_TEXT_AND_DATA,
1617
            'functionCall' => [TextData\Extract::class, 'left'],
1618
            'argumentCount' => '1,2',
1619
        ],
1620
        'LEFTB' => [
1621
            'category' => Category::CATEGORY_TEXT_AND_DATA,
1622
            'functionCall' => [TextData\Extract::class, 'left'],
1623
            'argumentCount' => '1,2',
1624
        ],
1625
        'LEN' => [
1626
            'category' => Category::CATEGORY_TEXT_AND_DATA,
1627
            'functionCall' => [TextData\Text::class, 'length'],
1628
            'argumentCount' => '1',
1629
        ],
1630
        'LENB' => [
1631
            'category' => Category::CATEGORY_TEXT_AND_DATA,
1632
            'functionCall' => [TextData\Text::class, 'length'],
1633
            'argumentCount' => '1',
1634
        ],
1635
        'LET' => [
1636
            'category' => Category::CATEGORY_LOGICAL,
1637
            'functionCall' => [Functions::class, 'DUMMY'],
1638
            'argumentCount' => '*',
1639
        ],
1640
        'LINEST' => [
1641
            'category' => Category::CATEGORY_STATISTICAL,
1642
            'functionCall' => [Statistical\Trends::class, 'LINEST'],
1643
            'argumentCount' => '1-4',
1644
        ],
1645
        'LN' => [
1646
            'category' => Category::CATEGORY_MATH_AND_TRIG,
1647
            'functionCall' => [MathTrig\Logarithms::class, 'natural'],
1648
            'argumentCount' => '1',
1649
        ],
1650
        'LOG' => [
1651
            'category' => Category::CATEGORY_MATH_AND_TRIG,
1652
            'functionCall' => [MathTrig\Logarithms::class, 'withBase'],
1653
            'argumentCount' => '1,2',
1654
        ],
1655
        'LOG10' => [
1656
            'category' => Category::CATEGORY_MATH_AND_TRIG,
1657
            'functionCall' => [MathTrig\Logarithms::class, 'base10'],
1658
            'argumentCount' => '1',
1659
        ],
1660
        'LOGEST' => [
1661
            'category' => Category::CATEGORY_STATISTICAL,
1662
            'functionCall' => [Statistical\Trends::class, 'LOGEST'],
1663
            'argumentCount' => '1-4',
1664
        ],
1665
        'LOGINV' => [
1666
            'category' => Category::CATEGORY_STATISTICAL,
1667
            'functionCall' => [Statistical\Distributions\LogNormal::class, 'inverse'],
1668
            'argumentCount' => '3',
1669
        ],
1670
        'LOGNORMDIST' => [
1671
            'category' => Category::CATEGORY_STATISTICAL,
1672
            'functionCall' => [Statistical\Distributions\LogNormal::class, 'cumulative'],
1673
            'argumentCount' => '3',
1674
        ],
1675
        'LOGNORM.DIST' => [
1676
            'category' => Category::CATEGORY_STATISTICAL,
1677
            'functionCall' => [Statistical\Distributions\LogNormal::class, 'distribution'],
1678
            'argumentCount' => '4',
1679
        ],
1680
        'LOGNORM.INV' => [
1681
            'category' => Category::CATEGORY_STATISTICAL,
1682
            'functionCall' => [Statistical\Distributions\LogNormal::class, 'inverse'],
1683
            'argumentCount' => '3',
1684
        ],
1685
        'LOOKUP' => [
1686
            'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE,
1687
            'functionCall' => [LookupRef\Lookup::class, 'lookup'],
1688
            'argumentCount' => '2,3',
1689
        ],
1690
        'LOWER' => [
1691
            'category' => Category::CATEGORY_TEXT_AND_DATA,
1692
            'functionCall' => [TextData\CaseConvert::class, 'lower'],
1693
            'argumentCount' => '1',
1694
        ],
1695
        'MAKEARRAY' => [
1696
            'category' => Category::CATEGORY_LOGICAL,
1697
            'functionCall' => [Functions::class, 'DUMMY'],
1698
            'argumentCount' => '*',
1699
        ],
1700
        'MAP' => [
1701
            'category' => Category::CATEGORY_LOGICAL,
1702
            'functionCall' => [Functions::class, 'DUMMY'],
1703
            'argumentCount' => '*',
1704
        ],
1705
        'MATCH' => [
1706
            'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE,
1707
            'functionCall' => [LookupRef\ExcelMatch::class, 'MATCH'],
1708
            'argumentCount' => '2,3',
1709
        ],
1710
        'MAX' => [
1711
            'category' => Category::CATEGORY_STATISTICAL,
1712
            'functionCall' => [Statistical\Maximum::class, 'max'],
1713
            'argumentCount' => '1+',
1714
        ],
1715
        'MAXA' => [
1716
            'category' => Category::CATEGORY_STATISTICAL,
1717
            'functionCall' => [Statistical\Maximum::class, 'maxA'],
1718
            'argumentCount' => '1+',
1719
        ],
1720
        'MAXIFS' => [
1721
            'category' => Category::CATEGORY_STATISTICAL,
1722
            'functionCall' => [Statistical\Conditional::class, 'MAXIFS'],
1723
            'argumentCount' => '3+',
1724
        ],
1725
        'MDETERM' => [
1726
            'category' => Category::CATEGORY_MATH_AND_TRIG,
1727
            'functionCall' => [MathTrig\MatrixFunctions::class, 'determinant'],
1728
            'argumentCount' => '1',
1729
        ],
1730
        'MDURATION' => [
1731
            'category' => Category::CATEGORY_FINANCIAL,
1732
            'functionCall' => [Functions::class, 'DUMMY'],
1733
            'argumentCount' => '5,6',
1734
        ],
1735
        'MEDIAN' => [
1736
            'category' => Category::CATEGORY_STATISTICAL,
1737
            'functionCall' => [Statistical\Averages::class, 'median'],
1738
            'argumentCount' => '1+',
1739
        ],
1740
        'MEDIANIF' => [
1741
            'category' => Category::CATEGORY_STATISTICAL,
1742
            'functionCall' => [Functions::class, 'DUMMY'],
1743
            'argumentCount' => '2+',
1744
        ],
1745
        'MID' => [
1746
            'category' => Category::CATEGORY_TEXT_AND_DATA,
1747
            'functionCall' => [TextData\Extract::class, 'mid'],
1748
            'argumentCount' => '3',
1749
        ],
1750
        'MIDB' => [
1751
            'category' => Category::CATEGORY_TEXT_AND_DATA,
1752
            'functionCall' => [TextData\Extract::class, 'mid'],
1753
            'argumentCount' => '3',
1754
        ],
1755
        'MIN' => [
1756
            'category' => Category::CATEGORY_STATISTICAL,
1757
            'functionCall' => [Statistical\Minimum::class, 'min'],
1758
            'argumentCount' => '1+',
1759
        ],
1760
        'MINA' => [
1761
            'category' => Category::CATEGORY_STATISTICAL,
1762
            'functionCall' => [Statistical\Minimum::class, 'minA'],
1763
            'argumentCount' => '1+',
1764
        ],
1765
        'MINIFS' => [
1766
            'category' => Category::CATEGORY_STATISTICAL,
1767
            'functionCall' => [Statistical\Conditional::class, 'MINIFS'],
1768
            'argumentCount' => '3+',
1769
        ],
1770
        'MINUTE' => [
1771
            'category' => Category::CATEGORY_DATE_AND_TIME,
1772
            'functionCall' => [DateTimeExcel\TimeParts::class, 'minute'],
1773
            'argumentCount' => '1',
1774
        ],
1775
        'MINVERSE' => [
1776
            'category' => Category::CATEGORY_MATH_AND_TRIG,
1777
            'functionCall' => [MathTrig\MatrixFunctions::class, 'inverse'],
1778
            'argumentCount' => '1',
1779
        ],
1780
        'MIRR' => [
1781
            'category' => Category::CATEGORY_FINANCIAL,
1782
            'functionCall' => [Financial\CashFlow\Variable\Periodic::class, 'modifiedRate'],
1783
            'argumentCount' => '3',
1784
        ],
1785
        'MMULT' => [
1786
            'category' => Category::CATEGORY_MATH_AND_TRIG,
1787
            'functionCall' => [MathTrig\MatrixFunctions::class, 'multiply'],
1788
            'argumentCount' => '2',
1789
        ],
1790
        'MOD' => [
1791
            'category' => Category::CATEGORY_MATH_AND_TRIG,
1792
            'functionCall' => [MathTrig\Operations::class, 'mod'],
1793
            'argumentCount' => '2',
1794
        ],
1795
        'MODE' => [
1796
            'category' => Category::CATEGORY_STATISTICAL,
1797
            'functionCall' => [Statistical\Averages::class, 'mode'],
1798
            'argumentCount' => '1+',
1799
        ],
1800
        'MODE.MULT' => [
1801
            'category' => Category::CATEGORY_STATISTICAL,
1802
            'functionCall' => [Functions::class, 'DUMMY'],
1803
            'argumentCount' => '1+',
1804
        ],
1805
        'MODE.SNGL' => [
1806
            'category' => Category::CATEGORY_STATISTICAL,
1807
            'functionCall' => [Statistical\Averages::class, 'mode'],
1808
            'argumentCount' => '1+',
1809
        ],
1810
        'MONTH' => [
1811
            'category' => Category::CATEGORY_DATE_AND_TIME,
1812
            'functionCall' => [DateTimeExcel\DateParts::class, 'month'],
1813
            'argumentCount' => '1',
1814
        ],
1815
        'MROUND' => [
1816
            'category' => Category::CATEGORY_MATH_AND_TRIG,
1817
            'functionCall' => [MathTrig\Round::class, 'multiple'],
1818
            'argumentCount' => '2',
1819
        ],
1820
        'MULTINOMIAL' => [
1821
            'category' => Category::CATEGORY_MATH_AND_TRIG,
1822
            'functionCall' => [MathTrig\Factorial::class, 'multinomial'],
1823
            'argumentCount' => '1+',
1824
        ],
1825
        'MUNIT' => [
1826
            'category' => Category::CATEGORY_MATH_AND_TRIG,
1827
            'functionCall' => [MathTrig\MatrixFunctions::class, 'identity'],
1828
            'argumentCount' => '1',
1829
        ],
1830
        'N' => [
1831
            'category' => Category::CATEGORY_INFORMATION,
1832
            'functionCall' => [Information\Value::class, 'asNumber'],
1833
            'argumentCount' => '1',
1834
        ],
1835
        'NA' => [
1836
            'category' => Category::CATEGORY_INFORMATION,
1837
            'functionCall' => [ExcelError::class, 'NA'],
1838
            'argumentCount' => '0',
1839
        ],
1840
        'NEGBINOMDIST' => [
1841
            'category' => Category::CATEGORY_STATISTICAL,
1842
            'functionCall' => [Statistical\Distributions\Binomial::class, 'negative'],
1843
            'argumentCount' => '3',
1844
        ],
1845
        'NEGBINOM.DIST' => [
1846
            'category' => Category::CATEGORY_STATISTICAL,
1847
            'functionCall' => [Functions::class, 'DUMMY'],
1848
            'argumentCount' => '4',
1849
        ],
1850
        'NETWORKDAYS' => [
1851
            'category' => Category::CATEGORY_DATE_AND_TIME,
1852
            'functionCall' => [DateTimeExcel\NetworkDays::class, 'count'],
1853
            'argumentCount' => '2-3',
1854
        ],
1855
        'NETWORKDAYS.INTL' => [
1856
            'category' => Category::CATEGORY_DATE_AND_TIME,
1857
            'functionCall' => [Functions::class, 'DUMMY'],
1858
            'argumentCount' => '2-4',
1859
        ],
1860
        'NOMINAL' => [
1861
            'category' => Category::CATEGORY_FINANCIAL,
1862
            'functionCall' => [Financial\InterestRate::class, 'nominal'],
1863
            'argumentCount' => '2',
1864
        ],
1865
        'NORMDIST' => [
1866
            'category' => Category::CATEGORY_STATISTICAL,
1867
            'functionCall' => [Statistical\Distributions\Normal::class, 'distribution'],
1868
            'argumentCount' => '4',
1869
        ],
1870
        'NORM.DIST' => [
1871
            'category' => Category::CATEGORY_STATISTICAL,
1872
            'functionCall' => [Statistical\Distributions\Normal::class, 'distribution'],
1873
            'argumentCount' => '4',
1874
        ],
1875
        'NORMINV' => [
1876
            'category' => Category::CATEGORY_STATISTICAL,
1877
            'functionCall' => [Statistical\Distributions\Normal::class, 'inverse'],
1878
            'argumentCount' => '3',
1879
        ],
1880
        'NORM.INV' => [
1881
            'category' => Category::CATEGORY_STATISTICAL,
1882
            'functionCall' => [Statistical\Distributions\Normal::class, 'inverse'],
1883
            'argumentCount' => '3',
1884
        ],
1885
        'NORMSDIST' => [
1886
            'category' => Category::CATEGORY_STATISTICAL,
1887
            'functionCall' => [Statistical\Distributions\StandardNormal::class, 'cumulative'],
1888
            'argumentCount' => '1',
1889
        ],
1890
        'NORM.S.DIST' => [
1891
            'category' => Category::CATEGORY_STATISTICAL,
1892
            'functionCall' => [Statistical\Distributions\StandardNormal::class, 'distribution'],
1893
            'argumentCount' => '1,2',
1894
        ],
1895
        'NORMSINV' => [
1896
            'category' => Category::CATEGORY_STATISTICAL,
1897
            'functionCall' => [Statistical\Distributions\StandardNormal::class, 'inverse'],
1898
            'argumentCount' => '1',
1899
        ],
1900
        'NORM.S.INV' => [
1901
            'category' => Category::CATEGORY_STATISTICAL,
1902
            'functionCall' => [Statistical\Distributions\StandardNormal::class, 'inverse'],
1903
            'argumentCount' => '1',
1904
        ],
1905
        'NOT' => [
1906
            'category' => Category::CATEGORY_LOGICAL,
1907
            'functionCall' => [Logical\Operations::class, 'NOT'],
1908
            'argumentCount' => '1',
1909
        ],
1910
        'NOW' => [
1911
            'category' => Category::CATEGORY_DATE_AND_TIME,
1912
            'functionCall' => [DateTimeExcel\Current::class, 'now'],
1913
            'argumentCount' => '0',
1914
        ],
1915
        'NPER' => [
1916
            'category' => Category::CATEGORY_FINANCIAL,
1917
            'functionCall' => [Financial\CashFlow\Constant\Periodic::class, 'periods'],
1918
            'argumentCount' => '3-5',
1919
        ],
1920
        'NPV' => [
1921
            'category' => Category::CATEGORY_FINANCIAL,
1922
            'functionCall' => [Financial\CashFlow\Variable\Periodic::class, 'presentValue'],
1923
            'argumentCount' => '2+',
1924
        ],
1925
        'NUMBERSTRING' => [
1926
            'category' => Category::CATEGORY_TEXT_AND_DATA,
1927
            'functionCall' => [Functions::class, 'DUMMY'],
1928
            'argumentCount' => '?',
1929
        ],
1930
        'NUMBERVALUE' => [
1931
            'category' => Category::CATEGORY_TEXT_AND_DATA,
1932
            'functionCall' => [TextData\Format::class, 'NUMBERVALUE'],
1933
            'argumentCount' => '1+',
1934
        ],
1935
        'OCT2BIN' => [
1936
            'category' => Category::CATEGORY_ENGINEERING,
1937
            'functionCall' => [Engineering\ConvertOctal::class, 'toBinary'],
1938
            'argumentCount' => '1,2',
1939
        ],
1940
        'OCT2DEC' => [
1941
            'category' => Category::CATEGORY_ENGINEERING,
1942
            'functionCall' => [Engineering\ConvertOctal::class, 'toDecimal'],
1943
            'argumentCount' => '1',
1944
        ],
1945
        'OCT2HEX' => [
1946
            'category' => Category::CATEGORY_ENGINEERING,
1947
            'functionCall' => [Engineering\ConvertOctal::class, 'toHex'],
1948
            'argumentCount' => '1,2',
1949
        ],
1950
        'ODD' => [
1951
            'category' => Category::CATEGORY_MATH_AND_TRIG,
1952
            'functionCall' => [MathTrig\Round::class, 'odd'],
1953
            'argumentCount' => '1',
1954
        ],
1955
        'ODDFPRICE' => [
1956
            'category' => Category::CATEGORY_FINANCIAL,
1957
            'functionCall' => [Functions::class, 'DUMMY'],
1958
            'argumentCount' => '8,9',
1959
        ],
1960
        'ODDFYIELD' => [
1961
            'category' => Category::CATEGORY_FINANCIAL,
1962
            'functionCall' => [Functions::class, 'DUMMY'],
1963
            'argumentCount' => '8,9',
1964
        ],
1965
        'ODDLPRICE' => [
1966
            'category' => Category::CATEGORY_FINANCIAL,
1967
            'functionCall' => [Functions::class, 'DUMMY'],
1968
            'argumentCount' => '7,8',
1969
        ],
1970
        'ODDLYIELD' => [
1971
            'category' => Category::CATEGORY_FINANCIAL,
1972
            'functionCall' => [Functions::class, 'DUMMY'],
1973
            'argumentCount' => '7,8',
1974
        ],
1975
        'OFFSET' => [
1976
            'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE,
1977
            'functionCall' => [LookupRef\Offset::class, 'OFFSET'],
1978
            'argumentCount' => '3-5',
1979
            'passCellReference' => true,
1980
            'passByReference' => [true],
1981
        ],
1982
        'OR' => [
1983
            'category' => Category::CATEGORY_LOGICAL,
1984
            'functionCall' => [Logical\Operations::class, 'logicalOr'],
1985
            'argumentCount' => '1+',
1986
        ],
1987
        'PDURATION' => [
1988
            'category' => Category::CATEGORY_FINANCIAL,
1989
            'functionCall' => [Financial\CashFlow\Single::class, 'periods'],
1990
            'argumentCount' => '3',
1991
        ],
1992
        'PEARSON' => [
1993
            'category' => Category::CATEGORY_STATISTICAL,
1994
            'functionCall' => [Statistical\Trends::class, 'CORREL'],
1995
            'argumentCount' => '2',
1996
        ],
1997
        'PERCENTILE' => [
1998
            'category' => Category::CATEGORY_STATISTICAL,
1999
            'functionCall' => [Statistical\Percentiles::class, 'PERCENTILE'],
2000
            'argumentCount' => '2',
2001
        ],
2002
        'PERCENTILE.EXC' => [
2003
            'category' => Category::CATEGORY_STATISTICAL,
2004
            'functionCall' => [Functions::class, 'DUMMY'],
2005
            'argumentCount' => '2',
2006
        ],
2007
        'PERCENTILE.INC' => [
2008
            'category' => Category::CATEGORY_STATISTICAL,
2009
            'functionCall' => [Statistical\Percentiles::class, 'PERCENTILE'],
2010
            'argumentCount' => '2',
2011
        ],
2012
        'PERCENTRANK' => [
2013
            'category' => Category::CATEGORY_STATISTICAL,
2014
            'functionCall' => [Statistical\Percentiles::class, 'PERCENTRANK'],
2015
            'argumentCount' => '2,3',
2016
        ],
2017
        'PERCENTRANK.EXC' => [
2018
            'category' => Category::CATEGORY_STATISTICAL,
2019
            'functionCall' => [Functions::class, 'DUMMY'],
2020
            'argumentCount' => '2,3',
2021
        ],
2022
        'PERCENTRANK.INC' => [
2023
            'category' => Category::CATEGORY_STATISTICAL,
2024
            'functionCall' => [Statistical\Percentiles::class, 'PERCENTRANK'],
2025
            'argumentCount' => '2,3',
2026
        ],
2027
        'PERMUT' => [
2028
            'category' => Category::CATEGORY_STATISTICAL,
2029
            'functionCall' => [Statistical\Permutations::class, 'PERMUT'],
2030
            'argumentCount' => '2',
2031
        ],
2032
        'PERMUTATIONA' => [
2033
            'category' => Category::CATEGORY_STATISTICAL,
2034
            'functionCall' => [Statistical\Permutations::class, 'PERMUTATIONA'],
2035
            'argumentCount' => '2',
2036
        ],
2037
        'PHONETIC' => [
2038
            'category' => Category::CATEGORY_TEXT_AND_DATA,
2039
            'functionCall' => [Functions::class, 'DUMMY'],
2040
            'argumentCount' => '1',
2041
        ],
2042
        'PHI' => [
2043
            'category' => Category::CATEGORY_STATISTICAL,
2044
            'functionCall' => [Functions::class, 'DUMMY'],
2045
            'argumentCount' => '1',
2046
        ],
2047
        'PI' => [
2048
            'category' => Category::CATEGORY_MATH_AND_TRIG,
2049
            'functionCall' => 'pi',
2050
            'argumentCount' => '0',
2051
        ],
2052
        'PMT' => [
2053
            'category' => Category::CATEGORY_FINANCIAL,
2054
            'functionCall' => [Financial\CashFlow\Constant\Periodic\Payments::class, 'annuity'],
2055
            'argumentCount' => '3-5',
2056
        ],
2057
        'POISSON' => [
2058
            'category' => Category::CATEGORY_STATISTICAL,
2059
            'functionCall' => [Statistical\Distributions\Poisson::class, 'distribution'],
2060
            'argumentCount' => '3',
2061
        ],
2062
        'POISSON.DIST' => [
2063
            'category' => Category::CATEGORY_STATISTICAL,
2064
            'functionCall' => [Statistical\Distributions\Poisson::class, 'distribution'],
2065
            'argumentCount' => '3',
2066
        ],
2067
        'POWER' => [
2068
            'category' => Category::CATEGORY_MATH_AND_TRIG,
2069
            'functionCall' => [MathTrig\Operations::class, 'power'],
2070
            'argumentCount' => '2',
2071
        ],
2072
        'PPMT' => [
2073
            'category' => Category::CATEGORY_FINANCIAL,
2074
            'functionCall' => [Financial\CashFlow\Constant\Periodic\Payments::class, 'interestPayment'],
2075
            'argumentCount' => '4-6',
2076
        ],
2077
        'PRICE' => [
2078
            'category' => Category::CATEGORY_FINANCIAL,
2079
            'functionCall' => [Financial\Securities\Price::class, 'price'],
2080
            'argumentCount' => '6,7',
2081
        ],
2082
        'PRICEDISC' => [
2083
            'category' => Category::CATEGORY_FINANCIAL,
2084
            'functionCall' => [Financial\Securities\Price::class, 'priceDiscounted'],
2085
            'argumentCount' => '4,5',
2086
        ],
2087
        'PRICEMAT' => [
2088
            'category' => Category::CATEGORY_FINANCIAL,
2089
            'functionCall' => [Financial\Securities\Price::class, 'priceAtMaturity'],
2090
            'argumentCount' => '5,6',
2091
        ],
2092
        'PROB' => [
2093
            'category' => Category::CATEGORY_STATISTICAL,
2094
            'functionCall' => [Functions::class, 'DUMMY'],
2095
            'argumentCount' => '3,4',
2096
        ],
2097
        'PRODUCT' => [
2098
            'category' => Category::CATEGORY_MATH_AND_TRIG,
2099
            'functionCall' => [MathTrig\Operations::class, 'product'],
2100
            'argumentCount' => '1+',
2101
        ],
2102
        'PROPER' => [
2103
            'category' => Category::CATEGORY_TEXT_AND_DATA,
2104
            'functionCall' => [TextData\CaseConvert::class, 'proper'],
2105
            'argumentCount' => '1',
2106
        ],
2107
        'PV' => [
2108
            'category' => Category::CATEGORY_FINANCIAL,
2109
            'functionCall' => [Financial\CashFlow\Constant\Periodic::class, 'presentValue'],
2110
            'argumentCount' => '3-5',
2111
        ],
2112
        'QUARTILE' => [
2113
            'category' => Category::CATEGORY_STATISTICAL,
2114
            'functionCall' => [Statistical\Percentiles::class, 'QUARTILE'],
2115
            'argumentCount' => '2',
2116
        ],
2117
        'QUARTILE.EXC' => [
2118
            'category' => Category::CATEGORY_STATISTICAL,
2119
            'functionCall' => [Functions::class, 'DUMMY'],
2120
            'argumentCount' => '2',
2121
        ],
2122
        'QUARTILE.INC' => [
2123
            'category' => Category::CATEGORY_STATISTICAL,
2124
            'functionCall' => [Statistical\Percentiles::class, 'QUARTILE'],
2125
            'argumentCount' => '2',
2126
        ],
2127
        'QUOTIENT' => [
2128
            'category' => Category::CATEGORY_MATH_AND_TRIG,
2129
            'functionCall' => [MathTrig\Operations::class, 'quotient'],
2130
            'argumentCount' => '2',
2131
        ],
2132
        'RADIANS' => [
2133
            'category' => Category::CATEGORY_MATH_AND_TRIG,
2134
            'functionCall' => [MathTrig\Angle::class, 'toRadians'],
2135
            'argumentCount' => '1',
2136
        ],
2137
        'RAND' => [
2138
            'category' => Category::CATEGORY_MATH_AND_TRIG,
2139
            'functionCall' => [MathTrig\Random::class, 'rand'],
2140
            'argumentCount' => '0',
2141
        ],
2142
        'RANDARRAY' => [
2143
            'category' => Category::CATEGORY_MATH_AND_TRIG,
2144
            'functionCall' => [MathTrig\Random::class, 'randArray'],
2145
            'argumentCount' => '0-5',
2146
        ],
2147
        'RANDBETWEEN' => [
2148
            'category' => Category::CATEGORY_MATH_AND_TRIG,
2149
            'functionCall' => [MathTrig\Random::class, 'randBetween'],
2150
            'argumentCount' => '2',
2151
        ],
2152
        'RANK' => [
2153
            'category' => Category::CATEGORY_STATISTICAL,
2154
            'functionCall' => [Statistical\Percentiles::class, 'RANK'],
2155
            'argumentCount' => '2,3',
2156
        ],
2157
        'RANK.AVG' => [
2158
            'category' => Category::CATEGORY_STATISTICAL,
2159
            'functionCall' => [Functions::class, 'DUMMY'],
2160
            'argumentCount' => '2,3',
2161
        ],
2162
        'RANK.EQ' => [
2163
            'category' => Category::CATEGORY_STATISTICAL,
2164
            'functionCall' => [Statistical\Percentiles::class, 'RANK'],
2165
            'argumentCount' => '2,3',
2166
        ],
2167
        'RATE' => [
2168
            'category' => Category::CATEGORY_FINANCIAL,
2169
            'functionCall' => [Financial\CashFlow\Constant\Periodic\Interest::class, 'rate'],
2170
            'argumentCount' => '3-6',
2171
        ],
2172
        'RECEIVED' => [
2173
            'category' => Category::CATEGORY_FINANCIAL,
2174
            'functionCall' => [Financial\Securities\Price::class, 'received'],
2175
            'argumentCount' => '4-5',
2176
        ],
2177
        'REDUCE' => [
2178
            'category' => Category::CATEGORY_LOGICAL,
2179
            'functionCall' => [Functions::class, 'DUMMY'],
2180
            'argumentCount' => '*',
2181
        ],
2182
        'REPLACE' => [
2183
            'category' => Category::CATEGORY_TEXT_AND_DATA,
2184
            'functionCall' => [TextData\Replace::class, 'replace'],
2185
            'argumentCount' => '4',
2186
        ],
2187
        'REPLACEB' => [
2188
            'category' => Category::CATEGORY_TEXT_AND_DATA,
2189
            'functionCall' => [TextData\Replace::class, 'replace'],
2190
            'argumentCount' => '4',
2191
        ],
2192
        'REPT' => [
2193
            'category' => Category::CATEGORY_TEXT_AND_DATA,
2194
            'functionCall' => [TextData\Concatenate::class, 'builtinREPT'],
2195
            'argumentCount' => '2',
2196
        ],
2197
        'RIGHT' => [
2198
            'category' => Category::CATEGORY_TEXT_AND_DATA,
2199
            'functionCall' => [TextData\Extract::class, 'right'],
2200
            'argumentCount' => '1,2',
2201
        ],
2202
        'RIGHTB' => [
2203
            'category' => Category::CATEGORY_TEXT_AND_DATA,
2204
            'functionCall' => [TextData\Extract::class, 'right'],
2205
            'argumentCount' => '1,2',
2206
        ],
2207
        'ROMAN' => [
2208
            'category' => Category::CATEGORY_MATH_AND_TRIG,
2209
            'functionCall' => [MathTrig\Roman::class, 'evaluate'],
2210
            'argumentCount' => '1,2',
2211
        ],
2212
        'ROUND' => [
2213
            'category' => Category::CATEGORY_MATH_AND_TRIG,
2214
            'functionCall' => [MathTrig\Round::class, 'round'],
2215
            'argumentCount' => '2',
2216
        ],
2217
        'ROUNDBAHTDOWN' => [
2218
            'category' => Category::CATEGORY_MATH_AND_TRIG,
2219
            'functionCall' => [Functions::class, 'DUMMY'],
2220
            'argumentCount' => '?',
2221
        ],
2222
        'ROUNDBAHTUP' => [
2223
            'category' => Category::CATEGORY_MATH_AND_TRIG,
2224
            'functionCall' => [Functions::class, 'DUMMY'],
2225
            'argumentCount' => '?',
2226
        ],
2227
        'ROUNDDOWN' => [
2228
            'category' => Category::CATEGORY_MATH_AND_TRIG,
2229
            'functionCall' => [MathTrig\Round::class, 'down'],
2230
            'argumentCount' => '2',
2231
        ],
2232
        'ROUNDUP' => [
2233
            'category' => Category::CATEGORY_MATH_AND_TRIG,
2234
            'functionCall' => [MathTrig\Round::class, 'up'],
2235
            'argumentCount' => '2',
2236
        ],
2237
        'ROW' => [
2238
            'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE,
2239
            'functionCall' => [LookupRef\RowColumnInformation::class, 'ROW'],
2240
            'argumentCount' => '-1',
2241
            'passCellReference' => true,
2242
            'passByReference' => [true],
2243
        ],
2244
        'ROWS' => [
2245
            'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE,
2246
            'functionCall' => [LookupRef\RowColumnInformation::class, 'ROWS'],
2247
            'argumentCount' => '1',
2248
        ],
2249
        'RRI' => [
2250
            'category' => Category::CATEGORY_FINANCIAL,
2251
            'functionCall' => [Financial\CashFlow\Single::class, 'interestRate'],
2252
            'argumentCount' => '3',
2253
        ],
2254
        'RSQ' => [
2255
            'category' => Category::CATEGORY_STATISTICAL,
2256
            'functionCall' => [Statistical\Trends::class, 'RSQ'],
2257
            'argumentCount' => '2',
2258
        ],
2259
        'RTD' => [
2260
            'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE,
2261
            'functionCall' => [Functions::class, 'DUMMY'],
2262
            'argumentCount' => '1+',
2263
        ],
2264
        'SEARCH' => [
2265
            'category' => Category::CATEGORY_TEXT_AND_DATA,
2266
            'functionCall' => [TextData\Search::class, 'insensitive'],
2267
            'argumentCount' => '2,3',
2268
        ],
2269
        'SCAN' => [
2270
            'category' => Category::CATEGORY_LOGICAL,
2271
            'functionCall' => [Functions::class, 'DUMMY'],
2272
            'argumentCount' => '*',
2273
        ],
2274
        'SEARCHB' => [
2275
            'category' => Category::CATEGORY_TEXT_AND_DATA,
2276
            'functionCall' => [TextData\Search::class, 'insensitive'],
2277
            'argumentCount' => '2,3',
2278
        ],
2279
        'SEC' => [
2280
            'category' => Category::CATEGORY_MATH_AND_TRIG,
2281
            'functionCall' => [MathTrig\Trig\Secant::class, 'sec'],
2282
            'argumentCount' => '1',
2283
        ],
2284
        'SECH' => [
2285
            'category' => Category::CATEGORY_MATH_AND_TRIG,
2286
            'functionCall' => [MathTrig\Trig\Secant::class, 'sech'],
2287
            'argumentCount' => '1',
2288
        ],
2289
        'SECOND' => [
2290
            'category' => Category::CATEGORY_DATE_AND_TIME,
2291
            'functionCall' => [DateTimeExcel\TimeParts::class, 'second'],
2292
            'argumentCount' => '1',
2293
        ],
2294
        'SEQUENCE' => [
2295
            'category' => Category::CATEGORY_MATH_AND_TRIG,
2296
            'functionCall' => [MathTrig\MatrixFunctions::class, 'sequence'],
2297
            'argumentCount' => '1-4',
2298
        ],
2299
        'SERIESSUM' => [
2300
            'category' => Category::CATEGORY_MATH_AND_TRIG,
2301
            'functionCall' => [MathTrig\SeriesSum::class, 'evaluate'],
2302
            'argumentCount' => '4',
2303
        ],
2304
        'SHEET' => [
2305
            'category' => Category::CATEGORY_INFORMATION,
2306
            'functionCall' => [Functions::class, 'DUMMY'],
2307
            'argumentCount' => '0,1',
2308
        ],
2309
        'SHEETS' => [
2310
            'category' => Category::CATEGORY_INFORMATION,
2311
            'functionCall' => [Functions::class, 'DUMMY'],
2312
            'argumentCount' => '0,1',
2313
        ],
2314
        'SIGN' => [
2315
            'category' => Category::CATEGORY_MATH_AND_TRIG,
2316
            'functionCall' => [MathTrig\Sign::class, 'evaluate'],
2317
            'argumentCount' => '1',
2318
        ],
2319
        'SIN' => [
2320
            'category' => Category::CATEGORY_MATH_AND_TRIG,
2321
            'functionCall' => [MathTrig\Trig\Sine::class, 'sin'],
2322
            'argumentCount' => '1',
2323
        ],
2324
        'SINGLE' => [
2325
            'category' => Category::CATEGORY_MICROSOFT_INTERNAL,
2326
            'functionCall' => [Internal\ExcelArrayPseudoFunctions::class, 'single'],
2327
            'argumentCount' => '1',
2328
            'passCellReference' => true,
2329
            'passByReference' => [true],
2330
        ],
2331
        'SINH' => [
2332
            'category' => Category::CATEGORY_MATH_AND_TRIG,
2333
            'functionCall' => [MathTrig\Trig\Sine::class, 'sinh'],
2334
            'argumentCount' => '1',
2335
        ],
2336
        'SKEW' => [
2337
            'category' => Category::CATEGORY_STATISTICAL,
2338
            'functionCall' => [Statistical\Deviations::class, 'skew'],
2339
            'argumentCount' => '1+',
2340
        ],
2341
        'SKEW.P' => [
2342
            'category' => Category::CATEGORY_STATISTICAL,
2343
            'functionCall' => [Functions::class, 'DUMMY'],
2344
            'argumentCount' => '1+',
2345
        ],
2346
        'SLN' => [
2347
            'category' => Category::CATEGORY_FINANCIAL,
2348
            'functionCall' => [Financial\Depreciation::class, 'SLN'],
2349
            'argumentCount' => '3',
2350
        ],
2351
        'SLOPE' => [
2352
            'category' => Category::CATEGORY_STATISTICAL,
2353
            'functionCall' => [Statistical\Trends::class, 'SLOPE'],
2354
            'argumentCount' => '2',
2355
        ],
2356
        'SMALL' => [
2357
            'category' => Category::CATEGORY_STATISTICAL,
2358
            'functionCall' => [Statistical\Size::class, 'small'],
2359
            'argumentCount' => '2',
2360
        ],
2361
        'SORT' => [
2362
            'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE,
2363
            'functionCall' => [LookupRef\Sort::class, 'sort'],
2364
            'argumentCount' => '1-4',
2365
        ],
2366
        'SORTBY' => [
2367
            'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE,
2368
            'functionCall' => [LookupRef\Sort::class, 'sortBy'],
2369
            'argumentCount' => '2+',
2370
        ],
2371
        'SQRT' => [
2372
            'category' => Category::CATEGORY_MATH_AND_TRIG,
2373
            'functionCall' => [MathTrig\Sqrt::class, 'sqrt'],
2374
            'argumentCount' => '1',
2375
        ],
2376
        'SQRTPI' => [
2377
            'category' => Category::CATEGORY_MATH_AND_TRIG,
2378
            'functionCall' => [MathTrig\Sqrt::class, 'pi'],
2379
            'argumentCount' => '1',
2380
        ],
2381
        'STANDARDIZE' => [
2382
            'category' => Category::CATEGORY_STATISTICAL,
2383
            'functionCall' => [Statistical\Standardize::class, 'execute'],
2384
            'argumentCount' => '3',
2385
        ],
2386
        'STDEV' => [
2387
            'category' => Category::CATEGORY_STATISTICAL,
2388
            'functionCall' => [Statistical\StandardDeviations::class, 'STDEV'],
2389
            'argumentCount' => '1+',
2390
        ],
2391
        'STDEV.S' => [
2392
            'category' => Category::CATEGORY_STATISTICAL,
2393
            'functionCall' => [Statistical\StandardDeviations::class, 'STDEV'],
2394
            'argumentCount' => '1+',
2395
        ],
2396
        'STDEV.P' => [
2397
            'category' => Category::CATEGORY_STATISTICAL,
2398
            'functionCall' => [Statistical\StandardDeviations::class, 'STDEVP'],
2399
            'argumentCount' => '1+',
2400
        ],
2401
        'STDEVA' => [
2402
            'category' => Category::CATEGORY_STATISTICAL,
2403
            'functionCall' => [Statistical\StandardDeviations::class, 'STDEVA'],
2404
            'argumentCount' => '1+',
2405
        ],
2406
        'STDEVP' => [
2407
            'category' => Category::CATEGORY_STATISTICAL,
2408
            'functionCall' => [Statistical\StandardDeviations::class, 'STDEVP'],
2409
            'argumentCount' => '1+',
2410
        ],
2411
        'STDEVPA' => [
2412
            'category' => Category::CATEGORY_STATISTICAL,
2413
            'functionCall' => [Statistical\StandardDeviations::class, 'STDEVPA'],
2414
            'argumentCount' => '1+',
2415
        ],
2416
        'STEYX' => [
2417
            'category' => Category::CATEGORY_STATISTICAL,
2418
            'functionCall' => [Statistical\Trends::class, 'STEYX'],
2419
            'argumentCount' => '2',
2420
        ],
2421
        'SUBSTITUTE' => [
2422
            'category' => Category::CATEGORY_TEXT_AND_DATA,
2423
            'functionCall' => [TextData\Replace::class, 'substitute'],
2424
            'argumentCount' => '3,4',
2425
        ],
2426
        'SUBTOTAL' => [
2427
            'category' => Category::CATEGORY_MATH_AND_TRIG,
2428
            'functionCall' => [MathTrig\Subtotal::class, 'evaluate'],
2429
            'argumentCount' => '2+',
2430
            'passCellReference' => true,
2431
        ],
2432
        'SUM' => [
2433
            'category' => Category::CATEGORY_MATH_AND_TRIG,
2434
            'functionCall' => [MathTrig\Sum::class, 'sumErroringStrings'],
2435
            'argumentCount' => '1+',
2436
        ],
2437
        'SUMIF' => [
2438
            'category' => Category::CATEGORY_MATH_AND_TRIG,
2439
            'functionCall' => [Statistical\Conditional::class, 'SUMIF'],
2440
            'argumentCount' => '2,3',
2441
        ],
2442
        'SUMIFS' => [
2443
            'category' => Category::CATEGORY_MATH_AND_TRIG,
2444
            'functionCall' => [Statistical\Conditional::class, 'SUMIFS'],
2445
            'argumentCount' => '3+',
2446
        ],
2447
        'SUMPRODUCT' => [
2448
            'category' => Category::CATEGORY_MATH_AND_TRIG,
2449
            'functionCall' => [MathTrig\Sum::class, 'product'],
2450
            'argumentCount' => '1+',
2451
        ],
2452
        'SUMSQ' => [
2453
            'category' => Category::CATEGORY_MATH_AND_TRIG,
2454
            'functionCall' => [MathTrig\SumSquares::class, 'sumSquare'],
2455
            'argumentCount' => '1+',
2456
        ],
2457
        'SUMX2MY2' => [
2458
            'category' => Category::CATEGORY_MATH_AND_TRIG,
2459
            'functionCall' => [MathTrig\SumSquares::class, 'sumXSquaredMinusYSquared'],
2460
            'argumentCount' => '2',
2461
        ],
2462
        'SUMX2PY2' => [
2463
            'category' => Category::CATEGORY_MATH_AND_TRIG,
2464
            'functionCall' => [MathTrig\SumSquares::class, 'sumXSquaredPlusYSquared'],
2465
            'argumentCount' => '2',
2466
        ],
2467
        'SUMXMY2' => [
2468
            'category' => Category::CATEGORY_MATH_AND_TRIG,
2469
            'functionCall' => [MathTrig\SumSquares::class, 'sumXMinusYSquared'],
2470
            'argumentCount' => '2',
2471
        ],
2472
        'SWITCH' => [
2473
            'category' => Category::CATEGORY_LOGICAL,
2474
            'functionCall' => [Logical\Conditional::class, 'statementSwitch'],
2475
            'argumentCount' => '3+',
2476
        ],
2477
        'SYD' => [
2478
            'category' => Category::CATEGORY_FINANCIAL,
2479
            'functionCall' => [Financial\Depreciation::class, 'SYD'],
2480
            'argumentCount' => '4',
2481
        ],
2482
        'T' => [
2483
            'category' => Category::CATEGORY_TEXT_AND_DATA,
2484
            'functionCall' => [TextData\Text::class, 'test'],
2485
            'argumentCount' => '1',
2486
        ],
2487
        'TAKE' => [
2488
            'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE,
2489
            'functionCall' => [LookupRef\ChooseRowsEtc::class, 'take'],
2490
            'argumentCount' => '2-3',
2491
        ],
2492
        'TAN' => [
2493
            'category' => Category::CATEGORY_MATH_AND_TRIG,
2494
            'functionCall' => [MathTrig\Trig\Tangent::class, 'tan'],
2495
            'argumentCount' => '1',
2496
        ],
2497
        'TANH' => [
2498
            'category' => Category::CATEGORY_MATH_AND_TRIG,
2499
            'functionCall' => [MathTrig\Trig\Tangent::class, 'tanh'],
2500
            'argumentCount' => '1',
2501
        ],
2502
        'TBILLEQ' => [
2503
            'category' => Category::CATEGORY_FINANCIAL,
2504
            'functionCall' => [Financial\TreasuryBill::class, 'bondEquivalentYield'],
2505
            'argumentCount' => '3',
2506
        ],
2507
        'TBILLPRICE' => [
2508
            'category' => Category::CATEGORY_FINANCIAL,
2509
            'functionCall' => [Financial\TreasuryBill::class, 'price'],
2510
            'argumentCount' => '3',
2511
        ],
2512
        'TBILLYIELD' => [
2513
            'category' => Category::CATEGORY_FINANCIAL,
2514
            'functionCall' => [Financial\TreasuryBill::class, 'yield'],
2515
            'argumentCount' => '3',
2516
        ],
2517
        'TDIST' => [
2518
            'category' => Category::CATEGORY_STATISTICAL,
2519
            'functionCall' => [Statistical\Distributions\StudentT::class, 'distribution'],
2520
            'argumentCount' => '3',
2521
        ],
2522
        'T.DIST' => [
2523
            'category' => Category::CATEGORY_STATISTICAL,
2524
            'functionCall' => [Functions::class, 'DUMMY'],
2525
            'argumentCount' => '3',
2526
        ],
2527
        'T.DIST.2T' => [
2528
            'category' => Category::CATEGORY_STATISTICAL,
2529
            'functionCall' => [Functions::class, 'DUMMY'],
2530
            'argumentCount' => '2',
2531
        ],
2532
        'T.DIST.RT' => [
2533
            'category' => Category::CATEGORY_STATISTICAL,
2534
            'functionCall' => [Functions::class, 'DUMMY'],
2535
            'argumentCount' => '2',
2536
        ],
2537
        'TEXT' => [
2538
            'category' => Category::CATEGORY_TEXT_AND_DATA,
2539
            'functionCall' => [TextData\Format::class, 'TEXTFORMAT'],
2540
            'argumentCount' => '2',
2541
        ],
2542
        'TEXTAFTER' => [
2543
            'category' => Category::CATEGORY_TEXT_AND_DATA,
2544
            'functionCall' => [TextData\Extract::class, 'after'],
2545
            'argumentCount' => '2-6',
2546
        ],
2547
        'TEXTBEFORE' => [
2548
            'category' => Category::CATEGORY_TEXT_AND_DATA,
2549
            'functionCall' => [TextData\Extract::class, 'before'],
2550
            'argumentCount' => '2-6',
2551
        ],
2552
        'TEXTJOIN' => [
2553
            'category' => Category::CATEGORY_TEXT_AND_DATA,
2554
            'functionCall' => [TextData\Concatenate::class, 'TEXTJOIN'],
2555
            'argumentCount' => '3+',
2556
        ],
2557
        'TEXTSPLIT' => [
2558
            'category' => Category::CATEGORY_TEXT_AND_DATA,
2559
            'functionCall' => [TextData\Text::class, 'split'],
2560
            'argumentCount' => '2-6',
2561
        ],
2562
        'THAIDAYOFWEEK' => [
2563
            'category' => Category::CATEGORY_DATE_AND_TIME,
2564
            'functionCall' => [Functions::class, 'DUMMY'],
2565
            'argumentCount' => '?',
2566
        ],
2567
        'THAIDIGIT' => [
2568
            'category' => Category::CATEGORY_TEXT_AND_DATA,
2569
            'functionCall' => [Functions::class, 'DUMMY'],
2570
            'argumentCount' => '?',
2571
        ],
2572
        'THAIMONTHOFYEAR' => [
2573
            'category' => Category::CATEGORY_DATE_AND_TIME,
2574
            'functionCall' => [Functions::class, 'DUMMY'],
2575
            'argumentCount' => '?',
2576
        ],
2577
        'THAINUMSOUND' => [
2578
            'category' => Category::CATEGORY_TEXT_AND_DATA,
2579
            'functionCall' => [Functions::class, 'DUMMY'],
2580
            'argumentCount' => '?',
2581
        ],
2582
        'THAINUMSTRING' => [
2583
            'category' => Category::CATEGORY_TEXT_AND_DATA,
2584
            'functionCall' => [Functions::class, 'DUMMY'],
2585
            'argumentCount' => '?',
2586
        ],
2587
        'THAISTRINGLENGTH' => [
2588
            'category' => Category::CATEGORY_TEXT_AND_DATA,
2589
            'functionCall' => [Functions::class, 'DUMMY'],
2590
            'argumentCount' => '?',
2591
        ],
2592
        'THAIYEAR' => [
2593
            'category' => Category::CATEGORY_DATE_AND_TIME,
2594
            'functionCall' => [Functions::class, 'DUMMY'],
2595
            'argumentCount' => '?',
2596
        ],
2597
        'TIME' => [
2598
            'category' => Category::CATEGORY_DATE_AND_TIME,
2599
            'functionCall' => [DateTimeExcel\Time::class, 'fromHMS'],
2600
            'argumentCount' => '3',
2601
        ],
2602
        'TIMEVALUE' => [
2603
            'category' => Category::CATEGORY_DATE_AND_TIME,
2604
            'functionCall' => [DateTimeExcel\TimeValue::class, 'fromString'],
2605
            'argumentCount' => '1',
2606
        ],
2607
        'TINV' => [
2608
            'category' => Category::CATEGORY_STATISTICAL,
2609
            'functionCall' => [Statistical\Distributions\StudentT::class, 'inverse'],
2610
            'argumentCount' => '2',
2611
        ],
2612
        'T.INV' => [
2613
            'category' => Category::CATEGORY_STATISTICAL,
2614
            'functionCall' => [Statistical\Distributions\StudentT::class, 'inverse'],
2615
            'argumentCount' => '2',
2616
        ],
2617
        'T.INV.2T' => [
2618
            'category' => Category::CATEGORY_STATISTICAL,
2619
            'functionCall' => [Functions::class, 'DUMMY'],
2620
            'argumentCount' => '2',
2621
        ],
2622
        'TODAY' => [
2623
            'category' => Category::CATEGORY_DATE_AND_TIME,
2624
            'functionCall' => [DateTimeExcel\Current::class, 'today'],
2625
            'argumentCount' => '0',
2626
        ],
2627
        'TOCOL' => [
2628
            'category' => Category::CATEGORY_MATH_AND_TRIG,
2629
            'functionCall' => [Functions::class, 'DUMMY'],
2630
            'argumentCount' => '1-3',
2631
        ],
2632
        'TOROW' => [
2633
            'category' => Category::CATEGORY_MATH_AND_TRIG,
2634
            'functionCall' => [Functions::class, 'DUMMY'],
2635
            'argumentCount' => '1-3',
2636
        ],
2637
        'TRANSPOSE' => [
2638
            'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE,
2639
            'functionCall' => [LookupRef\Matrix::class, 'transpose'],
2640
            'argumentCount' => '1',
2641
        ],
2642
        'TREND' => [
2643
            'category' => Category::CATEGORY_STATISTICAL,
2644
            'functionCall' => [Statistical\Trends::class, 'TREND'],
2645
            'argumentCount' => '1-4',
2646
        ],
2647
        'TRIM' => [
2648
            'category' => Category::CATEGORY_TEXT_AND_DATA,
2649
            'functionCall' => [TextData\Trim::class, 'spaces'],
2650
            'argumentCount' => '1',
2651
        ],
2652
        'TRIMMEAN' => [
2653
            'category' => Category::CATEGORY_STATISTICAL,
2654
            'functionCall' => [Statistical\Averages\Mean::class, 'trim'],
2655
            'argumentCount' => '2',
2656
        ],
2657
        'TRUE' => [
2658
            'category' => Category::CATEGORY_LOGICAL,
2659
            'functionCall' => [Logical\Boolean::class, 'TRUE'],
2660
            'argumentCount' => '0',
2661
        ],
2662
        'TRUNC' => [
2663
            'category' => Category::CATEGORY_MATH_AND_TRIG,
2664
            'functionCall' => [MathTrig\Trunc::class, 'evaluate'],
2665
            'argumentCount' => '1,2',
2666
        ],
2667
        'TTEST' => [
2668
            'category' => Category::CATEGORY_STATISTICAL,
2669
            'functionCall' => [Functions::class, 'DUMMY'],
2670
            'argumentCount' => '4',
2671
        ],
2672
        'T.TEST' => [
2673
            'category' => Category::CATEGORY_STATISTICAL,
2674
            'functionCall' => [Functions::class, 'DUMMY'],
2675
            'argumentCount' => '4',
2676
        ],
2677
        'TYPE' => [
2678
            'category' => Category::CATEGORY_INFORMATION,
2679
            'functionCall' => [Information\Value::class, 'type'],
2680
            'argumentCount' => '1',
2681
        ],
2682
        'UNICHAR' => [
2683
            'category' => Category::CATEGORY_TEXT_AND_DATA,
2684
            'functionCall' => [TextData\CharacterConvert::class, 'character'],
2685
            'argumentCount' => '1',
2686
        ],
2687
        'UNICODE' => [
2688
            'category' => Category::CATEGORY_TEXT_AND_DATA,
2689
            'functionCall' => [TextData\CharacterConvert::class, 'code'],
2690
            'argumentCount' => '1',
2691
        ],
2692
        'UNIQUE' => [
2693
            'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE,
2694
            'functionCall' => [LookupRef\Unique::class, 'unique'],
2695
            'argumentCount' => '1+',
2696
        ],
2697
        'UPPER' => [
2698
            'category' => Category::CATEGORY_TEXT_AND_DATA,
2699
            'functionCall' => [TextData\CaseConvert::class, 'upper'],
2700
            'argumentCount' => '1',
2701
        ],
2702
        'USDOLLAR' => [
2703
            'category' => Category::CATEGORY_FINANCIAL,
2704
            'functionCall' => [Financial\Dollar::class, 'format'],
2705
            'argumentCount' => '2',
2706
        ],
2707
        'VALUE' => [
2708
            'category' => Category::CATEGORY_TEXT_AND_DATA,
2709
            'functionCall' => [TextData\Format::class, 'VALUE'],
2710
            'argumentCount' => '1',
2711
        ],
2712
        'VALUETOTEXT' => [
2713
            'category' => Category::CATEGORY_TEXT_AND_DATA,
2714
            'functionCall' => [TextData\Format::class, 'valueToText'],
2715
            'argumentCount' => '1,2',
2716
        ],
2717
        'VAR' => [
2718
            'category' => Category::CATEGORY_STATISTICAL,
2719
            'functionCall' => [Statistical\Variances::class, 'VAR'],
2720
            'argumentCount' => '1+',
2721
        ],
2722
        'VAR.P' => [
2723
            'category' => Category::CATEGORY_STATISTICAL,
2724
            'functionCall' => [Statistical\Variances::class, 'VARP'],
2725
            'argumentCount' => '1+',
2726
        ],
2727
        'VAR.S' => [
2728
            'category' => Category::CATEGORY_STATISTICAL,
2729
            'functionCall' => [Statistical\Variances::class, 'VAR'],
2730
            'argumentCount' => '1+',
2731
        ],
2732
        'VARA' => [
2733
            'category' => Category::CATEGORY_STATISTICAL,
2734
            'functionCall' => [Statistical\Variances::class, 'VARA'],
2735
            'argumentCount' => '1+',
2736
        ],
2737
        'VARP' => [
2738
            'category' => Category::CATEGORY_STATISTICAL,
2739
            'functionCall' => [Statistical\Variances::class, 'VARP'],
2740
            'argumentCount' => '1+',
2741
        ],
2742
        'VARPA' => [
2743
            'category' => Category::CATEGORY_STATISTICAL,
2744
            'functionCall' => [Statistical\Variances::class, 'VARPA'],
2745
            'argumentCount' => '1+',
2746
        ],
2747
        'VDB' => [
2748
            'category' => Category::CATEGORY_FINANCIAL,
2749
            'functionCall' => [Functions::class, 'DUMMY'],
2750
            'argumentCount' => '5-7',
2751
        ],
2752
        'VLOOKUP' => [
2753
            'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE,
2754
            'functionCall' => [LookupRef\VLookup::class, 'lookup'],
2755
            'argumentCount' => '3,4',
2756
        ],
2757
        'VSTACK' => [
2758
            'category' => Category::CATEGORY_MATH_AND_TRIG,
2759
            'functionCall' => [Functions::class, 'DUMMY'],
2760
            'argumentCount' => '1+',
2761
        ],
2762
        'WEBSERVICE' => [
2763
            'category' => Category::CATEGORY_WEB,
2764
            'functionCall' => [Web\Service::class, 'webService'],
2765
            'argumentCount' => '1',
2766
        ],
2767
        'WEEKDAY' => [
2768
            'category' => Category::CATEGORY_DATE_AND_TIME,
2769
            'functionCall' => [DateTimeExcel\Week::class, 'day'],
2770
            'argumentCount' => '1,2',
2771
        ],
2772
        'WEEKNUM' => [
2773
            'category' => Category::CATEGORY_DATE_AND_TIME,
2774
            'functionCall' => [DateTimeExcel\Week::class, 'number'],
2775
            'argumentCount' => '1,2',
2776
        ],
2777
        'WEIBULL' => [
2778
            'category' => Category::CATEGORY_STATISTICAL,
2779
            'functionCall' => [Statistical\Distributions\Weibull::class, 'distribution'],
2780
            'argumentCount' => '4',
2781
        ],
2782
        'WEIBULL.DIST' => [
2783
            'category' => Category::CATEGORY_STATISTICAL,
2784
            'functionCall' => [Statistical\Distributions\Weibull::class, 'distribution'],
2785
            'argumentCount' => '4',
2786
        ],
2787
        'WORKDAY' => [
2788
            'category' => Category::CATEGORY_DATE_AND_TIME,
2789
            'functionCall' => [DateTimeExcel\WorkDay::class, 'date'],
2790
            'argumentCount' => '2-3',
2791
        ],
2792
        'WORKDAY.INTL' => [
2793
            'category' => Category::CATEGORY_DATE_AND_TIME,
2794
            'functionCall' => [Functions::class, 'DUMMY'],
2795
            'argumentCount' => '2-4',
2796
        ],
2797
        'WRAPCOLS' => [
2798
            'category' => Category::CATEGORY_MATH_AND_TRIG,
2799
            'functionCall' => [Functions::class, 'DUMMY'],
2800
            'argumentCount' => '2-3',
2801
        ],
2802
        'WRAPROWS' => [
2803
            'category' => Category::CATEGORY_MATH_AND_TRIG,
2804
            'functionCall' => [Functions::class, 'DUMMY'],
2805
            'argumentCount' => '2-3',
2806
        ],
2807
        'XIRR' => [
2808
            'category' => Category::CATEGORY_FINANCIAL,
2809
            'functionCall' => [Financial\CashFlow\Variable\NonPeriodic::class, 'rate'],
2810
            'argumentCount' => '2,3',
2811
        ],
2812
        'XLOOKUP' => [
2813
            'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE,
2814
            'functionCall' => [Functions::class, 'DUMMY'],
2815
            'argumentCount' => '3-6',
2816
        ],
2817
        'XNPV' => [
2818
            'category' => Category::CATEGORY_FINANCIAL,
2819
            'functionCall' => [Financial\CashFlow\Variable\NonPeriodic::class, 'presentValue'],
2820
            'argumentCount' => '3',
2821
        ],
2822
        'XMATCH' => [
2823
            'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE,
2824
            'functionCall' => [Functions::class, 'DUMMY'],
2825
            'argumentCount' => '2,3',
2826
        ],
2827
        'XOR' => [
2828
            'category' => Category::CATEGORY_LOGICAL,
2829
            'functionCall' => [Logical\Operations::class, 'logicalXor'],
2830
            'argumentCount' => '1+',
2831
        ],
2832
        'YEAR' => [
2833
            'category' => Category::CATEGORY_DATE_AND_TIME,
2834
            'functionCall' => [DateTimeExcel\DateParts::class, 'year'],
2835
            'argumentCount' => '1',
2836
        ],
2837
        'YEARFRAC' => [
2838
            'category' => Category::CATEGORY_DATE_AND_TIME,
2839
            'functionCall' => [DateTimeExcel\YearFrac::class, 'fraction'],
2840
            'argumentCount' => '2,3',
2841
        ],
2842
        'YIELD' => [
2843
            'category' => Category::CATEGORY_FINANCIAL,
2844
            'functionCall' => [Functions::class, 'DUMMY'],
2845
            'argumentCount' => '6,7',
2846
        ],
2847
        'YIELDDISC' => [
2848
            'category' => Category::CATEGORY_FINANCIAL,
2849
            'functionCall' => [Financial\Securities\Yields::class, 'yieldDiscounted'],
2850
            'argumentCount' => '4,5',
2851
        ],
2852
        'YIELDMAT' => [
2853
            'category' => Category::CATEGORY_FINANCIAL,
2854
            'functionCall' => [Financial\Securities\Yields::class, 'yieldAtMaturity'],
2855
            'argumentCount' => '5,6',
2856
        ],
2857
        'ZTEST' => [
2858
            'category' => Category::CATEGORY_STATISTICAL,
2859
            'functionCall' => [Statistical\Distributions\StandardNormal::class, 'zTest'],
2860
            'argumentCount' => '2-3',
2861
        ],
2862
        'Z.TEST' => [
2863
            'category' => Category::CATEGORY_STATISTICAL,
2864
            'functionCall' => [Statistical\Distributions\StandardNormal::class, 'zTest'],
2865
            'argumentCount' => '2-3',
2866
        ],
2867
    ];
2868
2869
    /**
2870
     *    Internal functions used for special control purposes.
2871
     */
2872
    private static array $controlFunctions = [
2873
        'MKMATRIX' => [
2874
            'argumentCount' => '*',
2875
            'functionCall' => [Internal\MakeMatrix::class, 'make'],
2876
        ],
2877
        'NAME.ERROR' => [
2878
            'argumentCount' => '*',
2879
            'functionCall' => [ExcelError::class, 'NAME'],
2880
        ],
2881
        'WILDCARDMATCH' => [
2882
            'argumentCount' => '2',
2883
            'functionCall' => [Internal\WildcardMatch::class, 'compare'],
2884
        ],
2885
    ];
2886
2887 10419
    public function __construct(?Spreadsheet $spreadsheet = null)
2888
    {
2889 10419
        $this->spreadsheet = $spreadsheet;
2890 10419
        $this->cyclicReferenceStack = new CyclicReferenceStack();
2891 10419
        $this->debugLog = new Logger($this->cyclicReferenceStack);
2892 10419
        $this->branchPruner = new BranchPruner($this->branchPruningEnabled);
2893
    }
2894
2895 1
    private static function loadLocales(): void
2896
    {
2897 1
        $localeFileDirectory = __DIR__ . '/locale/';
2898 1
        $localeFileNames = glob($localeFileDirectory . '*', GLOB_ONLYDIR) ?: [];
2899 1
        foreach ($localeFileNames as $filename) {
2900 1
            $filename = substr($filename, strlen($localeFileDirectory));
2901 1
            if ($filename != 'en') {
2902 1
                self::$validLocaleLanguages[] = $filename;
2903
            }
2904
        }
2905
    }
2906
2907
    /**
2908
     * Get an instance of this class.
2909
     *
2910
     * @param ?Spreadsheet $spreadsheet Injected spreadsheet for working with a PhpSpreadsheet Spreadsheet object,
2911
     *                                    or NULL to create a standalone calculation engine
2912
     */
2913 12948
    public static function getInstance(?Spreadsheet $spreadsheet = null): self
2914
    {
2915 12948
        if ($spreadsheet !== null) {
2916 9194
            $instance = $spreadsheet->getCalculationEngine();
2917 9194
            if (isset($instance)) {
2918 9194
                return $instance;
2919
            }
2920
        }
2921
2922 4611
        if (!self::$instance) {
2923 16
            self::$instance = new self();
2924
        }
2925
2926 4611
        return self::$instance;
2927
    }
2928
2929
    /**
2930
     * Flush the calculation cache for any existing instance of this class
2931
     *        but only if a Calculation instance exists.
2932
     */
2933 203
    public function flushInstance(): void
2934
    {
2935 203
        $this->clearCalculationCache();
2936 203
        $this->branchPruner->clearBranchStore();
2937
    }
2938
2939
    /**
2940
     * Get the Logger for this calculation engine instance.
2941
     */
2942 1083
    public function getDebugLog(): Logger
2943
    {
2944 1083
        return $this->debugLog;
2945
    }
2946
2947
    /**
2948
     * __clone implementation. Cloning should not be allowed in a Singleton!
2949
     */
2950
    final public function __clone()
2951
    {
2952
        throw new Exception('Cloning the calculation engine is not allowed!');
2953
    }
2954
2955
    /**
2956
     * Return the locale-specific translation of TRUE.
2957
     *
2958
     * @return string locale-specific translation of TRUE
2959
     */
2960 968
    public static function getTRUE(): string
2961
    {
2962 968
        return self::$localeBoolean['TRUE'];
2963
    }
2964
2965
    /**
2966
     * Return the locale-specific translation of FALSE.
2967
     *
2968
     * @return string locale-specific translation of FALSE
2969
     */
2970 952
    public static function getFALSE(): string
2971
    {
2972 952
        return self::$localeBoolean['FALSE'];
2973
    }
2974
2975
    /**
2976
     * Set the Array Return Type (Array or Value of first element in the array).
2977
     *
2978
     * @param string $returnType Array return type
2979
     *
2980
     * @return bool Success or failure
2981
     */
2982 529
    public static function setArrayReturnType(string $returnType): bool
2983
    {
2984
        if (
2985 529
            ($returnType == self::RETURN_ARRAY_AS_VALUE)
2986 529
            || ($returnType == self::RETURN_ARRAY_AS_ERROR)
2987 529
            || ($returnType == self::RETURN_ARRAY_AS_ARRAY)
2988
        ) {
2989 529
            self::$returnArrayAsType = $returnType;
2990
2991 529
            return true;
2992
        }
2993
2994 1
        return false;
2995
    }
2996
2997
    /**
2998
     * Return the Array Return Type (Array or Value of first element in the array).
2999
     *
3000
     * @return string $returnType Array return type
3001
     */
3002 529
    public static function getArrayReturnType(): string
3003
    {
3004 529
        return self::$returnArrayAsType;
3005
    }
3006
3007
    /**
3008
     * Set the Instance Array Return Type (Array or Value of first element in the array).
3009
     *
3010
     * @param string $returnType Array return type
3011
     *
3012
     * @return bool Success or failure
3013
     */
3014 298
    public function setInstanceArrayReturnType(string $returnType): bool
3015
    {
3016
        if (
3017 298
            ($returnType == self::RETURN_ARRAY_AS_VALUE)
3018 298
            || ($returnType == self::RETURN_ARRAY_AS_ERROR)
3019 298
            || ($returnType == self::RETURN_ARRAY_AS_ARRAY)
3020
        ) {
3021 298
            $this->instanceArrayReturnType = $returnType;
3022
3023 298
            return true;
3024
        }
3025
3026
        return false;
3027
    }
3028
3029
    /**
3030
     * Return the Array Return Type (Array or Value of first element in the array).
3031
     *
3032
     * @return string $returnType Array return type for instance if non-null, otherwise static property
3033
     */
3034 8697
    public function getInstanceArrayReturnType(): string
3035
    {
3036 8697
        return $this->instanceArrayReturnType ?? self::$returnArrayAsType;
3037
    }
3038
3039
    /**
3040
     * Is calculation caching enabled?
3041
     */
3042 179
    public function getCalculationCacheEnabled(): bool
3043
    {
3044 179
        return $this->calculationCacheEnabled;
3045
    }
3046
3047
    /**
3048
     * Enable/disable calculation cache.
3049
     */
3050
    public function setCalculationCacheEnabled(bool $calculationCacheEnabled): void
3051
    {
3052
        $this->calculationCacheEnabled = $calculationCacheEnabled;
3053
        $this->clearCalculationCache();
3054
    }
3055
3056
    /**
3057
     * Enable calculation cache.
3058
     */
3059
    public function enableCalculationCache(): void
3060
    {
3061
        $this->setCalculationCacheEnabled(true);
3062
    }
3063
3064
    /**
3065
     * Disable calculation cache.
3066
     */
3067
    public function disableCalculationCache(): void
3068
    {
3069
        $this->setCalculationCacheEnabled(false);
3070
    }
3071
3072
    /**
3073
     * Clear calculation cache.
3074
     */
3075 205
    public function clearCalculationCache(): void
3076
    {
3077 205
        $this->calculationCache = [];
3078
    }
3079
3080
    /**
3081
     * Clear calculation cache for a specified worksheet.
3082
     */
3083 120
    public function clearCalculationCacheForWorksheet(string $worksheetName): void
3084
    {
3085 120
        if (isset($this->calculationCache[$worksheetName])) {
3086
            unset($this->calculationCache[$worksheetName]);
3087
        }
3088
    }
3089
3090
    /**
3091
     * Rename calculation cache for a specified worksheet.
3092
     */
3093 1373
    public function renameCalculationCacheForWorksheet(string $fromWorksheetName, string $toWorksheetName): void
3094
    {
3095 1373
        if (isset($this->calculationCache[$fromWorksheetName])) {
3096
            $this->calculationCache[$toWorksheetName] = &$this->calculationCache[$fromWorksheetName];
3097
            unset($this->calculationCache[$fromWorksheetName]);
3098
        }
3099
    }
3100
3101
    /**
3102
     * Enable/disable calculation cache.
3103
     */
3104 7972
    public function setBranchPruningEnabled(mixed $enabled): void
3105
    {
3106 7972
        $this->branchPruningEnabled = $enabled;
3107 7972
        $this->branchPruner = new BranchPruner($this->branchPruningEnabled);
3108
    }
3109
3110
    public function enableBranchPruning(): void
3111
    {
3112
        $this->setBranchPruningEnabled(true);
3113
    }
3114
3115 7972
    public function disableBranchPruning(): void
3116
    {
3117 7972
        $this->setBranchPruningEnabled(false);
3118
    }
3119
3120
    /**
3121
     * Get the currently defined locale code.
3122
     */
3123 772
    public function getLocale(): string
3124
    {
3125 772
        return self::$localeLanguage;
3126
    }
3127
3128 120
    private function getLocaleFile(string $localeDir, string $locale, string $language, string $file): string
3129
    {
3130 120
        $localeFileName = $localeDir . str_replace('_', DIRECTORY_SEPARATOR, $locale)
3131 120
            . DIRECTORY_SEPARATOR . $file;
3132 120
        if (!file_exists($localeFileName)) {
3133
            //    If there isn't a locale specific file, look for a language specific file
3134 29
            $localeFileName = $localeDir . $language . DIRECTORY_SEPARATOR . $file;
3135 29
            if (!file_exists($localeFileName)) {
3136 3
                throw new Exception('Locale file not found');
3137
            }
3138
        }
3139
3140 117
        return $localeFileName;
3141
    }
3142
3143
    /** @var array<int, array<int, string>> */
3144
    private static array $falseTrueArray = [];
3145
3146
    /** @return array<int, array<int, string>> */
3147 1
    public function getFalseTrueArray(): array
3148
    {
3149 1
        if (!empty(self::$falseTrueArray)) {
3150
            return self::$falseTrueArray;
3151
        }
3152 1
        if (count(self::$validLocaleLanguages) == 1) {
3153
            self::loadLocales();
3154
        }
3155 1
        $falseTrueArray = [['FALSE'], ['TRUE']];
3156 1
        foreach (self::$validLocaleLanguages as $language) {
3157 1
            if (str_starts_with($language, 'en')) {
3158 1
                continue;
3159
            }
3160 1
            $locale = $language;
3161 1
            if (str_contains($locale, '_')) {
3162
                [$language] = explode('_', $locale);
3163
            }
3164 1
            $localeDir = implode(DIRECTORY_SEPARATOR, [__DIR__, 'locale', null]);
3165
3166
            try {
3167 1
                $functionNamesFile = $this->getLocaleFile($localeDir, $locale, $language, 'functions');
3168
            } catch (Exception $e) {
3169
                continue;
3170
            }
3171
            //    Retrieve the list of locale or language specific function names
3172 1
            $localeFunctions = file($functionNamesFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: [];
3173 1
            foreach ($localeFunctions as $localeFunction) {
3174 1
                [$localeFunction] = explode('##', $localeFunction); //    Strip out comments
3175 1
                if (str_contains($localeFunction, '=')) {
3176 1
                    [$fName, $lfName] = array_map('trim', explode('=', $localeFunction));
3177 1
                    if ($fName === 'FALSE') {
3178 1
                        $falseTrueArray[0][] = $lfName;
3179 1
                    } elseif ($fName === 'TRUE') {
3180 1
                        $falseTrueArray[1][] = $lfName;
3181
                    }
3182
                }
3183
            }
3184
        }
3185 1
        self::$falseTrueArray = $falseTrueArray;
3186
3187 1
        return $falseTrueArray;
3188
    }
3189
3190
    /**
3191
     * Set the locale code.
3192
     *
3193
     * @param string $locale The locale to use for formula translation, eg: 'en_us'
3194
     */
3195 772
    public function setLocale(string $locale): bool
3196
    {
3197
        //    Identify our locale and language
3198 772
        $language = $locale = strtolower($locale);
3199 772
        if (str_contains($locale, '_')) {
3200 772
            [$language] = explode('_', $locale);
3201
        }
3202 772
        if (count(self::$validLocaleLanguages) == 1) {
3203 1
            self::loadLocales();
3204
        }
3205
3206
        //    Test whether we have any language data for this language (any locale)
3207 772
        if (in_array($language, self::$validLocaleLanguages, true)) {
3208
            //    initialise language/locale settings
3209 772
            self::$localeFunctions = [];
3210 772
            self::$localeArgumentSeparator = ',';
3211 772
            self::$localeBoolean = ['TRUE' => 'TRUE', 'FALSE' => 'FALSE', 'NULL' => 'NULL'];
3212
3213
            //    Default is US English, if user isn't requesting US english, then read the necessary data from the locale files
3214 772
            if ($locale !== 'en_us') {
3215 119
                $localeDir = implode(DIRECTORY_SEPARATOR, [__DIR__, 'locale', null]);
3216
3217
                //    Search for a file with a list of function names for locale
3218
                try {
3219 119
                    $functionNamesFile = $this->getLocaleFile($localeDir, $locale, $language, 'functions');
3220 3
                } catch (Exception $e) {
3221 3
                    return false;
3222
                }
3223
3224
                //    Retrieve the list of locale or language specific function names
3225 116
                $localeFunctions = file($functionNamesFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: [];
3226 116
                foreach ($localeFunctions as $localeFunction) {
3227 116
                    [$localeFunction] = explode('##', $localeFunction); //    Strip out comments
3228 116
                    if (str_contains($localeFunction, '=')) {
3229 116
                        [$fName, $lfName] = array_map('trim', explode('=', $localeFunction));
3230 116
                        if ((str_starts_with($fName, '*') || isset(self::$phpSpreadsheetFunctions[$fName])) && ($lfName != '') && ($fName != $lfName)) {
3231 116
                            self::$localeFunctions[$fName] = $lfName;
3232
                        }
3233
                    }
3234
                }
3235
                //    Default the TRUE and FALSE constants to the locale names of the TRUE() and FALSE() functions
3236 116
                if (isset(self::$localeFunctions['TRUE'])) {
3237 116
                    self::$localeBoolean['TRUE'] = self::$localeFunctions['TRUE'];
3238
                }
3239 116
                if (isset(self::$localeFunctions['FALSE'])) {
3240 116
                    self::$localeBoolean['FALSE'] = self::$localeFunctions['FALSE'];
3241
                }
3242
3243
                try {
3244 116
                    $configFile = $this->getLocaleFile($localeDir, $locale, $language, 'config');
3245
                } catch (Exception) {
3246
                    return false;
3247
                }
3248
3249 116
                $localeSettings = file($configFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: [];
3250 116
                foreach ($localeSettings as $localeSetting) {
3251 116
                    [$localeSetting] = explode('##', $localeSetting); //    Strip out comments
3252 116
                    if (str_contains($localeSetting, '=')) {
3253 116
                        [$settingName, $settingValue] = array_map('trim', explode('=', $localeSetting));
3254 116
                        $settingName = strtoupper($settingName);
3255 116
                        if ($settingValue !== '') {
3256
                            switch ($settingName) {
3257 116
                                case 'ARGUMENTSEPARATOR':
3258 116
                                    self::$localeArgumentSeparator = $settingValue;
3259
3260 116
                                    break;
3261
                            }
3262
                        }
3263
                    }
3264
                }
3265
            }
3266
3267 772
            self::$functionReplaceFromExcel = self::$functionReplaceToExcel
3268 772
            = self::$functionReplaceFromLocale = self::$functionReplaceToLocale = null;
3269 772
            self::$localeLanguage = $locale;
3270
3271 772
            return true;
3272
        }
3273
3274 3
        return false;
3275
    }
3276
3277 47
    public static function translateSeparator(
3278
        string $fromSeparator,
3279
        string $toSeparator,
3280
        string $formula,
3281
        int &$inBracesLevel,
3282
        string $openBrace = self::FORMULA_OPEN_FUNCTION_BRACE,
3283
        string $closeBrace = self::FORMULA_CLOSE_FUNCTION_BRACE
3284
    ): string {
3285 47
        $strlen = mb_strlen($formula);
3286 47
        for ($i = 0; $i < $strlen; ++$i) {
3287 47
            $chr = mb_substr($formula, $i, 1);
3288
            switch ($chr) {
3289 47
                case $openBrace:
3290 42
                    ++$inBracesLevel;
3291
3292 42
                    break;
3293 47
                case $closeBrace:
3294 42
                    --$inBracesLevel;
3295
3296 42
                    break;
3297 47
                case $fromSeparator:
3298 27
                    if ($inBracesLevel > 0) {
3299 27
                        $formula = mb_substr($formula, 0, $i) . $toSeparator . mb_substr($formula, $i + 1);
3300
                    }
3301
            }
3302
        }
3303
3304 47
        return $formula;
3305
    }
3306
3307 19
    private static function translateFormulaBlock(
3308
        array $from,
3309
        array $to,
3310
        string $formula,
3311
        int &$inFunctionBracesLevel,
3312
        int &$inMatrixBracesLevel,
3313
        string $fromSeparator,
3314
        string $toSeparator
3315
    ): string {
3316
        // Function Names
3317 19
        $formula = (string) preg_replace($from, $to, $formula);
3318
3319
        // Temporarily adjust matrix separators so that they won't be confused with function arguments
3320 19
        $formula = self::translateSeparator(';', '|', $formula, $inMatrixBracesLevel, self::FORMULA_OPEN_MATRIX_BRACE, self::FORMULA_CLOSE_MATRIX_BRACE);
3321 19
        $formula = self::translateSeparator(',', '!', $formula, $inMatrixBracesLevel, self::FORMULA_OPEN_MATRIX_BRACE, self::FORMULA_CLOSE_MATRIX_BRACE);
3322
        // Function Argument Separators
3323 19
        $formula = self::translateSeparator($fromSeparator, $toSeparator, $formula, $inFunctionBracesLevel);
3324
        // Restore matrix separators
3325 19
        $formula = self::translateSeparator('|', ';', $formula, $inMatrixBracesLevel, self::FORMULA_OPEN_MATRIX_BRACE, self::FORMULA_CLOSE_MATRIX_BRACE);
3326 19
        $formula = self::translateSeparator('!', ',', $formula, $inMatrixBracesLevel, self::FORMULA_OPEN_MATRIX_BRACE, self::FORMULA_CLOSE_MATRIX_BRACE);
3327
3328 19
        return $formula;
3329
    }
3330
3331 19
    private static function translateFormula(array $from, array $to, string $formula, string $fromSeparator, string $toSeparator): string
3332
    {
3333
        // Convert any Excel function names and constant names to the required language;
3334
        //     and adjust function argument separators
3335 19
        if (self::$localeLanguage !== 'en_us') {
3336 19
            $inFunctionBracesLevel = 0;
3337 19
            $inMatrixBracesLevel = 0;
3338
            //    If there is the possibility of separators within a quoted string, then we treat them as literals
3339 19
            if (str_contains($formula, self::FORMULA_STRING_QUOTE)) {
3340
                //    So instead we skip replacing in any quoted strings by only replacing in every other array element
3341
                //       after we've exploded the formula
3342 6
                $temp = explode(self::FORMULA_STRING_QUOTE, $formula);
3343 6
                $notWithinQuotes = false;
3344 6
                foreach ($temp as &$value) {
3345
                    //    Only adjust in alternating array entries
3346 6
                    $notWithinQuotes = $notWithinQuotes === false;
3347 6
                    if ($notWithinQuotes === true) {
3348 6
                        $value = self::translateFormulaBlock($from, $to, $value, $inFunctionBracesLevel, $inMatrixBracesLevel, $fromSeparator, $toSeparator);
3349
                    }
3350
                }
3351 6
                unset($value);
3352
                //    Then rebuild the formula string
3353 6
                $formula = implode(self::FORMULA_STRING_QUOTE, $temp);
3354
            } else {
3355
                //    If there's no quoted strings, then we do a simple count/replace
3356 13
                $formula = self::translateFormulaBlock($from, $to, $formula, $inFunctionBracesLevel, $inMatrixBracesLevel, $fromSeparator, $toSeparator);
3357
            }
3358
        }
3359
3360 19
        return $formula;
3361
    }
3362
3363
    private static ?array $functionReplaceFromExcel;
3364
3365
    private static ?array $functionReplaceToLocale;
3366
3367 19
    public function translateFormulaToLocale(string $formula): string
3368
    {
3369 19
        $formula = preg_replace(self::CALCULATION_REGEXP_STRIP_XLFN_XLWS, '', $formula) ?? '';
3370
        // Build list of function names and constants for translation
3371 19
        if (self::$functionReplaceFromExcel === null) {
3372 19
            self::$functionReplaceFromExcel = [];
3373 19
            foreach (array_keys(self::$localeFunctions) as $excelFunctionName) {
3374 19
                self::$functionReplaceFromExcel[] = '/(@?[^\w\.])' . preg_quote($excelFunctionName, '/') . '([\s]*\()/ui';
3375
            }
3376 19
            foreach (array_keys(self::$localeBoolean) as $excelBoolean) {
3377 19
                self::$functionReplaceFromExcel[] = '/(@?[^\w\.])' . preg_quote($excelBoolean, '/') . '([^\w\.])/ui';
3378
            }
3379
        }
3380
3381 19
        if (self::$functionReplaceToLocale === null) {
3382 19
            self::$functionReplaceToLocale = [];
3383 19
            foreach (self::$localeFunctions as $localeFunctionName) {
3384 19
                self::$functionReplaceToLocale[] = '$1' . trim($localeFunctionName) . '$2';
3385
            }
3386 19
            foreach (self::$localeBoolean as $localeBoolean) {
3387 19
                self::$functionReplaceToLocale[] = '$1' . trim($localeBoolean) . '$2';
3388
            }
3389
        }
3390
3391 19
        return self::translateFormula(
3392 19
            self::$functionReplaceFromExcel,
3393 19
            self::$functionReplaceToLocale,
3394 19
            $formula,
3395 19
            ',',
3396 19
            self::$localeArgumentSeparator
3397 19
        );
3398
    }
3399
3400
    private static ?array $functionReplaceFromLocale;
3401
3402
    private static ?array $functionReplaceToExcel;
3403
3404 19
    public function translateFormulaToEnglish(string $formula): string
3405
    {
3406 19
        if (self::$functionReplaceFromLocale === null) {
3407 19
            self::$functionReplaceFromLocale = [];
3408 19
            foreach (self::$localeFunctions as $localeFunctionName) {
3409 19
                self::$functionReplaceFromLocale[] = '/(@?[^\w\.])' . preg_quote($localeFunctionName, '/') . '([\s]*\()/ui';
3410
            }
3411 19
            foreach (self::$localeBoolean as $excelBoolean) {
3412 19
                self::$functionReplaceFromLocale[] = '/(@?[^\w\.])' . preg_quote($excelBoolean, '/') . '([^\w\.])/ui';
3413
            }
3414
        }
3415
3416 19
        if (self::$functionReplaceToExcel === null) {
3417 19
            self::$functionReplaceToExcel = [];
3418 19
            foreach (array_keys(self::$localeFunctions) as $excelFunctionName) {
3419 19
                self::$functionReplaceToExcel[] = '$1' . trim($excelFunctionName) . '$2';
3420
            }
3421 19
            foreach (array_keys(self::$localeBoolean) as $excelBoolean) {
3422 19
                self::$functionReplaceToExcel[] = '$1' . trim($excelBoolean) . '$2';
3423
            }
3424
        }
3425
3426 19
        return self::translateFormula(self::$functionReplaceFromLocale, self::$functionReplaceToExcel, $formula, self::$localeArgumentSeparator, ',');
3427
    }
3428
3429 11693
    public static function localeFunc(string $function): string
3430
    {
3431 11693
        if (self::$localeLanguage !== 'en_us') {
3432 73
            $functionName = trim($function, '(');
3433 73
            if (isset(self::$localeFunctions[$functionName])) {
3434 71
                $brace = ($functionName != $function);
3435 71
                $function = self::$localeFunctions[$functionName];
3436 71
                if ($brace) {
3437 68
                    $function .= '(';
3438
                }
3439
            }
3440
        }
3441
3442 11693
        return $function;
3443
    }
3444
3445
    /**
3446
     * Wrap string values in quotes.
3447
     */
3448 11438
    public static function wrapResult(mixed $value): mixed
3449
    {
3450 11438
        if (is_string($value)) {
3451
            //    Error values cannot be "wrapped"
3452 3959
            if (preg_match('/^' . self::CALCULATION_REGEXP_ERROR . '$/i', $value, $match)) {
3453
                //    Return Excel errors "as is"
3454 1242
                return $value;
3455
            }
3456
3457
            //    Return strings wrapped in quotes
3458 3178
            return self::FORMULA_STRING_QUOTE . $value . self::FORMULA_STRING_QUOTE;
3459 9048
        } elseif ((is_float($value)) && ((is_nan($value)) || (is_infinite($value)))) {
3460
            //    Convert numeric errors to NaN error
3461 4
            return ExcelError::NAN();
3462
        }
3463
3464 9045
        return $value;
3465
    }
3466
3467
    /**
3468
     * Remove quotes used as a wrapper to identify string values.
3469
     */
3470 11618
    public static function unwrapResult(mixed $value): mixed
3471
    {
3472 11618
        if (is_string($value)) {
3473 3654
            if ((isset($value[0])) && ($value[0] == self::FORMULA_STRING_QUOTE) && (substr($value, -1) == self::FORMULA_STRING_QUOTE)) {
3474 2945
                return substr($value, 1, -1);
3475
            }
3476
            //    Convert numeric errors to NAN error
3477 10375
        } elseif ((is_float($value)) && ((is_nan($value)) || (is_infinite($value)))) {
3478
            return ExcelError::NAN();
3479
        }
3480
3481 10442
        return $value;
3482
    }
3483
3484
    /**
3485
     * Calculate cell value (using formula from a cell ID)
3486
     * Retained for backward compatibility.
3487
     *
3488
     * @param ?Cell $cell Cell to calculate
3489
     */
3490
    public function calculate(?Cell $cell = null): mixed
3491
    {
3492
        try {
3493
            return $this->calculateCellValue($cell);
3494
        } catch (\Exception $e) {
3495
            throw new Exception($e->getMessage());
3496
        }
3497
    }
3498
3499
    /**
3500
     * Calculate the value of a cell formula.
3501
     *
3502
     * @param ?Cell $cell Cell to calculate
3503
     * @param bool $resetLog Flag indicating whether the debug log should be reset or not
3504
     */
3505 8035
    public function calculateCellValue(?Cell $cell = null, bool $resetLog = true): mixed
3506
    {
3507 8035
        if ($cell === null) {
3508
            return null;
3509
        }
3510
3511 8035
        if ($resetLog) {
3512
            //    Initialise the logging settings if requested
3513 8023
            $this->formulaError = null;
3514 8023
            $this->debugLog->clearLog();
3515 8023
            $this->cyclicReferenceStack->clear();
3516 8023
            $this->cyclicFormulaCounter = 1;
3517
        }
3518
3519
        //    Execute the calculation for the cell formula
3520 8035
        $this->cellStack[] = [
3521 8035
            'sheet' => $cell->getWorksheet()->getTitle(),
3522 8035
            'cell' => $cell->getCoordinate(),
3523 8035
        ];
3524
3525 8035
        $cellAddressAttempted = false;
3526 8035
        $cellAddress = null;
3527
3528
        try {
3529 8035
            $value = $cell->getValue();
3530 8035
            if ($cell->getDataType() === DataType::TYPE_FORMULA) {
3531 8035
                $value = preg_replace_callback(
3532 8035
                    self::CALCULATION_REGEXP_CELLREF_SPILL,
3533 8035
                    fn (array $matches) => 'ANCHORARRAY(' . substr($matches[0], 0, -1) . ')',
3534 8035
                    $value
3535 8035
                );
3536
            }
3537 8035
            $result = self::unwrapResult($this->_calculateFormulaValue($value, $cell->getCoordinate(), $cell));
3538 7788
            if ($this->spreadsheet === null) {
3539
                throw new Exception('null spreadsheet in calculateCellValue');
3540
            }
3541 7788
            $cellAddressAttempted = true;
3542 7788
            $cellAddress = array_pop($this->cellStack);
3543 7788
            if ($cellAddress === null) {
3544
                throw new Exception('null cellAddress in calculateCellValue');
3545
            }
3546 7788
            $testSheet = $this->spreadsheet->getSheetByName($cellAddress['sheet']);
3547 7788
            if ($testSheet === null) {
3548
                throw new Exception('worksheet not found in calculateCellValue');
3549
            }
3550 7788
            $testSheet->getCell($cellAddress['cell']);
3551 265
        } catch (\Exception $e) {
3552 265
            if (!$cellAddressAttempted) {
3553 265
                $cellAddress = array_pop($this->cellStack);
3554
            }
3555 265
            if ($this->spreadsheet !== null && is_array($cellAddress) && array_key_exists('sheet', $cellAddress)) {
3556 265
                $testSheet = $this->spreadsheet->getSheetByName($cellAddress['sheet']);
3557 265
                if ($testSheet !== null && array_key_exists('cell', $cellAddress)) {
3558 265
                    $testSheet->getCell($cellAddress['cell']);
3559
                }
3560
            }
3561
3562 265
            throw new Exception($e->getMessage(), $e->getCode(), $e);
3563
        }
3564
3565 7788
        if (is_array($result) && $this->getInstanceArrayReturnType() !== self::RETURN_ARRAY_AS_ARRAY) {
3566 4777
            $testResult = Functions::flattenArray($result);
3567 4777
            if ($this->getInstanceArrayReturnType() == self::RETURN_ARRAY_AS_ERROR) {
3568 1
                return ExcelError::VALUE();
3569
            }
3570 4777
            $result = array_shift($testResult);
3571
        }
3572
3573 7788
        if ($result === null && $cell->getWorksheet()->getSheetView()->getShowZeros()) {
3574 16
            return 0;
3575 7787
        } elseif ((is_float($result)) && ((is_nan($result)) || (is_infinite($result)))) {
3576
            return ExcelError::NAN();
3577
        }
3578
3579 7787
        return $result;
3580
    }
3581
3582
    /**
3583
     * Validate and parse a formula string.
3584
     *
3585
     * @param string $formula Formula to parse
3586
     */
3587 8015
    public function parseFormula(string $formula): array|bool
3588
    {
3589 8015
        $formula = preg_replace_callback(
3590 8015
            self::CALCULATION_REGEXP_CELLREF_SPILL,
3591 8015
            fn (array $matches) => 'ANCHORARRAY(' . substr($matches[0], 0, -1) . ')',
3592 8015
            $formula
3593 8015
        ) ?? $formula;
3594
        //    Basic validation that this is indeed a formula
3595
        //    We return an empty array if not
3596 8015
        $formula = trim($formula);
3597 8015
        if ((!isset($formula[0])) || ($formula[0] != '=')) {
3598
            return [];
3599
        }
3600 8015
        $formula = ltrim(substr($formula, 1));
3601 8015
        if (!isset($formula[0])) {
3602
            return [];
3603
        }
3604
3605
        //    Parse the formula and return the token stack
3606 8015
        return $this->internalParseFormula($formula);
3607
    }
3608
3609
    /**
3610
     * Calculate the value of a formula.
3611
     *
3612
     * @param string $formula Formula to parse
3613
     * @param ?string $cellID Address of the cell to calculate
3614
     * @param ?Cell $cell Cell to calculate
3615
     */
3616 179
    public function calculateFormula(string $formula, ?string $cellID = null, ?Cell $cell = null): mixed
3617
    {
3618
        //    Initialise the logging settings
3619 179
        $this->formulaError = null;
3620 179
        $this->debugLog->clearLog();
3621 179
        $this->cyclicReferenceStack->clear();
3622
3623 179
        $resetCache = $this->getCalculationCacheEnabled();
3624 179
        if ($this->spreadsheet !== null && $cellID === null && $cell === null) {
3625 167
            $cellID = 'A1';
3626 167
            $cell = $this->spreadsheet->getActiveSheet()->getCell($cellID);
3627
        } else {
3628
            //    Disable calculation cacheing because it only applies to cell calculations, not straight formulae
3629
            //    But don't actually flush any cache
3630 12
            $this->calculationCacheEnabled = false;
3631
        }
3632
3633
        //    Execute the calculation
3634
        try {
3635 179
            $result = self::unwrapResult($this->_calculateFormulaValue($formula, $cellID, $cell));
3636 2
        } catch (\Exception $e) {
3637 2
            throw new Exception($e->getMessage());
3638
        }
3639
3640 178
        if ($this->spreadsheet === null) {
3641
            //    Reset calculation cacheing to its previous state
3642
            $this->calculationCacheEnabled = $resetCache;
3643
        }
3644
3645 178
        return $result;
3646
    }
3647
3648 8184
    public function getValueFromCache(string $cellReference, mixed &$cellValue): bool
3649
    {
3650 8184
        $this->debugLog->writeDebugLog('Testing cache value for cell %s', $cellReference);
3651
        // Is calculation cacheing enabled?
3652
        // If so, is the required value present in calculation cache?
3653 8184
        if (($this->calculationCacheEnabled) && (isset($this->calculationCache[$cellReference]))) {
3654 324
            $this->debugLog->writeDebugLog('Retrieving value for cell %s from cache', $cellReference);
3655
            // Return the cached result
3656
3657 324
            $cellValue = $this->calculationCache[$cellReference];
3658
3659 324
            return true;
3660
        }
3661
3662 8184
        return false;
3663
    }
3664
3665 7935
    public function saveValueToCache(string $cellReference, mixed $cellValue): void
3666
    {
3667 7935
        if ($this->calculationCacheEnabled) {
3668 7927
            $this->calculationCache[$cellReference] = $cellValue;
3669
        }
3670
    }
3671
3672
    /**
3673
     * Parse a cell formula and calculate its value.
3674
     *
3675
     * @param string $formula The formula to parse and calculate
3676
     * @param ?string $cellID The ID (e.g. A3) of the cell that we are calculating
3677
     * @param ?Cell $cell Cell to calculate
3678
     * @param bool $ignoreQuotePrefix If set to true, evaluate the formyla even if the referenced cell is quote prefixed
3679
     */
3680 11887
    public function _calculateFormulaValue(string $formula, ?string $cellID = null, ?Cell $cell = null, bool $ignoreQuotePrefix = false): mixed
3681
    {
3682 11887
        $cellValue = null;
3683
3684
        //  Quote-Prefixed cell values cannot be formulae, but are treated as strings
3685 11887
        if ($cell !== null && $ignoreQuotePrefix === false && $cell->getStyle()->getQuotePrefix() === true) {
3686 1
            return self::wrapResult((string) $formula);
3687
        }
3688
3689 11887
        if (preg_match('/^=\s*cmd\s*\|/miu', $formula) !== 0) {
3690
            return self::wrapResult($formula);
3691
        }
3692
3693
        //    Basic validation that this is indeed a formula
3694
        //    We simply return the cell value if not
3695 11887
        $formula = trim($formula);
3696 11887
        if ($formula === '' || $formula[0] !== '=') {
3697 2
            return self::wrapResult($formula);
3698
        }
3699 11887
        $formula = ltrim(substr($formula, 1));
3700 11887
        if (!isset($formula[0])) {
3701 5
            return self::wrapResult($formula);
3702
        }
3703
3704 11886
        $pCellParent = ($cell !== null) ? $cell->getWorksheet() : null;
3705 11886
        $wsTitle = ($pCellParent !== null) ? $pCellParent->getTitle() : "\x00Wrk";
3706 11886
        $wsCellReference = $wsTitle . '!' . $cellID;
3707
3708 11886
        if (($cellID !== null) && ($this->getValueFromCache($wsCellReference, $cellValue))) {
3709 320
            return $cellValue;
3710
        }
3711 11886
        $this->debugLog->writeDebugLog('Evaluating formula for cell %s', $wsCellReference);
3712
3713 11886
        if (($wsTitle[0] !== "\x00") && ($this->cyclicReferenceStack->onStack($wsCellReference))) {
3714 12
            if ($this->cyclicFormulaCount <= 0) {
3715 1
                $this->cyclicFormulaCell = '';
3716
3717 1
                return $this->raiseFormulaError('Cyclic Reference in Formula');
3718 11
            } elseif ($this->cyclicFormulaCell === $wsCellReference) {
3719 1
                ++$this->cyclicFormulaCounter;
3720 1
                if ($this->cyclicFormulaCounter >= $this->cyclicFormulaCount) {
3721 1
                    $this->cyclicFormulaCell = '';
3722
3723 1
                    return $cellValue;
3724
                }
3725 11
            } elseif ($this->cyclicFormulaCell == '') {
3726 11
                if ($this->cyclicFormulaCounter >= $this->cyclicFormulaCount) {
3727 10
                    return $cellValue;
3728
                }
3729 1
                $this->cyclicFormulaCell = $wsCellReference;
3730
            }
3731
        }
3732
3733 11886
        $this->debugLog->writeDebugLog('Formula for cell %s is %s', $wsCellReference, $formula);
3734
        //    Parse the formula onto the token stack and calculate the value
3735 11886
        $this->cyclicReferenceStack->push($wsCellReference);
3736
3737 11886
        $cellValue = $this->processTokenStack($this->internalParseFormula($formula, $cell), $cellID, $cell);
3738 11635
        $this->cyclicReferenceStack->pop();
3739
3740
        // Save to calculation cache
3741 11635
        if ($cellID !== null) {
3742 7935
            $this->saveValueToCache($wsCellReference, $cellValue);
3743
        }
3744
3745
        //    Return the calculated value
3746 11635
        return $cellValue;
3747
    }
3748
3749
    /**
3750
     * Ensure that paired matrix operands are both matrices and of the same size.
3751
     *
3752
     * @param mixed $operand1 First matrix operand
3753
     * @param mixed $operand2 Second matrix operand
3754
     * @param int $resize Flag indicating whether the matrices should be resized to match
3755
     *                                        and (if so), whether the smaller dimension should grow or the
3756
     *                                        larger should shrink.
3757
     *                                            0 = no resize
3758
     *                                            1 = shrink to fit
3759
     *                                            2 = extend to fit
3760
     */
3761 64
    public static function checkMatrixOperands(mixed &$operand1, mixed &$operand2, int $resize = 1): array
3762
    {
3763
        //    Examine each of the two operands, and turn them into an array if they aren't one already
3764
        //    Note that this function should only be called if one or both of the operand is already an array
3765 64
        if (!is_array($operand1)) {
3766 19
            [$matrixRows, $matrixColumns] = self::getMatrixDimensions($operand2);
3767 19
            $operand1 = array_fill(0, $matrixRows, array_fill(0, $matrixColumns, $operand1));
3768 19
            $resize = 0;
3769 51
        } elseif (!is_array($operand2)) {
3770 16
            [$matrixRows, $matrixColumns] = self::getMatrixDimensions($operand1);
3771 16
            $operand2 = array_fill(0, $matrixRows, array_fill(0, $matrixColumns, $operand2));
3772 16
            $resize = 0;
3773
        }
3774
3775 64
        [$matrix1Rows, $matrix1Columns] = self::getMatrixDimensions($operand1);
3776 64
        [$matrix2Rows, $matrix2Columns] = self::getMatrixDimensions($operand2);
3777 64
        if ($resize === 3) {
3778 22
            $resize = 2;
3779 45
        } elseif (($matrix1Rows == $matrix2Columns) && ($matrix2Rows == $matrix1Columns)) {
3780 37
            $resize = 1;
3781
        }
3782
3783 64
        if ($resize == 2) {
3784
            //    Given two matrices of (potentially) unequal size, convert the smaller in each dimension to match the larger
3785 24
            self::resizeMatricesExtend($operand1, $operand2, $matrix1Rows, $matrix1Columns, $matrix2Rows, $matrix2Columns);
3786 44
        } elseif ($resize == 1) {
3787
            //    Given two matrices of (potentially) unequal size, convert the larger in each dimension to match the smaller
3788 37
            self::resizeMatricesShrink($operand1, $operand2, $matrix1Rows, $matrix1Columns, $matrix2Rows, $matrix2Columns);
3789
        }
3790 64
        [$matrix1Rows, $matrix1Columns] = self::getMatrixDimensions($operand1);
3791 64
        [$matrix2Rows, $matrix2Columns] = self::getMatrixDimensions($operand2);
3792
3793 64
        return [$matrix1Rows, $matrix1Columns, $matrix2Rows, $matrix2Columns];
3794
    }
3795
3796
    /**
3797
     * Read the dimensions of a matrix, and re-index it with straight numeric keys starting from row 0, column 0.
3798
     *
3799
     * @param array $matrix matrix operand
3800
     *
3801
     * @return int[] An array comprising the number of rows, and number of columns
3802
     */
3803 100
    public static function getMatrixDimensions(array &$matrix): array
3804
    {
3805 100
        $matrixRows = count($matrix);
3806 100
        $matrixColumns = 0;
3807 100
        foreach ($matrix as $rowKey => $rowValue) {
3808 98
            if (!is_array($rowValue)) {
3809 4
                $matrix[$rowKey] = [$rowValue];
3810 4
                $matrixColumns = max(1, $matrixColumns);
3811
            } else {
3812 94
                $matrix[$rowKey] = array_values($rowValue);
3813 94
                $matrixColumns = max(count($rowValue), $matrixColumns);
3814
            }
3815
        }
3816 100
        $matrix = array_values($matrix);
3817
3818 100
        return [$matrixRows, $matrixColumns];
3819
    }
3820
3821
    /**
3822
     * Ensure that paired matrix operands are both matrices of the same size.
3823
     *
3824
     * @param array $matrix1 First matrix operand
3825
     * @param array $matrix2 Second matrix operand
3826
     * @param int $matrix1Rows Row size of first matrix operand
3827
     * @param int $matrix1Columns Column size of first matrix operand
3828
     * @param int $matrix2Rows Row size of second matrix operand
3829
     * @param int $matrix2Columns Column size of second matrix operand
3830
     */
3831 37
    private static function resizeMatricesShrink(array &$matrix1, array &$matrix2, int $matrix1Rows, int $matrix1Columns, int $matrix2Rows, int $matrix2Columns): void
3832
    {
3833 37
        if (($matrix2Columns < $matrix1Columns) || ($matrix2Rows < $matrix1Rows)) {
3834
            if ($matrix2Rows < $matrix1Rows) {
3835
                for ($i = $matrix2Rows; $i < $matrix1Rows; ++$i) {
3836
                    unset($matrix1[$i]);
3837
                }
3838
            }
3839
            if ($matrix2Columns < $matrix1Columns) {
3840
                for ($i = 0; $i < $matrix1Rows; ++$i) {
3841
                    for ($j = $matrix2Columns; $j < $matrix1Columns; ++$j) {
3842
                        unset($matrix1[$i][$j]);
3843
                    }
3844
                }
3845
            }
3846
        }
3847
3848 37
        if (($matrix1Columns < $matrix2Columns) || ($matrix1Rows < $matrix2Rows)) {
3849
            if ($matrix1Rows < $matrix2Rows) {
3850
                for ($i = $matrix1Rows; $i < $matrix2Rows; ++$i) {
3851
                    unset($matrix2[$i]);
3852
                }
3853
            }
3854
            if ($matrix1Columns < $matrix2Columns) {
3855
                for ($i = 0; $i < $matrix2Rows; ++$i) {
3856
                    for ($j = $matrix1Columns; $j < $matrix2Columns; ++$j) {
3857
                        unset($matrix2[$i][$j]);
3858
                    }
3859
                }
3860
            }
3861
        }
3862
    }
3863
3864
    /**
3865
     * Ensure that paired matrix operands are both matrices of the same size.
3866
     *
3867
     * @param array $matrix1 First matrix operand
3868
     * @param array $matrix2 Second matrix operand
3869
     * @param int $matrix1Rows Row size of first matrix operand
3870
     * @param int $matrix1Columns Column size of first matrix operand
3871
     * @param int $matrix2Rows Row size of second matrix operand
3872
     * @param int $matrix2Columns Column size of second matrix operand
3873
     */
3874 24
    private static function resizeMatricesExtend(array &$matrix1, array &$matrix2, int $matrix1Rows, int $matrix1Columns, int $matrix2Rows, int $matrix2Columns): void
3875
    {
3876 24
        if (($matrix2Columns < $matrix1Columns) || ($matrix2Rows < $matrix1Rows)) {
3877 16
            if ($matrix2Columns < $matrix1Columns) {
3878 15
                for ($i = 0; $i < $matrix2Rows; ++$i) {
3879 15
                    $x = $matrix2[$i][$matrix2Columns - 1];
3880 15
                    for ($j = $matrix2Columns; $j < $matrix1Columns; ++$j) {
3881 15
                        $matrix2[$i][$j] = $x;
3882
                    }
3883
                }
3884
            }
3885 16
            if ($matrix2Rows < $matrix1Rows) {
3886 2
                $x = $matrix2[$matrix2Rows - 1];
3887 2
                for ($i = 0; $i < $matrix1Rows; ++$i) {
3888 2
                    $matrix2[$i] = $x;
3889
                }
3890
            }
3891
        }
3892
3893 24
        if (($matrix1Columns < $matrix2Columns) || ($matrix1Rows < $matrix2Rows)) {
3894 15
            if ($matrix1Columns < $matrix2Columns) {
3895
                for ($i = 0; $i < $matrix1Rows; ++$i) {
3896
                    $x = $matrix1[$i][$matrix1Columns - 1];
3897
                    for ($j = $matrix1Columns; $j < $matrix2Columns; ++$j) {
3898
                        $matrix1[$i][$j] = $x;
3899
                    }
3900
                }
3901
            }
3902 15
            if ($matrix1Rows < $matrix2Rows) {
3903 15
                $x = $matrix1[$matrix1Rows - 1];
3904 15
                for ($i = 0; $i < $matrix2Rows; ++$i) {
3905 15
                    $matrix1[$i] = $x;
3906
                }
3907
            }
3908
        }
3909
    }
3910
3911
    /**
3912
     * Format details of an operand for display in the log (based on operand type).
3913
     *
3914
     * @param mixed $value First matrix operand
3915
     */
3916 11622
    private function showValue(mixed $value): mixed
3917
    {
3918 11622
        if ($this->debugLog->getWriteDebugLog()) {
3919 3
            $testArray = Functions::flattenArray($value);
3920 3
            if (count($testArray) == 1) {
3921 3
                $value = array_pop($testArray);
3922
            }
3923
3924 3
            if (is_array($value)) {
3925 2
                $returnMatrix = [];
3926 2
                $pad = $rpad = ', ';
3927 2
                foreach ($value as $row) {
3928 2
                    if (is_array($row)) {
3929 2
                        $returnMatrix[] = implode($pad, array_map([$this, 'showValue'], $row));
3930 2
                        $rpad = '; ';
3931
                    } else {
3932
                        $returnMatrix[] = $this->showValue($row);
3933
                    }
3934
                }
3935
3936 2
                return '{ ' . implode($rpad, $returnMatrix) . ' }';
3937 3
            } elseif (is_string($value) && (trim($value, self::FORMULA_STRING_QUOTE) == $value)) {
3938 2
                return self::FORMULA_STRING_QUOTE . $value . self::FORMULA_STRING_QUOTE;
3939 3
            } elseif (is_bool($value)) {
3940
                return ($value) ? self::$localeBoolean['TRUE'] : self::$localeBoolean['FALSE'];
3941 3
            } elseif ($value === null) {
3942
                return self::$localeBoolean['NULL'];
3943
            }
3944
        }
3945
3946 11622
        return Functions::flattenSingleValue($value);
3947
    }
3948
3949
    /**
3950
     * Format type and details of an operand for display in the log (based on operand type).
3951
     *
3952
     * @param mixed $value First matrix operand
3953
     */
3954 11637
    private function showTypeDetails(mixed $value): ?string
3955
    {
3956 11637
        if ($this->debugLog->getWriteDebugLog()) {
3957 3
            $testArray = Functions::flattenArray($value);
3958 3
            if (count($testArray) == 1) {
3959 3
                $value = array_pop($testArray);
3960
            }
3961
3962 3
            if ($value === null) {
3963
                return 'a NULL value';
3964 3
            } elseif (is_float($value)) {
3965 3
                $typeString = 'a floating point number';
3966 3
            } elseif (is_int($value)) {
3967 3
                $typeString = 'an integer number';
3968 2
            } elseif (is_bool($value)) {
3969
                $typeString = 'a boolean';
3970 2
            } elseif (is_array($value)) {
3971 2
                $typeString = 'a matrix';
3972
            } else {
3973
                if ($value == '') {
3974
                    return 'an empty string';
3975
                } elseif ($value[0] == '#') {
3976
                    return 'a ' . $value . ' error';
3977
                }
3978
                $typeString = 'a string';
3979
            }
3980
3981 3
            return $typeString . ' with a value of ' . $this->showValue($value);
3982
        }
3983
3984 11634
        return null;
3985
    }
3986
3987
    /**
3988
     * @return false|string False indicates an error
3989
     */
3990 12024
    private function convertMatrixReferences(string $formula): false|string
3991
    {
3992 12024
        static $matrixReplaceFrom = [self::FORMULA_OPEN_MATRIX_BRACE, ';', self::FORMULA_CLOSE_MATRIX_BRACE];
3993 12024
        static $matrixReplaceTo = ['MKMATRIX(MKMATRIX(', '),MKMATRIX(', '))'];
3994
3995
        //    Convert any Excel matrix references to the MKMATRIX() function
3996 12024
        if (str_contains($formula, self::FORMULA_OPEN_MATRIX_BRACE)) {
3997
            //    If there is the possibility of braces within a quoted string, then we don't treat those as matrix indicators
3998 797
            if (str_contains($formula, self::FORMULA_STRING_QUOTE)) {
3999
                //    So instead we skip replacing in any quoted strings by only replacing in every other array element after we've exploded
4000
                //        the formula
4001 246
                $temp = explode(self::FORMULA_STRING_QUOTE, $formula);
4002
                //    Open and Closed counts used for trapping mismatched braces in the formula
4003 246
                $openCount = $closeCount = 0;
4004 246
                $notWithinQuotes = false;
4005 246
                foreach ($temp as &$value) {
4006
                    //    Only count/replace in alternating array entries
4007 246
                    $notWithinQuotes = $notWithinQuotes === false;
4008 246
                    if ($notWithinQuotes === true) {
4009 246
                        $openCount += substr_count($value, self::FORMULA_OPEN_MATRIX_BRACE);
4010 246
                        $closeCount += substr_count($value, self::FORMULA_CLOSE_MATRIX_BRACE);
4011 246
                        $value = str_replace($matrixReplaceFrom, $matrixReplaceTo, $value);
4012
                    }
4013
                }
4014 246
                unset($value);
4015
                //    Then rebuild the formula string
4016 246
                $formula = implode(self::FORMULA_STRING_QUOTE, $temp);
4017
            } else {
4018
                //    If there's no quoted strings, then we do a simple count/replace
4019 553
                $openCount = substr_count($formula, self::FORMULA_OPEN_MATRIX_BRACE);
4020 553
                $closeCount = substr_count($formula, self::FORMULA_CLOSE_MATRIX_BRACE);
4021 553
                $formula = str_replace($matrixReplaceFrom, $matrixReplaceTo, $formula);
4022
            }
4023
            //    Trap for mismatched braces and trigger an appropriate error
4024 797
            if ($openCount < $closeCount) {
4025
                if ($openCount > 0) {
4026
                    return $this->raiseFormulaError("Formula Error: Mismatched matrix braces '}'");
4027
                }
4028
4029
                return $this->raiseFormulaError("Formula Error: Unexpected '}' encountered");
4030 797
            } elseif ($openCount > $closeCount) {
4031
                if ($closeCount > 0) {
4032
                    return $this->raiseFormulaError("Formula Error: Mismatched matrix braces '{'");
4033
                }
4034
4035
                return $this->raiseFormulaError("Formula Error: Unexpected '{' encountered");
4036
            }
4037
        }
4038
4039 12024
        return $formula;
4040
    }
4041
4042
    /**
4043
     *    Binary Operators.
4044
     *    These operators always work on two values.
4045
     *    Array key is the operator, the value indicates whether this is a left or right associative operator.
4046
     */
4047
    private static array $operatorAssociativity = [
4048
        '^' => 0, //    Exponentiation
4049
        '*' => 0, '/' => 0, //    Multiplication and Division
4050
        '+' => 0, '-' => 0, //    Addition and Subtraction
4051
        '&' => 0, //    Concatenation
4052
        '∪' => 0, '∩' => 0, ':' => 0, //    Union, Intersect and Range
4053
        '>' => 0, '<' => 0, '=' => 0, '>=' => 0, '<=' => 0, '<>' => 0, //    Comparison
4054
    ];
4055
4056
    /**
4057
     *    Comparison (Boolean) Operators.
4058
     *    These operators work on two values, but always return a boolean result.
4059
     */
4060
    private static array $comparisonOperators = ['>' => true, '<' => true, '=' => true, '>=' => true, '<=' => true, '<>' => true];
4061
4062
    /**
4063
     *    Operator Precedence.
4064
     *    This list includes all valid operators, whether binary (including boolean) or unary (such as %).
4065
     *    Array key is the operator, the value is its precedence.
4066
     */
4067
    private static array $operatorPrecedence = [
4068
        ':' => 9, //    Range
4069
        '∩' => 8, //    Intersect
4070
        '∪' => 7, //    Union
4071
        '~' => 6, //    Negation
4072
        '%' => 5, //    Percentage
4073
        '^' => 4, //    Exponentiation
4074
        '*' => 3, '/' => 3, //    Multiplication and Division
4075
        '+' => 2, '-' => 2, //    Addition and Subtraction
4076
        '&' => 1, //    Concatenation
4077
        '>' => 0, '<' => 0, '=' => 0, '>=' => 0, '<=' => 0, '<>' => 0, //    Comparison
4078
    ];
4079
4080
    // Convert infix to postfix notation
4081
4082
    /**
4083
     * @return array<int, mixed>|false
4084
     */
4085 12024
    private function internalParseFormula(string $formula, ?Cell $cell = null): bool|array
4086
    {
4087 12024
        if (($formula = $this->convertMatrixReferences(trim($formula))) === false) {
4088
            return false;
4089
        }
4090
4091
        //    If we're using cell caching, then $pCell may well be flushed back to the cache (which detaches the parent worksheet),
4092
        //        so we store the parent worksheet so that we can re-attach it when necessary
4093 12024
        $pCellParent = ($cell !== null) ? $cell->getWorksheet() : null;
4094
4095 12024
        $regexpMatchString = '/^((?<string>' . self::CALCULATION_REGEXP_STRING
4096 12024
                                . ')|(?<function>' . self::CALCULATION_REGEXP_FUNCTION
4097 12024
                                . ')|(?<cellRef>' . self::CALCULATION_REGEXP_CELLREF
4098 12024
                                . ')|(?<colRange>' . self::CALCULATION_REGEXP_COLUMN_RANGE
4099 12024
                                . ')|(?<rowRange>' . self::CALCULATION_REGEXP_ROW_RANGE
4100 12024
                                . ')|(?<number>' . self::CALCULATION_REGEXP_NUMBER
4101 12024
                                . ')|(?<openBrace>' . self::CALCULATION_REGEXP_OPENBRACE
4102 12024
                                . ')|(?<structuredReference>' . self::CALCULATION_REGEXP_STRUCTURED_REFERENCE
4103 12024
                                . ')|(?<definedName>' . self::CALCULATION_REGEXP_DEFINEDNAME
4104 12024
                                . ')|(?<error>' . self::CALCULATION_REGEXP_ERROR
4105 12024
                                . '))/sui';
4106
4107
        //    Start with initialisation
4108 12024
        $index = 0;
4109 12024
        $stack = new Stack($this->branchPruner);
4110 12024
        $output = [];
4111 12024
        $expectingOperator = false; //    We use this test in syntax-checking the expression to determine when a
4112
        //        - is a negation or + is a positive operator rather than an operation
4113 12024
        $expectingOperand = false; //    We use this test in syntax-checking the expression to determine whether an operand
4114
        //        should be null in a function call
4115
4116
        //    The guts of the lexical parser
4117
        //    Loop through the formula extracting each operator and operand in turn
4118 12024
        while (true) {
4119
            // Branch pruning: we adapt the output item to the context (it will
4120
            // be used to limit its computation)
4121 12024
            $this->branchPruner->initialiseForLoop();
4122
4123 12024
            $opCharacter = $formula[$index]; //    Get the first character of the value at the current index position
4124
4125
            // Check for two-character operators (e.g. >=, <=, <>)
4126 12024
            if ((isset(self::$comparisonOperators[$opCharacter])) && (strlen($formula) > $index) && isset($formula[$index + 1], self::$comparisonOperators[$formula[$index + 1]])) {
4127 83
                $opCharacter .= $formula[++$index];
4128
            }
4129
            //    Find out if we're currently at the beginning of a number, variable, cell/row/column reference,
4130
            //         function, defined name, structured reference, parenthesis, error or operand
4131 12024
            $isOperandOrFunction = (bool) preg_match($regexpMatchString, substr($formula, $index), $match);
4132
4133 12024
            $expectingOperatorCopy = $expectingOperator;
4134 12024
            if ($opCharacter === '-' && !$expectingOperator) {                //    Is it a negation instead of a minus?
4135
                //    Put a negation on the stack
4136 1146
                $stack->push('Unary Operator', '~');
4137 1146
                ++$index; //        and drop the negation symbol
4138 12024
            } elseif ($opCharacter === '%' && $expectingOperator) {
4139
                //    Put a percentage on the stack
4140 10
                $stack->push('Unary Operator', '%');
4141 10
                ++$index;
4142 12024
            } elseif ($opCharacter === '+' && !$expectingOperator) {            //    Positive (unary plus rather than binary operator plus) can be discarded?
4143 7
                ++$index; //    Drop the redundant plus symbol
4144 12024
            } elseif ((($opCharacter === '~') || ($opCharacter === '∩') || ($opCharacter === '∪')) && (!$isOperandOrFunction)) {
4145
                //    We have to explicitly deny a tilde, union or intersect because they are legal
4146
                return $this->raiseFormulaError("Formula Error: Illegal character '~'"); //        on the stack but not in the input expression
4147 12024
            } elseif ((isset(self::CALCULATION_OPERATORS[$opCharacter]) || $isOperandOrFunction) && $expectingOperator) {    //    Are we putting an operator on the stack?
4148
                while (
4149 1767
                    $stack->count() > 0
4150 1767
                    && ($o2 = $stack->last())
4151 1767
                    && isset(self::CALCULATION_OPERATORS[$o2['value']])
4152 1767
                    && @(self::$operatorAssociativity[$opCharacter] ? self::$operatorPrecedence[$opCharacter] < self::$operatorPrecedence[$o2['value']] : self::$operatorPrecedence[$opCharacter] <= self::$operatorPrecedence[$o2['value']])
4153
                ) {
4154 87
                    $output[] = $stack->pop(); //    Swap operands and higher precedence operators from the stack to the output
4155
                }
4156
4157
                //    Finally put our current operator onto the stack
4158 1767
                $stack->push('Binary Operator', $opCharacter);
4159
4160 1767
                ++$index;
4161 1767
                $expectingOperator = false;
4162 12024
            } elseif ($opCharacter === ')' && $expectingOperator) { //    Are we expecting to close a parenthesis?
4163 11661
                $expectingOperand = false;
4164 11661
                while (($o2 = $stack->pop()) && $o2['value'] !== '(') { //    Pop off the stack back to the last (
4165 1365
                    $output[] = $o2;
4166
                }
4167 11661
                $d = $stack->last(2);
4168
4169
                // Branch pruning we decrease the depth whether is it a function
4170
                // call or a parenthesis
4171 11661
                $this->branchPruner->decrementDepth();
4172
4173 11661
                if (is_array($d) && preg_match('/^' . self::CALCULATION_REGEXP_FUNCTION . '$/miu', $d['value'], $matches)) {
4174
                    //    Did this parenthesis just close a function?
4175
                    try {
4176 11657
                        $this->branchPruner->closingBrace($d['value']);
4177 4
                    } catch (Exception $e) {
4178 4
                        return $this->raiseFormulaError($e->getMessage(), $e->getCode(), $e);
4179
                    }
4180
4181 11657
                    $functionName = $matches[1]; //    Get the function name
4182 11657
                    $d = $stack->pop();
4183 11657
                    $argumentCount = $d['value'] ?? 0; //    See how many arguments there were (argument count is the next value stored on the stack)
4184 11657
                    $output[] = $d; //    Dump the argument count on the output
4185 11657
                    $output[] = $stack->pop(); //    Pop the function and push onto the output
4186 11657
                    if (isset(self::$controlFunctions[$functionName])) {
4187 816
                        $expectedArgumentCount = self::$controlFunctions[$functionName]['argumentCount'];
4188 11654
                    } elseif (isset(self::$phpSpreadsheetFunctions[$functionName])) {
4189 11654
                        $expectedArgumentCount = self::$phpSpreadsheetFunctions[$functionName]['argumentCount'];
4190
                    } else {    // did we somehow push a non-function on the stack? this should never happen
4191
                        return $this->raiseFormulaError('Formula Error: Internal error, non-function on stack');
4192
                    }
4193
                    //    Check the argument count
4194 11657
                    $argumentCountError = false;
4195 11657
                    $expectedArgumentCountString = null;
4196 11657
                    if (is_numeric($expectedArgumentCount)) {
4197 5859
                        if ($expectedArgumentCount < 0) {
4198 36
                            if ($argumentCount > abs($expectedArgumentCount + 0)) {
4199
                                $argumentCountError = true;
4200
                                $expectedArgumentCountString = 'no more than ' . abs($expectedArgumentCount + 0);
4201
                            }
4202
                        } else {
4203 5825
                            if ($argumentCount != $expectedArgumentCount) {
4204 142
                                $argumentCountError = true;
4205 142
                                $expectedArgumentCountString = $expectedArgumentCount;
4206
                            }
4207
                        }
4208 6553
                    } elseif ($expectedArgumentCount != '*') {
4209 6078
                        if (1 !== preg_match('/(\d*)([-+,])(\d*)/', $expectedArgumentCount, $argMatch)) {
4210 1
                            $argMatch = ['', '', '', ''];
4211
                        }
4212 6078
                        switch ($argMatch[2]) {
4213 6078
                            case '+':
4214 1160
                                if ($argumentCount < $argMatch[1]) {
4215 27
                                    $argumentCountError = true;
4216 27
                                    $expectedArgumentCountString = $argMatch[1] . ' or more ';
4217
                                }
4218
4219 1160
                                break;
4220 5083
                            case '-':
4221 872
                                if (($argumentCount < $argMatch[1]) || ($argumentCount > $argMatch[3])) {
4222 15
                                    $argumentCountError = true;
4223 15
                                    $expectedArgumentCountString = 'between ' . $argMatch[1] . ' and ' . $argMatch[3];
4224
                                }
4225
4226 872
                                break;
4227 4250
                            case ',':
4228 4250
                                if (($argumentCount != $argMatch[1]) && ($argumentCount != $argMatch[3])) {
4229 39
                                    $argumentCountError = true;
4230 39
                                    $expectedArgumentCountString = 'either ' . $argMatch[1] . ' or ' . $argMatch[3];
4231
                                }
4232
4233 4250
                                break;
4234
                        }
4235
                    }
4236 11657
                    if ($argumentCountError) {
4237 223
                        return $this->raiseFormulaError("Formula Error: Wrong number of arguments for $functionName() function: $argumentCount given, " . $expectedArgumentCountString . ' expected');
4238
                    }
4239
                }
4240 11441
                ++$index;
4241 12024
            } elseif ($opCharacter === ',') { // Is this the separator for function arguments?
4242
                try {
4243 7954
                    $this->branchPruner->argumentSeparator();
4244
                } catch (Exception $e) {
4245
                    return $this->raiseFormulaError($e->getMessage(), $e->getCode(), $e);
4246
                }
4247
4248 7954
                while (($o2 = $stack->pop()) && $o2['value'] !== '(') {        //    Pop off the stack back to the last (
4249 1437
                    $output[] = $o2; // pop the argument expression stuff and push onto the output
4250
                }
4251
                //    If we've a comma when we're expecting an operand, then what we actually have is a null operand;
4252
                //        so push a null onto the stack
4253 7954
                if (($expectingOperand) || (!$expectingOperator)) {
4254 118
                    $output[] = $stack->getStackItem('Empty Argument', null, 'NULL');
4255
                }
4256
                // make sure there was a function
4257 7954
                $d = $stack->last(2);
4258 7954
                if (!preg_match('/^' . self::CALCULATION_REGEXP_FUNCTION . '$/miu', $d['value'] ?? '', $matches)) {
4259
                    // Can we inject a dummy function at this point so that the braces at least have some context
4260
                    //     because at least the braces are paired up (at this stage in the formula)
4261
                    // MS Excel allows this if the content is cell references; but doesn't allow actual values,
4262
                    //    but at this point, we can't differentiate (so allow both)
4263
                    return $this->raiseFormulaError('Formula Error: Unexpected ,');
4264
                }
4265
4266
                /** @var array $d */
4267 7954
                $d = $stack->pop();
4268 7954
                ++$d['value']; // increment the argument count
4269
4270 7954
                $stack->pushStackItem($d);
4271 7954
                $stack->push('Brace', '('); // put the ( back on, we'll need to pop back to it again
4272
4273 7954
                $expectingOperator = false;
4274 7954
                $expectingOperand = true;
4275 7954
                ++$index;
4276 12024
            } elseif ($opCharacter === '(' && !$expectingOperator) {
4277
                // Branch pruning: we go deeper
4278 31
                $this->branchPruner->incrementDepth();
4279 31
                $stack->push('Brace', '(', null);
4280 31
                ++$index;
4281 12024
            } elseif ($isOperandOrFunction && !$expectingOperatorCopy) {
4282
                // do we now have a function/variable/number?
4283 12020
                $expectingOperator = true;
4284 12020
                $expectingOperand = false;
4285 12020
                $val = $match[1] ?? ''; //* @phpstan-ignore-line
4286 12020
                $length = strlen($val);
4287
4288 12020
                if (preg_match('/^' . self::CALCULATION_REGEXP_FUNCTION . '$/miu', $val, $matches)) {
4289 11663
                    $val = (string) preg_replace('/\s/u', '', $val);
4290 11663
                    if (isset(self::$phpSpreadsheetFunctions[strtoupper($matches[1])]) || isset(self::$controlFunctions[strtoupper($matches[1])])) {    // it's a function
4291 11661
                        $valToUpper = strtoupper($val);
4292
                    } else {
4293 4
                        $valToUpper = 'NAME.ERROR(';
4294
                    }
4295
                    // here $matches[1] will contain values like "IF"
4296
                    // and $val "IF("
4297
4298 11663
                    $this->branchPruner->functionCall($valToUpper);
4299
4300 11663
                    $stack->push('Function', $valToUpper);
4301
                    // tests if the function is closed right after opening
4302 11663
                    $ax = preg_match('/^\s*\)/u', substr($formula, $index + $length));
4303 11663
                    if ($ax) {
4304 324
                        $stack->push('Operand Count for Function ' . $valToUpper . ')', 0);
4305 324
                        $expectingOperator = true;
4306
                    } else {
4307 11485
                        $stack->push('Operand Count for Function ' . $valToUpper . ')', 1);
4308 11485
                        $expectingOperator = false;
4309
                    }
4310 11663
                    $stack->push('Brace', '(');
4311 11819
                } elseif (preg_match('/^' . self::CALCULATION_REGEXP_CELLREF . '$/miu', $val, $matches)) {
4312
                    //    Watch for this case-change when modifying to allow cell references in different worksheets...
4313
                    //    Should only be applied to the actual cell column, not the worksheet name
4314
                    //    If the last entry on the stack was a : operator, then we have a cell range reference
4315 6957
                    $testPrevOp = $stack->last(1);
4316 6957
                    if ($testPrevOp !== null && $testPrevOp['value'] === ':') {
4317
                        //    If we have a worksheet reference, then we're playing with a 3D reference
4318 1202
                        if ($matches[2] === '') {
4319
                            //    Otherwise, we 'inherit' the worksheet reference from the start cell reference
4320
                            //    The start of the cell range reference should be the last entry in $output
4321 1198
                            $rangeStartCellRef = $output[count($output) - 1]['value'] ?? '';
4322 1198
                            if ($rangeStartCellRef === ':') {
4323
                                // Do we have chained range operators?
4324 5
                                $rangeStartCellRef = $output[count($output) - 2]['value'] ?? '';
4325
                            }
4326 1198
                            preg_match('/^' . self::CALCULATION_REGEXP_CELLREF . '$/miu', $rangeStartCellRef, $rangeStartMatches);
4327 1198
                            if (array_key_exists(2, $rangeStartMatches)) {
4328 1193
                                if ($rangeStartMatches[2] > '') {
4329 1176
                                    $val = $rangeStartMatches[2] . '!' . $val;
4330
                                }
4331
                            } else {
4332 5
                                $val = ExcelError::REF();
4333
                            }
4334
                        } else {
4335 4
                            $rangeStartCellRef = $output[count($output) - 1]['value'] ?? '';
4336 4
                            if ($rangeStartCellRef === ':') {
4337
                                // Do we have chained range operators?
4338
                                $rangeStartCellRef = $output[count($output) - 2]['value'] ?? '';
4339
                            }
4340 4
                            preg_match('/^' . self::CALCULATION_REGEXP_CELLREF . '$/miu', $rangeStartCellRef, $rangeStartMatches);
4341 4
                            if (isset($rangeStartMatches[2]) && $rangeStartMatches[2] !== $matches[2]) {
4342 2
                                return $this->raiseFormulaError('3D Range references are not yet supported');
4343
                            }
4344
                        }
4345 6952
                    } elseif (!str_contains($val, '!') && $pCellParent !== null) {
4346 6749
                        $worksheet = $pCellParent->getTitle();
4347 6749
                        $val = "'{$worksheet}'!{$val}";
4348
                    }
4349
                    // unescape any apostrophes or double quotes in worksheet name
4350 6957
                    $val = str_replace(["''", '""'], ["'", '"'], $val);
4351 6957
                    $outputItem = $stack->getStackItem('Cell Reference', $val, $val);
4352
4353 6957
                    $output[] = $outputItem;
4354 6285
                } elseif (preg_match('/^' . self::CALCULATION_REGEXP_STRUCTURED_REFERENCE . '$/miu', $val, $matches)) {
4355
                    try {
4356 75
                        $structuredReference = Operands\StructuredReference::fromParser($formula, $index, $matches);
4357
                    } catch (Exception $e) {
4358
                        return $this->raiseFormulaError($e->getMessage(), $e->getCode(), $e);
4359
                    }
4360
4361 75
                    $val = $structuredReference->value();
4362 75
                    $length = strlen($val);
4363 75
                    $outputItem = $stack->getStackItem(Operands\StructuredReference::NAME, $structuredReference, null);
4364
4365 75
                    $output[] = $outputItem;
4366 75
                    $expectingOperator = true;
4367
                } else {
4368
                    // it's a variable, constant, string, number or boolean
4369 6219
                    $localeConstant = false;
4370 6219
                    $stackItemType = 'Value';
4371 6219
                    $stackItemReference = null;
4372
4373
                    //    If the last entry on the stack was a : operator, then we may have a row or column range reference
4374 6219
                    $testPrevOp = $stack->last(1);
4375 6219
                    if ($testPrevOp !== null && $testPrevOp['value'] === ':') {
4376 35
                        $stackItemType = 'Cell Reference';
4377
4378
                        if (
4379 35
                            !is_numeric($val)
4380 35
                            && ((ctype_alpha($val) === false || strlen($val) > 3))
4381 35
                            && (preg_match('/^' . self::CALCULATION_REGEXP_DEFINEDNAME . '$/mui', $val) !== false)
4382 35
                            && ($this->spreadsheet === null || $this->spreadsheet->getNamedRange($val) !== null)
4383
                        ) {
4384 10
                            $namedRange = ($this->spreadsheet === null) ? null : $this->spreadsheet->getNamedRange($val);
4385 10
                            if ($namedRange !== null) {
4386 4
                                $stackItemType = 'Defined Name';
4387 4
                                $address = str_replace('$', '', $namedRange->getValue());
4388 4
                                $stackItemReference = $val;
4389 4
                                if (str_contains($address, ':')) {
4390
                                    // We'll need to manipulate the stack for an actual named range rather than a named cell
4391 3
                                    $fromTo = explode(':', $address);
4392 3
                                    $to = array_pop($fromTo);
4393 3
                                    foreach ($fromTo as $from) {
4394 3
                                        $output[] = $stack->getStackItem($stackItemType, $from, $stackItemReference);
4395 3
                                        $output[] = $stack->getStackItem('Binary Operator', ':');
4396
                                    }
4397 3
                                    $address = $to;
4398
                                }
4399 4
                                $val = $address;
4400
                            }
4401 31
                        } elseif ($val === ExcelError::REF()) {
4402 3
                            $stackItemReference = $val;
4403
                        } else {
4404
                            /** @var non-empty-string $startRowColRef */
4405 28
                            $startRowColRef = $output[count($output) - 1]['value'] ?? '';
4406 28
                            [$rangeWS1, $startRowColRef] = Worksheet::extractSheetTitle($startRowColRef, true);
4407 28
                            $rangeSheetRef = $rangeWS1;
4408 28
                            if ($rangeWS1 !== '') {
4409 18
                                $rangeWS1 .= '!';
4410
                            }
4411 28
                            $rangeSheetRef = trim($rangeSheetRef, "'");
4412 28
                            [$rangeWS2, $val] = Worksheet::extractSheetTitle($val, true);
4413 28
                            if ($rangeWS2 !== '') {
4414
                                $rangeWS2 .= '!';
4415
                            } else {
4416 28
                                $rangeWS2 = $rangeWS1;
4417
                            }
4418
4419 28
                            $refSheet = $pCellParent;
4420 28
                            if ($pCellParent !== null && $rangeSheetRef !== '' && $rangeSheetRef !== $pCellParent->getTitle()) {
4421 4
                                $refSheet = $pCellParent->getParentOrThrow()->getSheetByName($rangeSheetRef);
4422
                            }
4423
4424 28
                            if (ctype_digit($val) && $val <= 1048576) {
4425
                                //    Row range
4426 8
                                $stackItemType = 'Row Reference';
4427
                                /** @var int $valx */
4428 8
                                $valx = $val;
4429 8
                                $endRowColRef = ($refSheet !== null) ? $refSheet->getHighestDataColumn($valx) : AddressRange::MAX_COLUMN; //    Max 16,384 columns for Excel2007
4430 8
                                $val = "{$rangeWS2}{$endRowColRef}{$val}";
4431 20
                            } elseif (ctype_alpha($val) && is_string($val) && strlen($val) <= 3) {
4432
                                //    Column range
4433 14
                                $stackItemType = 'Column Reference';
4434 14
                                $endRowColRef = ($refSheet !== null) ? $refSheet->getHighestDataRow($val) : AddressRange::MAX_ROW; //    Max 1,048,576 rows for Excel2007
4435 14
                                $val = "{$rangeWS2}{$val}{$endRowColRef}";
4436
                            }
4437 28
                            $stackItemReference = $val;
4438
                        }
4439 6214
                    } elseif ($opCharacter === self::FORMULA_STRING_QUOTE) {
4440
                        //    UnEscape any quotes within the string
4441 2798
                        $val = self::wrapResult(str_replace('""', self::FORMULA_STRING_QUOTE, self::unwrapResult($val)));
4442 4615
                    } elseif (isset(self::$excelConstants[trim(strtoupper($val))])) {
4443 553
                        $stackItemType = 'Constant';
4444 553
                        $excelConstant = trim(strtoupper($val));
4445 553
                        $val = self::$excelConstants[$excelConstant];
4446 553
                        $stackItemReference = $excelConstant;
4447 4328
                    } elseif (($localeConstant = array_search(trim(strtoupper($val)), self::$localeBoolean)) !== false) {
4448 37
                        $stackItemType = 'Constant';
4449 37
                        $val = self::$excelConstants[$localeConstant];
4450 37
                        $stackItemReference = $localeConstant;
4451
                    } elseif (
4452 4309
                        preg_match('/^' . self::CALCULATION_REGEXP_ROW_RANGE . '/miu', substr($formula, $index), $rowRangeReference)
4453
                    ) {
4454 8
                        $val = $rowRangeReference[1];
4455 8
                        $length = strlen($rowRangeReference[1]);
4456 8
                        $stackItemType = 'Row Reference';
4457
                        // unescape any apostrophes or double quotes in worksheet name
4458 8
                        $val = str_replace(["''", '""'], ["'", '"'], $val);
4459 8
                        $column = 'A';
4460 8
                        if (($testPrevOp !== null && $testPrevOp['value'] === ':') && $pCellParent !== null) {
4461
                            $column = $pCellParent->getHighestDataColumn($val);
4462
                        }
4463 8
                        $val = "{$rowRangeReference[2]}{$column}{$rowRangeReference[7]}";
4464 8
                        $stackItemReference = $val;
4465
                    } elseif (
4466 4302
                        preg_match('/^' . self::CALCULATION_REGEXP_COLUMN_RANGE . '/miu', substr($formula, $index), $columnRangeReference)
4467
                    ) {
4468 14
                        $val = $columnRangeReference[1];
4469 14
                        $length = strlen($val);
4470 14
                        $stackItemType = 'Column Reference';
4471
                        // unescape any apostrophes or double quotes in worksheet name
4472 14
                        $val = str_replace(["''", '""'], ["'", '"'], $val);
4473 14
                        $row = '1';
4474 14
                        if (($testPrevOp !== null && $testPrevOp['value'] === ':') && $pCellParent !== null) {
4475
                            $row = $pCellParent->getHighestDataRow($val);
4476
                        }
4477 14
                        $val = "{$val}{$row}";
4478 14
                        $stackItemReference = $val;
4479 4288
                    } elseif (preg_match('/^' . self::CALCULATION_REGEXP_DEFINEDNAME . '.*/miu', $val, $match)) {
4480 146
                        $stackItemType = 'Defined Name';
4481 146
                        $stackItemReference = $val;
4482 4169
                    } elseif (is_numeric($val)) {
4483 4163
                        if ((str_contains((string) $val, '.')) || (stripos((string) $val, 'e') !== false) || ($val > PHP_INT_MAX) || ($val < -PHP_INT_MAX)) {
4484 1669
                            $val = (float) $val;
4485
                        } else {
4486 3408
                            $val = (int) $val;
4487
                        }
4488
                    }
4489
4490 6219
                    $details = $stack->getStackItem($stackItemType, $val, $stackItemReference);
4491 6219
                    if ($localeConstant) {
4492 37
                        $details['localeValue'] = $localeConstant;
4493
                    }
4494 6219
                    $output[] = $details;
4495
                }
4496 12020
                $index += $length;
4497 95
            } elseif ($opCharacter === '$') { // absolute row or column range
4498 6
                ++$index;
4499 89
            } elseif ($opCharacter === ')') { // miscellaneous error checking
4500 83
                if ($expectingOperand) {
4501 83
                    $output[] = $stack->getStackItem('Empty Argument', null, 'NULL');
4502 83
                    $expectingOperand = false;
4503 83
                    $expectingOperator = true;
4504
                } else {
4505
                    return $this->raiseFormulaError("Formula Error: Unexpected ')'");
4506
                }
4507 6
            } elseif (isset(self::CALCULATION_OPERATORS[$opCharacter]) && !$expectingOperator) {
4508
                return $this->raiseFormulaError("Formula Error: Unexpected operator '$opCharacter'");
4509
            } else {    // I don't even want to know what you did to get here
4510 6
                return $this->raiseFormulaError('Formula Error: An unexpected error occurred');
4511
            }
4512
            //    Test for end of formula string
4513 12020
            if ($index == strlen($formula)) {
4514
                //    Did we end with an operator?.
4515
                //    Only valid for the % unary operator
4516 11796
                if ((isset(self::CALCULATION_OPERATORS[$opCharacter])) && ($opCharacter != '%')) {
4517 1
                    return $this->raiseFormulaError("Formula Error: Operator '$opCharacter' has no operands");
4518
                }
4519
4520 11795
                break;
4521
            }
4522
            //    Ignore white space
4523 11995
            while (($formula[$index] === "\n") || ($formula[$index] === "\r")) {
4524
                ++$index;
4525
            }
4526
4527 11995
            if ($formula[$index] === ' ') {
4528 2041
                while ($formula[$index] === ' ') {
4529 2041
                    ++$index;
4530
                }
4531
4532
                //    If we're expecting an operator, but only have a space between the previous and next operands (and both are
4533
                //        Cell References, Defined Names or Structured References) then we have an INTERSECTION operator
4534 2041
                $countOutputMinus1 = count($output) - 1;
4535
                if (
4536 2041
                    ($expectingOperator)
4537 2041
                    && array_key_exists($countOutputMinus1, $output)
4538 2041
                    && is_array($output[$countOutputMinus1])
4539 2041
                    && array_key_exists('type', $output[$countOutputMinus1])
4540
                    && (
4541 2041
                        (preg_match('/^' . self::CALCULATION_REGEXP_CELLREF . '.*/miu', substr($formula, $index), $match))
4542 2041
                            && ($output[$countOutputMinus1]['type'] === 'Cell Reference')
4543 2041
                        || (preg_match('/^' . self::CALCULATION_REGEXP_DEFINEDNAME . '.*/miu', substr($formula, $index), $match))
4544 2041
                            && ($output[$countOutputMinus1]['type'] === 'Defined Name' || $output[$countOutputMinus1]['type'] === 'Value')
4545 2041
                        || (preg_match('/^' . self::CALCULATION_REGEXP_STRUCTURED_REFERENCE . '.*/miu', substr($formula, $index), $match))
4546 2041
                            && ($output[$countOutputMinus1]['type'] === Operands\StructuredReference::NAME || $output[$countOutputMinus1]['type'] === 'Value')
4547
                    )
4548
                ) {
4549
                    while (
4550 18
                        $stack->count() > 0
4551 18
                        && ($o2 = $stack->last())
4552 18
                        && isset(self::CALCULATION_OPERATORS[$o2['value']])
4553 18
                        && @(self::$operatorAssociativity[$opCharacter] ? self::$operatorPrecedence[$opCharacter] < self::$operatorPrecedence[$o2['value']] : self::$operatorPrecedence[$opCharacter] <= self::$operatorPrecedence[$o2['value']])
4554
                    ) {
4555 11
                        $output[] = $stack->pop(); //    Swap operands and higher precedence operators from the stack to the output
4556
                    }
4557 18
                    $stack->push('Binary Operator', '∩'); //    Put an Intersect Operator on the stack
4558 18
                    $expectingOperator = false;
4559
                }
4560
            }
4561
        }
4562
4563 11795
        while (($op = $stack->pop()) !== null) {
4564
            // pop everything off the stack and push onto output
4565 705
            if ((is_array($op) && $op['value'] == '(')) {
4566 4
                return $this->raiseFormulaError("Formula Error: Expecting ')'"); // if there are any opening braces on the stack, then braces were unbalanced
4567
            }
4568 703
            $output[] = $op;
4569
        }
4570
4571 11793
        return $output;
4572
    }
4573
4574 1646
    private static function dataTestReference(array &$operandData): mixed
4575
    {
4576 1646
        $operand = $operandData['value'];
4577 1646
        if (($operandData['reference'] === null) && (is_array($operand))) {
4578 42
            $rKeys = array_keys($operand);
4579 42
            $rowKey = array_shift($rKeys);
4580 42
            if (is_array($operand[$rowKey]) === false) {
4581 6
                $operandData['value'] = $operand[$rowKey];
4582
4583 6
                return $operand[$rowKey];
4584
            }
4585
4586 40
            $cKeys = array_keys(array_keys($operand[$rowKey]));
4587 40
            $colKey = array_shift($cKeys);
4588 40
            if (ctype_upper("$colKey")) {
4589
                $operandData['reference'] = $colKey . $rowKey;
4590
            }
4591
        }
4592
4593 1646
        return $operand;
4594
    }
4595
4596
    private static int $matchIndex8 = 8;
4597
4598
    private static int $matchIndex9 = 9;
4599
4600
    private static int $matchIndex10 = 10;
4601
4602
    /**
4603
     * @return array<int, mixed>|false|string
4604
     */
4605 11663
    private function processTokenStack(mixed $tokens, ?string $cellID = null, ?Cell $cell = null)
4606
    {
4607 11663
        if ($tokens === false) {
4608 2
            return false;
4609
        }
4610
4611
        //    If we're using cell caching, then $pCell may well be flushed back to the cache (which detaches the parent cell collection),
4612
        //        so we store the parent cell collection so that we can re-attach it when necessary
4613 11662
        $pCellWorksheet = ($cell !== null) ? $cell->getWorksheet() : null;
4614 11662
        $originalCoordinate = $cell?->getCoordinate();
4615 11662
        $pCellParent = ($cell !== null) ? $cell->getParent() : null;
4616 11662
        $stack = new Stack($this->branchPruner);
4617
4618
        // Stores branches that have been pruned
4619 11662
        $fakedForBranchPruning = [];
4620
        // help us to know when pruning ['branchTestId' => true/false]
4621 11662
        $branchStore = [];
4622
        //    Loop through each token in turn
4623 11662
        foreach ($tokens as $tokenIdx => $tokenData) {
4624 11662
            $this->processingAnchorArray = false;
4625 11662
            if ($tokenData['type'] === 'Cell Reference' && isset($tokens[$tokenIdx + 1]) && $tokens[$tokenIdx + 1]['type'] === 'Operand Count for Function ANCHORARRAY()') {
4626 5
                $this->processingAnchorArray = true;
4627
            }
4628 11662
            $token = $tokenData['value'];
4629
            // Branch pruning: skip useless resolutions
4630 11662
            $storeKey = $tokenData['storeKey'] ?? null;
4631 11662
            if ($this->branchPruningEnabled && isset($tokenData['onlyIf'])) {
4632 83
                $onlyIfStoreKey = $tokenData['onlyIf'];
4633 83
                $storeValue = $branchStore[$onlyIfStoreKey] ?? null;
4634 83
                $storeValueAsBool = ($storeValue === null)
4635 83
                    ? true : (bool) Functions::flattenSingleValue($storeValue);
4636 83
                if (is_array($storeValue)) {
4637 56
                    $wrappedItem = end($storeValue);
4638 56
                    $storeValue = is_array($wrappedItem) ? end($wrappedItem) : $wrappedItem;
4639
                }
4640
4641
                if (
4642 83
                    (isset($storeValue) || $tokenData['reference'] === 'NULL')
4643 83
                    && (!$storeValueAsBool || Information\ErrorValue::isError($storeValue) || ($storeValue === 'Pruned branch'))
4644
                ) {
4645
                    // If branching value is not true, we don't need to compute
4646 60
                    if (!isset($fakedForBranchPruning['onlyIf-' . $onlyIfStoreKey])) {
4647 58
                        $stack->push('Value', 'Pruned branch (only if ' . $onlyIfStoreKey . ') ' . $token);
4648 58
                        $fakedForBranchPruning['onlyIf-' . $onlyIfStoreKey] = true;
4649
                    }
4650
4651 60
                    if (isset($storeKey)) {
4652
                        // We are processing an if condition
4653
                        // We cascade the pruning to the depending branches
4654 3
                        $branchStore[$storeKey] = 'Pruned branch';
4655 3
                        $fakedForBranchPruning['onlyIfNot-' . $storeKey] = true;
4656 3
                        $fakedForBranchPruning['onlyIf-' . $storeKey] = true;
4657
                    }
4658
4659 60
                    continue;
4660
                }
4661
            }
4662
4663 11662
            if ($this->branchPruningEnabled && isset($tokenData['onlyIfNot'])) {
4664 78
                $onlyIfNotStoreKey = $tokenData['onlyIfNot'];
4665 78
                $storeValue = $branchStore[$onlyIfNotStoreKey] ?? null;
4666 78
                $storeValueAsBool = ($storeValue === null)
4667 78
                    ? true : (bool) Functions::flattenSingleValue($storeValue);
4668 78
                if (is_array($storeValue)) {
4669 51
                    $wrappedItem = end($storeValue);
4670 51
                    $storeValue = is_array($wrappedItem) ? end($wrappedItem) : $wrappedItem;
4671
                }
4672
4673
                if (
4674 78
                    (isset($storeValue) || $tokenData['reference'] === 'NULL')
4675 78
                    && ($storeValueAsBool || Information\ErrorValue::isError($storeValue) || ($storeValue === 'Pruned branch'))
4676
                ) {
4677
                    // If branching value is true, we don't need to compute
4678 56
                    if (!isset($fakedForBranchPruning['onlyIfNot-' . $onlyIfNotStoreKey])) {
4679 56
                        $stack->push('Value', 'Pruned branch (only if not ' . $onlyIfNotStoreKey . ') ' . $token);
4680 56
                        $fakedForBranchPruning['onlyIfNot-' . $onlyIfNotStoreKey] = true;
4681
                    }
4682
4683 56
                    if (isset($storeKey)) {
4684
                        // We are processing an if condition
4685
                        // We cascade the pruning to the depending branches
4686 10
                        $branchStore[$storeKey] = 'Pruned branch';
4687 10
                        $fakedForBranchPruning['onlyIfNot-' . $storeKey] = true;
4688 10
                        $fakedForBranchPruning['onlyIf-' . $storeKey] = true;
4689
                    }
4690
4691 56
                    continue;
4692
                }
4693
            }
4694
4695 11662
            if ($token instanceof Operands\StructuredReference) {
4696 16
                if ($cell === null) {
4697
                    return $this->raiseFormulaError('Structured References must exist in a Cell context');
4698
                }
4699
4700
                try {
4701 16
                    $cellRange = $token->parse($cell);
4702 16
                    if (str_contains($cellRange, ':')) {
4703 7
                        $this->debugLog->writeDebugLog('Evaluating Structured Reference %s as Cell Range %s', $token->value(), $cellRange);
4704 7
                        $rangeValue = self::getInstance($cell->getWorksheet()->getParent())->_calculateFormulaValue("={$cellRange}", $cellRange, $cell);
4705 7
                        $stack->push('Value', $rangeValue);
4706 7
                        $this->debugLog->writeDebugLog('Evaluated Structured Reference %s as value %s', $token->value(), $this->showValue($rangeValue));
4707
                    } else {
4708 10
                        $this->debugLog->writeDebugLog('Evaluating Structured Reference %s as Cell %s', $token->value(), $cellRange);
4709 10
                        $cellValue = $cell->getWorksheet()->getCell($cellRange)->getCalculatedValue(false);
4710 10
                        $stack->push('Cell Reference', $cellValue, $cellRange);
4711 16
                        $this->debugLog->writeDebugLog('Evaluated Structured Reference %s as value %s', $token->value(), $this->showValue($cellValue));
4712
                    }
4713 2
                } catch (Exception $e) {
4714 2
                    if ($e->getCode() === Exception::CALCULATION_ENGINE_PUSH_TO_STACK) {
4715 2
                        $stack->push('Error', ExcelError::REF(), null);
4716 2
                        $this->debugLog->writeDebugLog('Evaluated Structured Reference %s as error value %s', $token->value(), ExcelError::REF());
4717
                    } else {
4718
                        return $this->raiseFormulaError($e->getMessage(), $e->getCode(), $e);
4719
                    }
4720
                }
4721 11661
            } elseif (!is_numeric($token) && !is_object($token) && isset(self::BINARY_OPERATORS[$token])) {
4722
                // 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
4723
                //    We must have two operands, error if we don't
4724 1646
                $operand2Data = $stack->pop();
4725 1646
                if ($operand2Data === null) {
4726
                    return $this->raiseFormulaError('Internal error - Operand value missing from stack');
4727
                }
4728 1646
                $operand1Data = $stack->pop();
4729 1646
                if ($operand1Data === null) {
4730
                    return $this->raiseFormulaError('Internal error - Operand value missing from stack');
4731
                }
4732
4733 1646
                $operand1 = self::dataTestReference($operand1Data);
4734 1646
                $operand2 = self::dataTestReference($operand2Data);
4735
4736
                //    Log what we're doing
4737 1646
                if ($token == ':') {
4738 1181
                    $this->debugLog->writeDebugLog('Evaluating Range %s %s %s', $this->showValue($operand1Data['reference']), $token, $this->showValue($operand2Data['reference']));
4739
                } else {
4740 714
                    $this->debugLog->writeDebugLog('Evaluating %s %s %s', $this->showValue($operand1), $token, $this->showValue($operand2));
4741
                }
4742
4743
                //    Process the operation in the appropriate manner
4744
                switch ($token) {
4745
                    // Comparison (Boolean) Operators
4746 1646
                    case '>': // Greater than
4747 1633
                    case '<': // Less than
4748 1616
                    case '>=': // Greater than or Equal to
4749 1608
                    case '<=': // Less than or Equal to
4750 1590
                    case '=': // Equality
4751 1440
                    case '<>': // Inequality
4752 404
                        $result = $this->executeBinaryComparisonOperation($operand1, $operand2, (string) $token, $stack);
4753 404
                        if (isset($storeKey)) {
4754 70
                            $branchStore[$storeKey] = $result;
4755
                        }
4756
4757 404
                        break;
4758
                    // Binary Operators
4759 1430
                    case ':': // Range
4760 1181
                        if ($operand1Data['type'] === 'Defined Name') {
4761 3
                            if (preg_match('/$' . self::CALCULATION_REGEXP_DEFINEDNAME . '^/mui', $operand1Data['reference']) !== false && $this->spreadsheet !== null) {
4762 3
                                $definedName = $this->spreadsheet->getNamedRange($operand1Data['reference']);
4763 3
                                if ($definedName !== null) {
4764 3
                                    $operand1Data['reference'] = $operand1Data['value'] = str_replace('$', '', $definedName->getValue());
4765
                                }
4766
                            }
4767
                        }
4768 1181
                        if (str_contains($operand1Data['reference'] ?? '', '!')) {
4769 1175
                            [$sheet1, $operand1Data['reference']] = Worksheet::extractSheetTitle($operand1Data['reference'], true);
4770
                        } else {
4771 10
                            $sheet1 = ($pCellWorksheet !== null) ? $pCellWorksheet->getTitle() : '';
4772
                        }
4773 1181
                        $sheet1 ??= '';
4774
4775 1181
                        [$sheet2, $operand2Data['reference']] = Worksheet::extractSheetTitle($operand2Data['reference'], true);
4776 1181
                        if (empty($sheet2)) {
4777 4
                            $sheet2 = $sheet1;
4778
                        }
4779
4780 1181
                        if (trim($sheet1, "'") === trim($sheet2, "'")) {
4781 1178
                            if ($operand1Data['reference'] === null && $cell !== null) {
4782
                                if (is_array($operand1Data['value'])) {
4783
                                    $operand1Data['reference'] = $cell->getCoordinate();
4784
                                } elseif ((trim($operand1Data['value']) != '') && (is_numeric($operand1Data['value']))) {
4785
                                    $operand1Data['reference'] = $cell->getColumn() . $operand1Data['value'];
4786
                                } elseif (trim($operand1Data['value']) == '') {
4787
                                    $operand1Data['reference'] = $cell->getCoordinate();
4788
                                } else {
4789
                                    $operand1Data['reference'] = $operand1Data['value'] . $cell->getRow();
4790
                                }
4791
                            }
4792 1178
                            if ($operand2Data['reference'] === null && $cell !== null) {
4793 2
                                if (is_array($operand2Data['value'])) {
4794 1
                                    $operand2Data['reference'] = $cell->getCoordinate();
4795 1
                                } elseif ((trim($operand2Data['value']) != '') && (is_numeric($operand2Data['value']))) {
4796
                                    $operand2Data['reference'] = $cell->getColumn() . $operand2Data['value'];
4797 1
                                } elseif (trim($operand2Data['value']) == '') {
4798
                                    $operand2Data['reference'] = $cell->getCoordinate();
4799
                                } else {
4800 1
                                    $operand2Data['reference'] = $operand2Data['value'] . $cell->getRow();
4801
                                }
4802
                            }
4803
4804 1178
                            $oData = array_merge(explode(':', $operand1Data['reference'] ?? ''), explode(':', $operand2Data['reference'] ?? ''));
4805 1178
                            $oCol = $oRow = [];
4806 1178
                            $breakNeeded = false;
4807 1178
                            foreach ($oData as $oDatum) {
4808
                                try {
4809 1178
                                    $oCR = Coordinate::coordinateFromString($oDatum);
4810 1178
                                    $oCol[] = Coordinate::columnIndexFromString($oCR[0]) - 1;
4811 1178
                                    $oRow[] = $oCR[1];
4812 1
                                } catch (\Exception) {
4813 1
                                    $stack->push('Error', ExcelError::REF(), null);
4814 1
                                    $breakNeeded = true;
4815
4816 1
                                    break;
4817
                                }
4818
                            }
4819 1178
                            if ($breakNeeded) {
4820 1
                                break;
4821
                            }
4822 1177
                            $cellRef = Coordinate::stringFromColumnIndex(min($oCol) + 1) . min($oRow) . ':' . Coordinate::stringFromColumnIndex(max($oCol) + 1) . max($oRow);
4823 1177
                            if ($pCellParent !== null && $this->spreadsheet !== null) {
4824 1177
                                $cellValue = $this->extractCellRange($cellRef, $this->spreadsheet->getSheetByName($sheet1), false);
4825
                            } else {
4826
                                return $this->raiseFormulaError('Unable to access Cell Reference');
4827
                            }
4828
4829 1177
                            $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($cellValue));
4830 1177
                            $stack->push('Cell Reference', $cellValue, $cellRef);
4831
                        } else {
4832 4
                            $this->debugLog->writeDebugLog('Evaluation Result is a #REF! Error');
4833 4
                            $stack->push('Error', ExcelError::REF(), null);
4834
                        }
4835
4836 1180
                        break;
4837 374
                    case '+':            //    Addition
4838 296
                    case '-':            //    Subtraction
4839 257
                    case '*':            //    Multiplication
4840 134
                    case '/':            //    Division
4841 42
                    case '^':            //    Exponential
4842 348
                        $result = $this->executeNumericBinaryOperation($operand1, $operand2, $token, $stack);
4843 348
                        if (isset($storeKey)) {
4844 5
                            $branchStore[$storeKey] = $result;
4845
                        }
4846
4847 348
                        break;
4848 39
                    case '&':            //    Concatenation
4849
                        //    If either of the operands is a matrix, we need to treat them both as matrices
4850
                        //        (converting the other operand to a matrix if need be); then perform the required
4851
                        //        matrix operation
4852 25
                        $operand1 = self::boolToString($operand1);
4853 25
                        $operand2 = self::boolToString($operand2);
4854 25
                        if (is_array($operand1) || is_array($operand2)) {
4855 16
                            if (is_string($operand1)) {
4856 7
                                $operand1 = self::unwrapResult($operand1);
4857
                            }
4858 16
                            if (is_string($operand2)) {
4859 5
                                $operand2 = self::unwrapResult($operand2);
4860
                            }
4861
                            //    Ensure that both operands are arrays/matrices
4862 16
                            [$rows, $columns] = self::checkMatrixOperands($operand1, $operand2, 2);
4863
4864 16
                            for ($row = 0; $row < $rows; ++$row) {
4865 16
                                for ($column = 0; $column < $columns; ++$column) {
4866 16
                                    $op1x = self::boolToString($operand1[$row][$column]);
4867 16
                                    $op2x = self::boolToString($operand2[$row][$column]);
4868 16
                                    if (Information\ErrorValue::isError($op1x)) {
4869
                                        // no need to do anything
4870 16
                                    } elseif (Information\ErrorValue::isError($op2x)) {
4871 1
                                        $operand1[$row][$column] = $op2x;
4872
                                    } else {
4873 15
                                        $operand1[$row][$column]
4874 15
                                            = Shared\StringHelper::substring(
4875 15
                                                $op1x . $op2x,
4876 15
                                                0,
4877 15
                                                DataType::MAX_STRING_LENGTH
4878 15
                                            );
4879
                                    }
4880
                                }
4881
                            }
4882 16
                            $result = $operand1;
4883
                        } else {
4884 11
                            if (Information\ErrorValue::isError($operand1)) {
4885
                                $result = $operand1;
4886 11
                            } elseif (Information\ErrorValue::isError($operand2)) {
4887
                                $result = $operand2;
4888
                            } else {
4889 11
                                $result = str_replace('""', self::FORMULA_STRING_QUOTE, self::unwrapResult($operand1) . self::unwrapResult($operand2));
4890 11
                                $result = Shared\StringHelper::substring(
4891 11
                                    $result,
4892 11
                                    0,
4893 11
                                    DataType::MAX_STRING_LENGTH
4894 11
                                );
4895 11
                                $result = self::FORMULA_STRING_QUOTE . $result . self::FORMULA_STRING_QUOTE;
4896
                            }
4897
                        }
4898 25
                        $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($result));
4899 25
                        $stack->push('Value', $result);
4900
4901 25
                        if (isset($storeKey)) {
4902
                            $branchStore[$storeKey] = $result;
4903
                        }
4904
4905 25
                        break;
4906 14
                    case '∩':            //    Intersect
4907 14
                        $rowIntersect = array_intersect_key($operand1, $operand2);
4908 14
                        $cellIntersect = $oCol = $oRow = [];
4909 14
                        foreach (array_keys($rowIntersect) as $row) {
4910 14
                            $oRow[] = $row;
4911 14
                            foreach ($rowIntersect[$row] as $col => $data) {
4912 14
                                $oCol[] = Coordinate::columnIndexFromString($col) - 1;
4913 14
                                $cellIntersect[$row] = array_intersect_key($operand1[$row], $operand2[$row]);
4914
                            }
4915
                        }
4916 14
                        if (count(Functions::flattenArray($cellIntersect)) === 0) {
4917 2
                            $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($cellIntersect));
4918 2
                            $stack->push('Error', ExcelError::null(), null);
4919
                        } else {
4920 12
                            $cellRef = Coordinate::stringFromColumnIndex(min($oCol) + 1) . min($oRow) . ':'
4921 12
                                . Coordinate::stringFromColumnIndex(max($oCol) + 1) . max($oRow);
4922 12
                            $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($cellIntersect));
4923 12
                            $stack->push('Value', $cellIntersect, $cellRef);
4924
                        }
4925
4926 14
                        break;
4927
                }
4928 11654
            } elseif (($token === '~') || ($token === '%')) {
4929
                // if the token is a unary operator, pop one value off the stack, do the operation, and push it back on
4930 1140
                if (($arg = $stack->pop()) === null) {
4931
                    return $this->raiseFormulaError('Internal error - Operand value missing from stack');
4932
                }
4933 1140
                $arg = $arg['value'];
4934 1140
                if ($token === '~') {
4935 1137
                    $this->debugLog->writeDebugLog('Evaluating Negation of %s', $this->showValue($arg));
4936 1137
                    $multiplier = -1;
4937
                } else {
4938 5
                    $this->debugLog->writeDebugLog('Evaluating Percentile of %s', $this->showValue($arg));
4939 5
                    $multiplier = 0.01;
4940
                }
4941 1140
                if (is_array($arg)) {
4942 4
                    $operand2 = $multiplier;
4943 4
                    $result = $arg;
4944 4
                    [$rows, $columns] = self::checkMatrixOperands($result, $operand2, 0);
4945 4
                    for ($row = 0; $row < $rows; ++$row) {
4946 4
                        for ($column = 0; $column < $columns; ++$column) {
4947 4
                            if (self::isNumericOrBool($result[$row][$column])) {
4948 4
                                $result[$row][$column] *= $multiplier;
4949
                            } else {
4950 2
                                $result[$row][$column] = self::makeError($result[$row][$column]);
4951
                            }
4952
                        }
4953
                    }
4954
4955 4
                    $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($result));
4956 4
                    $stack->push('Value', $result);
4957 4
                    if (isset($storeKey)) {
4958
                        $branchStore[$storeKey] = $result;
4959
                    }
4960
                } else {
4961 1139
                    $this->executeNumericBinaryOperation($multiplier, $arg, '*', $stack);
4962
                }
4963 11654
            } elseif (preg_match('/^' . self::CALCULATION_REGEXP_CELLREF . '$/i', $token ?? '', $matches)) {
4964 6854
                $cellRef = null;
4965
4966
                /* Phpstan says matches[8/9/10] is never set,
4967
                   and code coverage report seems to confirm.
4968
                   Appease PhpStan for now;
4969
                   probably delete this block later.
4970
                */
4971 6854
                if (isset($matches[self::$matchIndex8])) {
4972
                    if ($cell === null) {
4973
                        // We can't access the range, so return a REF error
4974
                        $cellValue = ExcelError::REF();
4975
                    } else {
4976
                        $cellRef = $matches[6] . $matches[7] . ':' . $matches[self::$matchIndex9] . $matches[self::$matchIndex10];
4977
                        if ($matches[2] > '') {
4978
                            $matches[2] = trim($matches[2], "\"'");
4979
                            if ((str_contains($matches[2], '[')) || (str_contains($matches[2], ']'))) {
4980
                                //    It's a Reference to an external spreadsheet (not currently supported)
4981
                                return $this->raiseFormulaError('Unable to access External Workbook');
4982
                            }
4983
                            $matches[2] = trim($matches[2], "\"'");
4984
                            $this->debugLog->writeDebugLog('Evaluating Cell Range %s in worksheet %s', $cellRef, $matches[2]);
4985
                            if ($pCellParent !== null && $this->spreadsheet !== null) {
4986
                                $cellValue = $this->extractCellRange($cellRef, $this->spreadsheet->getSheetByName($matches[2]), false);
4987
                            } else {
4988
                                return $this->raiseFormulaError('Unable to access Cell Reference');
4989
                            }
4990
                            $this->debugLog->writeDebugLog('Evaluation Result for cells %s in worksheet %s is %s', $cellRef, $matches[2], $this->showTypeDetails($cellValue));
4991
                        } else {
4992
                            $this->debugLog->writeDebugLog('Evaluating Cell Range %s in current worksheet', $cellRef);
4993
                            if ($pCellParent !== null) {
4994
                                $cellValue = $this->extractCellRange($cellRef, $pCellWorksheet, false);
4995
                            } else {
4996
                                return $this->raiseFormulaError('Unable to access Cell Reference');
4997
                            }
4998
                            $this->debugLog->writeDebugLog('Evaluation Result for cells %s is %s', $cellRef, $this->showTypeDetails($cellValue));
4999
                        }
5000
                    }
5001
                } else {
5002 6854
                    if ($cell === null) {
5003
                        // We can't access the cell, so return a REF error
5004
                        $cellValue = ExcelError::REF();
5005
                    } else {
5006 6854
                        $cellRef = $matches[6] . $matches[7];
5007 6854
                        if ($matches[2] > '') {
5008 6849
                            $matches[2] = trim($matches[2], "\"'");
5009 6849
                            if ((str_contains($matches[2], '[')) || (str_contains($matches[2], ']'))) {
5010
                                //    It's a Reference to an external spreadsheet (not currently supported)
5011 1
                                return $this->raiseFormulaError('Unable to access External Workbook');
5012
                            }
5013 6849
                            $this->debugLog->writeDebugLog('Evaluating Cell %s in worksheet %s', $cellRef, $matches[2]);
5014 6849
                            if ($pCellParent !== null && $this->spreadsheet !== null) {
5015 6849
                                $cellSheet = $this->spreadsheet->getSheetByName($matches[2]);
5016 6849
                                if ($cellSheet && $cellSheet->cellExists($cellRef)) {
5017 6736
                                    $cellValue = $this->extractCellRange($cellRef, $this->spreadsheet->getSheetByName($matches[2]), false);
5018 6736
                                    $cell->attach($pCellParent);
5019
                                } else {
5020 327
                                    $cellRef = ($cellSheet !== null) ? "'{$matches[2]}'!{$cellRef}" : $cellRef;
5021 327
                                    $cellValue = ($cellSheet !== null) ? null : ExcelError::REF();
5022
                                }
5023
                            } else {
5024
                                return $this->raiseFormulaError('Unable to access Cell Reference');
5025
                            }
5026 6849
                            $this->debugLog->writeDebugLog('Evaluation Result for cell %s in worksheet %s is %s', $cellRef, $matches[2], $this->showTypeDetails($cellValue));
5027
                        } else {
5028 9
                            $this->debugLog->writeDebugLog('Evaluating Cell %s in current worksheet', $cellRef);
5029 9
                            if ($pCellParent !== null && $pCellParent->has($cellRef)) {
5030 9
                                $cellValue = $this->extractCellRange($cellRef, $pCellWorksheet, false);
5031 9
                                $cell->attach($pCellParent);
5032
                            } else {
5033 2
                                $cellValue = null;
5034
                            }
5035 9
                            $this->debugLog->writeDebugLog('Evaluation Result for cell %s is %s', $cellRef, $this->showTypeDetails($cellValue));
5036
                        }
5037
                    }
5038
                }
5039
5040 6854
                if ($this->getInstanceArrayReturnType() === self::RETURN_ARRAY_AS_ARRAY && !$this->processingAnchorArray && is_array($cellValue)) {
5041 128
                    while (is_array($cellValue)) {
5042 128
                        $cellValue = array_shift($cellValue);
5043
                    }
5044 128
                    if (is_string($cellValue)) {
5045 94
                        $cellValue = preg_replace('/"/', '""', $cellValue);
5046
                    }
5047 128
                    $this->debugLog->writeDebugLog('Scalar Result for cell %s is %s', $cellRef, $this->showTypeDetails($cellValue));
5048
                }
5049 6854
                $this->processingAnchorArray = false;
5050 6854
                $stack->push('Cell Value', $cellValue, $cellRef);
5051 6854
                if (isset($storeKey)) {
5052 58
                    $branchStore[$storeKey] = $cellValue;
5053
                }
5054 11574
            } elseif (preg_match('/^' . self::CALCULATION_REGEXP_FUNCTION . '$/miu', $token ?? '', $matches)) {
5055
                // if the token is a function, pop arguments off the stack, hand them to the function, and push the result back on
5056 11370
                if ($cell !== null && $pCellParent !== null) {
5057 7800
                    $cell->attach($pCellParent);
5058
                }
5059
5060 11370
                $functionName = $matches[1];
5061 11370
                $argCount = $stack->pop();
5062 11370
                $argCount = $argCount['value'];
5063 11370
                if ($functionName !== 'MKMATRIX') {
5064 11369
                    $this->debugLog->writeDebugLog('Evaluating Function %s() with %s argument%s', self::localeFunc($functionName), (($argCount == 0) ? 'no' : $argCount), (($argCount == 1) ? '' : 's'));
5065
                }
5066 11370
                if ((isset(self::$phpSpreadsheetFunctions[$functionName])) || (isset(self::$controlFunctions[$functionName]))) {    // function
5067 11370
                    $passByReference = false;
5068 11370
                    $passCellReference = false;
5069 11370
                    $functionCall = null;
5070 11370
                    if (isset(self::$phpSpreadsheetFunctions[$functionName])) {
5071 11367
                        $functionCall = self::$phpSpreadsheetFunctions[$functionName]['functionCall'];
5072 11367
                        $passByReference = isset(self::$phpSpreadsheetFunctions[$functionName]['passByReference']);
5073 11367
                        $passCellReference = isset(self::$phpSpreadsheetFunctions[$functionName]['passCellReference']);
5074 815
                    } elseif (isset(self::$controlFunctions[$functionName])) {
5075 815
                        $functionCall = self::$controlFunctions[$functionName]['functionCall'];
5076 815
                        $passByReference = isset(self::$controlFunctions[$functionName]['passByReference']);
5077 815
                        $passCellReference = isset(self::$controlFunctions[$functionName]['passCellReference']);
5078
                    }
5079
5080
                    // get the arguments for this function
5081 11370
                    $args = $argArrayVals = [];
5082 11370
                    $emptyArguments = [];
5083 11370
                    for ($i = 0; $i < $argCount; ++$i) {
5084 11352
                        $arg = $stack->pop();
5085 11352
                        $a = $argCount - $i - 1;
5086
                        if (
5087 11352
                            ($passByReference)
5088 11352
                            && (isset(self::$phpSpreadsheetFunctions[$functionName]['passByReference'][$a]))
5089 11352
                            && (self::$phpSpreadsheetFunctions[$functionName]['passByReference'][$a])
5090
                        ) {
5091 53
                            if ($arg['reference'] === null) {
5092 1
                                $nextArg = $cellID;
5093 1
                                if ($functionName === 'ISREF' && is_array($arg) && ($arg['type'] ?? '') === 'Value') {
5094
                                    if (array_key_exists('value', $arg)) {
5095
                                        $argValue = $arg['value'];
5096
                                        if (is_scalar($argValue)) {
5097
                                            $nextArg = $argValue;
5098
                                        } elseif (empty($argValue)) {
5099
                                            $nextArg = '';
5100
                                        }
5101
                                    }
5102
                                }
5103 1
                                $args[] = $nextArg;
5104 1
                                if ($functionName !== 'MKMATRIX') {
5105 1
                                    $argArrayVals[] = $this->showValue($cellID);
5106
                                }
5107
                            } else {
5108 52
                                $args[] = $arg['reference'];
5109 52
                                if ($functionName !== 'MKMATRIX') {
5110 52
                                    $argArrayVals[] = $this->showValue($arg['reference']);
5111
                                }
5112
                            }
5113
                        } else {
5114 11319
                            if ($arg['type'] === 'Empty Argument' && in_array($functionName, ['MIN', 'MINA', 'MAX', 'MAXA', 'IF'], true)) {
5115 15
                                $emptyArguments[] = false;
5116 15
                                $args[] = $arg['value'] = 0;
5117 15
                                $this->debugLog->writeDebugLog('Empty Argument reevaluated as 0');
5118
                            } else {
5119 11319
                                $emptyArguments[] = $arg['type'] === 'Empty Argument';
5120 11319
                                $args[] = self::unwrapResult($arg['value']);
5121
                            }
5122 11319
                            if ($functionName !== 'MKMATRIX') {
5123 11318
                                $argArrayVals[] = $this->showValue($arg['value']);
5124
                            }
5125
                        }
5126
                    }
5127
5128
                    //    Reverse the order of the arguments
5129 11370
                    krsort($args);
5130 11370
                    krsort($emptyArguments);
5131
5132 11370
                    if ($argCount > 0 && is_array($functionCall)) {
5133 11352
                        $args = $this->addDefaultArgumentValues($functionCall, $args, $emptyArguments);
5134
                    }
5135
5136 11370
                    if (($passByReference) && ($argCount == 0)) {
5137 9
                        $args[] = $cellID;
5138 9
                        $argArrayVals[] = $this->showValue($cellID);
5139
                    }
5140
5141 11370
                    if ($functionName !== 'MKMATRIX') {
5142 11369
                        if ($this->debugLog->getWriteDebugLog()) {
5143 2
                            krsort($argArrayVals);
5144 2
                            $this->debugLog->writeDebugLog('Evaluating %s ( %s )', self::localeFunc($functionName), implode(self::$localeArgumentSeparator . ' ', Functions::flattenArray($argArrayVals)));
5145
                        }
5146
                    }
5147
5148
                    //    Process the argument with the appropriate function call
5149 11370
                    if ($pCellWorksheet !== null && $originalCoordinate !== null) {
5150 7800
                        $pCellWorksheet->getCell($originalCoordinate);
5151
                    }
5152 11370
                    $args = $this->addCellReference($args, $passCellReference, $functionCall, $cell);
5153
5154 11370
                    if (!is_array($functionCall)) {
5155 53
                        foreach ($args as &$arg) {
5156
                            $arg = Functions::flattenSingleValue($arg);
5157
                        }
5158 53
                        unset($arg);
5159
                    }
5160
5161 11370
                    $result = call_user_func_array($functionCall, $args);
5162
5163 11364
                    if ($functionName !== 'MKMATRIX') {
5164 11361
                        $this->debugLog->writeDebugLog('Evaluation Result for %s() function call is %s', self::localeFunc($functionName), $this->showTypeDetails($result));
5165
                    }
5166 11364
                    $stack->push('Value', self::wrapResult($result));
5167 11364
                    if (isset($storeKey)) {
5168 22
                        $branchStore[$storeKey] = $result;
5169
                    }
5170
                }
5171
            } else {
5172
                // if the token is a number, boolean, string or an Excel error, push it onto the stack
5173 11574
                if (isset(self::$excelConstants[strtoupper($token ?? '')])) {
5174
                    $excelConstant = strtoupper($token);
5175
                    $stack->push('Constant Value', self::$excelConstants[$excelConstant]);
5176
                    if (isset($storeKey)) {
5177
                        $branchStore[$storeKey] = self::$excelConstants[$excelConstant];
5178
                    }
5179
                    $this->debugLog->writeDebugLog('Evaluating Constant %s as %s', $excelConstant, $this->showTypeDetails(self::$excelConstants[$excelConstant]));
5180 11574
                } elseif ((is_numeric($token)) || ($token === null) || (is_bool($token)) || ($token == '') || ($token[0] == self::FORMULA_STRING_QUOTE) || ($token[0] == '#')) {
5181 11524
                    $stack->push($tokenData['type'], $token, $tokenData['reference']);
5182 11524
                    if (isset($storeKey)) {
5183 73
                        $branchStore[$storeKey] = $token;
5184
                    }
5185 140
                } elseif (preg_match('/^' . self::CALCULATION_REGEXP_DEFINEDNAME . '$/miu', $token, $matches)) {
5186
                    // if the token is a named range or formula, evaluate it and push the result onto the stack
5187 140
                    $definedName = $matches[6];
5188 140
                    if (str_starts_with($definedName, '_xleta')) {
5189 1
                        return Functions::NOT_YET_IMPLEMENTED;
5190
                    }
5191 139
                    if ($cell === null || $pCellWorksheet === null) {
5192
                        return $this->raiseFormulaError("undefined name '$token'");
5193
                    }
5194 139
                    $specifiedWorksheet = trim($matches[2], "'");
5195
5196 139
                    $this->debugLog->writeDebugLog('Evaluating Defined Name %s', $definedName);
5197 139
                    $namedRange = DefinedName::resolveName($definedName, $pCellWorksheet, $specifiedWorksheet);
5198
                    // If not Defined Name, try as Table.
5199 139
                    if ($namedRange === null && $this->spreadsheet !== null) {
5200 34
                        $table = $this->spreadsheet->getTableByName($definedName);
5201 34
                        if ($table !== null) {
5202 3
                            $tableRange = Coordinate::getRangeBoundaries($table->getRange());
5203 3
                            if ($table->getShowHeaderRow()) {
5204 3
                                ++$tableRange[0][1];
5205
                            }
5206 3
                            if ($table->getShowTotalsRow()) {
5207
                                --$tableRange[1][1];
5208
                            }
5209 3
                            $tableRangeString
5210 3
                                = '$' . $tableRange[0][0]
5211 3
                                . '$' . $tableRange[0][1]
5212 3
                                . ':'
5213 3
                                . '$' . $tableRange[1][0]
5214 3
                                . '$' . $tableRange[1][1];
5215 3
                            $namedRange = new NamedRange($definedName, $table->getWorksheet(), $tableRangeString);
5216
                        }
5217
                    }
5218 139
                    if ($namedRange === null) {
5219 31
                        return $this->raiseFormulaError("undefined name '$definedName'");
5220
                    }
5221
5222 118
                    $result = $this->evaluateDefinedName($cell, $namedRange, $pCellWorksheet, $stack, $specifiedWorksheet !== '');
5223
5224 118
                    if (isset($storeKey)) {
5225 1
                        $branchStore[$storeKey] = $result;
5226
                    }
5227
                } else {
5228
                    return $this->raiseFormulaError("undefined name '$token'");
5229
                }
5230
            }
5231
        }
5232
        // when we're out of tokens, the stack should have a single element, the final result
5233 11633
        if ($stack->count() != 1) {
5234 1
            return $this->raiseFormulaError('internal error');
5235
        }
5236 11633
        $output = $stack->pop();
5237 11633
        $output = $output['value'];
5238
5239 11633
        return $output;
5240
    }
5241
5242 1424
    private function validateBinaryOperand(mixed &$operand, mixed &$stack): bool
5243
    {
5244 1424
        if (is_array($operand)) {
5245 220
            if ((count($operand, COUNT_RECURSIVE) - count($operand)) == 1) {
5246
                do {
5247 188
                    $operand = array_pop($operand);
5248 188
                } while (is_array($operand));
5249
            }
5250
        }
5251
        //    Numbers, matrices and booleans can pass straight through, as they're already valid
5252 1424
        if (is_string($operand)) {
5253
            //    We only need special validations for the operand if it is a string
5254
            //    Start by stripping off the quotation marks we use to identify true excel string values internally
5255 15
            if ($operand > '' && $operand[0] == self::FORMULA_STRING_QUOTE) {
5256 5
                $operand = self::unwrapResult($operand);
5257
            }
5258
            //    If the string is a numeric value, we treat it as a numeric, so no further testing
5259 15
            if (!is_numeric($operand)) {
5260
                //    If not a numeric, test to see if the value is an Excel error, and so can't be used in normal binary operations
5261 14
                if ($operand > '' && $operand[0] == '#') {
5262 6
                    $stack->push('Value', $operand);
5263 6
                    $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($operand));
5264
5265 6
                    return false;
5266 10
                } elseif (Engine\FormattedNumber::convertToNumberIfFormatted($operand) === false) {
5267
                    //    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
5268 6
                    $stack->push('Error', '#VALUE!');
5269 6
                    $this->debugLog->writeDebugLog('Evaluation Result is a %s', $this->showTypeDetails('#VALUE!'));
5270
5271 6
                    return false;
5272
                }
5273
            }
5274
        }
5275
5276
        //    return a true if the value of the operand is one that we can use in normal binary mathematical operations
5277 1422
        return true;
5278
    }
5279
5280 54
    private function executeArrayComparison(mixed $operand1, mixed $operand2, string $operation, Stack &$stack, bool $recursingArrays): array
5281
    {
5282 54
        $result = [];
5283 54
        if (!is_array($operand2)) {
5284
            // Operand 1 is an array, Operand 2 is a scalar
5285 51
            foreach ($operand1 as $x => $operandData) {
5286 51
                $this->debugLog->writeDebugLog('Evaluating Comparison %s %s %s', $this->showValue($operandData), $operation, $this->showValue($operand2));
5287 51
                $this->executeBinaryComparisonOperation($operandData, $operand2, $operation, $stack);
5288 51
                $r = $stack->pop();
5289 51
                $result[$x] = $r['value'];
5290
            }
5291 10
        } elseif (!is_array($operand1)) {
5292
            // Operand 1 is a scalar, Operand 2 is an array
5293 3
            foreach ($operand2 as $x => $operandData) {
5294 3
                $this->debugLog->writeDebugLog('Evaluating Comparison %s %s %s', $this->showValue($operand1), $operation, $this->showValue($operandData));
5295 3
                $this->executeBinaryComparisonOperation($operand1, $operandData, $operation, $stack);
5296 3
                $r = $stack->pop();
5297 3
                $result[$x] = $r['value'];
5298
            }
5299
        } else {
5300
            // Operand 1 and Operand 2 are both arrays
5301 9
            if (!$recursingArrays) {
5302 9
                self::checkMatrixOperands($operand1, $operand2, 2);
5303
            }
5304 9
            foreach ($operand1 as $x => $operandData) {
5305 9
                $this->debugLog->writeDebugLog('Evaluating Comparison %s %s %s', $this->showValue($operandData), $operation, $this->showValue($operand2[$x]));
5306 9
                $this->executeBinaryComparisonOperation($operandData, $operand2[$x], $operation, $stack, true);
5307 9
                $r = $stack->pop();
5308 9
                $result[$x] = $r['value'];
5309
            }
5310
        }
5311
        //    Log the result details
5312 54
        $this->debugLog->writeDebugLog('Comparison Evaluation Result is %s', $this->showTypeDetails($result));
5313
        //    And push the result onto the stack
5314 54
        $stack->push('Array', $result);
5315
5316 54
        return $result;
5317
    }
5318
5319 404
    private function executeBinaryComparisonOperation(mixed $operand1, mixed $operand2, string $operation, Stack &$stack, bool $recursingArrays = false): array|bool
5320
    {
5321
        //    If we're dealing with matrix operations, we want a matrix result
5322 404
        if ((is_array($operand1)) || (is_array($operand2))) {
5323 54
            return $this->executeArrayComparison($operand1, $operand2, $operation, $stack, $recursingArrays);
5324
        }
5325
5326 404
        $result = BinaryComparison::compare($operand1, $operand2, $operation);
5327
5328
        //    Log the result details
5329 404
        $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($result));
5330
        //    And push the result onto the stack
5331 404
        $stack->push('Value', $result);
5332
5333 404
        return $result;
5334
    }
5335
5336 1424
    private function executeNumericBinaryOperation(mixed $operand1, mixed $operand2, string $operation, Stack &$stack): mixed
5337
    {
5338
        //    Validate the two operands
5339
        if (
5340 1424
            ($this->validateBinaryOperand($operand1, $stack) === false)
5341 1424
            || ($this->validateBinaryOperand($operand2, $stack) === false)
5342
        ) {
5343 10
            return false;
5344
        }
5345
5346
        if (
5347 1417
            (Functions::getCompatibilityMode() != Functions::COMPATIBILITY_OPENOFFICE)
5348 1417
            && ((is_string($operand1) && !is_numeric($operand1) && $operand1 !== '')
5349 1417
                || (is_string($operand2) && !is_numeric($operand2) && $operand2 !== ''))
5350
        ) {
5351
            $result = ExcelError::VALUE();
5352 1417
        } elseif (is_array($operand1) || is_array($operand2)) {
5353
            //    Ensure that both operands are arrays/matrices
5354 34
            if (is_array($operand1)) {
5355 28
                foreach ($operand1 as $key => $value) {
5356 28
                    $operand1[$key] = Functions::flattenArray($value);
5357
                }
5358
            }
5359 34
            if (is_array($operand2)) {
5360 28
                foreach ($operand2 as $key => $value) {
5361 28
                    $operand2[$key] = Functions::flattenArray($value);
5362
                }
5363
            }
5364 34
            [$rows, $columns] = self::checkMatrixOperands($operand1, $operand2, 3);
5365
5366 34
            for ($row = 0; $row < $rows; ++$row) {
5367 34
                for ($column = 0; $column < $columns; ++$column) {
5368 34
                    if ($operand1[$row][$column] === null) {
5369 1
                        $operand1[$row][$column] = 0;
5370 34
                    } elseif (!self::isNumericOrBool($operand1[$row][$column])) {
5371 1
                        $operand1[$row][$column] = self::makeError($operand1[$row][$column]);
5372
5373 1
                        continue;
5374
                    }
5375 34
                    if ($operand2[$row][$column] === null) {
5376 1
                        $operand2[$row][$column] = 0;
5377 34
                    } elseif (!self::isNumericOrBool($operand2[$row][$column])) {
5378
                        $operand1[$row][$column] = self::makeError($operand2[$row][$column]);
5379
5380
                        continue;
5381
                    }
5382
                    switch ($operation) {
5383 34
                        case '+':
5384 3
                            $operand1[$row][$column] += $operand2[$row][$column];
5385
5386 3
                            break;
5387 31
                        case '-':
5388 3
                            $operand1[$row][$column] -= $operand2[$row][$column];
5389
5390 3
                            break;
5391 29
                        case '*':
5392 22
                            $operand1[$row][$column] *= $operand2[$row][$column];
5393
5394 22
                            break;
5395 7
                        case '/':
5396 5
                            if ($operand2[$row][$column] == 0) {
5397 3
                                $operand1[$row][$column] = ExcelError::DIV0();
5398
                            } else {
5399 4
                                $operand1[$row][$column] /= $operand2[$row][$column];
5400
                            }
5401
5402 5
                            break;
5403 2
                        case '^':
5404 2
                            $operand1[$row][$column] = $operand1[$row][$column] ** $operand2[$row][$column];
5405
5406 2
                            break;
5407
5408
                        default:
5409
                            throw new Exception('Unsupported numeric binary operation');
5410
                    }
5411
                }
5412
            }
5413 34
            $result = $operand1;
5414
        } else {
5415
            //    If we're dealing with non-matrix operations, execute the necessary operation
5416
            switch ($operation) {
5417
                //    Addition
5418 1402
                case '+':
5419 158
                    $result = $operand1 + $operand2;
5420
5421 158
                    break;
5422
                //    Subtraction
5423 1325
                case '-':
5424 50
                    $result = $operand1 - $operand2;
5425
5426 50
                    break;
5427
                //    Multiplication
5428 1291
                case '*':
5429 1233
                    $result = $operand1 * $operand2;
5430
5431 1233
                    break;
5432
                //    Division
5433 91
                case '/':
5434 90
                    if ($operand2 == 0) {
5435
                        //    Trap for Divide by Zero error
5436 41
                        $stack->push('Error', ExcelError::DIV0());
5437 41
                        $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails(ExcelError::DIV0()));
5438
5439 41
                        return false;
5440
                    }
5441 59
                    $result = $operand1 / $operand2;
5442
5443 59
                    break;
5444
                //    Power
5445 2
                case '^':
5446 2
                    $result = $operand1 ** $operand2;
5447
5448 2
                    break;
5449
5450
                default:
5451
                    throw new Exception('Unsupported numeric binary operation');
5452
            }
5453
        }
5454
5455
        //    Log the result details
5456 1391
        $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($result));
5457
        //    And push the result onto the stack
5458 1391
        $stack->push('Value', $result);
5459
5460 1391
        return $result;
5461
    }
5462
5463
    /**
5464
     * Trigger an error, but nicely, if need be.
5465
     *
5466
     * @return false
5467
     */
5468 269
    protected function raiseFormulaError(string $errorMessage, int $code = 0, ?Throwable $exception = null): bool
5469
    {
5470 269
        $this->formulaError = $errorMessage;
5471 269
        $this->cyclicReferenceStack->clear();
5472 269
        $suppress = $this->suppressFormulaErrors;
5473 269
        if (!$suppress) {
5474 268
            throw new Exception($errorMessage, $code, $exception);
5475
        }
5476
5477 2
        return false;
5478
    }
5479
5480
    /**
5481
     * Extract range values.
5482
     *
5483
     * @param string $range String based range representation
5484
     * @param ?Worksheet $worksheet Worksheet
5485
     * @param bool $resetLog Flag indicating whether calculation log should be reset or not
5486
     *
5487
     * @return array Array of values in range if range contains more than one element. Otherwise, a single value is returned.
5488
     */
5489 6816
    public function extractCellRange(string &$range = 'A1', ?Worksheet $worksheet = null, bool $resetLog = true): array
5490
    {
5491
        // Return value
5492 6816
        $returnValue = [];
5493
5494 6816
        if ($worksheet !== null) {
5495 6816
            $worksheetName = $worksheet->getTitle();
5496
5497 6816
            if (str_contains($range, '!')) {
5498 10
                [$worksheetName, $range] = Worksheet::extractSheetTitle($range, true);
5499 10
                $worksheet = ($this->spreadsheet === null) ? null : $this->spreadsheet->getSheetByName($worksheetName);
5500
            }
5501
5502
            // Extract range
5503 6816
            $aReferences = Coordinate::extractAllCellReferencesInRange($range);
5504 6816
            $range = "'" . $worksheetName . "'" . '!' . $range;
5505 6816
            $currentCol = '';
5506 6816
            $currentRow = 0;
5507 6816
            if (!isset($aReferences[1])) {
5508
                //    Single cell in range
5509 6784
                sscanf($aReferences[0], '%[A-Z]%d', $currentCol, $currentRow);
5510 6784
                if ($worksheet !== null && $worksheet->cellExists($aReferences[0])) {
5511 6782
                    $temp = $worksheet->getCell($aReferences[0])->getCalculatedValue($resetLog);
5512 6782
                    if ($this->getInstanceArrayReturnType() === self::RETURN_ARRAY_AS_ARRAY) {
5513 130
                        while (is_array($temp)) {
5514 7
                            $temp = array_shift($temp);
5515
                        }
5516
                    }
5517 6782
                    $returnValue[$currentRow][$currentCol] = $temp;
5518
                } else {
5519 5
                    $returnValue[$currentRow][$currentCol] = null;
5520
                }
5521
            } else {
5522
                // Extract cell data for all cells in the range
5523 1179
                foreach ($aReferences as $reference) {
5524
                    // Extract range
5525 1179
                    sscanf($reference, '%[A-Z]%d', $currentCol, $currentRow);
5526 1179
                    if ($worksheet !== null && $worksheet->cellExists($reference)) {
5527 1147
                        $temp = $worksheet->getCell($reference)->getCalculatedValue($resetLog);
5528 1147
                        if ($this->getInstanceArrayReturnType() === self::RETURN_ARRAY_AS_ARRAY) {
5529 109
                            while (is_array($temp)) {
5530
                                $temp = array_shift($temp);
5531
                            }
5532
                        }
5533 1147
                        $returnValue[$currentRow][$currentCol] = $temp;
5534
                    } else {
5535 163
                        $returnValue[$currentRow][$currentCol] = null;
5536
                    }
5537
                }
5538
            }
5539
        }
5540
5541 6816
        return $returnValue;
5542
    }
5543
5544
    /**
5545
     * Extract range values.
5546
     *
5547
     * @param string $range String based range representation
5548
     * @param null|Worksheet $worksheet Worksheet
5549
     * @param bool $resetLog Flag indicating whether calculation log should be reset or not
5550
     *
5551
     * @return array|string Array of values in range if range contains more than one element. Otherwise, a single value is returned.
5552
     */
5553
    public function extractNamedRange(string &$range = 'A1', ?Worksheet $worksheet = null, bool $resetLog = true): string|array
5554
    {
5555
        // Return value
5556
        $returnValue = [];
5557
5558
        if ($worksheet !== null) {
5559
            if (str_contains($range, '!')) {
5560
                [$worksheetName, $range] = Worksheet::extractSheetTitle($range, true);
5561
                $worksheet = ($this->spreadsheet === null) ? null : $this->spreadsheet->getSheetByName($worksheetName);
5562
            }
5563
5564
            // Named range?
5565
            $namedRange = ($worksheet === null) ? null : DefinedName::resolveName($range, $worksheet);
5566
            if ($namedRange === null) {
5567
                return ExcelError::REF();
5568
            }
5569
5570
            $worksheet = $namedRange->getWorksheet();
5571
            $range = $namedRange->getValue();
5572
            $splitRange = Coordinate::splitRange($range);
5573
            //    Convert row and column references
5574
            if ($worksheet !== null && ctype_alpha($splitRange[0][0])) {
5575
                $range = $splitRange[0][0] . '1:' . $splitRange[0][1] . $worksheet->getHighestRow();
5576
            } elseif ($worksheet !== null && ctype_digit($splitRange[0][0])) {
5577
                $range = 'A' . $splitRange[0][0] . ':' . $worksheet->getHighestColumn() . $splitRange[0][1];
5578
            }
5579
5580
            // Extract range
5581
            $aReferences = Coordinate::extractAllCellReferencesInRange($range);
5582
            if (!isset($aReferences[1])) {
5583
                //    Single cell (or single column or row) in range
5584
                [$currentCol, $currentRow] = Coordinate::coordinateFromString($aReferences[0]);
5585
                if ($worksheet !== null && $worksheet->cellExists($aReferences[0])) {
5586
                    $returnValue[$currentRow][$currentCol] = $worksheet->getCell($aReferences[0])->getCalculatedValue($resetLog);
5587
                } else {
5588
                    $returnValue[$currentRow][$currentCol] = null;
5589
                }
5590
            } else {
5591
                // Extract cell data for all cells in the range
5592
                foreach ($aReferences as $reference) {
5593
                    // Extract range
5594
                    [$currentCol, $currentRow] = Coordinate::coordinateFromString($reference);
5595
                    if ($worksheet !== null && $worksheet->cellExists($reference)) {
5596
                        $returnValue[$currentRow][$currentCol] = $worksheet->getCell($reference)->getCalculatedValue($resetLog);
5597
                    } else {
5598
                        $returnValue[$currentRow][$currentCol] = null;
5599
                    }
5600
                }
5601
            }
5602
        }
5603
5604
        return $returnValue;
5605
    }
5606
5607
    /**
5608
     * Is a specific function implemented?
5609
     *
5610
     * @param string $function Function Name
5611
     */
5612 3
    public function isImplemented(string $function): bool
5613
    {
5614 3
        $function = strtoupper($function);
5615 3
        $notImplemented = !isset(self::$phpSpreadsheetFunctions[$function]) || (is_array(self::$phpSpreadsheetFunctions[$function]['functionCall']) && self::$phpSpreadsheetFunctions[$function]['functionCall'][1] === 'DUMMY');
5616
5617 3
        return !$notImplemented;
5618
    }
5619
5620
    /**
5621
     * Get a list of all implemented functions as an array of function objects.
5622
     */
5623 2
    public static function getFunctions(): array
5624
    {
5625 2
        return self::$phpSpreadsheetFunctions;
5626
    }
5627
5628
    /**
5629
     * Get a list of implemented Excel function names.
5630
     */
5631 2
    public function getImplementedFunctionNames(): array
5632
    {
5633 2
        $returnValue = [];
5634 2
        foreach (self::$phpSpreadsheetFunctions as $functionName => $function) {
5635 2
            if ($this->isImplemented($functionName)) {
5636 2
                $returnValue[] = $functionName;
5637
            }
5638
        }
5639
5640 2
        return $returnValue;
5641
    }
5642
5643 11352
    private function addDefaultArgumentValues(array $functionCall, array $args, array $emptyArguments): array
5644
    {
5645 11352
        $reflector = new ReflectionMethod($functionCall[0], $functionCall[1]);
5646 11352
        $methodArguments = $reflector->getParameters();
5647
5648 11352
        if (count($methodArguments) > 0) {
5649
            // Apply any defaults for empty argument values
5650 11345
            foreach ($emptyArguments as $argumentId => $isArgumentEmpty) {
5651 11312
                if ($isArgumentEmpty === true) {
5652 146
                    $reflectedArgumentId = count($args) - (int) $argumentId - 1;
5653
                    if (
5654 146
                        !array_key_exists($reflectedArgumentId, $methodArguments)
5655 146
                        || $methodArguments[$reflectedArgumentId]->isVariadic()
5656
                    ) {
5657 12
                        break;
5658
                    }
5659
5660 134
                    $args[$argumentId] = $this->getArgumentDefaultValue($methodArguments[$reflectedArgumentId]);
5661
                }
5662
            }
5663
        }
5664
5665 11352
        return $args;
5666
    }
5667
5668 134
    private function getArgumentDefaultValue(ReflectionParameter $methodArgument): mixed
5669
    {
5670 134
        $defaultValue = null;
5671
5672 134
        if ($methodArgument->isDefaultValueAvailable()) {
5673 63
            $defaultValue = $methodArgument->getDefaultValue();
5674 63
            if ($methodArgument->isDefaultValueConstant()) {
5675 2
                $constantName = $methodArgument->getDefaultValueConstantName() ?? '';
5676
                // read constant value
5677 2
                if (str_contains($constantName, '::')) {
5678 2
                    [$className, $constantName] = explode('::', $constantName);
5679 2
                    $constantReflector = new ReflectionClassConstant($className, $constantName);
5680
5681 2
                    return $constantReflector->getValue();
5682
                }
5683
5684
                return constant($constantName);
5685
            }
5686
        }
5687
5688 133
        return $defaultValue;
5689
    }
5690
5691
    /**
5692
     * Add cell reference if needed while making sure that it is the last argument.
5693
     */
5694 11370
    private function addCellReference(array $args, bool $passCellReference, array|string $functionCall, ?Cell $cell = null): array
5695
    {
5696 11370
        if ($passCellReference) {
5697 209
            if (is_array($functionCall)) {
5698 209
                $className = $functionCall[0];
5699 209
                $methodName = $functionCall[1];
5700
5701 209
                $reflectionMethod = new ReflectionMethod($className, $methodName);
5702 209
                $argumentCount = count($reflectionMethod->getParameters());
5703 209
                while (count($args) < $argumentCount - 1) {
5704 51
                    $args[] = null;
5705
                }
5706
            }
5707
5708 209
            $args[] = $cell;
5709
        }
5710
5711 11370
        return $args;
5712
    }
5713
5714 118
    private function evaluateDefinedName(Cell $cell, DefinedName $namedRange, Worksheet $cellWorksheet, Stack $stack, bool $ignoreScope = false): mixed
5715
    {
5716 118
        $definedNameScope = $namedRange->getScope();
5717 118
        if ($definedNameScope !== null && $definedNameScope !== $cellWorksheet && !$ignoreScope) {
5718
            // The defined name isn't in our current scope, so #REF
5719
            $result = ExcelError::REF();
5720
            $stack->push('Error', $result, $namedRange->getName());
5721
5722
            return $result;
5723
        }
5724
5725 118
        $definedNameValue = $namedRange->getValue();
5726 118
        $definedNameType = $namedRange->isFormula() ? 'Formula' : 'Range';
5727 118
        $definedNameWorksheet = $namedRange->getWorksheet();
5728
5729 118
        if ($definedNameValue[0] !== '=') {
5730 96
            $definedNameValue = '=' . $definedNameValue;
5731
        }
5732
5733 118
        $this->debugLog->writeDebugLog('Defined Name is a %s with a value of %s', $definedNameType, $definedNameValue);
5734
5735 118
        $originalCoordinate = $cell->getCoordinate();
5736 118
        $recursiveCalculationCell = ($definedNameType !== 'Formula' && $definedNameWorksheet !== null && $definedNameWorksheet !== $cellWorksheet)
5737 16
            ? $definedNameWorksheet->getCell('A1')
5738 111
            : $cell;
5739 118
        $recursiveCalculationCellAddress = $recursiveCalculationCell->getCoordinate();
5740
5741
        // Adjust relative references in ranges and formulae so that we execute the calculation for the correct rows and columns
5742 118
        $definedNameValue = ReferenceHelper::getInstance()
5743 118
            ->updateFormulaReferencesAnyWorksheet(
5744 118
                $definedNameValue,
5745 118
                Coordinate::columnIndexFromString(
5746 118
                    $cell->getColumn()
5747 118
                ) - 1,
5748 118
                $cell->getRow() - 1
5749 118
            );
5750
5751 118
        $this->debugLog->writeDebugLog('Value adjusted for relative references is %s', $definedNameValue);
5752
5753 118
        $recursiveCalculator = new self($this->spreadsheet);
5754 118
        $recursiveCalculator->getDebugLog()->setWriteDebugLog($this->getDebugLog()->getWriteDebugLog());
5755 118
        $recursiveCalculator->getDebugLog()->setEchoDebugLog($this->getDebugLog()->getEchoDebugLog());
5756 118
        $result = $recursiveCalculator->_calculateFormulaValue($definedNameValue, $recursiveCalculationCellAddress, $recursiveCalculationCell, true);
5757 118
        $cellWorksheet->getCell($originalCoordinate);
5758
5759 118
        if ($this->getDebugLog()->getWriteDebugLog()) {
5760
            $this->debugLog->mergeDebugLog(array_slice($recursiveCalculator->getDebugLog()->getLog(), 3));
5761
            $this->debugLog->writeDebugLog('Evaluation Result for Named %s %s is %s', $definedNameType, $namedRange->getName(), $this->showTypeDetails($result));
5762
        }
5763
5764 118
        $stack->push('Defined Name', $result, $namedRange->getName());
5765
5766 118
        return $result;
5767
    }
5768
5769 2
    public function setSuppressFormulaErrors(bool $suppressFormulaErrors): void
5770
    {
5771 2
        $this->suppressFormulaErrors = $suppressFormulaErrors;
5772
    }
5773
5774 4
    public function getSuppressFormulaErrors(): bool
5775
    {
5776 4
        return $this->suppressFormulaErrors;
5777
    }
5778
5779 31
    public static function boolToString(mixed $operand1): mixed
5780
    {
5781 31
        if (is_bool($operand1)) {
5782 1
            $operand1 = ($operand1) ? self::$localeBoolean['TRUE'] : self::$localeBoolean['FALSE'];
5783 31
        } elseif ($operand1 === null) {
5784
            $operand1 = '';
5785
        }
5786
5787 31
        return $operand1;
5788
    }
5789
5790 38
    private static function isNumericOrBool(mixed $operand): bool
5791
    {
5792 38
        return is_numeric($operand) || is_bool($operand);
5793
    }
5794
5795 3
    private static function makeError(mixed $operand = ''): string
5796
    {
5797 3
        return Information\ErrorValue::isError($operand) ? $operand : ExcelError::VALUE();
5798
    }
5799
}
5800