Failed Conditions
Pull Request — master (#3962)
by Owen
11:35
created

Calculation::extractCellRange()   C

Complexity

Conditions 14
Paths 13

Size

Total Lines 53
Code Lines 32

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 132.7613

Importance

Changes 0
Metric Value
eloc 32
c 0
b 0
f 0
dl 0
loc 53
rs 6.2666
ccs 4
cts 26
cp 0.1538
cc 14
nc 13
nop 3
crap 132.7613

How to fix   Long Method    Complexity   

Long Method

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

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

Commonly applied refactorings include:

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