Failed Conditions
Pull Request — master (#3528)
by Owen
22:55 queued 12:36
created

Calculation::renameCalculationCacheForWorksheet()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 2.5

Importance

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