Failed Conditions
Pull Request — master (#3962)
by Owen
17:41 queued 07:20
created

Calculation::calculateCellValue()   F

Complexity

Conditions 22
Paths 233

Size

Total Lines 75
Code Lines 48

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 45
CRAP Score 22.4838

Importance

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

How to fix   Long Method    Complexity   

Long Method

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

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

Commonly applied refactorings include:

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