Failed Conditions
Pull Request — master (#4257)
by Owen
12:35
created

Calculation::calculateCellValue()   F

Complexity

Conditions 22
Paths 233

Size

Total Lines 75
Code Lines 48

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 35
CRAP Score 22.2377

Importance

Changes 0
Metric Value
eloc 48
c 0
b 0
f 0
dl 0
loc 75
ccs 35
cts 38
cp 0.9211
rs 2.9208
cc 22
nc 233
nop 2
crap 22.2377

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
     * @var array<string, string>
188
     */
189
    private static array $localeBoolean = [
190
        'TRUE' => 'TRUE',
191
        'FALSE' => 'FALSE',
192
        'NULL' => 'NULL',
193
    ];
194
195 7
    public static function getLocaleBoolean(string $index): string
196
    {
197 7
        return self::$localeBoolean[$index];
198
    }
199
200
    /**
201
     * Excel constant string translations to their PHP equivalents
202
     * Constant conversion from text name/value to actual (datatyped) value.
203
     *
204
     * @var array<string, null|bool>
205
     */
206
    private static array $excelConstants = [
207
        'TRUE' => true,
208
        'FALSE' => false,
209
        'NULL' => null,
210
    ];
211
212 20
    public static function keyInExcelConstants(string $key): bool
213
    {
214 20
        return array_key_exists($key, self::$excelConstants);
215
    }
216
217 3
    public static function getExcelConstants(string $key): bool|null
218
    {
219 3
        return self::$excelConstants[$key];
220
    }
221
222
    /**
223
     * Array of functions usable on Spreadsheet.
224
     * In theory, this could be const rather than static;
225
     *   however, Phpstan breaks trying to analyze it when attempted.
226
     */
227
    private static array $phpSpreadsheetFunctions = [
228
        'ABS' => [
229
            'category' => Category::CATEGORY_MATH_AND_TRIG,
230
            'functionCall' => [MathTrig\Absolute::class, 'evaluate'],
231
            'argumentCount' => '1',
232
        ],
233
        'ACCRINT' => [
234
            'category' => Category::CATEGORY_FINANCIAL,
235
            'functionCall' => [Financial\Securities\AccruedInterest::class, 'periodic'],
236
            'argumentCount' => '4-8',
237
        ],
238
        'ACCRINTM' => [
239
            'category' => Category::CATEGORY_FINANCIAL,
240
            'functionCall' => [Financial\Securities\AccruedInterest::class, 'atMaturity'],
241
            'argumentCount' => '3-5',
242
        ],
243
        'ACOS' => [
244
            'category' => Category::CATEGORY_MATH_AND_TRIG,
245
            'functionCall' => [MathTrig\Trig\Cosine::class, 'acos'],
246
            'argumentCount' => '1',
247
        ],
248
        'ACOSH' => [
249
            'category' => Category::CATEGORY_MATH_AND_TRIG,
250
            'functionCall' => [MathTrig\Trig\Cosine::class, 'acosh'],
251
            'argumentCount' => '1',
252
        ],
253
        'ACOT' => [
254
            'category' => Category::CATEGORY_MATH_AND_TRIG,
255
            'functionCall' => [MathTrig\Trig\Cotangent::class, 'acot'],
256
            'argumentCount' => '1',
257
        ],
258
        'ACOTH' => [
259
            'category' => Category::CATEGORY_MATH_AND_TRIG,
260
            'functionCall' => [MathTrig\Trig\Cotangent::class, 'acoth'],
261
            'argumentCount' => '1',
262
        ],
263
        'ADDRESS' => [
264
            'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE,
265
            'functionCall' => [LookupRef\Address::class, 'cell'],
266
            'argumentCount' => '2-5',
267
        ],
268
        'AGGREGATE' => [
269
            'category' => Category::CATEGORY_MATH_AND_TRIG,
270
            'functionCall' => [Functions::class, 'DUMMY'],
271
            'argumentCount' => '3+',
272
        ],
273
        'AMORDEGRC' => [
274
            'category' => Category::CATEGORY_FINANCIAL,
275
            'functionCall' => [Financial\Amortization::class, 'AMORDEGRC'],
276
            'argumentCount' => '6,7',
277
        ],
278
        'AMORLINC' => [
279
            'category' => Category::CATEGORY_FINANCIAL,
280
            'functionCall' => [Financial\Amortization::class, 'AMORLINC'],
281
            'argumentCount' => '6,7',
282
        ],
283
        'ANCHORARRAY' => [
284
            'category' => Category::CATEGORY_MICROSOFT_INTERNAL,
285
            'functionCall' => [Internal\ExcelArrayPseudoFunctions::class, 'anchorArray'],
286
            'argumentCount' => '1',
287
            'passCellReference' => true,
288
            'passByReference' => [true],
289
        ],
290
        'AND' => [
291
            'category' => Category::CATEGORY_LOGICAL,
292
            'functionCall' => [Logical\Operations::class, 'logicalAnd'],
293
            'argumentCount' => '1+',
294
        ],
295
        'ARABIC' => [
296
            'category' => Category::CATEGORY_MATH_AND_TRIG,
297
            'functionCall' => [MathTrig\Arabic::class, 'evaluate'],
298
            'argumentCount' => '1',
299
        ],
300
        'AREAS' => [
301
            'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE,
302
            'functionCall' => [Functions::class, 'DUMMY'],
303
            'argumentCount' => '1',
304
        ],
305
        'ARRAYTOTEXT' => [
306
            'category' => Category::CATEGORY_TEXT_AND_DATA,
307
            'functionCall' => [TextData\Text::class, 'fromArray'],
308
            'argumentCount' => '1,2',
309
        ],
310
        'ASC' => [
311
            'category' => Category::CATEGORY_TEXT_AND_DATA,
312
            'functionCall' => [Functions::class, 'DUMMY'],
313
            'argumentCount' => '1',
314
        ],
315
        'ASIN' => [
316
            'category' => Category::CATEGORY_MATH_AND_TRIG,
317
            'functionCall' => [MathTrig\Trig\Sine::class, 'asin'],
318
            'argumentCount' => '1',
319
        ],
320
        'ASINH' => [
321
            'category' => Category::CATEGORY_MATH_AND_TRIG,
322
            'functionCall' => [MathTrig\Trig\Sine::class, 'asinh'],
323
            'argumentCount' => '1',
324
        ],
325
        'ATAN' => [
326
            'category' => Category::CATEGORY_MATH_AND_TRIG,
327
            'functionCall' => [MathTrig\Trig\Tangent::class, 'atan'],
328
            'argumentCount' => '1',
329
        ],
330
        'ATAN2' => [
331
            'category' => Category::CATEGORY_MATH_AND_TRIG,
332
            'functionCall' => [MathTrig\Trig\Tangent::class, 'atan2'],
333
            'argumentCount' => '2',
334
        ],
335
        'ATANH' => [
336
            'category' => Category::CATEGORY_MATH_AND_TRIG,
337
            'functionCall' => [MathTrig\Trig\Tangent::class, 'atanh'],
338
            'argumentCount' => '1',
339
        ],
340
        'AVEDEV' => [
341
            'category' => Category::CATEGORY_STATISTICAL,
342
            'functionCall' => [Statistical\Averages::class, 'averageDeviations'],
343
            'argumentCount' => '1+',
344
        ],
345
        'AVERAGE' => [
346
            'category' => Category::CATEGORY_STATISTICAL,
347
            'functionCall' => [Statistical\Averages::class, 'average'],
348
            'argumentCount' => '1+',
349
        ],
350
        'AVERAGEA' => [
351
            'category' => Category::CATEGORY_STATISTICAL,
352
            'functionCall' => [Statistical\Averages::class, 'averageA'],
353
            'argumentCount' => '1+',
354
        ],
355
        'AVERAGEIF' => [
356
            'category' => Category::CATEGORY_STATISTICAL,
357
            'functionCall' => [Statistical\Conditional::class, 'AVERAGEIF'],
358
            'argumentCount' => '2,3',
359
        ],
360
        'AVERAGEIFS' => [
361
            'category' => Category::CATEGORY_STATISTICAL,
362
            'functionCall' => [Statistical\Conditional::class, 'AVERAGEIFS'],
363
            'argumentCount' => '3+',
364
        ],
365
        'BAHTTEXT' => [
366
            'category' => Category::CATEGORY_TEXT_AND_DATA,
367
            'functionCall' => [Functions::class, 'DUMMY'],
368
            'argumentCount' => '1',
369
        ],
370
        'BASE' => [
371
            'category' => Category::CATEGORY_MATH_AND_TRIG,
372
            'functionCall' => [MathTrig\Base::class, 'evaluate'],
373
            'argumentCount' => '2,3',
374
        ],
375
        'BESSELI' => [
376
            'category' => Category::CATEGORY_ENGINEERING,
377
            'functionCall' => [Engineering\BesselI::class, 'BESSELI'],
378
            'argumentCount' => '2',
379
        ],
380
        'BESSELJ' => [
381
            'category' => Category::CATEGORY_ENGINEERING,
382
            'functionCall' => [Engineering\BesselJ::class, 'BESSELJ'],
383
            'argumentCount' => '2',
384
        ],
385
        'BESSELK' => [
386
            'category' => Category::CATEGORY_ENGINEERING,
387
            'functionCall' => [Engineering\BesselK::class, 'BESSELK'],
388
            'argumentCount' => '2',
389
        ],
390
        'BESSELY' => [
391
            'category' => Category::CATEGORY_ENGINEERING,
392
            'functionCall' => [Engineering\BesselY::class, 'BESSELY'],
393
            'argumentCount' => '2',
394
        ],
395
        'BETADIST' => [
396
            'category' => Category::CATEGORY_STATISTICAL,
397
            'functionCall' => [Statistical\Distributions\Beta::class, 'distribution'],
398
            'argumentCount' => '3-5',
399
        ],
400
        'BETA.DIST' => [
401
            'category' => Category::CATEGORY_STATISTICAL,
402
            'functionCall' => [Functions::class, 'DUMMY'],
403
            'argumentCount' => '4-6',
404
        ],
405
        'BETAINV' => [
406
            'category' => Category::CATEGORY_STATISTICAL,
407
            'functionCall' => [Statistical\Distributions\Beta::class, 'inverse'],
408
            'argumentCount' => '3-5',
409
        ],
410
        'BETA.INV' => [
411
            'category' => Category::CATEGORY_STATISTICAL,
412
            'functionCall' => [Statistical\Distributions\Beta::class, 'inverse'],
413
            'argumentCount' => '3-5',
414
        ],
415
        'BIN2DEC' => [
416
            'category' => Category::CATEGORY_ENGINEERING,
417
            'functionCall' => [Engineering\ConvertBinary::class, 'toDecimal'],
418
            'argumentCount' => '1',
419
        ],
420
        'BIN2HEX' => [
421
            'category' => Category::CATEGORY_ENGINEERING,
422
            'functionCall' => [Engineering\ConvertBinary::class, 'toHex'],
423
            'argumentCount' => '1,2',
424
        ],
425
        'BIN2OCT' => [
426
            'category' => Category::CATEGORY_ENGINEERING,
427
            'functionCall' => [Engineering\ConvertBinary::class, 'toOctal'],
428
            'argumentCount' => '1,2',
429
        ],
430
        'BINOMDIST' => [
431
            'category' => Category::CATEGORY_STATISTICAL,
432
            'functionCall' => [Statistical\Distributions\Binomial::class, 'distribution'],
433
            'argumentCount' => '4',
434
        ],
435
        'BINOM.DIST' => [
436
            'category' => Category::CATEGORY_STATISTICAL,
437
            'functionCall' => [Statistical\Distributions\Binomial::class, 'distribution'],
438
            'argumentCount' => '4',
439
        ],
440
        'BINOM.DIST.RANGE' => [
441
            'category' => Category::CATEGORY_STATISTICAL,
442
            'functionCall' => [Statistical\Distributions\Binomial::class, 'range'],
443
            'argumentCount' => '3,4',
444
        ],
445
        'BINOM.INV' => [
446
            'category' => Category::CATEGORY_STATISTICAL,
447
            'functionCall' => [Statistical\Distributions\Binomial::class, 'inverse'],
448
            'argumentCount' => '3',
449
        ],
450
        'BITAND' => [
451
            'category' => Category::CATEGORY_ENGINEERING,
452
            'functionCall' => [Engineering\BitWise::class, 'BITAND'],
453
            'argumentCount' => '2',
454
        ],
455
        'BITOR' => [
456
            'category' => Category::CATEGORY_ENGINEERING,
457
            'functionCall' => [Engineering\BitWise::class, 'BITOR'],
458
            'argumentCount' => '2',
459
        ],
460
        'BITXOR' => [
461
            'category' => Category::CATEGORY_ENGINEERING,
462
            'functionCall' => [Engineering\BitWise::class, 'BITXOR'],
463
            'argumentCount' => '2',
464
        ],
465
        'BITLSHIFT' => [
466
            'category' => Category::CATEGORY_ENGINEERING,
467
            'functionCall' => [Engineering\BitWise::class, 'BITLSHIFT'],
468
            'argumentCount' => '2',
469
        ],
470
        'BITRSHIFT' => [
471
            'category' => Category::CATEGORY_ENGINEERING,
472
            'functionCall' => [Engineering\BitWise::class, 'BITRSHIFT'],
473
            'argumentCount' => '2',
474
        ],
475
        'BYCOL' => [
476
            'category' => Category::CATEGORY_LOGICAL,
477
            'functionCall' => [Functions::class, 'DUMMY'],
478
            'argumentCount' => '*',
479
        ],
480
        'BYROW' => [
481
            'category' => Category::CATEGORY_LOGICAL,
482
            'functionCall' => [Functions::class, 'DUMMY'],
483
            'argumentCount' => '*',
484
        ],
485
        'CEILING' => [
486
            'category' => Category::CATEGORY_MATH_AND_TRIG,
487
            'functionCall' => [MathTrig\Ceiling::class, 'ceiling'],
488
            'argumentCount' => '1-2', // 2 for Excel, 1-2 for Ods/Gnumeric
489
        ],
490
        'CEILING.MATH' => [
491
            'category' => Category::CATEGORY_MATH_AND_TRIG,
492
            'functionCall' => [MathTrig\Ceiling::class, 'math'],
493
            'argumentCount' => '1-3',
494
        ],
495
        'CEILING.PRECISE' => [
496
            'category' => Category::CATEGORY_MATH_AND_TRIG,
497
            'functionCall' => [MathTrig\Ceiling::class, 'precise'],
498
            'argumentCount' => '1,2',
499
        ],
500
        'CELL' => [
501
            'category' => Category::CATEGORY_INFORMATION,
502
            'functionCall' => [Functions::class, 'DUMMY'],
503
            'argumentCount' => '1,2',
504
        ],
505
        'CHAR' => [
506
            'category' => Category::CATEGORY_TEXT_AND_DATA,
507
            'functionCall' => [TextData\CharacterConvert::class, 'character'],
508
            'argumentCount' => '1',
509
        ],
510
        'CHIDIST' => [
511
            'category' => Category::CATEGORY_STATISTICAL,
512
            'functionCall' => [Statistical\Distributions\ChiSquared::class, 'distributionRightTail'],
513
            'argumentCount' => '2',
514
        ],
515
        'CHISQ.DIST' => [
516
            'category' => Category::CATEGORY_STATISTICAL,
517
            'functionCall' => [Statistical\Distributions\ChiSquared::class, 'distributionLeftTail'],
518
            'argumentCount' => '3',
519
        ],
520
        'CHISQ.DIST.RT' => [
521
            'category' => Category::CATEGORY_STATISTICAL,
522
            'functionCall' => [Statistical\Distributions\ChiSquared::class, 'distributionRightTail'],
523
            'argumentCount' => '2',
524
        ],
525
        'CHIINV' => [
526
            'category' => Category::CATEGORY_STATISTICAL,
527
            'functionCall' => [Statistical\Distributions\ChiSquared::class, 'inverseRightTail'],
528
            'argumentCount' => '2',
529
        ],
530
        'CHISQ.INV' => [
531
            'category' => Category::CATEGORY_STATISTICAL,
532
            'functionCall' => [Statistical\Distributions\ChiSquared::class, 'inverseLeftTail'],
533
            'argumentCount' => '2',
534
        ],
535
        'CHISQ.INV.RT' => [
536
            'category' => Category::CATEGORY_STATISTICAL,
537
            'functionCall' => [Statistical\Distributions\ChiSquared::class, 'inverseRightTail'],
538
            'argumentCount' => '2',
539
        ],
540
        'CHITEST' => [
541
            'category' => Category::CATEGORY_STATISTICAL,
542
            'functionCall' => [Statistical\Distributions\ChiSquared::class, 'test'],
543
            'argumentCount' => '2',
544
        ],
545
        'CHISQ.TEST' => [
546
            'category' => Category::CATEGORY_STATISTICAL,
547
            'functionCall' => [Statistical\Distributions\ChiSquared::class, 'test'],
548
            'argumentCount' => '2',
549
        ],
550
        'CHOOSE' => [
551
            'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE,
552
            'functionCall' => [LookupRef\Selection::class, 'CHOOSE'],
553
            'argumentCount' => '2+',
554
        ],
555
        'CHOOSECOLS' => [
556
            'category' => Category::CATEGORY_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
            'functionCall' => [Internal\MakeMatrix::class, 'make'],
2876
        ],
2877
        'NAME.ERROR' => [
2878
            'argumentCount' => '*',
2879
            'functionCall' => [ExcelError::class, 'NAME'],
2880
        ],
2881
        'WILDCARDMATCH' => [
2882
            'argumentCount' => '2',
2883
            'functionCall' => [Internal\WildcardMatch::class, 'compare'],
2884
        ],
2885
    ];
2886
2887 10257
    public function __construct(?Spreadsheet $spreadsheet = null)
2888
    {
2889 10257
        $this->spreadsheet = $spreadsheet;
2890 10257
        $this->cyclicReferenceStack = new CyclicReferenceStack();
2891 10257
        $this->debugLog = new Logger($this->cyclicReferenceStack);
2892 10257
        $this->branchPruner = new BranchPruner($this->branchPruningEnabled);
2893 10257
        self::$referenceHelper = ReferenceHelper::getInstance();
2894
    }
2895
2896 1
    private static function loadLocales(): void
2897
    {
2898 1
        $localeFileDirectory = __DIR__ . '/locale/';
2899 1
        $localeFileNames = glob($localeFileDirectory . '*', GLOB_ONLYDIR) ?: [];
2900 1
        foreach ($localeFileNames as $filename) {
2901 1
            $filename = substr($filename, strlen($localeFileDirectory));
2902 1
            if ($filename != 'en') {
2903 1
                self::$validLocaleLanguages[] = $filename;
2904
            }
2905
        }
2906
    }
2907
2908
    /**
2909
     * Get an instance of this class.
2910
     *
2911
     * @param ?Spreadsheet $spreadsheet Injected spreadsheet for working with a PhpSpreadsheet Spreadsheet object,
2912
     *                                    or NULL to create a standalone calculation engine
2913
     */
2914 12794
    public static function getInstance(?Spreadsheet $spreadsheet = null): self
2915
    {
2916 12794
        if ($spreadsheet !== null) {
2917 9041
            $instance = $spreadsheet->getCalculationEngine();
2918 9041
            if (isset($instance)) {
2919 9041
                return $instance;
2920
            }
2921
        }
2922
2923 4596
        if (!self::$instance) {
2924 16
            self::$instance = new self();
2925
        }
2926
2927 4596
        return self::$instance;
2928
    }
2929
2930
    /**
2931
     * Flush the calculation cache for any existing instance of this class
2932
     *        but only if a Calculation instance exists.
2933
     */
2934 201
    public function flushInstance(): void
2935
    {
2936 201
        $this->clearCalculationCache();
2937 201
        $this->branchPruner->clearBranchStore();
2938
    }
2939
2940
    /**
2941
     * Get the Logger for this calculation engine instance.
2942
     */
2943 1047
    public function getDebugLog(): Logger
2944
    {
2945 1047
        return $this->debugLog;
2946
    }
2947
2948
    /**
2949
     * __clone implementation. Cloning should not be allowed in a Singleton!
2950
     */
2951
    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
     * @return string locale-specific translation of TRUE
2960
     */
2961 419
    public static function getTRUE(): string
2962
    {
2963 419
        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 403
    public static function getFALSE(): string
2972
    {
2973 403
        return self::$localeBoolean['FALSE'];
2974
    }
2975
2976
    /**
2977
     * Set the Array Return Type (Array or Value of first element in the array).
2978
     *
2979
     * @param string $returnType Array return type
2980
     *
2981
     * @return bool Success or failure
2982
     */
2983 1
    public static function setArrayReturnType(string $returnType): bool
2984
    {
2985
        if (
2986 1
            ($returnType == self::RETURN_ARRAY_AS_VALUE)
2987 1
            || ($returnType == self::RETURN_ARRAY_AS_ERROR)
2988 1
            || ($returnType == self::RETURN_ARRAY_AS_ARRAY)
2989
        ) {
2990 1
            self::$returnArrayAsType = $returnType;
2991
2992 1
            return true;
2993
        }
2994
2995 1
        return false;
2996
    }
2997
2998
    /**
2999
     * Return the Array Return Type (Array or Value of first element in the array).
3000
     *
3001
     * @return string $returnType Array return type
3002
     */
3003 1
    public static function getArrayReturnType(): string
3004
    {
3005 1
        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 65
    public function setInstanceArrayReturnType(string $returnType): bool
3016
    {
3017
        if (
3018 65
            ($returnType == self::RETURN_ARRAY_AS_VALUE)
3019 65
            || ($returnType == self::RETURN_ARRAY_AS_ERROR)
3020 65
            || ($returnType == self::RETURN_ARRAY_AS_ARRAY)
3021
        ) {
3022 65
            $this->instanceArrayReturnType = $returnType;
3023
3024 65
            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
     *
3033
     * @return string $returnType Array return type for instance if non-null, otherwise static property
3034
     */
3035 7650
    public function getInstanceArrayReturnType(): string
3036
    {
3037 7650
        return $this->instanceArrayReturnType ?? self::$returnArrayAsType;
3038
    }
3039
3040
    /**
3041
     * Is calculation caching enabled?
3042
     */
3043 174
    public function getCalculationCacheEnabled(): bool
3044
    {
3045 174
        return $this->calculationCacheEnabled;
3046
    }
3047
3048
    /**
3049
     * Enable/disable calculation cache.
3050
     */
3051
    public function setCalculationCacheEnabled(bool $calculationCacheEnabled): void
3052
    {
3053
        $this->calculationCacheEnabled = $calculationCacheEnabled;
3054
        $this->clearCalculationCache();
3055
    }
3056
3057
    /**
3058
     * Enable calculation cache.
3059
     */
3060
    public function enableCalculationCache(): void
3061
    {
3062
        $this->setCalculationCacheEnabled(true);
3063
    }
3064
3065
    /**
3066
     * Disable calculation cache.
3067
     */
3068
    public function disableCalculationCache(): void
3069
    {
3070
        $this->setCalculationCacheEnabled(false);
3071
    }
3072
3073
    /**
3074
     * Clear calculation cache.
3075
     */
3076 203
    public function clearCalculationCache(): void
3077
    {
3078 203
        $this->calculationCache = [];
3079
    }
3080
3081
    /**
3082
     * Clear calculation cache for a specified worksheet.
3083
     */
3084 113
    public function clearCalculationCacheForWorksheet(string $worksheetName): void
3085
    {
3086 113
        if (isset($this->calculationCache[$worksheetName])) {
3087
            unset($this->calculationCache[$worksheetName]);
3088
        }
3089
    }
3090
3091
    /**
3092
     * Rename calculation cache for a specified worksheet.
3093
     */
3094 10251
    public function renameCalculationCacheForWorksheet(string $fromWorksheetName, string $toWorksheetName): void
3095
    {
3096 10251
        if (isset($this->calculationCache[$fromWorksheetName])) {
3097
            $this->calculationCache[$toWorksheetName] = &$this->calculationCache[$fromWorksheetName];
3098
            unset($this->calculationCache[$fromWorksheetName]);
3099
        }
3100
    }
3101
3102
    /**
3103
     * Enable/disable calculation cache.
3104
     */
3105 7859
    public function setBranchPruningEnabled(mixed $enabled): void
3106
    {
3107 7859
        $this->branchPruningEnabled = $enabled;
3108 7859
        $this->branchPruner = new BranchPruner($this->branchPruningEnabled);
3109
    }
3110
3111
    public function enableBranchPruning(): void
3112
    {
3113
        $this->setBranchPruningEnabled(true);
3114
    }
3115
3116 7859
    public function disableBranchPruning(): void
3117
    {
3118 7859
        $this->setBranchPruningEnabled(false);
3119
    }
3120
3121
    /**
3122
     * Get the currently defined locale code.
3123
     */
3124 766
    public function getLocale(): string
3125
    {
3126 766
        return self::$localeLanguage;
3127
    }
3128
3129 117
    private function getLocaleFile(string $localeDir, string $locale, string $language, string $file): string
3130
    {
3131 117
        $localeFileName = $localeDir . str_replace('_', DIRECTORY_SEPARATOR, $locale)
3132 117
            . DIRECTORY_SEPARATOR . $file;
3133 117
        if (!file_exists($localeFileName)) {
3134
            //    If there isn't a locale specific file, look for a language specific file
3135 29
            $localeFileName = $localeDir . $language . DIRECTORY_SEPARATOR . $file;
3136 29
            if (!file_exists($localeFileName)) {
3137 3
                throw new Exception('Locale file not found');
3138
            }
3139
        }
3140
3141 114
        return $localeFileName;
3142
    }
3143
3144
    /** @var array<int, array<int, string>> */
3145
    private static array $falseTrueArray = [];
3146
3147
    /** @return array<int, array<int, string>> */
3148
    public function getFalseTrueArray(): array
3149 766
    {
3150
        if (!empty(self::$falseTrueArray)) {
3151
            return self::$falseTrueArray;
3152 766
        }
3153 766
        if (count(self::$validLocaleLanguages) == 1) {
3154 766
            self::loadLocales();
3155
        }
3156 766
        $falseTrueArray = [['FALSE'], ['TRUE']];
3157 1
        foreach (self::$validLocaleLanguages as $language) {
3158
            if (str_starts_with($language, 'en')) {
3159
                continue;
3160
            }
3161 766
            $locale = $language;
3162
            if (str_contains($locale, '_')) {
3163 766
                [$language] = explode('_', $locale);
3164 766
            }
3165 766
            $localeDir = implode(DIRECTORY_SEPARATOR, [__DIR__, 'locale', null]);
3166
3167
            try {
3168 766
                $functionNamesFile = $this->getLocaleFile($localeDir, $locale, $language, 'functions');
3169 117
            } catch (Exception $e) {
3170
                continue;
3171
            }
3172
            //    Retrieve the list of locale or language specific function names
3173 117
            $localeFunctions = file($functionNamesFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: [];
3174 3
            foreach ($localeFunctions as $localeFunction) {
3175 3
                [$localeFunction] = explode('##', $localeFunction); //    Strip out comments
3176
                if (str_contains($localeFunction, '=')) {
3177
                    [$fName, $lfName] = array_map('trim', explode('=', $localeFunction));
3178
                    if ($fName === 'FALSE') {
3179 114
                        $falseTrueArray[0][] = $lfName;
3180 114
                    } elseif ($fName === 'TRUE') {
3181 114
                        $falseTrueArray[1][] = $lfName;
3182 114
                    }
3183 114
                }
3184 114
            }
3185 114
        }
3186
        self::$falseTrueArray = $falseTrueArray;
3187
3188
        return $falseTrueArray;
3189
    }
3190 114
3191 114
    /**
3192
     * Set the locale code.
3193 114
     *
3194 114
     * @param string $locale The locale to use for formula translation, eg: 'en_us'
3195
     */
3196
    public function setLocale(string $locale): bool
3197
    {
3198 114
        //    Identify our locale and language
3199
        $language = $locale = strtolower($locale);
3200
        if (str_contains($locale, '_')) {
3201
            [$language] = explode('_', $locale);
3202
        }
3203 114
        if (count(self::$validLocaleLanguages) == 1) {
3204 114
            self::loadLocales();
3205 114
        }
3206 114
3207 114
        //    Test whether we have any language data for this language (any locale)
3208 114
        if (in_array($language, self::$validLocaleLanguages, true)) {
3209 114
            //    initialise language/locale settings
3210
            self::$localeFunctions = [];
3211 114
            self::$localeArgumentSeparator = ',';
3212 114
            self::$localeBoolean = ['TRUE' => 'TRUE', 'FALSE' => 'FALSE', 'NULL' => 'NULL'];
3213
3214 114
            //    Default is US English, if user isn't requesting US english, then read the necessary data from the locale files
3215
            if ($locale !== 'en_us') {
3216
                $localeDir = implode(DIRECTORY_SEPARATOR, [__DIR__, 'locale', null]);
3217
3218
                //    Search for a file with a list of function names for locale
3219
                try {
3220
                    $functionNamesFile = $this->getLocaleFile($localeDir, $locale, $language, 'functions');
3221 766
                } catch (Exception $e) {
3222 766
                    return false;
3223 766
                }
3224
3225 766
                //    Retrieve the list of locale or language specific function names
3226
                $localeFunctions = file($functionNamesFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: [];
3227
                foreach ($localeFunctions as $localeFunction) {
3228 3
                    [$localeFunction] = explode('##', $localeFunction); //    Strip out comments
3229
                    if (str_contains($localeFunction, '=')) {
3230
                        [$fName, $lfName] = array_map('trim', explode('=', $localeFunction));
3231 42
                        if ((str_starts_with($fName, '*') || isset(self::$phpSpreadsheetFunctions[$fName])) && ($lfName != '') && ($fName != $lfName)) {
3232
                            self::$localeFunctions[$fName] = $lfName;
3233
                        }
3234
                    }
3235
                }
3236
                //    Default the TRUE and FALSE constants to the locale names of the TRUE() and FALSE() functions
3237
                if (isset(self::$localeFunctions['TRUE'])) {
3238
                    self::$localeBoolean['TRUE'] = self::$localeFunctions['TRUE'];
3239 42
                }
3240 42
                if (isset(self::$localeFunctions['FALSE'])) {
3241 42
                    self::$localeBoolean['FALSE'] = self::$localeFunctions['FALSE'];
3242
                }
3243 42
3244 38
                try {
3245
                    $configFile = $this->getLocaleFile($localeDir, $locale, $language, 'config');
3246 38
                } catch (Exception) {
3247 42
                    return false;
3248 38
                }
3249
3250 38
                $localeSettings = file($configFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: [];
3251 42
                foreach ($localeSettings as $localeSetting) {
3252 23
                    [$localeSetting] = explode('##', $localeSetting); //    Strip out comments
3253 23
                    if (str_contains($localeSetting, '=')) {
3254
                        [$settingName, $settingValue] = array_map('trim', explode('=', $localeSetting));
3255
                        $settingName = strtoupper($settingName);
3256
                        if ($settingValue !== '') {
3257
                            switch ($settingName) {
3258 42
                                case 'ARGUMENTSEPARATOR':
3259
                                    self::$localeArgumentSeparator = $settingValue;
3260
3261 19
                                    break;
3262
                            }
3263
                        }
3264
                    }
3265
                }
3266
            }
3267
3268
            self::$functionReplaceFromExcel = self::$functionReplaceToExcel
3269
            = self::$functionReplaceFromLocale = self::$functionReplaceToLocale = null;
3270
            self::$localeLanguage = $locale;
3271 19
3272
            return true;
3273
        }
3274 19
3275 19
        return false;
3276
    }
3277 19
3278
    public static function translateSeparator(
3279 19
        string $fromSeparator,
3280 19
        string $toSeparator,
3281
        string $formula,
3282 19
        int &$inBracesLevel,
3283
        string $openBrace = self::FORMULA_OPEN_FUNCTION_BRACE,
3284
        string $closeBrace = self::FORMULA_CLOSE_FUNCTION_BRACE
3285 19
    ): string {
3286
        $strlen = mb_strlen($formula);
3287
        for ($i = 0; $i < $strlen; ++$i) {
3288
            $chr = mb_substr($formula, $i, 1);
3289 19
            switch ($chr) {
3290 19
                case $openBrace:
3291 19
                    ++$inBracesLevel;
3292
3293 19
                    break;
3294
                case $closeBrace:
3295
                    --$inBracesLevel;
3296 6
3297 6
                    break;
3298 6
                case $fromSeparator:
3299
                    if ($inBracesLevel > 0) {
3300 6
                        $formula = mb_substr($formula, 0, $i) . $toSeparator . mb_substr($formula, $i + 1);
3301 6
                    }
3302 6
            }
3303
        }
3304
3305 6
        return $formula;
3306
    }
3307 6
3308
    private static function translateFormulaBlock(
3309
        array $from,
3310 13
        array $to,
3311
        string $formula,
3312
        int &$inFunctionBracesLevel,
3313
        int &$inMatrixBracesLevel,
3314 19
        string $fromSeparator,
3315
        string $toSeparator
3316
    ): string {
3317
        // Function Names
3318
        $formula = (string) preg_replace($from, $to, $formula);
3319
3320
        // Temporarily adjust matrix separators so that they won't be confused with function arguments
3321 19
        $formula = self::translateSeparator(';', '|', $formula, $inMatrixBracesLevel, self::FORMULA_OPEN_MATRIX_BRACE, self::FORMULA_CLOSE_MATRIX_BRACE);
3322
        $formula = self::translateSeparator(',', '!', $formula, $inMatrixBracesLevel, self::FORMULA_OPEN_MATRIX_BRACE, self::FORMULA_CLOSE_MATRIX_BRACE);
3323 19
        // Function Argument Separators
3324
        $formula = self::translateSeparator($fromSeparator, $toSeparator, $formula, $inFunctionBracesLevel);
3325 19
        // Restore matrix separators
3326 19
        $formula = self::translateSeparator('|', ';', $formula, $inMatrixBracesLevel, self::FORMULA_OPEN_MATRIX_BRACE, self::FORMULA_CLOSE_MATRIX_BRACE);
3327 19
        $formula = self::translateSeparator('!', ',', $formula, $inMatrixBracesLevel, self::FORMULA_OPEN_MATRIX_BRACE, self::FORMULA_CLOSE_MATRIX_BRACE);
3328 19
3329
        return $formula;
3330 19
    }
3331 19
3332
    private static function translateFormula(array $from, array $to, string $formula, string $fromSeparator, string $toSeparator): string
3333
    {
3334
        // Convert any Excel function names and constant names to the required language;
3335 19
        //     and adjust function argument separators
3336 19
        if (self::$localeLanguage !== 'en_us') {
3337 19
            $inFunctionBracesLevel = 0;
3338 19
            $inMatrixBracesLevel = 0;
3339
            //    If there is the possibility of separators within a quoted string, then we treat them as literals
3340 19
            if (str_contains($formula, self::FORMULA_STRING_QUOTE)) {
3341 19
                //    So instead we skip replacing in any quoted strings by only replacing in every other array element
3342
                //       after we've exploded the formula
3343
                $temp = explode(self::FORMULA_STRING_QUOTE, $formula);
3344
                $notWithinQuotes = false;
3345 19
                foreach ($temp as &$value) {
3346 19
                    //    Only adjust in alternating array entries
3347 19
                    $notWithinQuotes = $notWithinQuotes === false;
3348 19
                    if ($notWithinQuotes === true) {
3349 19
                        $value = self::translateFormulaBlock($from, $to, $value, $inFunctionBracesLevel, $inMatrixBracesLevel, $fromSeparator, $toSeparator);
3350 19
                    }
3351 19
                }
3352
                unset($value);
3353
                //    Then rebuild the formula string
3354
                $formula = implode(self::FORMULA_STRING_QUOTE, $temp);
3355
            } else {
3356
                //    If there's no quoted strings, then we do a simple count/replace
3357
                $formula = self::translateFormulaBlock($from, $to, $formula, $inFunctionBracesLevel, $inMatrixBracesLevel, $fromSeparator, $toSeparator);
3358 19
            }
3359
        }
3360 19
3361 19
        return $formula;
3362 19
    }
3363 19
3364
    private static ?array $functionReplaceFromExcel;
3365 19
3366 19
    private static ?array $functionReplaceToLocale;
3367
3368
    public function translateFormulaToLocale(string $formula): string
3369
    {
3370 19
        $formula = preg_replace(self::CALCULATION_REGEXP_STRIP_XLFN_XLWS, '', $formula) ?? '';
3371 19
        // Build list of function names and constants for translation
3372 19
        if (self::$functionReplaceFromExcel === null) {
3373 19
            self::$functionReplaceFromExcel = [];
3374
            foreach (array_keys(self::$localeFunctions) as $excelFunctionName) {
3375 19
                self::$functionReplaceFromExcel[] = '/(@?[^\w\.])' . preg_quote($excelFunctionName, '/') . '([\s]*\()/ui';
3376 19
            }
3377
            foreach (array_keys(self::$localeBoolean) as $excelBoolean) {
3378
                self::$functionReplaceFromExcel[] = '/(@?[^\w\.])' . preg_quote($excelBoolean, '/') . '([^\w\.])/ui';
3379
            }
3380 19
        }
3381
3382
        if (self::$functionReplaceToLocale === null) {
3383 11581
            self::$functionReplaceToLocale = [];
3384
            foreach (self::$localeFunctions as $localeFunctionName) {
3385 11581
                self::$functionReplaceToLocale[] = '$1' . trim($localeFunctionName) . '$2';
3386 71
            }
3387 71
            foreach (self::$localeBoolean as $localeBoolean) {
3388 69
                self::$functionReplaceToLocale[] = '$1' . trim($localeBoolean) . '$2';
3389 69
            }
3390 69
        }
3391 66
3392
        return self::translateFormula(
3393
            self::$functionReplaceFromExcel,
3394
            self::$functionReplaceToLocale,
3395
            $formula,
3396 11581
            ',',
3397
            self::$localeArgumentSeparator
3398
        );
3399
    }
3400
3401
    private static ?array $functionReplaceFromLocale;
3402 11333
3403
    private static ?array $functionReplaceToExcel;
3404 11333
3405
    public function translateFormulaToEnglish(string $formula): string
3406 3906
    {
3407
        if (self::$functionReplaceFromLocale === null) {
3408 1214
            self::$functionReplaceFromLocale = [];
3409
            foreach (self::$localeFunctions as $localeFunctionName) {
3410
                self::$functionReplaceFromLocale[] = '/(@?[^\w\.])' . preg_quote($localeFunctionName, '/') . '([\s]*\()/ui';
3411
            }
3412 3141
            foreach (self::$localeBoolean as $excelBoolean) {
3413 8970
                self::$functionReplaceFromLocale[] = '/(@?[^\w\.])' . preg_quote($excelBoolean, '/') . '([^\w\.])/ui';
3414
            }
3415 4
        }
3416
3417
        if (self::$functionReplaceToExcel === null) {
3418 8967
            self::$functionReplaceToExcel = [];
3419
            foreach (array_keys(self::$localeFunctions) as $excelFunctionName) {
3420
                self::$functionReplaceToExcel[] = '$1' . trim($excelFunctionName) . '$2';
3421
            }
3422
            foreach (array_keys(self::$localeBoolean) as $excelBoolean) {
3423
                self::$functionReplaceToExcel[] = '$1' . trim($excelBoolean) . '$2';
3424 11501
            }
3425
        }
3426 11501
3427 3597
        return self::translateFormula(self::$functionReplaceFromLocale, self::$functionReplaceToExcel, $formula, self::$localeArgumentSeparator, ',');
3428 2908
    }
3429
3430
    public static function localeFunc(string $function): string
3431 10261
    {
3432
        if (self::$localeLanguage !== 'en_us') {
3433
            $functionName = trim($function, '(');
3434
            if (isset(self::$localeFunctions[$functionName])) {
3435 10326
                $brace = ($functionName != $function);
3436
                $function = self::$localeFunctions[$functionName];
3437
                if ($brace) {
3438
                    $function .= '(';
3439
                }
3440
            }
3441
        }
3442
3443
        return $function;
3444
    }
3445
3446
    /**
3447
     * Wrap string values in quotes.
3448
     */
3449
    public static function wrapResult(mixed $value): mixed
3450
    {
3451
        if (is_string($value)) {
3452
            //    Error values cannot be "wrapped"
3453
            if (preg_match('/^' . self::CALCULATION_REGEXP_ERROR . '$/i', $value, $match)) {
3454
                //    Return Excel errors "as is"
3455
                return $value;
3456
            }
3457
3458
            //    Return strings wrapped in quotes
3459 7916
            return self::FORMULA_STRING_QUOTE . $value . self::FORMULA_STRING_QUOTE;
3460
        } elseif ((is_float($value)) && ((is_nan($value)) || (is_infinite($value)))) {
3461 7916
            //    Convert numeric errors to NaN error
3462
            return ExcelError::NAN();
3463
        }
3464
3465 7916
        return $value;
3466
    }
3467 7905
3468 7905
    /**
3469 7905
     * Remove quotes used as a wrapper to identify string values.
3470 7905
     */
3471
    public static function unwrapResult(mixed $value): mixed
3472
    {
3473
        if (is_string($value)) {
3474 7916
            if ((isset($value[0])) && ($value[0] == self::FORMULA_STRING_QUOTE) && (substr($value, -1) == self::FORMULA_STRING_QUOTE)) {
3475 7916
                return substr($value, 1, -1);
3476 7916
            }
3477 7916
            //    Convert numeric errors to NAN error
3478
        } elseif ((is_float($value)) && ((is_nan($value)) || (is_infinite($value)))) {
3479 7916
            return ExcelError::NAN();
3480 7916
        }
3481
3482
        return $value;
3483 7916
    }
3484 7916
3485 7916
    /**
3486 7916
     * Calculate cell value (using formula from a cell ID)
3487 7916
     * Retained for backward compatibility.
3488 7916
     *
3489 7916
     * @param ?Cell $cell Cell to calculate
3490
     */
3491 7916
    public function calculate(?Cell $cell = null): mixed
3492 7674
    {
3493
        try {
3494
            return $this->calculateCellValue($cell);
3495 7674
        } catch (\Exception $e) {
3496 7674
            throw new Exception($e->getMessage());
3497 7674
        }
3498
    }
3499
3500 7674
    /**
3501 7674
     * Calculate the value of a cell formula.
3502
     *
3503
     * @param ?Cell $cell Cell to calculate
3504 7674
     * @param bool $resetLog Flag indicating whether the debug log should be reset or not
3505 260
     */
3506 260
    public function calculateCellValue(?Cell $cell = null, bool $resetLog = true): mixed
3507 260
    {
3508
        if ($cell === null) {
3509 260
            return null;
3510 260
        }
3511 260
3512 260
        if ($resetLog) {
3513
            //    Initialise the logging settings if requested
3514
            $this->formulaError = null;
3515
            $this->debugLog->clearLog();
3516 260
            $this->cyclicReferenceStack->clear();
3517
            $this->cyclicFormulaCounter = 1;
3518
        }
3519 7674
3520 4772
        //    Execute the calculation for the cell formula
3521 4772
        $this->cellStack[] = [
3522 1
            'sheet' => $cell->getWorksheet()->getTitle(),
3523
            'cell' => $cell->getCoordinate(),
3524 4772
        ];
3525
3526
        $cellAddressAttempted = false;
3527 7674
        $cellAddress = null;
3528 16
3529 7673
        try {
3530
            $value = $cell->getValue();
3531
            if ($cell->getDataType() === DataType::TYPE_FORMULA) {
3532
                $value = preg_replace_callback(
3533 7673
                    self::CALCULATION_REGEXP_CELLREF_SPILL,
3534
                    fn (array $matches) => 'ANCHORARRAY(' . substr($matches[0], 0, -1) . ')',
3535
                    $value
3536
                );
3537
            }
3538
            $result = self::unwrapResult($this->_calculateFormulaValue($value, $cell->getCoordinate(), $cell));
3539
            if ($this->spreadsheet === null) {
3540
                throw new Exception('null spreadsheet in calculateCellValue');
3541 7902
            }
3542
            $cellAddressAttempted = true;
3543 7902
            $cellAddress = array_pop($this->cellStack);
3544 7902
            if ($cellAddress === null) {
3545 7902
                throw new Exception('null cellAddress in calculateCellValue');
3546 7902
            }
3547 7902
            $testSheet = $this->spreadsheet->getSheetByName($cellAddress['sheet']);
3548
            if ($testSheet === null) {
3549
                throw new Exception('worksheet not found in calculateCellValue');
3550 7902
            }
3551 7902
            $testSheet->getCell($cellAddress['cell']);
3552
        } catch (\Exception $e) {
3553
            if (!$cellAddressAttempted) {
3554 7902
                $cellAddress = array_pop($this->cellStack);
3555 7902
            }
3556
            if ($this->spreadsheet !== null && is_array($cellAddress) && array_key_exists('sheet', $cellAddress)) {
3557
                $testSheet = $this->spreadsheet->getSheetByName($cellAddress['sheet']);
3558
                if ($testSheet !== null && array_key_exists('cell', $cellAddress)) {
3559
                    $testSheet->getCell($cellAddress['cell']);
3560 7902
                }
3561
            }
3562
3563
            throw new Exception($e->getMessage(), $e->getCode(), $e);
3564
        }
3565
3566
        if (is_array($result) && $this->getInstanceArrayReturnType() !== self::RETURN_ARRAY_AS_ARRAY) {
3567
            $testResult = Functions::flattenArray($result);
3568
            if ($this->getInstanceArrayReturnType() == self::RETURN_ARRAY_AS_ERROR) {
3569
                return ExcelError::VALUE();
3570 174
            }
3571
            $result = array_shift($testResult);
3572
        }
3573 174
3574 174
        if ($result === null && $cell->getWorksheet()->getSheetView()->getShowZeros()) {
3575 174
            return 0;
3576
        } elseif ((is_float($result)) && ((is_nan($result)) || (is_infinite($result)))) {
3577 174
            return ExcelError::NAN();
3578 174
        }
3579 167
3580 167
        return $result;
3581
    }
3582
3583
    /**
3584 7
     * Validate and parse a formula string.
3585
     *
3586
     * @param string $formula Formula to parse
3587
     */
3588
    public function parseFormula(string $formula): array|bool
3589 174
    {
3590 1
        $formula = preg_replace_callback(
3591 1
            self::CALCULATION_REGEXP_CELLREF_SPILL,
3592
            fn (array $matches) => 'ANCHORARRAY(' . substr($matches[0], 0, -1) . ')',
3593
            $formula
3594 174
        ) ?? $formula;
3595
        //    Basic validation that this is indeed a formula
3596
        //    We return an empty array if not
3597
        $formula = trim($formula);
3598
        if ((!isset($formula[0])) || ($formula[0] != '=')) {
3599 174
            return [];
3600
        }
3601
        $formula = ltrim(substr($formula, 1));
3602 8061
        if (!isset($formula[0])) {
3603
            return [];
3604 8061
        }
3605
3606
        //    Parse the formula and return the token stack
3607 8061
        return $this->internalParseFormula($formula);
3608 311
    }
3609
3610
    /**
3611 311
     * Calculate the value of a formula.
3612
     *
3613 311
     * @param string $formula Formula to parse
3614
     * @param ?string $cellID Address of the cell to calculate
3615
     * @param ?Cell $cell Cell to calculate
3616 8061
     */
3617
    public function calculateFormula(string $formula, ?string $cellID = null, ?Cell $cell = null): mixed
3618
    {
3619 7818
        //    Initialise the logging settings
3620
        $this->formulaError = null;
3621 7818
        $this->debugLog->clearLog();
3622 7813
        $this->cyclicReferenceStack->clear();
3623
3624
        $resetCache = $this->getCalculationCacheEnabled();
3625
        if ($this->spreadsheet !== null && $cellID === null && $cell === null) {
3626
            $cellID = 'A1';
3627
            $cell = $this->spreadsheet->getActiveSheet()->getCell($cellID);
3628
        } else {
3629
            //    Disable calculation cacheing because it only applies to cell calculations, not straight formulae
3630
            //    But don't actually flush any cache
3631
            $this->calculationCacheEnabled = false;
3632
        }
3633
3634 11764
        //    Execute the calculation
3635
        try {
3636 11764
            $result = self::unwrapResult($this->_calculateFormulaValue($formula, $cellID, $cell));
3637
        } catch (\Exception $e) {
3638
            throw new Exception($e->getMessage());
3639 11764
        }
3640 1
3641
        if ($this->spreadsheet === null) {
3642
            //    Reset calculation cacheing to its previous state
3643 11764
            $this->calculationCacheEnabled = $resetCache;
3644
        }
3645
3646
        return $result;
3647
    }
3648
3649 11764
    public function getValueFromCache(string $cellReference, mixed &$cellValue): bool
3650 11764
    {
3651 2
        $this->debugLog->writeDebugLog('Testing cache value for cell %s', $cellReference);
3652
        // Is calculation cacheing enabled?
3653 11764
        // If so, is the required value present in calculation cache?
3654 11764
        if (($this->calculationCacheEnabled) && (isset($this->calculationCache[$cellReference]))) {
3655 5
            $this->debugLog->writeDebugLog('Retrieving value for cell %s from cache', $cellReference);
3656
            // Return the cached result
3657
3658 11763
            $cellValue = $this->calculationCache[$cellReference];
3659 11763
3660 11763
            return true;
3661
        }
3662 11763
3663 307
        return false;
3664
    }
3665 11763
3666
    public function saveValueToCache(string $cellReference, mixed $cellValue): void
3667 11763
    {
3668 12
        if ($this->calculationCacheEnabled) {
3669 1
            $this->calculationCache[$cellReference] = $cellValue;
3670
        }
3671 1
    }
3672 11
3673 1
    /**
3674 1
     * Parse a cell formula and calculate its value.
3675 1
     *
3676
     * @param string $formula The formula to parse and calculate
3677 1
     * @param ?string $cellID The ID (e.g. A3) of the cell that we are calculating
3678
     * @param ?Cell $cell Cell to calculate
3679 11
     * @param bool $ignoreQuotePrefix If set to true, evaluate the formyla even if the referenced cell is quote prefixed
3680 11
     */
3681 10
    public function _calculateFormulaValue(string $formula, ?string $cellID = null, ?Cell $cell = null, bool $ignoreQuotePrefix = false): mixed
3682
    {
3683 1
        $cellValue = null;
3684
3685
        //  Quote-Prefixed cell values cannot be formulae, but are treated as strings
3686
        if ($cell !== null && $ignoreQuotePrefix === false && $cell->getStyle()->getQuotePrefix() === true) {
3687 11763
            return self::wrapResult((string) $formula);
3688
        }
3689 11763
3690
        if (preg_match('/^=\s*cmd\s*\|/miu', $formula) !== 0) {
3691 11763
            return self::wrapResult($formula);
3692 11518
        }
3693
3694
        //    Basic validation that this is indeed a formula
3695 11518
        //    We simply return the cell value if not
3696 7818
        $formula = trim($formula);
3697
        if ($formula === '' || $formula[0] !== '=') {
3698
            return self::wrapResult($formula);
3699
        }
3700 11518
        $formula = ltrim(substr($formula, 1));
3701
        if (!isset($formula[0])) {
3702
            return self::wrapResult($formula);
3703
        }
3704
3705
        $pCellParent = ($cell !== null) ? $cell->getWorksheet() : null;
3706
        $wsTitle = ($pCellParent !== null) ? $pCellParent->getTitle() : "\x00Wrk";
3707
        $wsCellReference = $wsTitle . '!' . $cellID;
3708
3709
        if (($cellID !== null) && ($this->getValueFromCache($wsCellReference, $cellValue))) {
3710
            return $cellValue;
3711
        }
3712
        $this->debugLog->writeDebugLog('Evaluating formula for cell %s', $wsCellReference);
3713
3714
        if (($wsTitle[0] !== "\x00") && ($this->cyclicReferenceStack->onStack($wsCellReference))) {
3715 60
            if ($this->cyclicFormulaCount <= 0) {
3716
                $this->cyclicFormulaCell = '';
3717
3718
                return $this->raiseFormulaError('Cyclic Reference in Formula');
3719 60
            } elseif ($this->cyclicFormulaCell === $wsCellReference) {
3720 18
                ++$this->cyclicFormulaCounter;
3721 18
                if ($this->cyclicFormulaCounter >= $this->cyclicFormulaCount) {
3722 18
                    $this->cyclicFormulaCell = '';
3723 48
3724 16
                    return $cellValue;
3725 16
                }
3726 16
            } elseif ($this->cyclicFormulaCell == '') {
3727
                if ($this->cyclicFormulaCounter >= $this->cyclicFormulaCount) {
3728
                    return $cellValue;
3729 60
                }
3730 60
                $this->cyclicFormulaCell = $wsCellReference;
3731 60
            }
3732 22
        }
3733 41
3734 33
        $this->debugLog->writeDebugLog('Formula for cell %s is %s', $wsCellReference, $formula);
3735
        //    Parse the formula onto the token stack and calculate the value
3736
        $this->cyclicReferenceStack->push($wsCellReference);
3737 60
3738
        $cellValue = $this->processTokenStack($this->internalParseFormula($formula, $cell), $cellID, $cell);
3739 24
        $this->cyclicReferenceStack->pop();
3740 40
3741
        // Save to calculation cache
3742 33
        if ($cellID !== null) {
3743
            $this->saveValueToCache($wsCellReference, $cellValue);
3744 60
        }
3745 60
3746
        //    Return the calculated value
3747 60
        return $cellValue;
3748
    }
3749
3750
    /**
3751
     * Ensure that paired matrix operands are both matrices and of the same size.
3752
     *
3753
     * @param mixed $operand1 First matrix operand
3754
     * @param mixed $operand2 Second matrix operand
3755
     * @param int $resize Flag indicating whether the matrices should be resized to match
3756
     *                                        and (if so), whether the smaller dimension should grow or the
3757 94
     *                                        larger should shrink.
3758
     *                                            0 = no resize
3759 94
     *                                            1 = shrink to fit
3760 94
     *                                            2 = extend to fit
3761 94
     */
3762 92
    public static function checkMatrixOperands(mixed &$operand1, mixed &$operand2, int $resize = 1): array
3763 4
    {
3764 4
        //    Examine each of the two operands, and turn them into an array if they aren't one already
3765
        //    Note that this function should only be called if one or both of the operand is already an array
3766 88
        if (!is_array($operand1)) {
3767 88
            [$matrixRows, $matrixColumns] = self::getMatrixDimensions($operand2);
3768
            $operand1 = array_fill(0, $matrixRows, array_fill(0, $matrixColumns, $operand1));
3769
            $resize = 0;
3770 94
        } elseif (!is_array($operand2)) {
3771
            [$matrixRows, $matrixColumns] = self::getMatrixDimensions($operand1);
3772 94
            $operand2 = array_fill(0, $matrixRows, array_fill(0, $matrixColumns, $operand2));
3773
            $resize = 0;
3774
        }
3775
3776
        [$matrix1Rows, $matrix1Columns] = self::getMatrixDimensions($operand1);
3777
        [$matrix2Rows, $matrix2Columns] = self::getMatrixDimensions($operand2);
3778
        if ($resize === 3) {
3779
            $resize = 2;
3780
        } elseif (($matrix1Rows == $matrix2Columns) && ($matrix2Rows == $matrix1Columns)) {
3781
            $resize = 1;
3782
        }
3783
3784
        if ($resize == 2) {
3785 33
            //    Given two matrices of (potentially) unequal size, convert the smaller in each dimension to match the larger
3786
            self::resizeMatricesExtend($operand1, $operand2, $matrix1Rows, $matrix1Columns, $matrix2Rows, $matrix2Columns);
3787 33
        } elseif ($resize == 1) {
3788
            //    Given two matrices of (potentially) unequal size, convert the larger in each dimension to match the smaller
3789
            self::resizeMatricesShrink($operand1, $operand2, $matrix1Rows, $matrix1Columns, $matrix2Rows, $matrix2Columns);
3790
        }
3791
        [$matrix1Rows, $matrix1Columns] = self::getMatrixDimensions($operand1);
3792
        [$matrix2Rows, $matrix2Columns] = self::getMatrixDimensions($operand2);
3793
3794
        return [$matrix1Rows, $matrix1Columns, $matrix2Rows, $matrix2Columns];
3795
    }
3796
3797
    /**
3798
     * Read the dimensions of a matrix, and re-index it with straight numeric keys starting from row 0, column 0.
3799
     *
3800
     * @param array $matrix matrix operand
3801
     *
3802 33
     * @return int[] An array comprising the number of rows, and number of columns
3803
     */
3804
    public static function getMatrixDimensions(array &$matrix): array
3805
    {
3806
        $matrixRows = count($matrix);
3807
        $matrixColumns = 0;
3808
        foreach ($matrix as $rowKey => $rowValue) {
3809
            if (!is_array($rowValue)) {
3810
                $matrix[$rowKey] = [$rowValue];
3811
                $matrixColumns = max(1, $matrixColumns);
3812
            } else {
3813
                $matrix[$rowKey] = array_values($rowValue);
3814
                $matrixColumns = max(count($rowValue), $matrixColumns);
3815
            }
3816
        }
3817
        $matrix = array_values($matrix);
3818
3819
        return [$matrixRows, $matrixColumns];
3820
    }
3821
3822
    /**
3823
     * Ensure that paired matrix operands are both matrices of the same size.
3824
     *
3825
     * @param array $matrix1 First matrix operand
3826
     * @param array $matrix2 Second matrix operand
3827
     * @param int $matrix1Rows Row size of first matrix operand
3828 24
     * @param int $matrix1Columns Column size of first matrix operand
3829
     * @param int $matrix2Rows Row size of second matrix operand
3830 24
     * @param int $matrix2Columns Column size of second matrix operand
3831 16
     */
3832 15
    private static function resizeMatricesShrink(array &$matrix1, array &$matrix2, int $matrix1Rows, int $matrix1Columns, int $matrix2Rows, int $matrix2Columns): void
3833 15
    {
3834 15
        if (($matrix2Columns < $matrix1Columns) || ($matrix2Rows < $matrix1Rows)) {
3835 15
            if ($matrix2Rows < $matrix1Rows) {
3836
                for ($i = $matrix2Rows; $i < $matrix1Rows; ++$i) {
3837
                    unset($matrix1[$i]);
3838
                }
3839 16
            }
3840 2
            if ($matrix2Columns < $matrix1Columns) {
3841 2
                for ($i = 0; $i < $matrix1Rows; ++$i) {
3842 2
                    for ($j = $matrix2Columns; $j < $matrix1Columns; ++$j) {
3843
                        unset($matrix1[$i][$j]);
3844
                    }
3845
                }
3846
            }
3847 24
        }
3848 15
3849
        if (($matrix1Columns < $matrix2Columns) || ($matrix1Rows < $matrix2Rows)) {
3850
            if ($matrix1Rows < $matrix2Rows) {
3851
                for ($i = $matrix1Rows; $i < $matrix2Rows; ++$i) {
3852
                    unset($matrix2[$i]);
3853
                }
3854
            }
3855
            if ($matrix1Columns < $matrix2Columns) {
3856 15
                for ($i = 0; $i < $matrix2Rows; ++$i) {
3857 15
                    for ($j = $matrix1Columns; $j < $matrix2Columns; ++$j) {
3858 15
                        unset($matrix2[$i][$j]);
3859 15
                    }
3860
                }
3861
            }
3862
        }
3863
    }
3864
3865
    /**
3866
     * Ensure that paired matrix operands are both matrices of the same size.
3867
     *
3868
     * @param array $matrix1 First matrix operand
3869
     * @param array $matrix2 Second matrix operand
3870 11506
     * @param int $matrix1Rows Row size of first matrix operand
3871
     * @param int $matrix1Columns Column size of first matrix operand
3872 11506
     * @param int $matrix2Rows Row size of second matrix operand
3873 3
     * @param int $matrix2Columns Column size of second matrix operand
3874 3
     */
3875 3
    private static function resizeMatricesExtend(array &$matrix1, array &$matrix2, int $matrix1Rows, int $matrix1Columns, int $matrix2Rows, int $matrix2Columns): void
3876
    {
3877
        if (($matrix2Columns < $matrix1Columns) || ($matrix2Rows < $matrix1Rows)) {
3878 3
            if ($matrix2Columns < $matrix1Columns) {
3879 2
                for ($i = 0; $i < $matrix2Rows; ++$i) {
3880 2
                    $x = $matrix2[$i][$matrix2Columns - 1];
3881 2
                    for ($j = $matrix2Columns; $j < $matrix1Columns; ++$j) {
3882 2
                        $matrix2[$i][$j] = $x;
3883 2
                    }
3884 2
                }
3885
            }
3886
            if ($matrix2Rows < $matrix1Rows) {
3887
                $x = $matrix2[$matrix2Rows - 1];
3888
                for ($i = 0; $i < $matrix1Rows; ++$i) {
3889
                    $matrix2[$i] = $x;
3890 2
                }
3891 3
            }
3892 2
        }
3893 3
3894
        if (($matrix1Columns < $matrix2Columns) || ($matrix1Rows < $matrix2Rows)) {
3895 3
            if ($matrix1Columns < $matrix2Columns) {
3896
                for ($i = 0; $i < $matrix1Rows; ++$i) {
3897
                    $x = $matrix1[$i][$matrix1Columns - 1];
3898
                    for ($j = $matrix1Columns; $j < $matrix2Columns; ++$j) {
3899
                        $matrix1[$i][$j] = $x;
3900 11506
                    }
3901
                }
3902
            }
3903
            if ($matrix1Rows < $matrix2Rows) {
3904
                $x = $matrix1[$matrix1Rows - 1];
3905
                for ($i = 0; $i < $matrix2Rows; ++$i) {
3906
                    $matrix1[$i] = $x;
3907
                }
3908 11520
            }
3909
        }
3910 11520
    }
3911 3
3912 3
    /**
3913 3
     * Format details of an operand for display in the log (based on operand type).
3914
     *
3915
     * @param mixed $value First matrix operand
3916 3
     */
3917
    private function showValue(mixed $value): mixed
3918 3
    {
3919 3
        if ($this->debugLog->getWriteDebugLog()) {
3920 3
            $testArray = Functions::flattenArray($value);
3921 3
            if (count($testArray) == 1) {
3922 2
                $value = array_pop($testArray);
3923
            }
3924 2
3925 2
            if (is_array($value)) {
3926
                $returnMatrix = [];
3927
                $pad = $rpad = ', ';
3928
                foreach ($value as $row) {
3929
                    if (is_array($row)) {
3930
                        $returnMatrix[] = implode($pad, array_map([$this, 'showValue'], $row));
3931
                        $rpad = '; ';
3932
                    } else {
3933
                        $returnMatrix[] = $this->showValue($row);
3934
                    }
3935 3
                }
3936
3937
                return '{ ' . implode($rpad, $returnMatrix) . ' }';
3938 11517
            } elseif (is_string($value) && (trim($value, self::FORMULA_STRING_QUOTE) == $value)) {
3939
                return self::FORMULA_STRING_QUOTE . $value . self::FORMULA_STRING_QUOTE;
3940
            } elseif (is_bool($value)) {
3941
                return ($value) ? self::$localeBoolean['TRUE'] : self::$localeBoolean['FALSE'];
3942
            } elseif ($value === null) {
3943
                return self::$localeBoolean['NULL'];
3944 11897
            }
3945
        }
3946 11897
3947 11897
        return Functions::flattenSingleValue($value);
3948
    }
3949
3950 11897
    /**
3951
     * Format type and details of an operand for display in the log (based on operand type).
3952 781
     *
3953
     * @param mixed $value First matrix operand
3954
     */
3955 241
    private function showTypeDetails(mixed $value): ?string
3956
    {
3957 241
        if ($this->debugLog->getWriteDebugLog()) {
3958 241
            $testArray = Functions::flattenArray($value);
3959 241
            if (count($testArray) == 1) {
3960
                $value = array_pop($testArray);
3961 241
            }
3962 241
3963 241
            if ($value === null) {
3964 241
                return 'a NULL value';
3965 241
            } elseif (is_float($value)) {
3966
                $typeString = 'a floating point number';
3967
            } elseif (is_int($value)) {
3968 241
                $typeString = 'an integer number';
3969
            } elseif (is_bool($value)) {
3970 241
                $typeString = 'a boolean';
3971
            } elseif (is_array($value)) {
3972
                $typeString = 'a matrix';
3973 541
            } else {
3974 541
                if ($value == '') {
3975 541
                    return 'an empty string';
3976
                } elseif ($value[0] == '#') {
3977
                    return 'a ' . $value . ' error';
3978 781
                }
3979
                $typeString = 'a string';
3980
            }
3981
3982
            return $typeString . ' with a value of ' . $this->showValue($value);
3983
        }
3984 781
3985
        return null;
3986
    }
3987
3988
    /**
3989
     * @return false|string False indicates an error
3990
     */
3991
    private function convertMatrixReferences(string $formula): false|string
3992
    {
3993 11897
        static $matrixReplaceFrom = [self::FORMULA_OPEN_MATRIX_BRACE, ';', self::FORMULA_CLOSE_MATRIX_BRACE];
3994
        static $matrixReplaceTo = ['MKMATRIX(MKMATRIX(', '),MKMATRIX(', '))'];
3995
3996
        //    Convert any Excel matrix references to the MKMATRIX() function
3997
        if (str_contains($formula, self::FORMULA_OPEN_MATRIX_BRACE)) {
3998
            //    If there is the possibility of braces within a quoted string, then we don't treat those as matrix indicators
3999
            if (str_contains($formula, self::FORMULA_STRING_QUOTE)) {
4000
                //    So instead we skip replacing in any quoted strings by only replacing in every other array element after we've exploded
4001
                //        the formula
4002
                $temp = explode(self::FORMULA_STRING_QUOTE, $formula);
4003
                //    Open and Closed counts used for trapping mismatched braces in the formula
4004
                $openCount = $closeCount = 0;
4005
                $notWithinQuotes = false;
4006
                foreach ($temp as &$value) {
4007
                    //    Only count/replace in alternating array entries
4008
                    $notWithinQuotes = $notWithinQuotes === false;
4009
                    if ($notWithinQuotes === true) {
4010
                        $openCount += substr_count($value, self::FORMULA_OPEN_MATRIX_BRACE);
4011
                        $closeCount += substr_count($value, self::FORMULA_CLOSE_MATRIX_BRACE);
4012
                        $value = str_replace($matrixReplaceFrom, $matrixReplaceTo, $value);
4013
                    }
4014
                }
4015
                unset($value);
4016
                //    Then rebuild the formula string
4017
                $formula = implode(self::FORMULA_STRING_QUOTE, $temp);
4018
            } else {
4019
                //    If there's no quoted strings, then we do a simple count/replace
4020
                $openCount = substr_count($formula, self::FORMULA_OPEN_MATRIX_BRACE);
4021
                $closeCount = substr_count($formula, self::FORMULA_CLOSE_MATRIX_BRACE);
4022
                $formula = str_replace($matrixReplaceFrom, $matrixReplaceTo, $formula);
4023
            }
4024
            //    Trap for mismatched braces and trigger an appropriate error
4025
            if ($openCount < $closeCount) {
4026
                if ($openCount > 0) {
4027
                    return $this->raiseFormulaError("Formula Error: Mismatched matrix braces '}'");
4028
                }
4029
4030
                return $this->raiseFormulaError("Formula Error: Unexpected '}' encountered");
4031
            } elseif ($openCount > $closeCount) {
4032
                if ($closeCount > 0) {
4033
                    return $this->raiseFormulaError("Formula Error: Mismatched matrix braces '{'");
4034
                }
4035
4036
                return $this->raiseFormulaError("Formula Error: Unexpected '{' encountered");
4037
            }
4038
        }
4039 11897
4040
        return $formula;
4041 11897
    }
4042
4043
    /**
4044
     *    Binary Operators.
4045
     *    These operators always work on two values.
4046
     *    Array key is the operator, the value indicates whether this is a left or right associative operator.
4047 11897
     */
4048
    private static array $operatorAssociativity = [
4049 11897
        '^' => 0, //    Exponentiation
4050 11897
        '*' => 0, '/' => 0, //    Multiplication and Division
4051 11897
        '+' => 0, '-' => 0, //    Addition and Subtraction
4052 11897
        '&' => 0, //    Concatenation
4053 11897
        '∪' => 0, '∩' => 0, ':' => 0, //    Union, Intersect and Range
4054 11897
        '>' => 0, '<' => 0, '=' => 0, '>=' => 0, '<=' => 0, '<>' => 0, //    Comparison
4055 11897
    ];
4056 11897
4057 11897
    /**
4058 11897
     *    Comparison (Boolean) Operators.
4059 11897
     *    These operators work on two values, but always return a boolean result.
4060
     */
4061
    private static array $comparisonOperators = ['>' => true, '<' => true, '=' => true, '>=' => true, '<=' => true, '<>' => true];
4062 11897
4063 11897
    /**
4064 11897
     *    Operator Precedence.
4065 11897
     *    This list includes all valid operators, whether binary (including boolean) or unary (such as %).
4066
     *    Array key is the operator, the value is its precedence.
4067 11897
     */
4068
    private static array $operatorPrecedence = [
4069
        ':' => 9, //    Range
4070
        '∩' => 8, //    Intersect
4071
        '∪' => 7, //    Union
4072 11897
        '~' => 6, //    Negation
4073
        '%' => 5, //    Percentage
4074
        '^' => 4, //    Exponentiation
4075 11897
        '*' => 3, '/' => 3, //    Multiplication and Division
4076
        '+' => 2, '-' => 2, //    Addition and Subtraction
4077 11897
        '&' => 1, //    Concatenation
4078
        '>' => 0, '<' => 0, '=' => 0, '>=' => 0, '<=' => 0, '<>' => 0, //    Comparison
4079
    ];
4080 11897
4081 80
    // Convert infix to postfix notation
4082
4083
    /**
4084
     * @return array<int, mixed>|false
4085 11897
     */
4086
    private function internalParseFormula(string $formula, ?Cell $cell = null): bool|array
4087 11897
    {
4088 11897
        if (($formula = $this->convertMatrixReferences(trim($formula))) === false) {
4089
            return false;
4090 1117
        }
4091 1117
4092 11897
        //    If we're using cell caching, then $pCell may well be flushed back to the cache (which detaches the parent worksheet),
4093
        //        so we store the parent worksheet so that we can re-attach it when necessary
4094 8
        $pCellParent = ($cell !== null) ? $cell->getWorksheet() : null;
4095 8
4096 11897
        $regexpMatchString = '/^((?<string>' . self::CALCULATION_REGEXP_STRING
4097 6
                                . ')|(?<function>' . self::CALCULATION_REGEXP_FUNCTION
4098 11897
                                . ')|(?<cellRef>' . self::CALCULATION_REGEXP_CELLREF
4099
                                . ')|(?<colRange>' . self::CALCULATION_REGEXP_COLUMN_RANGE
4100
                                . ')|(?<rowRange>' . self::CALCULATION_REGEXP_ROW_RANGE
4101 11897
                                . ')|(?<number>' . self::CALCULATION_REGEXP_NUMBER
4102
                                . ')|(?<openBrace>' . self::CALCULATION_REGEXP_OPENBRACE
4103 1670
                                . ')|(?<structuredReference>' . self::CALCULATION_REGEXP_STRUCTURED_REFERENCE
4104 1670
                                . ')|(?<definedName>' . self::CALCULATION_REGEXP_DEFINEDNAME
4105 1670
                                . ')|(?<error>' . self::CALCULATION_REGEXP_ERROR
4106 1670
                                . '))/sui';
4107
4108 82
        //    Start with initialisation
4109
        $index = 0;
4110
        $stack = new Stack($this->branchPruner);
4111
        $output = [];
4112 1670
        $expectingOperator = false; //    We use this test in syntax-checking the expression to determine when a
4113
        //        - is a negation or + is a positive operator rather than an operation
4114 1670
        $expectingOperand = false; //    We use this test in syntax-checking the expression to determine whether an operand
4115 1670
        //        should be null in a function call
4116 11897
4117 11549
        //    The guts of the lexical parser
4118 11549
        //    Loop through the formula extracting each operator and operand in turn
4119 1330
        while (true) {
4120
            // Branch pruning: we adapt the output item to the context (it will
4121 11549
            // be used to limit its computation)
4122
            $this->branchPruner->initialiseForLoop();
4123
4124
            $opCharacter = $formula[$index]; //    Get the first character of the value at the current index position
4125 11549
4126
            // Check for two-character operators (e.g. >=, <=, <>)
4127 11549
            if ((isset(self::$comparisonOperators[$opCharacter])) && (strlen($formula) > $index) && isset($formula[$index + 1], self::$comparisonOperators[$formula[$index + 1]])) {
4128
                $opCharacter .= $formula[++$index];
4129
            }
4130 11545
            //    Find out if we're currently at the beginning of a number, variable, cell/row/column reference,
4131 4
            //         function, defined name, structured reference, parenthesis, error or operand
4132 4
            $isOperandOrFunction = (bool) preg_match($regexpMatchString, substr($formula, $index), $match);
4133
4134
            $expectingOperatorCopy = $expectingOperator;
4135 11545
            if ($opCharacter === '-' && !$expectingOperator) {                //    Is it a negation instead of a minus?
4136 11545
                //    Put a negation on the stack
4137 11545
                $stack->push('Unary Operator', '~');
4138 11545
                ++$index; //        and drop the negation symbol
4139 11545
            } elseif ($opCharacter === '%' && $expectingOperator) {
4140 11545
                //    Put a percentage on the stack
4141 800
                $stack->push('Unary Operator', '%');
4142 11542
                ++$index;
4143 11542
            } elseif ($opCharacter === '+' && !$expectingOperator) {            //    Positive (unary plus rather than binary operator plus) can be discarded?
4144
                ++$index; //    Drop the redundant plus symbol
4145
            } elseif ((($opCharacter === '~') || ($opCharacter === '∩') || ($opCharacter === '∪')) && (!$isOperandOrFunction)) {
4146
                //    We have to explicitly deny a tilde, union or intersect because they are legal
4147
                return $this->raiseFormulaError("Formula Error: Illegal character '~'"); //        on the stack but not in the input expression
4148 11545
            } elseif ((isset(self::CALCULATION_OPERATORS[$opCharacter]) || $isOperandOrFunction) && $expectingOperator) {    //    Are we putting an operator on the stack?
4149 11545
                while (
4150 11545
                    $stack->count() > 0
4151 5851
                    && ($o2 = $stack->last())
4152 36
                    && isset(self::CALCULATION_OPERATORS[$o2['value']])
4153
                    && @(self::$operatorAssociativity[$opCharacter] ? self::$operatorPrecedence[$opCharacter] < self::$operatorPrecedence[$o2['value']] : self::$operatorPrecedence[$opCharacter] <= self::$operatorPrecedence[$o2['value']])
4154
                ) {
4155
                    $output[] = $stack->pop(); //    Swap operands and higher precedence operators from the stack to the output
4156
                }
4157 5817
4158 142
                //    Finally put our current operator onto the stack
4159 142
                $stack->push('Binary Operator', $opCharacter);
4160
4161
                ++$index;
4162 6441
                $expectingOperator = false;
4163 5966
            } elseif ($opCharacter === ')' && $expectingOperator) { //    Are we expecting to close a parenthesis?
4164 1
                $expectingOperand = false;
4165
                while (($o2 = $stack->pop()) && $o2['value'] !== '(') { //    Pop off the stack back to the last (
4166 5966
                    $output[] = $o2;
4167 5966
                }
4168 1102
                $d = $stack->last(2);
4169 25
4170 25
                // Branch pruning we decrease the depth whether is it a function
4171
                // call or a parenthesis
4172
                $this->branchPruner->decrementDepth();
4173 1102
4174 5023
                if (is_array($d) && preg_match('/^' . self::CALCULATION_REGEXP_FUNCTION . '$/miu', $d['value'], $matches)) {
4175 811
                    //    Did this parenthesis just close a function?
4176 12
                    try {
4177 12
                        $this->branchPruner->closingBrace($d['value']);
4178
                    } catch (Exception $e) {
4179
                        return $this->raiseFormulaError($e->getMessage(), $e->getCode(), $e);
4180 811
                    }
4181 4250
4182 4250
                    $functionName = $matches[1]; //    Get the function name
4183 39
                    $d = $stack->pop();
4184 39
                    $argumentCount = $d['value'] ?? 0; //    See how many arguments there were (argument count is the next value stored on the stack)
4185
                    $output[] = $d; //    Dump the argument count on the output
4186
                    $output[] = $stack->pop(); //    Pop the function and push onto the output
4187 4250
                    if (isset(self::$controlFunctions[$functionName])) {
4188
                        $expectedArgumentCount = self::$controlFunctions[$functionName]['argumentCount'];
4189
                    } elseif (isset(self::$phpSpreadsheetFunctions[$functionName])) {
4190 11545
                        $expectedArgumentCount = self::$phpSpreadsheetFunctions[$functionName]['argumentCount'];
4191 218
                    } else {    // did we somehow push a non-function on the stack? this should never happen
4192
                        return $this->raiseFormulaError('Formula Error: Internal error, non-function on stack');
4193
                    }
4194 11334
                    //    Check the argument count
4195 11897
                    $argumentCountError = false;
4196
                    $expectedArgumentCountString = null;
4197 7859
                    if (is_numeric($expectedArgumentCount)) {
4198
                        if ($expectedArgumentCount < 0) {
4199
                            if ($argumentCount > abs($expectedArgumentCount + 0)) {
4200
                                $argumentCountError = true;
4201
                                $expectedArgumentCountString = 'no more than ' . abs($expectedArgumentCount + 0);
4202 7859
                            }
4203 1365
                        } else {
4204
                            if ($argumentCount != $expectedArgumentCount) {
4205
                                $argumentCountError = true;
4206
                                $expectedArgumentCountString = $expectedArgumentCount;
4207 7859
                            }
4208 106
                        }
4209
                    } elseif ($expectedArgumentCount != '*') {
4210
                        if (1 !== preg_match('/(\d*)([-+,])(\d*)/', $expectedArgumentCount, $argMatch)) {
4211 7859
                            $argMatch = ['', '', '', ''];
4212 7859
                        }
4213
                        switch ($argMatch[2]) {
4214
                            case '+':
4215
                                if ($argumentCount < $argMatch[1]) {
4216
                                    $argumentCountError = true;
4217
                                    $expectedArgumentCountString = $argMatch[1] . ' or more ';
4218
                                }
4219
4220
                                break;
4221 7859
                            case '-':
4222 7859
                                if (($argumentCount < $argMatch[1]) || ($argumentCount > $argMatch[3])) {
4223
                                    $argumentCountError = true;
4224 7859
                                    $expectedArgumentCountString = 'between ' . $argMatch[1] . ' and ' . $argMatch[3];
4225 7859
                                }
4226
4227 7859
                                break;
4228 7859
                            case ',':
4229 7859
                                if (($argumentCount != $argMatch[1]) && ($argumentCount != $argMatch[3])) {
4230 11897
                                    $argumentCountError = true;
4231
                                    $expectedArgumentCountString = 'either ' . $argMatch[1] . ' or ' . $argMatch[3];
4232 29
                                }
4233 29
4234 29
                                break;
4235 11897
                        }
4236
                    }
4237 11893
                    if ($argumentCountError) {
4238 11893
                        return $this->raiseFormulaError("Formula Error: Wrong number of arguments for $functionName() function: $argumentCount given, " . $expectedArgumentCountString . ' expected');
4239 11893
                    }
4240 11893
                }
4241
                ++$index;
4242 11893
            } elseif ($opCharacter === ',') { // Is this the separator for function arguments?
4243 11551
                try {
4244 11551
                    $this->branchPruner->argumentSeparator();
4245 11549
                } catch (Exception $e) {
4246
                    return $this->raiseFormulaError($e->getMessage(), $e->getCode(), $e);
4247 4
                }
4248
4249
                while (($o2 = $stack->pop()) && $o2['value'] !== '(') {        //    Pop off the stack back to the last (
4250
                    $output[] = $o2; // pop the argument expression stuff and push onto the output
4251
                }
4252 11551
                //    If we've a comma when we're expecting an operand, then what we actually have is a null operand;
4253
                //        so push a null onto the stack
4254 11551
                if (($expectingOperand) || (!$expectingOperator)) {
4255
                    $output[] = $stack->getStackItem('Empty Argument', null, 'NULL');
4256 11551
                }
4257 11551
                // make sure there was a function
4258 321
                $d = $stack->last(2);
4259 321
                if (!preg_match('/^' . self::CALCULATION_REGEXP_FUNCTION . '$/miu', $d['value'] ?? '', $matches)) {
4260
                    // Can we inject a dummy function at this point so that the braces at least have some context
4261 11373
                    //     because at least the braces are paired up (at this stage in the formula)
4262 11373
                    // MS Excel allows this if the content is cell references; but doesn't allow actual values,
4263
                    //    but at this point, we can't differentiate (so allow both)
4264 11551
                    return $this->raiseFormulaError('Formula Error: Unexpected ,');
4265 11692
                }
4266
4267
                /** @var array $d */
4268
                $d = $stack->pop();
4269 6860
                ++$d['value']; // increment the argument count
4270 6860
4271
                $stack->pushStackItem($d);
4272 1118
                $stack->push('Brace', '('); // put the ( back on, we'll need to pop back to it again
4273
4274
                $expectingOperator = false;
4275 1114
                $expectingOperand = true;
4276 1114
                ++$index;
4277
            } elseif ($opCharacter === '(' && !$expectingOperator) {
4278 5
                // Branch pruning: we go deeper
4279
                $this->branchPruner->incrementDepth();
4280 1114
                $stack->push('Brace', '(', null);
4281 1114
                ++$index;
4282 1109
            } elseif ($isOperandOrFunction && !$expectingOperatorCopy) {
4283 1092
                // do we now have a function/variable/number?
4284
                $expectingOperator = true;
4285
                $expectingOperand = false;
4286 5
                $val = $match[1] ?? ''; //* @phpstan-ignore-line
4287
                $length = strlen($val);
4288
4289 4
                if (preg_match('/^' . self::CALCULATION_REGEXP_FUNCTION . '$/miu', $val, $matches)) {
4290 4
                    $val = (string) preg_replace('/\s/u', '', $val);
4291
                    if (isset(self::$phpSpreadsheetFunctions[strtoupper($matches[1])]) || isset(self::$controlFunctions[strtoupper($matches[1])])) {    // it's a function
4292
                        $valToUpper = strtoupper($val);
4293
                    } else {
4294 4
                        $valToUpper = 'NAME.ERROR(';
4295 4
                    }
4296 2
                    // here $matches[1] will contain values like "IF"
4297
                    // and $val "IF("
4298
4299 6855
                    $this->branchPruner->functionCall($valToUpper);
4300 6657
4301 6657
                    $stack->push('Function', $valToUpper);
4302
                    // tests if the function is closed right after opening
4303
                    $ax = preg_match('/^\s*\)/u', substr($formula, $index + $length));
4304 6860
                    if ($ax) {
4305 6860
                        $stack->push('Operand Count for Function ' . $valToUpper . ')', 0);
4306
                        $expectingOperator = true;
4307 6860
                    } else {
4308 6171
                        $stack->push('Operand Count for Function ' . $valToUpper . ')', 1);
4309
                        $expectingOperator = false;
4310 75
                    }
4311
                    $stack->push('Brace', '(');
4312
                } elseif (preg_match('/^' . self::CALCULATION_REGEXP_CELLREF . '$/miu', $val, $matches)) {
4313
                    //    Watch for this case-change when modifying to allow cell references in different worksheets...
4314
                    //    Should only be applied to the actual cell column, not the worksheet name
4315 75
                    //    If the last entry on the stack was a : operator, then we have a cell range reference
4316 75
                    $testPrevOp = $stack->last(1);
4317 75
                    if ($testPrevOp !== null && $testPrevOp['value'] === ':') {
4318
                        //    If we have a worksheet reference, then we're playing with a 3D reference
4319 75
                        if ($matches[2] === '') {
4320 75
                            //    Otherwise, we 'inherit' the worksheet reference from the start cell reference
4321
                            //    The start of the cell range reference should be the last entry in $output
4322
                            $rangeStartCellRef = $output[count($output) - 1]['value'] ?? '';
4323 6105
                            if ($rangeStartCellRef === ':') {
4324 6105
                                // Do we have chained range operators?
4325 6105
                                $rangeStartCellRef = $output[count($output) - 2]['value'] ?? '';
4326
                            }
4327
                            preg_match('/^' . self::CALCULATION_REGEXP_CELLREF . '$/miu', $rangeStartCellRef, $rangeStartMatches);
4328 6105
                            if (array_key_exists(2, $rangeStartMatches)) {
4329 6105
                                if ($rangeStartMatches[2] > '') {
4330 34
                                    $val = $rangeStartMatches[2] . '!' . $val;
4331
                                }
4332
                            } else {
4333 34
                                $val = ExcelError::REF();
4334 34
                            }
4335 34
                        } else {
4336 34
                            $rangeStartCellRef = $output[count($output) - 1]['value'] ?? '';
4337
                            if ($rangeStartCellRef === ':') {
4338 10
                                // Do we have chained range operators?
4339 10
                                $rangeStartCellRef = $output[count($output) - 2]['value'] ?? '';
4340 4
                            }
4341 4
                            preg_match('/^' . self::CALCULATION_REGEXP_CELLREF . '$/miu', $rangeStartCellRef, $rangeStartMatches);
4342 4
                            if (isset($rangeStartMatches[2]) && $rangeStartMatches[2] !== $matches[2]) {
4343 4
                                return $this->raiseFormulaError('3D Range references are not yet supported');
4344
                            }
4345 3
                        }
4346 3
                    } elseif (!str_contains($val, '!') && $pCellParent !== null) {
4347 3
                        $worksheet = $pCellParent->getTitle();
4348 3
                        $val = "'{$worksheet}'!{$val}";
4349 3
                    }
4350
                    // unescape any apostrophes or double quotes in worksheet name
4351 3
                    $val = str_replace(["''", '""'], ["'", '"'], $val);
4352
                    $outputItem = $stack->getStackItem('Cell Reference', $val, $val);
4353 4
4354
                    $output[] = $outputItem;
4355 30
                } elseif (preg_match('/^' . self::CALCULATION_REGEXP_STRUCTURED_REFERENCE . '$/miu', $val, $matches)) {
4356 3
                    try {
4357
                        $structuredReference = Operands\StructuredReference::fromParser($formula, $index, $matches);
4358
                    } catch (Exception $e) {
4359 27
                        return $this->raiseFormulaError($e->getMessage(), $e->getCode(), $e);
4360 27
                    }
4361 27
4362 27
                    $val = $structuredReference->value();
4363 18
                    $length = strlen($val);
4364
                    $outputItem = $stack->getStackItem(Operands\StructuredReference::NAME, $structuredReference, null);
4365 27
4366 27
                    $output[] = $outputItem;
4367 27
                    $expectingOperator = true;
4368
                } else {
4369
                    // it's a variable, constant, string, number or boolean
4370 27
                    $localeConstant = false;
4371
                    $stackItemType = 'Value';
4372
                    $stackItemReference = null;
4373 27
4374 27
                    //    If the last entry on the stack was a : operator, then we may have a row or column range reference
4375 4
                    $testPrevOp = $stack->last(1);
4376
                    if ($testPrevOp !== null && $testPrevOp['value'] === ':') {
4377
                        $stackItemType = 'Cell Reference';
4378 27
4379
                        if (
4380 8
                            !is_numeric($val)
4381
                            && ((ctype_alpha($val) === false || strlen($val) > 3))
4382 8
                            && (preg_match('/^' . self::CALCULATION_REGEXP_DEFINEDNAME . '$/mui', $val) !== false)
4383 8
                            && ($this->spreadsheet === null || $this->spreadsheet->getNamedRange($val) !== null)
4384 8
                        ) {
4385 19
                            $namedRange = ($this->spreadsheet === null) ? null : $this->spreadsheet->getNamedRange($val);
4386
                            if ($namedRange !== null) {
4387 14
                                $stackItemType = 'Defined Name';
4388 14
                                $address = str_replace('$', '', $namedRange->getValue());
4389 14
                                $stackItemReference = $val;
4390
                                if (str_contains($address, ':')) {
4391 27
                                    // We'll need to manipulate the stack for an actual named range rather than a named cell
4392
                                    $fromTo = explode(':', $address);
4393 6100
                                    $to = array_pop($fromTo);
4394
                                    foreach ($fromTo as $from) {
4395 2761
                                        $output[] = $stack->getStackItem($stackItemType, $from, $stackItemReference);
4396 4512
                                        $output[] = $stack->getStackItem('Binary Operator', ':');
4397 535
                                    }
4398 535
                                    $address = $to;
4399 535
                                }
4400 535
                                $val = $address;
4401 4235
                            }
4402 37
                        } elseif ($val === ExcelError::REF()) {
4403 37
                            $stackItemReference = $val;
4404 37
                        } else {
4405
                            /** @var non-empty-string $startRowColRef */
4406 4216
                            $startRowColRef = $output[count($output) - 1]['value'] ?? '';
4407
                            [$rangeWS1, $startRowColRef] = Worksheet::extractSheetTitle($startRowColRef, true);
4408 8
                            $rangeSheetRef = $rangeWS1;
4409 8
                            if ($rangeWS1 !== '') {
4410 8
                                $rangeWS1 .= '!';
4411
                            }
4412 8
                            $rangeSheetRef = trim($rangeSheetRef, "'");
4413 8
                            [$rangeWS2, $val] = Worksheet::extractSheetTitle($val, true);
4414 8
                            if ($rangeWS2 !== '') {
4415
                                $rangeWS2 .= '!';
4416
                            } else {
4417 8
                                $rangeWS2 = $rangeWS1;
4418 8
                            }
4419
4420 4209
                            $refSheet = $pCellParent;
4421
                            if ($pCellParent !== null && $rangeSheetRef !== '' && $rangeSheetRef !== $pCellParent->getTitle()) {
4422 14
                                $refSheet = $pCellParent->getParentOrThrow()->getSheetByName($rangeSheetRef);
4423 14
                            }
4424 14
4425
                            if (ctype_digit($val) && $val <= 1048576) {
4426 14
                                //    Row range
4427 14
                                $stackItemType = 'Row Reference';
4428 14
                                /** @var int $valx */
4429
                                $valx = $val;
4430
                                $endRowColRef = ($refSheet !== null) ? $refSheet->getHighestDataColumn($valx) : AddressRange::MAX_COLUMN; //    Max 16,384 columns for Excel2007
4431 14
                                $val = "{$rangeWS2}{$endRowColRef}{$val}";
4432 14
                            } elseif (ctype_alpha($val) && is_string($val) && strlen($val) <= 3) {
4433 4195
                                //    Column range
4434 136
                                $stackItemType = 'Column Reference';
4435 136
                                $endRowColRef = ($refSheet !== null) ? $refSheet->getHighestDataRow($val) : AddressRange::MAX_ROW; //    Max 1,048,576 rows for Excel2007
4436 4083
                                $val = "{$rangeWS2}{$val}{$endRowColRef}";
4437 4077
                            }
4438 1660
                            $stackItemReference = $val;
4439
                        }
4440 3327
                    } elseif ($opCharacter === self::FORMULA_STRING_QUOTE) {
4441
                        //    UnEscape any quotes within the string
4442
                        $val = self::wrapResult(str_replace('""', self::FORMULA_STRING_QUOTE, self::unwrapResult($val)));
4443
                    } elseif (isset(self::$excelConstants[trim(strtoupper($val))])) {
4444 6105
                        $stackItemType = 'Constant';
4445 6105
                        $excelConstant = trim(strtoupper($val));
4446 37
                        $val = self::$excelConstants[$excelConstant];
4447
                        $stackItemReference = $excelConstant;
4448 6105
                    } elseif (($localeConstant = array_search(trim(strtoupper($val)), self::$localeBoolean)) !== false) {
4449
                        $stackItemType = 'Constant';
4450 11893
                        $val = self::$excelConstants[$localeConstant];
4451 95
                        $stackItemReference = $localeConstant;
4452 6
                    } elseif (
4453 89
                        preg_match('/^' . self::CALCULATION_REGEXP_ROW_RANGE . '/miu', substr($formula, $index), $rowRangeReference)
4454 83
                    ) {
4455 83
                        $val = $rowRangeReference[1];
4456 83
                        $length = strlen($rowRangeReference[1]);
4457 83
                        $stackItemType = 'Row Reference';
4458
                        // unescape any apostrophes or double quotes in worksheet name
4459
                        $val = str_replace(["''", '""'], ["'", '"'], $val);
4460
                        $column = 'A';
4461 6
                        if (($testPrevOp !== null && $testPrevOp['value'] === ':') && $pCellParent !== null) {
4462
                            $column = $pCellParent->getHighestDataColumn($val);
4463
                        }
4464 6
                        $val = "{$rowRangeReference[2]}{$column}{$rowRangeReference[7]}";
4465
                        $stackItemReference = $val;
4466
                    } elseif (
4467 11893
                        preg_match('/^' . self::CALCULATION_REGEXP_COLUMN_RANGE . '/miu', substr($formula, $index), $columnRangeReference)
4468
                    ) {
4469
                        $val = $columnRangeReference[1];
4470 11674
                        $length = strlen($val);
4471 1
                        $stackItemType = 'Column Reference';
4472
                        // unescape any apostrophes or double quotes in worksheet name
4473
                        $val = str_replace(["''", '""'], ["'", '"'], $val);
4474 11673
                        $row = '1';
4475
                        if (($testPrevOp !== null && $testPrevOp['value'] === ':') && $pCellParent !== null) {
4476
                            $row = $pCellParent->getHighestDataRow($val);
4477 11869
                        }
4478
                        $val = "{$val}{$row}";
4479
                        $stackItemReference = $val;
4480
                    } elseif (preg_match('/^' . self::CALCULATION_REGEXP_DEFINEDNAME . '.*/miu', $val, $match)) {
4481 11869
                        $stackItemType = 'Defined Name';
4482 1946
                        $stackItemReference = $val;
4483 1946
                    } elseif (is_numeric($val)) {
4484
                        if ((str_contains((string) $val, '.')) || (stripos((string) $val, 'e') !== false) || ($val > PHP_INT_MAX) || ($val < -PHP_INT_MAX)) {
4485
                            $val = (float) $val;
4486
                        } else {
4487
                            $val = (int) $val;
4488 1946
                        }
4489
                    }
4490 1946
4491 1946
                    $details = $stack->getStackItem($stackItemType, $val, $stackItemReference);
4492 1946
                    if ($localeConstant) {
4493 1946
                        $details['localeValue'] = $localeConstant;
4494
                    }
4495 1946
                    $output[] = $details;
4496 1946
                }
4497 1946
                $index += $length;
4498 1946
            } elseif ($opCharacter === '$') { // absolute row or column range
4499 1946
                ++$index;
4500 1946
            } elseif ($opCharacter === ')') { // miscellaneous error checking
4501
                if ($expectingOperand) {
4502
                    $output[] = $stack->getStackItem('Empty Argument', null, 'NULL');
4503
                    $expectingOperand = false;
4504 18
                    $expectingOperator = true;
4505 18
                } else {
4506 18
                    return $this->raiseFormulaError("Formula Error: Unexpected ')'");
4507 18
                }
4508
            } elseif (isset(self::CALCULATION_OPERATORS[$opCharacter]) && !$expectingOperator) {
4509 11
                return $this->raiseFormulaError("Formula Error: Unexpected operator '$opCharacter'");
4510
            } else {    // I don't even want to know what you did to get here
4511 18
                return $this->raiseFormulaError('Formula Error: An unexpected error occurred');
4512 18
            }
4513
            //    Test for end of formula string
4514
            if ($index == strlen($formula)) {
4515
                //    Did we end with an operator?.
4516
                //    Only valid for the % unary operator
4517 11673
                if ((isset(self::CALCULATION_OPERATORS[$opCharacter])) && ($opCharacter != '%')) {
4518
                    return $this->raiseFormulaError("Formula Error: Operator '$opCharacter' has no operands");
4519 678
                }
4520 4
4521
                break;
4522 676
            }
4523
            //    Ignore white space
4524
            while (($formula[$index] === "\n") || ($formula[$index] === "\r")) {
4525 11671
                ++$index;
4526
            }
4527
4528 1558
            if ($formula[$index] === ' ') {
4529
                while ($formula[$index] === ' ') {
4530 1558
                    ++$index;
4531 1558
                }
4532 41
4533 41
                //    If we're expecting an operator, but only have a space between the previous and next operands (and both are
4534 41
                //        Cell References, Defined Names or Structured References) then we have an INTERSECTION operator
4535 5
                $countOutputMinus1 = count($output) - 1;
4536
                if (
4537 5
                    ($expectingOperator)
4538
                    && array_key_exists($countOutputMinus1, $output)
4539
                    && is_array($output[$countOutputMinus1])
4540 40
                    && array_key_exists('type', $output[$countOutputMinus1])
4541 40
                    && (
4542 40
                        (preg_match('/^' . self::CALCULATION_REGEXP_CELLREF . '.*/miu', substr($formula, $index), $match))
4543
                            && ($output[$countOutputMinus1]['type'] === 'Cell Reference')
4544
                        || (preg_match('/^' . self::CALCULATION_REGEXP_DEFINEDNAME . '.*/miu', substr($formula, $index), $match))
4545
                            && ($output[$countOutputMinus1]['type'] === 'Defined Name' || $output[$countOutputMinus1]['type'] === 'Value')
4546
                        || (preg_match('/^' . self::CALCULATION_REGEXP_STRUCTURED_REFERENCE . '.*/miu', substr($formula, $index), $match))
4547 1558
                            && ($output[$countOutputMinus1]['type'] === Operands\StructuredReference::NAME || $output[$countOutputMinus1]['type'] === 'Value')
4548
                    )
4549
                ) {
4550
                    while (
4551
                        $stack->count() > 0
4552
                        && ($o2 = $stack->last())
4553
                        && isset(self::CALCULATION_OPERATORS[$o2['value']])
4554
                        && @(self::$operatorAssociativity[$opCharacter] ? self::$operatorPrecedence[$opCharacter] < self::$operatorPrecedence[$o2['value']] : self::$operatorPrecedence[$opCharacter] <= self::$operatorPrecedence[$o2['value']])
4555
                    ) {
4556
                        $output[] = $stack->pop(); //    Swap operands and higher precedence operators from the stack to the output
4557
                    }
4558
                    $stack->push('Binary Operator', '∩'); //    Put an Intersect Operator on the stack
4559 11545
                    $expectingOperator = false;
4560
                }
4561 11545
            }
4562 2
        }
4563
4564
        while (($op = $stack->pop()) !== null) {
4565
            // pop everything off the stack and push onto output
4566
            if ((is_array($op) && $op['value'] == '(')) {
4567 11544
                return $this->raiseFormulaError("Formula Error: Expecting ')'"); // if there are any opening braces on the stack, then braces were unbalanced
4568 11544
            }
4569 11544
            $output[] = $op;
4570 11544
        }
4571
4572
        return $output;
4573 11544
    }
4574
4575 11544
    private static function dataTestReference(array &$operandData): mixed
4576
    {
4577 11544
        $operand = $operandData['value'];
4578 11544
        if (($operandData['reference'] === null) && (is_array($operand))) {
4579 11544
            $rKeys = array_keys($operand);
4580 4
            $rowKey = array_shift($rKeys);
4581
            if (is_array($operand[$rowKey]) === false) {
4582 11544
                $operandData['value'] = $operand[$rowKey];
4583
4584 11544
                return $operand[$rowKey];
4585 11544
            }
4586 76
4587 76
            $cKeys = array_keys(array_keys($operand[$rowKey]));
4588 76
            $colKey = array_shift($cKeys);
4589 76
            if (ctype_upper("$colKey")) {
4590 76
                $operandData['reference'] = $colKey . $rowKey;
4591 53
            }
4592 53
        }
4593
4594
        return $operand;
4595
    }
4596 76
4597 76
    private static int $matchIndex8 = 8;
4598
4599
    private static int $matchIndex9 = 9;
4600 53
4601 51
    private static int $matchIndex10 = 10;
4602 51
4603
    /**
4604
     * @return array<int, mixed>|false
4605 53
     */
4606
    private function processTokenStack(mixed $tokens, ?string $cellID = null, ?Cell $cell = null)
4607
    {
4608 1
        if ($tokens === false) {
4609 1
            return false;
4610 1
        }
4611
4612
        //    If we're using cell caching, then $pCell may well be flushed back to the cache (which detaches the parent cell collection),
4613 53
        //        so we store the parent cell collection so that we can re-attach it when necessary
4614
        $pCellWorksheet = ($cell !== null) ? $cell->getWorksheet() : null;
4615
        $originalCoordinate = $cell?->getCoordinate();
4616
        $pCellParent = ($cell !== null) ? $cell->getParent() : null;
4617 11544
        $stack = new Stack($this->branchPruner);
4618 71
4619 71
        // Stores branches that have been pruned
4620 71
        $fakedForBranchPruning = [];
4621 71
        // help us to know when pruning ['branchTestId' => true/false]
4622 71
        $branchStore = [];
4623 48
        //    Loop through each token in turn
4624 48
        foreach ($tokens as $tokenIdx => $tokenData) {
4625
            $this->processingAnchorArray = false;
4626
            if ($tokenData['type'] === 'Cell Reference' && isset($tokens[$tokenIdx + 1]) && $tokens[$tokenIdx + 1]['type'] === 'Operand Count for Function ANCHORARRAY()') {
4627
                $this->processingAnchorArray = true;
4628 71
            }
4629 71
            $token = $tokenData['value'];
4630
            // Branch pruning: skip useless resolutions
4631
            $storeKey = $tokenData['storeKey'] ?? null;
4632 53
            if ($this->branchPruningEnabled && isset($tokenData['onlyIf'])) {
4633 53
                $onlyIfStoreKey = $tokenData['onlyIf'];
4634 53
                $storeValue = $branchStore[$onlyIfStoreKey] ?? null;
4635
                $storeValueAsBool = ($storeValue === null)
4636
                    ? true : (bool) Functions::flattenSingleValue($storeValue);
4637 53
                if (is_array($storeValue)) {
4638
                    $wrappedItem = end($storeValue);
4639
                    $storeValue = is_array($wrappedItem) ? end($wrappedItem) : $wrappedItem;
4640 7
                }
4641 7
4642 7
                if (
4643
                    (isset($storeValue) || $tokenData['reference'] === 'NULL')
4644
                    && (!$storeValueAsBool || Information\ErrorValue::isError($storeValue) || ($storeValue === 'Pruned branch'))
4645 53
                ) {
4646
                    // If branching value is not true, we don't need to compute
4647
                    if (!isset($fakedForBranchPruning['onlyIf-' . $onlyIfStoreKey])) {
4648
                        $stack->push('Value', 'Pruned branch (only if ' . $onlyIfStoreKey . ') ' . $token);
4649 11544
                        $fakedForBranchPruning['onlyIf-' . $onlyIfStoreKey] = true;
4650 16
                    }
4651
4652
                    if (isset($storeKey)) {
4653
                        // We are processing an if condition
4654
                        // We cascade the pruning to the depending branches
4655 16
                        $branchStore[$storeKey] = 'Pruned branch';
4656 16
                        $fakedForBranchPruning['onlyIfNot-' . $storeKey] = true;
4657 7
                        $fakedForBranchPruning['onlyIf-' . $storeKey] = true;
4658 7
                    }
4659 7
4660 7
                    continue;
4661
                }
4662 10
            }
4663 10
4664 10
            if ($this->branchPruningEnabled && isset($tokenData['onlyIfNot'])) {
4665 16
                $onlyIfNotStoreKey = $tokenData['onlyIfNot'];
4666
                $storeValue = $branchStore[$onlyIfNotStoreKey] ?? null;
4667 2
                $storeValueAsBool = ($storeValue === null)
4668 2
                    ? true : (bool) Functions::flattenSingleValue($storeValue);
4669 2
                if (is_array($storeValue)) {
4670 2
                    $wrappedItem = end($storeValue);
4671
                    $storeValue = is_array($wrappedItem) ? end($wrappedItem) : $wrappedItem;
4672
                }
4673
4674
                if (
4675 11543
                    (isset($storeValue) || $tokenData['reference'] === 'NULL')
4676
                    && ($storeValueAsBool || Information\ErrorValue::isError($storeValue) || ($storeValue === 'Pruned branch'))
4677
                ) {
4678 1558
                    // If branching value is true, we don't need to compute
4679 1558
                    if (!isset($fakedForBranchPruning['onlyIfNot-' . $onlyIfNotStoreKey])) {
4680
                        $stack->push('Value', 'Pruned branch (only if not ' . $onlyIfNotStoreKey . ') ' . $token);
4681
                        $fakedForBranchPruning['onlyIfNot-' . $onlyIfNotStoreKey] = true;
4682 1558
                    }
4683 1558
4684
                    if (isset($storeKey)) {
4685
                        // We are processing an if condition
4686
                        // We cascade the pruning to the depending branches
4687 1558
                        $branchStore[$storeKey] = 'Pruned branch';
4688 1558
                        $fakedForBranchPruning['onlyIfNot-' . $storeKey] = true;
4689
                        $fakedForBranchPruning['onlyIf-' . $storeKey] = true;
4690
                    }
4691 1558
4692 1103
                    continue;
4693
                }
4694 702
            }
4695
4696
            if ($token instanceof Operands\StructuredReference) {
4697
                if ($cell === null) {
4698
                    return $this->raiseFormulaError('Structured References must exist in a Cell context');
4699
                }
4700 1558
4701 1545
                try {
4702 1527
                    $cellRange = $token->parse($cell);
4703 1519
                    if (str_contains($cellRange, ':')) {
4704 1501
                        $this->debugLog->writeDebugLog('Evaluating Structured Reference %s as Cell Range %s', $token->value(), $cellRange);
4705 1351
                        $rangeValue = self::getInstance($cell->getWorksheet()->getParent())->_calculateFormulaValue("={$cellRange}", $cellRange, $cell);
4706 396
                        $stack->push('Value', $rangeValue);
4707 396
                        $this->debugLog->writeDebugLog('Evaluated Structured Reference %s as value %s', $token->value(), $this->showValue($rangeValue));
4708 63
                    } else {
4709
                        $this->debugLog->writeDebugLog('Evaluating Structured Reference %s as Cell %s', $token->value(), $cellRange);
4710
                        $cellValue = $cell->getWorksheet()->getCell($cellRange)->getCalculatedValue(false);
4711 396
                        $stack->push('Cell Reference', $cellValue, $cellRange);
4712
                        $this->debugLog->writeDebugLog('Evaluated Structured Reference %s as value %s', $token->value(), $this->showValue($cellValue));
4713 1341
                    }
4714 1103
                } catch (Exception $e) {
4715 3
                    if ($e->getCode() === Exception::CALCULATION_ENGINE_PUSH_TO_STACK) {
4716 3
                        $stack->push('Error', ExcelError::REF(), null);
4717 3
                        $this->debugLog->writeDebugLog('Evaluated Structured Reference %s as error value %s', $token->value(), ExcelError::REF());
4718 3
                    } else {
4719
                        return $this->raiseFormulaError($e->getMessage(), $e->getCode(), $e);
4720
                    }
4721
                }
4722 1103
            } elseif (!is_numeric($token) && !is_object($token) && isset(self::BINARY_OPERATORS[$token])) {
4723 1097
                // 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
4724
                //    We must have two operands, error if we don't
4725 10
                $operand2Data = $stack->pop();
4726
                if ($operand2Data === null) {
4727 1103
                    return $this->raiseFormulaError('Internal error - Operand value missing from stack');
4728
                }
4729 1103
                $operand1Data = $stack->pop();
4730 1103
                if ($operand1Data === null) {
4731 4
                    return $this->raiseFormulaError('Internal error - Operand value missing from stack');
4732
                }
4733
4734 1103
                $operand1 = self::dataTestReference($operand1Data);
4735 1100
                $operand2 = self::dataTestReference($operand2Data);
4736
4737
                //    Log what we're doing
4738
                if ($token == ':') {
4739
                    $this->debugLog->writeDebugLog('Evaluating Range %s %s %s', $this->showValue($operand1Data['reference']), $token, $this->showValue($operand2Data['reference']));
4740
                } else {
4741
                    $this->debugLog->writeDebugLog('Evaluating %s %s %s', $this->showValue($operand1), $token, $this->showValue($operand2));
4742
                }
4743
4744
                //    Process the operation in the appropriate manner
4745
                switch ($token) {
4746 1100
                    // Comparison (Boolean) Operators
4747 2
                    case '>': // Greater than
4748 1
                    case '<': // Less than
4749 1
                    case '>=': // Greater than or Equal to
4750
                    case '<=': // Less than or Equal to
4751 1
                    case '=': // Equality
4752
                    case '<>': // Inequality
4753
                        $result = $this->executeBinaryComparisonOperation($operand1, $operand2, (string) $token, $stack);
4754 1
                        if (isset($storeKey)) {
4755
                            $branchStore[$storeKey] = $result;
4756
                        }
4757
4758 1100
                        break;
4759 1100
                    // Binary Operators
4760 1100
                    case ':': // Range
4761 1100
                        if ($operand1Data['type'] === 'Defined Name') {
4762
                            if (preg_match('/$' . self::CALCULATION_REGEXP_DEFINEDNAME . '^/mui', $operand1Data['reference']) !== false && $this->spreadsheet !== null) {
4763 1100
                                $definedName = $this->spreadsheet->getNamedRange($operand1Data['reference']);
4764 1100
                                if ($definedName !== null) {
4765 1100
                                    $operand1Data['reference'] = $operand1Data['value'] = str_replace('$', '', $definedName->getValue());
4766 1
                                }
4767 1
                            }
4768 1
                        }
4769
                        if (str_contains($operand1Data['reference'] ?? '', '!')) {
4770 1
                            [$sheet1, $operand1Data['reference']] = Worksheet::extractSheetTitle($operand1Data['reference'], true);
4771
                        } else {
4772
                            $sheet1 = ($pCellWorksheet !== null) ? $pCellWorksheet->getTitle() : '';
4773 1100
                        }
4774 1
                        $sheet1 ??= '';
4775
4776 1099
                        [$sheet2, $operand2Data['reference']] = Worksheet::extractSheetTitle($operand2Data['reference'], true);
4777 1099
                        if (empty($sheet2)) {
4778 1099
                            $sheet2 = $sheet1;
4779
                        }
4780
4781
                        if (trim($sheet1, "'") === trim($sheet2, "'")) {
4782
                            if ($operand1Data['reference'] === null && $cell !== null) {
4783 1099
                                if (is_array($operand1Data['value'])) {
4784 1099
                                    $operand1Data['reference'] = $cell->getCoordinate();
4785
                                } elseif ((trim($operand1Data['value']) != '') && (is_numeric($operand1Data['value']))) {
4786 4
                                    $operand1Data['reference'] = $cell->getColumn() . $operand1Data['value'];
4787 4
                                } elseif (trim($operand1Data['value']) == '') {
4788
                                    $operand1Data['reference'] = $cell->getCoordinate();
4789
                                } else {
4790 1102
                                    $operand1Data['reference'] = $operand1Data['value'] . $cell->getRow();
4791 362
                                }
4792 285
                            }
4793 246
                            if ($operand2Data['reference'] === null && $cell !== null) {
4794 126
                                if (is_array($operand2Data['value'])) {
4795 36
                                    $operand2Data['reference'] = $cell->getCoordinate();
4796 337
                                } elseif ((trim($operand2Data['value']) != '') && (is_numeric($operand2Data['value']))) {
4797 337
                                    $operand2Data['reference'] = $cell->getColumn() . $operand2Data['value'];
4798 5
                                } elseif (trim($operand2Data['value']) == '') {
4799
                                    $operand2Data['reference'] = $cell->getCoordinate();
4800
                                } else {
4801 337
                                    $operand2Data['reference'] = $operand2Data['value'] . $cell->getRow();
4802 33
                                }
4803
                            }
4804
4805
                            $oData = array_merge(explode(':', $operand1Data['reference'] ?? ''), explode(':', $operand2Data['reference'] ?? ''));
4806 19
                            $oCol = $oRow = [];
4807 19
                            $breakNeeded = false;
4808 19
                            foreach ($oData as $oDatum) {
4809 15
                                try {
4810 6
                                    $oCR = Coordinate::coordinateFromString($oDatum);
4811
                                    $oCol[] = Coordinate::columnIndexFromString($oCR[0]) - 1;
4812 15
                                    $oRow[] = $oCR[1];
4813 5
                                } catch (\Exception) {
4814
                                    $stack->push('Error', ExcelError::REF(), null);
4815
                                    $breakNeeded = true;
4816 15
4817
                                    break;
4818 15
                                }
4819 15
                            }
4820 15
                            if ($breakNeeded) {
4821 15
                                break;
4822 15
                            }
4823
                            $cellRef = Coordinate::stringFromColumnIndex(min($oCol) + 1) . min($oRow) . ':' . Coordinate::stringFromColumnIndex(max($oCol) + 1) . max($oRow);
4824 15
                            if ($pCellParent !== null && $this->spreadsheet !== null) {
4825 1
                                $cellValue = $this->extractCellRange($cellRef, $this->spreadsheet->getSheetByName($sheet1), false);
4826
                            } else {
4827 14
                                return $this->raiseFormulaError('Unable to access Cell Reference');
4828 14
                            }
4829 14
4830 14
                            $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($cellValue));
4831 14
                            $stack->push('Cell Reference', $cellValue, $cellRef);
4832 14
                        } else {
4833
                            $this->debugLog->writeDebugLog('Evaluation Result is a #REF! Error');
4834
                            $stack->push('Error', ExcelError::REF(), null);
4835
                        }
4836 15
4837
                        break;
4838
                    case '+':            //    Addition
4839
                    case '-':            //    Subtraction
4840
                    case '*':            //    Multiplication
4841
                    case '/':            //    Division
4842
                    case '^':            //    Exponential
4843 6
                        $result = $this->executeNumericBinaryOperation($operand1, $operand2, $token, $stack);
4844
                        if (isset($storeKey)) {
4845 6
                            $branchStore[$storeKey] = $result;
4846
                        }
4847
4848 6
                        break;
4849
                    case '&':            //    Concatenation
4850
                        //    If either of the operands is a matrix, we need to treat them both as matrices
4851 19
                        //        (converting the other operand to a matrix if need be); then perform the required
4852 19
                        //        matrix operation
4853
                        $operand1 = self::boolToString($operand1);
4854 19
                        $operand2 = self::boolToString($operand2);
4855
                        if (is_array($operand1) || is_array($operand2)) {
4856
                            if (is_string($operand1)) {
4857
                                $operand1 = self::unwrapResult($operand1);
4858 19
                            }
4859 14
                            if (is_string($operand2)) {
4860 14
                                $operand2 = self::unwrapResult($operand2);
4861 14
                            }
4862 14
                            //    Ensure that both operands are arrays/matrices
4863 14
                            [$rows, $columns] = self::checkMatrixOperands($operand1, $operand2, 2);
4864 14
4865 14
                            for ($row = 0; $row < $rows; ++$row) {
4866 14
                                for ($column = 0; $column < $columns; ++$column) {
4867
                                    $op1x = self::boolToString($operand1[$row][$column]);
4868
                                    $op2x = self::boolToString($operand2[$row][$column]);
4869 14
                                    if (Information\ErrorValue::isError($op1x)) {
4870 2
                                        // no need to do anything
4871 2
                                    } elseif (Information\ErrorValue::isError($op2x)) {
4872
                                        $operand1[$row][$column] = $op2x;
4873 12
                                    } else {
4874 12
                                        $operand1[$row][$column]
4875 12
                                            = Shared\StringHelper::substring(
4876 12
                                                $op1x . $op2x,
4877
                                                0,
4878
                                                DataType::MAX_STRING_LENGTH
4879 14
                                            );
4880
                                    }
4881 11536
                                }
4882
                            }
4883 1111
                            $result = $operand1;
4884
                        } else {
4885
                            // In theory, we should truncate here.
4886 1111
                            // But I can't figure out a formula
4887 1111
                            // using the concatenation operator
4888 1108
                            // with literals that fits in 32K,
4889 1108
                            // so I don't think we can overflow here.
4890
                            if (Information\ErrorValue::isError($operand1)) {
4891 5
                                $result = $operand1;
4892 5
                            } elseif (Information\ErrorValue::isError($operand2)) {
4893
                                $result = $operand2;
4894 1111
                            } else {
4895 4
                                $result = self::FORMULA_STRING_QUOTE . str_replace('""', self::FORMULA_STRING_QUOTE, self::unwrapResult($operand1) . self::unwrapResult($operand2)) . self::FORMULA_STRING_QUOTE;
4896 4
                            }
4897 4
                        }
4898 4
                        $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($result));
4899 4
                        $stack->push('Value', $result);
4900 4
4901 4
                        if (isset($storeKey)) {
4902
                            $branchStore[$storeKey] = $result;
4903 2
                        }
4904
4905
                        break;
4906
                    case '∩':            //    Intersect
4907
                        $rowIntersect = array_intersect_key($operand1, $operand2);
4908 4
                        $cellIntersect = $oCol = $oRow = [];
4909 4
                        foreach (array_keys($rowIntersect) as $row) {
4910 4
                            $oRow[] = $row;
4911
                            foreach ($rowIntersect[$row] as $col => $data) {
4912
                                $oCol[] = Coordinate::columnIndexFromString($col) - 1;
4913
                                $cellIntersect[$row] = array_intersect_key($operand1[$row], $operand2[$row]);
4914 1110
                            }
4915
                        }
4916 11536
                        if (count(Functions::flattenArray($cellIntersect)) === 0) {
4917 6765
                            $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($cellIntersect));
4918
                            $stack->push('Error', ExcelError::null(), null);
4919
                        } else {
4920
                            $cellRef = Coordinate::stringFromColumnIndex(min($oCol) + 1) . min($oRow) . ':'
4921
                                . Coordinate::stringFromColumnIndex(max($oCol) + 1) . max($oRow);
4922
                            $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($cellIntersect));
4923
                            $stack->push('Value', $cellIntersect, $cellRef);
4924 6765
                        }
4925
4926
                        break;
4927
                }
4928
            } elseif (($token === '~') || ($token === '%')) {
4929
                // if the token is a unary operator, pop one value off the stack, do the operation, and push it back on
4930
                if (($arg = $stack->pop()) === null) {
4931
                    return $this->raiseFormulaError('Internal error - Operand value missing from stack');
4932
                }
4933
                $arg = $arg['value'];
4934
                if ($token === '~') {
4935
                    $this->debugLog->writeDebugLog('Evaluating Negation of %s', $this->showValue($arg));
4936
                    $multiplier = -1;
4937
                } else {
4938
                    $this->debugLog->writeDebugLog('Evaluating Percentile of %s', $this->showValue($arg));
4939
                    $multiplier = 0.01;
4940
                }
4941
                if (is_array($arg)) {
4942
                    $operand2 = $multiplier;
4943
                    $result = $arg;
4944
                    [$rows, $columns] = self::checkMatrixOperands($result, $operand2, 0);
4945
                    for ($row = 0; $row < $rows; ++$row) {
4946
                        for ($column = 0; $column < $columns; ++$column) {
4947
                            if (self::isNumericOrBool($result[$row][$column])) {
4948
                                $result[$row][$column] *= $multiplier;
4949
                            } else {
4950
                                $result[$row][$column] = self::makeError($result[$row][$column]);
4951
                            }
4952
                        }
4953
                    }
4954
4955 6765
                    $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($result));
4956
                    $stack->push('Value', $result);
4957
                    if (isset($storeKey)) {
4958
                        $branchStore[$storeKey] = $result;
4959 6765
                    }
4960 6765
                } else {
4961 6760
                    $this->executeNumericBinaryOperation($multiplier, $arg, '*', $stack);
4962 6760
                }
4963
            } elseif (preg_match('/^' . self::CALCULATION_REGEXP_CELLREF . '$/i', $token ?? '', $matches)) {
4964 1
                $cellRef = null;
4965
4966 6760
                /* Phpstan says matches[8/9/10] is never set,
4967 6760
                   and code coverage report seems to confirm.
4968 6760
                   Appease PhpStan for now;
4969 6760
                   probably delete this block later.
4970 6647
                */
4971 6647
                if (isset($matches[self::$matchIndex8])) {
4972
                    if ($cell === null) {
4973 326
                        // We can't access the range, so return a REF error
4974 326
                        $cellValue = ExcelError::REF();
4975
                    } else {
4976
                        $cellRef = $matches[6] . $matches[7] . ':' . $matches[self::$matchIndex9] . $matches[self::$matchIndex10];
4977
                        if ($matches[2] > '') {
4978
                            $matches[2] = trim($matches[2], "\"'");
4979 6760
                            if ((str_contains($matches[2], '[')) || (str_contains($matches[2], ']'))) {
4980
                                //    It's a Reference to an external spreadsheet (not currently supported)
4981 9
                                return $this->raiseFormulaError('Unable to access External Workbook');
4982 9
                            }
4983 9
                            $matches[2] = trim($matches[2], "\"'");
4984 9
                            $this->debugLog->writeDebugLog('Evaluating Cell Range %s in worksheet %s', $cellRef, $matches[2]);
4985
                            if ($pCellParent !== null && $this->spreadsheet !== null) {
4986 2
                                $cellValue = $this->extractCellRange($cellRef, $this->spreadsheet->getSheetByName($matches[2]), false);
4987
                            } else {
4988 9
                                return $this->raiseFormulaError('Unable to access Cell Reference');
4989
                            }
4990
                            $this->debugLog->writeDebugLog('Evaluation Result for cells %s in worksheet %s is %s', $cellRef, $matches[2], $this->showTypeDetails($cellValue));
4991
                        } else {
4992
                            $this->debugLog->writeDebugLog('Evaluating Cell Range %s in current worksheet', $cellRef);
4993 6765
                            if ($pCellParent !== null) {
4994 52
                                $cellValue = $this->extractCellRange($cellRef, $pCellWorksheet, false);
4995 52
                            } else {
4996
                                return $this->raiseFormulaError('Unable to access Cell Reference');
4997 52
                            }
4998
                            $this->debugLog->writeDebugLog('Evaluation Result for cells %s is %s', $cellRef, $this->showTypeDetails($cellValue));
4999 6765
                        }
5000 6765
                    }
5001 6765
                } else {
5002 55
                    if ($cell === null) {
5003
                        // We can't access the cell, so return a REF error
5004 11462
                        $cellValue = ExcelError::REF();
5005
                    } else {
5006 11266
                        $cellRef = $matches[6] . $matches[7];
5007 7696
                        if ($matches[2] > '') {
5008
                            $matches[2] = trim($matches[2], "\"'");
5009
                            if ((str_contains($matches[2], '[')) || (str_contains($matches[2], ']'))) {
5010 11266
                                //    It's a Reference to an external spreadsheet (not currently supported)
5011 11266
                                return $this->raiseFormulaError('Unable to access External Workbook');
5012 11266
                            }
5013 11266
                            $this->debugLog->writeDebugLog('Evaluating Cell %s in worksheet %s', $cellRef, $matches[2]);
5014 11265
                            if ($pCellParent !== null && $this->spreadsheet !== null) {
5015
                                $cellSheet = $this->spreadsheet->getSheetByName($matches[2]);
5016 11266
                                if ($cellSheet && $cellSheet->cellExists($cellRef)) {
5017 11266
                                    $cellValue = $this->extractCellRange($cellRef, $this->spreadsheet->getSheetByName($matches[2]), false);
5018 11266
                                    $cell->attach($pCellParent);
5019 11266
                                } else {
5020 11266
                                    $cellRef = ($cellSheet !== null) ? "'{$matches[2]}'!{$cellRef}" : $cellRef;
5021 11263
                                    $cellValue = ($cellSheet !== null) ? null : ExcelError::REF();
5022 11263
                                }
5023 11263
                            } else {
5024 799
                                return $this->raiseFormulaError('Unable to access Cell Reference');
5025 799
                            }
5026 799
                            $this->debugLog->writeDebugLog('Evaluation Result for cell %s in worksheet %s is %s', $cellRef, $matches[2], $this->showTypeDetails($cellValue));
5027 799
                        } else {
5028
                            $this->debugLog->writeDebugLog('Evaluating Cell %s in current worksheet', $cellRef);
5029
                            if ($pCellParent !== null && $pCellParent->has($cellRef)) {
5030
                                $cellValue = $this->extractCellRange($cellRef, $pCellWorksheet, false);
5031 11266
                                $cell->attach($pCellParent);
5032 11266
                            } else {
5033 11266
                                $cellValue = null;
5034 11248
                            }
5035 11248
                            $this->debugLog->writeDebugLog('Evaluation Result for cell %s is %s', $cellRef, $this->showTypeDetails($cellValue));
5036
                        }
5037 11248
                    }
5038 11248
                }
5039 11248
5040
                if ($this->getInstanceArrayReturnType() === self::RETURN_ARRAY_AS_ARRAY && !$this->processingAnchorArray && is_array($cellValue)) {
5041 52
                    while (is_array($cellValue)) {
5042 1
                        $cellValue = array_shift($cellValue);
5043 1
                    }
5044
                    $this->debugLog->writeDebugLog('Scalar Result for cell %s is %s', $cellRef, $this->showTypeDetails($cellValue));
5045
                }
5046
                $this->processingAnchorArray = false;
5047
                $stack->push('Cell Value', $cellValue, $cellRef);
5048
                if (isset($storeKey)) {
5049
                    $branchStore[$storeKey] = $cellValue;
5050
                }
5051
            } elseif (preg_match('/^' . self::CALCULATION_REGEXP_FUNCTION . '$/miu', $token ?? '', $matches)) {
5052
                // if the token is a function, pop arguments off the stack, hand them to the function, and push the result back on
5053 1
                if ($cell !== null && $pCellParent !== null) {
5054 1
                    $cell->attach($pCellParent);
5055 1
                }
5056
5057
                $functionName = $matches[1];
5058 51
                $argCount = $stack->pop();
5059 51
                $argCount = $argCount['value'];
5060 51
                if ($functionName !== 'MKMATRIX') {
5061
                    $this->debugLog->writeDebugLog('Evaluating Function %s() with %s argument%s', self::localeFunc($functionName), (($argCount == 0) ? 'no' : $argCount), (($argCount == 1) ? '' : 's'));
5062
                }
5063
                if ((isset(self::$phpSpreadsheetFunctions[$functionName])) || (isset(self::$controlFunctions[$functionName]))) {    // function
5064 11215
                    $passByReference = false;
5065 15
                    $passCellReference = false;
5066 15
                    $functionCall = null;
5067 15
                    if (isset(self::$phpSpreadsheetFunctions[$functionName])) {
5068
                        $functionCall = self::$phpSpreadsheetFunctions[$functionName]['functionCall'];
5069 11215
                        $passByReference = isset(self::$phpSpreadsheetFunctions[$functionName]['passByReference']);
5070 11215
                        $passCellReference = isset(self::$phpSpreadsheetFunctions[$functionName]['passCellReference']);
5071
                    } elseif (isset(self::$controlFunctions[$functionName])) {
5072 11215
                        $functionCall = self::$controlFunctions[$functionName]['functionCall'];
5073 11214
                        $passByReference = isset(self::$controlFunctions[$functionName]['passByReference']);
5074
                        $passCellReference = isset(self::$controlFunctions[$functionName]['passCellReference']);
5075
                    }
5076
5077
                    // get the arguments for this function
5078
                    $args = $argArrayVals = [];
5079 11266
                    $emptyArguments = [];
5080 11266
                    for ($i = 0; $i < $argCount; ++$i) {
5081
                        $arg = $stack->pop();
5082 11266
                        $a = $argCount - $i - 1;
5083 11248
                        if (
5084
                            ($passByReference)
5085
                            && (isset(self::$phpSpreadsheetFunctions[$functionName]['passByReference'][$a]))
5086 11266
                            && (self::$phpSpreadsheetFunctions[$functionName]['passByReference'][$a])
5087 9
                        ) {
5088 9
                            if ($arg['reference'] === null) {
5089
                                $nextArg = $cellID;
5090
                                if ($functionName === 'ISREF' && is_array($arg) && ($arg['type'] ?? '') === 'Value') {
5091 11266
                                    if (array_key_exists('value', $arg)) {
5092 11265
                                        $argValue = $arg['value'];
5093 2
                                        if (is_scalar($argValue)) {
5094 2
                                            $nextArg = $argValue;
5095
                                        } elseif (empty($argValue)) {
5096
                                            $nextArg = '';
5097
                                        }
5098
                                    }
5099 11266
                                }
5100 7696
                                $args[] = $nextArg;
5101
                                if ($functionName !== 'MKMATRIX') {
5102 11266
                                    $argArrayVals[] = $this->showValue($cellID);
5103
                                }
5104 11266
                            } else {
5105 53
                                $args[] = $arg['reference'];
5106
                                if ($functionName !== 'MKMATRIX') {
5107
                                    $argArrayVals[] = $this->showValue($arg['reference']);
5108 53
                                }
5109
                            }
5110
                        } else {
5111 11266
                            if ($arg['type'] === 'Empty Argument' && in_array($functionName, ['MIN', 'MINA', 'MAX', 'MAXA', 'IF'], true)) {
5112
                                $emptyArguments[] = false;
5113 11260
                                $args[] = $arg['value'] = 0;
5114 11257
                                $this->debugLog->writeDebugLog('Empty Argument reevaluated as 0');
5115
                            } else {
5116 11260
                                $emptyArguments[] = $arg['type'] === 'Empty Argument';
5117 11260
                                $args[] = self::unwrapResult($arg['value']);
5118 19
                            }
5119
                            if ($functionName !== 'MKMATRIX') {
5120
                                $argArrayVals[] = $this->showValue($arg['value']);
5121
                            }
5122
                        }
5123 11462
                    }
5124
5125
                    //    Reverse the order of the arguments
5126
                    krsort($args);
5127
                    krsort($emptyArguments);
5128
5129
                    if ($argCount > 0 && is_array($functionCall)) {
5130 11462
                        $args = $this->addDefaultArgumentValues($functionCall, $args, $emptyArguments);
5131 11417
                    }
5132 11417
5133 66
                    if (($passByReference) && ($argCount == 0)) {
5134
                        $args[] = $cellID;
5135 131
                        $argArrayVals[] = $this->showValue($cellID);
5136
                    }
5137 131
5138 131
                    if ($functionName !== 'MKMATRIX') {
5139
                        if ($this->debugLog->getWriteDebugLog()) {
5140
                            krsort($argArrayVals);
5141 131
                            $this->debugLog->writeDebugLog('Evaluating %s ( %s )', self::localeFunc($functionName), implode(self::$localeArgumentSeparator . ' ', Functions::flattenArray($argArrayVals)));
5142
                        }
5143 131
                    }
5144 131
5145
                    //    Process the argument with the appropriate function call
5146 131
                    if ($pCellWorksheet !== null && $originalCoordinate !== null) {
5147 33
                        $pCellWorksheet->getCell($originalCoordinate);
5148 33
                    }
5149 3
                    $args = $this->addCellReference($args, $passCellReference, $functionCall, $cell);
5150 3
5151 3
                    if (!is_array($functionCall)) {
5152
                        foreach ($args as &$arg) {
5153 3
                            $arg = Functions::flattenSingleValue($arg);
5154
                        }
5155
                        unset($arg);
5156 3
                    }
5157 3
5158 3
                    $result = call_user_func_array($functionCall, $args);
5159 3
5160 3
                    if ($functionName !== 'MKMATRIX') {
5161 3
                        $this->debugLog->writeDebugLog('Evaluation Result for %s() function call is %s', self::localeFunc($functionName), $this->showTypeDetails($result));
5162 3
                    }
5163
                    $stack->push('Value', self::wrapResult($result));
5164
                    if (isset($storeKey)) {
5165 131
                        $branchStore[$storeKey] = $result;
5166 30
                    }
5167
                }
5168
            } else {
5169 111
                // if the token is a number, boolean, string or an Excel error, push it onto the stack
5170 111
                if (isset(self::$excelConstants[strtoupper($token ?? '')])) {
5171 1
                    $excelConstant = strtoupper($token);
5172
                    $stack->push('Constant Value', self::$excelConstants[$excelConstant]);
5173
                    if (isset($storeKey)) {
5174
                        $branchStore[$storeKey] = self::$excelConstants[$excelConstant];
5175
                    }
5176
                    $this->debugLog->writeDebugLog('Evaluating Constant %s as %s', $excelConstant, $this->showTypeDetails(self::$excelConstants[$excelConstant]));
5177
                } elseif ((is_numeric($token)) || ($token === null) || (is_bool($token)) || ($token == '') || ($token[0] == self::FORMULA_STRING_QUOTE) || ($token[0] == '#')) {
5178
                    $stack->push($tokenData['type'], $token, $tokenData['reference']);
5179 11517
                    if (isset($storeKey)) {
5180 1
                        $branchStore[$storeKey] = $token;
5181
                    }
5182 11517
                } elseif (preg_match('/^' . self::CALCULATION_REGEXP_DEFINEDNAME . '$/miu', $token, $matches)) {
5183 11517
                    // if the token is a named range or formula, evaluate it and push the result onto the stack
5184
                    $definedName = $matches[6];
5185 11517
                    if ($cell === null || $pCellWorksheet === null) {
5186
                        return $this->raiseFormulaError("undefined name '$token'");
5187
                    }
5188 1384
                    $specifiedWorksheet = trim($matches[2], "'");
5189
5190 1384
                    $this->debugLog->writeDebugLog('Evaluating Defined Name %s', $definedName);
5191 214
                    $namedRange = DefinedName::resolveName($definedName, $pCellWorksheet, $specifiedWorksheet);
5192
                    // If not Defined Name, try as Table.
5193 182
                    if ($namedRange === null && $this->spreadsheet !== null) {
5194 182
                        $table = $this->spreadsheet->getTableByName($definedName);
5195
                        if ($table !== null) {
5196
                            $tableRange = Coordinate::getRangeBoundaries($table->getRange());
5197
                            if ($table->getShowHeaderRow()) {
5198 1384
                                ++$tableRange[0][1];
5199
                            }
5200
                            if ($table->getShowTotalsRow()) {
5201 13
                                --$tableRange[1][1];
5202 5
                            }
5203
                            $tableRangeString
5204
                                = '$' . $tableRange[0][0]
5205 13
                                . '$' . $tableRange[0][1]
5206
                                . ':'
5207 12
                                . '$' . $tableRange[1][0]
5208 4
                                . '$' . $tableRange[1][1];
5209 4
                            $namedRange = new NamedRange($definedName, $table->getWorksheet(), $tableRangeString);
5210
                        }
5211 4
                    }
5212 8
                    if ($namedRange === null) {
5213
                        return $this->raiseFormulaError("undefined name '$definedName'");
5214 4
                    }
5215 4
5216
                    $result = $this->evaluateDefinedName($cell, $namedRange, $pCellWorksheet, $stack, $specifiedWorksheet !== '');
5217 4
                    if (isset($storeKey)) {
5218
                        $branchStore[$storeKey] = $result;
5219
                    }
5220
                } else {
5221
                    return $this->raiseFormulaError("undefined name '$token'");
5222
                }
5223 1382
            }
5224
        }
5225
        // when we're out of tokens, the stack should have a single element, the final result
5226 50
        if ($stack->count() != 1) {
5227
            return $this->raiseFormulaError('internal error');
5228 50
        }
5229 50
        $output = $stack->pop();
5230
        $output = $output['value'];
5231 47
5232 47
        return $output;
5233 47
    }
5234 47
5235 47
    private function validateBinaryOperand(mixed &$operand, mixed &$stack): bool
5236
    {
5237 7
        if (is_array($operand)) {
5238
            if ((count($operand, COUNT_RECURSIVE) - count($operand)) == 1) {
5239 3
                do {
5240 3
                    $operand = array_pop($operand);
5241 3
                } while (is_array($operand));
5242 3
            }
5243 3
        }
5244
        //    Numbers, matrices and booleans can pass straight through, as they're already valid
5245
        if (is_string($operand)) {
5246
            //    We only need special validations for the operand if it is a string
5247 6
            //    Start by stripping off the quotation marks we use to identify true excel string values internally
5248 6
            if ($operand > '' && $operand[0] == self::FORMULA_STRING_QUOTE) {
5249
                $operand = self::unwrapResult($operand);
5250 6
            }
5251 6
            //    If the string is a numeric value, we treat it as a numeric, so no further testing
5252 6
            if (!is_numeric($operand)) {
5253 6
                //    If not a numeric, test to see if the value is an Excel error, and so can't be used in normal binary operations
5254 6
                if ($operand > '' && $operand[0] == '#') {
5255
                    $stack->push('Value', $operand);
5256
                    $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($operand));
5257
5258 50
                    return false;
5259
                } elseif (Engine\FormattedNumber::convertToNumberIfFormatted($operand) === false) {
5260 50
                    //    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
5261
                    $stack->push('Error', '#VALUE!');
5262 50
                    $this->debugLog->writeDebugLog('Evaluation Result is a %s', $this->showTypeDetails('#VALUE!'));
5263
5264
                    return false;
5265 396
                }
5266
            }
5267
        }
5268 396
5269 50
        //    return a true if the value of the operand is one that we can use in normal binary mathematical operations
5270
        return true;
5271
    }
5272 396
5273
    private function executeArrayComparison(mixed $operand1, mixed $operand2, string $operation, Stack &$stack, bool $recursingArrays): array
5274
    {
5275 396
        $result = [];
5276
        if (!is_array($operand2)) {
5277 396
            // Operand 1 is an array, Operand 2 is a scalar
5278
            foreach ($operand1 as $x => $operandData) {
5279 396
                $this->debugLog->writeDebugLog('Evaluating Comparison %s %s %s', $this->showValue($operandData), $operation, $this->showValue($operand2));
5280
                $this->executeBinaryComparisonOperation($operandData, $operand2, $operation, $stack);
5281
                $r = $stack->pop();
5282 1384
                $result[$x] = $r['value'];
5283
            }
5284
        } elseif (!is_array($operand1)) {
5285
            // Operand 1 is a scalar, Operand 2 is an array
5286 1384
            foreach ($operand2 as $x => $operandData) {
5287 1384
                $this->debugLog->writeDebugLog('Evaluating Comparison %s %s %s', $this->showValue($operand1), $operation, $this->showValue($operandData));
5288
                $this->executeBinaryComparisonOperation($operand1, $operandData, $operation, $stack);
5289 8
                $r = $stack->pop();
5290
                $result[$x] = $r['value'];
5291
            }
5292
        } else {
5293 1378
            // Operand 1 and Operand 2 are both arrays
5294 1378
            if (!$recursingArrays) {
5295 1378
                self::checkMatrixOperands($operand1, $operand2, 2);
5296
            }
5297
            foreach ($operand1 as $x => $operandData) {
5298 1378
                $this->debugLog->writeDebugLog('Evaluating Comparison %s %s %s', $this->showValue($operandData), $operation, $this->showValue($operand2[$x]));
5299
                $this->executeBinaryComparisonOperation($operandData, $operand2[$x], $operation, $stack, true);
5300 34
                $r = $stack->pop();
5301 28
                $result[$x] = $r['value'];
5302 28
            }
5303
        }
5304
        //    Log the result details
5305 34
        $this->debugLog->writeDebugLog('Comparison Evaluation Result is %s', $this->showTypeDetails($result));
5306 28
        //    And push the result onto the stack
5307 28
        $stack->push('Array', $result);
5308
5309
        return $result;
5310 34
    }
5311
5312 34
    private function executeBinaryComparisonOperation(mixed $operand1, mixed $operand2, string $operation, Stack &$stack, bool $recursingArrays = false): array|bool
5313 34
    {
5314 34
        //    If we're dealing with matrix operations, we want a matrix result
5315 1
        if ((is_array($operand1)) || (is_array($operand2))) {
5316 34
            return $this->executeArrayComparison($operand1, $operand2, $operation, $stack, $recursingArrays);
5317 1
        }
5318
5319 1
        $result = BinaryComparison::compare($operand1, $operand2, $operation);
5320
5321 34
        //    Log the result details
5322 1
        $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($result));
5323 34
        //    And push the result onto the stack
5324
        $stack->push('Value', $result);
5325
5326
        return $result;
5327
    }
5328
5329 34
    private function executeNumericBinaryOperation(mixed $operand1, mixed $operand2, string $operation, Stack &$stack): mixed
5330 3
    {
5331
        //    Validate the two operands
5332 3
        if (
5333 31
            ($this->validateBinaryOperand($operand1, $stack) === false)
5334 3
            || ($this->validateBinaryOperand($operand2, $stack) === false)
5335
        ) {
5336 3
            return false;
5337 29
        }
5338 22
5339
        if (
5340 22
            (Functions::getCompatibilityMode() != Functions::COMPATIBILITY_OPENOFFICE)
5341 7
            && ((is_string($operand1) && !is_numeric($operand1) && $operand1 !== '')
5342 5
                || (is_string($operand2) && !is_numeric($operand2) && $operand2 !== ''))
5343 3
        ) {
5344
            $result = ExcelError::VALUE();
5345 4
        } elseif (is_array($operand1) || is_array($operand2)) {
5346
            //    Ensure that both operands are arrays/matrices
5347
            if (is_array($operand1)) {
5348 5
                foreach ($operand1 as $key => $value) {
5349 2
                    $operand1[$key] = Functions::flattenArray($value);
5350 2
                }
5351
            }
5352 2
            if (is_array($operand2)) {
5353
                foreach ($operand2 as $key => $value) {
5354
                    $operand2[$key] = Functions::flattenArray($value);
5355
                }
5356
            }
5357
            [$rows, $columns] = self::checkMatrixOperands($operand1, $operand2, 3);
5358
5359 34
            for ($row = 0; $row < $rows; ++$row) {
5360
                for ($column = 0; $column < $columns; ++$column) {
5361
                    if ($operand1[$row][$column] === null) {
5362
                        $operand1[$row][$column] = 0;
5363
                    } elseif (!self::isNumericOrBool($operand1[$row][$column])) {
5364 1363
                        $operand1[$row][$column] = self::makeError($operand1[$row][$column]);
5365 152
5366
                        continue;
5367 152
                    }
5368
                    if ($operand2[$row][$column] === null) {
5369 1292
                        $operand2[$row][$column] = 0;
5370 50
                    } elseif (!self::isNumericOrBool($operand2[$row][$column])) {
5371
                        $operand1[$row][$column] = self::makeError($operand2[$row][$column]);
5372 50
5373
                        continue;
5374 1258
                    }
5375 1200
                    switch ($operation) {
5376
                        case '+':
5377 1200
                            $operand1[$row][$column] += $operand2[$row][$column];
5378
5379 90
                            break;
5380 89
                        case '-':
5381
                            $operand1[$row][$column] -= $operand2[$row][$column];
5382 41
5383 41
                            break;
5384
                        case '*':
5385 41
                            $operand1[$row][$column] *= $operand2[$row][$column];
5386
5387 58
                            break;
5388
                        case '/':
5389 58
                            if ($operand2[$row][$column] == 0) {
5390
                                $operand1[$row][$column] = ExcelError::DIV0();
5391 2
                            } else {
5392 2
                                $operand1[$row][$column] /= $operand2[$row][$column];
5393
                            }
5394 2
5395
                            break;
5396
                        case '^':
5397
                            $operand1[$row][$column] = $operand1[$row][$column] ** $operand2[$row][$column];
5398
5399
                            break;
5400
5401
                        default:
5402 1352
                            throw new Exception('Unsupported numeric binary operation');
5403
                    }
5404 1352
                }
5405
            }
5406 1352
            $result = $operand1;
5407
        } else {
5408
            //    If we're dealing with non-matrix operations, execute the necessary operation
5409
            switch ($operation) {
5410
                //    Addition
5411
                case '+':
5412
                    $result = $operand1 + $operand2;
5413
5414 263
                    break;
5415
                //    Subtraction
5416 263
                case '-':
5417 263
                    $result = $operand1 - $operand2;
5418 263
5419 263
                    break;
5420 262
                //    Multiplication
5421
                case '*':
5422
                    $result = $operand1 * $operand2;
5423 2
5424
                    break;
5425
                //    Division
5426
                case '/':
5427
                    if ($operand2 == 0) {
5428
                        //    Trap for Divide by Zero error
5429
                        $stack->push('Error', ExcelError::DIV0());
5430
                        $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails(ExcelError::DIV0()));
5431
5432
                        return false;
5433
                    }
5434
                    $result = $operand1 / $operand2;
5435 6727
5436
                    break;
5437
                //    Power
5438 6727
                case '^':
5439
                    $result = $operand1 ** $operand2;
5440 6727
5441 6727
                    break;
5442
5443 6727
                default:
5444 10
                    throw new Exception('Unsupported numeric binary operation');
5445 10
            }
5446
        }
5447
5448
        //    Log the result details
5449 6727
        $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($result));
5450 6727
        //    And push the result onto the stack
5451 6727
        $stack->push('Value', $result);
5452 6727
5453 6727
        return $result;
5454
    }
5455 6695
5456 6695
    /**
5457 6693
     * Trigger an error, but nicely, if need be.
5458 6693
     *
5459 54
     * @return false
5460 6
     */
5461
    protected function raiseFormulaError(string $errorMessage, int $code = 0, ?Throwable $exception = null): bool
5462
    {
5463 6693
        $this->formulaError = $errorMessage;
5464
        $this->cyclicReferenceStack->clear();
5465 4
        $suppress = $this->suppressFormulaErrors;
5466
        if (!$suppress) {
5467
            throw new Exception($errorMessage, $code, $exception);
5468
        }
5469 1102
5470
        return false;
5471 1102
    }
5472 1102
5473 1070
    /**
5474 1070
     * Extract range values.
5475 38
     *
5476
     * @param string $range String based range representation
5477
     * @param ?Worksheet $worksheet Worksheet
5478
     * @param bool $resetLog Flag indicating whether calculation log should be reset or not
5479 1070
     *
5480
     * @return array Array of values in range if range contains more than one element. Otherwise, a single value is returned.
5481 162
     */
5482
    public function extractCellRange(string &$range = 'A1', ?Worksheet $worksheet = null, bool $resetLog = true): array
5483
    {
5484
        // Return value
5485
        $returnValue = [];
5486
5487 6727
        if ($worksheet !== null) {
5488
            $worksheetName = $worksheet->getTitle();
5489
5490
            if (str_contains($range, '!')) {
5491
                [$worksheetName, $range] = Worksheet::extractSheetTitle($range, true);
5492
                $worksheet = ($this->spreadsheet === null) ? null : $this->spreadsheet->getSheetByName($worksheetName);
5493
            }
5494
5495
            // Extract range
5496
            $aReferences = Coordinate::extractAllCellReferencesInRange($range);
5497
            $range = "'" . $worksheetName . "'" . '!' . $range;
5498
            $currentCol = '';
5499
            $currentRow = 0;
5500
            if (!isset($aReferences[1])) {
5501
                //    Single cell in range
5502
                sscanf($aReferences[0], '%[A-Z]%d', $currentCol, $currentRow);
5503
                if ($worksheet !== null && $worksheet->cellExists($aReferences[0])) {
5504
                    $temp = $worksheet->getCell($aReferences[0])->getCalculatedValue($resetLog);
5505
                    if ($this->getInstanceArrayReturnType() === self::RETURN_ARRAY_AS_ARRAY) {
5506
                        while (is_array($temp)) {
5507
                            $temp = array_shift($temp);
5508
                        }
5509
                    }
5510
                    $returnValue[$currentRow][$currentCol] = $temp;
5511
                } else {
5512
                    $returnValue[$currentRow][$currentCol] = null;
5513
                }
5514
            } else {
5515
                // Extract cell data for all cells in the range
5516
                foreach ($aReferences as $reference) {
5517
                    // Extract range
5518
                    sscanf($reference, '%[A-Z]%d', $currentCol, $currentRow);
5519
                    if ($worksheet !== null && $worksheet->cellExists($reference)) {
5520
                        $temp = $worksheet->getCell($reference)->getCalculatedValue($resetLog);
5521
                        if ($this->getInstanceArrayReturnType() === self::RETURN_ARRAY_AS_ARRAY) {
5522
                            while (is_array($temp)) {
5523
                                $temp = array_shift($temp);
5524
                            }
5525
                        }
5526
                        $returnValue[$currentRow][$currentCol] = $temp;
5527
                    } else {
5528
                        $returnValue[$currentRow][$currentCol] = null;
5529
                    }
5530
                }
5531
            }
5532
        }
5533
5534
        return $returnValue;
5535
    }
5536
5537
    /**
5538
     * Extract range values.
5539
     *
5540
     * @param string $range String based range representation
5541
     * @param null|Worksheet $worksheet Worksheet
5542
     * @param bool $resetLog Flag indicating whether calculation log should be reset or not
5543
     *
5544
     * @return array|string Array of values in range if range contains more than one element. Otherwise, a single value is returned.
5545
     */
5546
    public function extractNamedRange(string &$range = 'A1', ?Worksheet $worksheet = null, bool $resetLog = true): string|array
5547
    {
5548
        // Return value
5549
        $returnValue = [];
5550
5551
        if ($worksheet !== null) {
5552
            if (str_contains($range, '!')) {
5553
                [$worksheetName, $range] = Worksheet::extractSheetTitle($range, true);
5554
                $worksheet = ($this->spreadsheet === null) ? null : $this->spreadsheet->getSheetByName($worksheetName);
5555
            }
5556
5557
            // Named range?
5558 3
            $namedRange = ($worksheet === null) ? null : DefinedName::resolveName($range, $worksheet);
5559
            if ($namedRange === null) {
5560 3
                return ExcelError::REF();
5561 3
            }
5562
5563 3
            $worksheet = $namedRange->getWorksheet();
5564
            $range = $namedRange->getValue();
5565
            $splitRange = Coordinate::splitRange($range);
5566
            //    Convert row and column references
5567
            if ($worksheet !== null && ctype_alpha($splitRange[0][0])) {
5568
                $range = $splitRange[0][0] . '1:' . $splitRange[0][1] . $worksheet->getHighestRow();
5569 2
            } elseif ($worksheet !== null && ctype_digit($splitRange[0][0])) {
5570
                $range = 'A' . $splitRange[0][0] . ':' . $worksheet->getHighestColumn() . $splitRange[0][1];
5571 2
            }
5572
5573
            // Extract range
5574
            $aReferences = Coordinate::extractAllCellReferencesInRange($range);
5575
            if (!isset($aReferences[1])) {
5576
                //    Single cell (or single column or row) in range
5577 2
                [$currentCol, $currentRow] = Coordinate::coordinateFromString($aReferences[0]);
5578
                if ($worksheet !== null && $worksheet->cellExists($aReferences[0])) {
5579 2
                    $returnValue[$currentRow][$currentCol] = $worksheet->getCell($aReferences[0])->getCalculatedValue($resetLog);
5580 2
                } else {
5581 2
                    $returnValue[$currentRow][$currentCol] = null;
5582 2
                }
5583
            } else {
5584
                // Extract cell data for all cells in the range
5585
                foreach ($aReferences as $reference) {
5586 2
                    // Extract range
5587
                    [$currentCol, $currentRow] = Coordinate::coordinateFromString($reference);
5588
                    if ($worksheet !== null && $worksheet->cellExists($reference)) {
5589 11248
                        $returnValue[$currentRow][$currentCol] = $worksheet->getCell($reference)->getCalculatedValue($resetLog);
5590
                    } else {
5591 11248
                        $returnValue[$currentRow][$currentCol] = null;
5592 11248
                    }
5593
                }
5594 11248
            }
5595
        }
5596 11240
5597 11207
        return $returnValue;
5598 134
    }
5599
5600 134
    /**
5601 134
     * Is a specific function implemented?
5602
     *
5603 12
     * @param string $function Function Name
5604
     */
5605
    public function isImplemented(string $function): bool
5606 122
    {
5607
        $function = strtoupper($function);
5608
        $notImplemented = !isset(self::$phpSpreadsheetFunctions[$function]) || (is_array(self::$phpSpreadsheetFunctions[$function]['functionCall']) && self::$phpSpreadsheetFunctions[$function]['functionCall'][1] === 'DUMMY');
5609
5610
        return !$notImplemented;
5611 11248
    }
5612
5613
    /**
5614 122
     * Get a list of all implemented functions as an array of function objects.
5615
     */
5616 122
    public static function getFunctions(): array
5617
    {
5618 122
        return self::$phpSpreadsheetFunctions;
5619 57
    }
5620 57
5621 2
    /**
5622
     * Get a list of implemented Excel function names.
5623 2
     */
5624 2
    public function getImplementedFunctionNames(): array
5625 2
    {
5626
        $returnValue = [];
5627 2
        foreach (self::$phpSpreadsheetFunctions as $functionName => $function) {
5628
            if ($this->isImplemented($functionName)) {
5629
                $returnValue[] = $functionName;
5630
            }
5631
        }
5632
5633
        return $returnValue;
5634 121
    }
5635
5636
    private function addDefaultArgumentValues(array $functionCall, array $args, array $emptyArguments): array
5637
    {
5638
        $reflector = new ReflectionMethod($functionCall[0], $functionCall[1]);
5639
        $methodArguments = $reflector->getParameters();
5640 11266
5641
        if (count($methodArguments) > 0) {
5642 11266
            // Apply any defaults for empty argument values
5643 206
            foreach ($emptyArguments as $argumentId => $isArgumentEmpty) {
5644 206
                if ($isArgumentEmpty === true) {
5645 206
                    $reflectedArgumentId = count($args) - (int) $argumentId - 1;
5646
                    if (
5647 206
                        !array_key_exists($reflectedArgumentId, $methodArguments)
5648 206
                        || $methodArguments[$reflectedArgumentId]->isVariadic()
5649 206
                    ) {
5650 49
                        break;
5651
                    }
5652
5653
                    $args[$argumentId] = $this->getArgumentDefaultValue($methodArguments[$reflectedArgumentId]);
5654 206
                }
5655
            }
5656
        }
5657 11266
5658
        return $args;
5659
    }
5660 111
5661
    private function getArgumentDefaultValue(ReflectionParameter $methodArgument): mixed
5662 111
    {
5663 111
        $defaultValue = null;
5664
5665
        if ($methodArgument->isDefaultValueAvailable()) {
5666
            $defaultValue = $methodArgument->getDefaultValue();
5667
            if ($methodArgument->isDefaultValueConstant()) {
5668
                $constantName = $methodArgument->getDefaultValueConstantName() ?? '';
5669
                // read constant value
5670
                if (str_contains($constantName, '::')) {
5671 111
                    [$className, $constantName] = explode('::', $constantName);
5672 111
                    $constantReflector = new ReflectionClassConstant($className, $constantName);
5673 111
5674
                    return $constantReflector->getValue();
5675 111
                }
5676 89
5677
                return constant($constantName);
5678
            }
5679 111
        }
5680
5681 111
        return $defaultValue;
5682 111
    }
5683 16
5684 104
    /**
5685 111
     * Add cell reference if needed while making sure that it is the last argument.
5686
     */
5687
    private function addCellReference(array $args, bool $passCellReference, array|string $functionCall, ?Cell $cell = null): array
5688 111
    {
5689 111
        if ($passCellReference) {
5690 111
            if (is_array($functionCall)) {
5691 111
                $className = $functionCall[0];
5692 111
                $methodName = $functionCall[1];
5693
5694 111
                $reflectionMethod = new ReflectionMethod($className, $methodName);
5695
                $argumentCount = count($reflectionMethod->getParameters());
5696 111
                while (count($args) < $argumentCount - 1) {
5697 111
                    $args[] = null;
5698 111
                }
5699 111
            }
5700 111
5701
            $args[] = $cell;
5702 111
        }
5703
5704
        return $args;
5705
    }
5706
5707 111
    private function evaluateDefinedName(Cell $cell, DefinedName $namedRange, Worksheet $cellWorksheet, Stack $stack, bool $ignoreScope = false): mixed
5708
    {
5709 111
        $definedNameScope = $namedRange->getScope();
5710
        if ($definedNameScope !== null && $definedNameScope !== $cellWorksheet && !$ignoreScope) {
5711
            // The defined name isn't in our current scope, so #REF
5712 2
            $result = ExcelError::REF();
5713
            $stack->push('Error', $result, $namedRange->getName());
5714 2
5715
            return $result;
5716
        }
5717 4
5718
        $definedNameValue = $namedRange->getValue();
5719 4
        $definedNameType = $namedRange->isFormula() ? 'Formula' : 'Range';
5720
        $definedNameWorksheet = $namedRange->getWorksheet();
5721
5722 25
        if ($definedNameValue[0] !== '=') {
5723
            $definedNameValue = '=' . $definedNameValue;
5724 25
        }
5725 1
5726 25
        $this->debugLog->writeDebugLog('Defined Name is a %s with a value of %s', $definedNameType, $definedNameValue);
5727
5728
        $originalCoordinate = $cell->getCoordinate();
5729
        $recursiveCalculationCell = ($definedNameType !== 'Formula' && $definedNameWorksheet !== null && $definedNameWorksheet !== $cellWorksheet)
5730 25
            ? $definedNameWorksheet->getCell('A1')
5731
            : $cell;
5732
        $recursiveCalculationCellAddress = $recursiveCalculationCell->getCoordinate();
5733 38
5734
        // Adjust relative references in ranges and formulae so that we execute the calculation for the correct rows and columns
5735 38
        $definedNameValue = self::$referenceHelper->updateFormulaReferencesAnyWorksheet(
5736
            $definedNameValue,
5737
            Coordinate::columnIndexFromString($cell->getColumn()) - 1,
5738 3
            $cell->getRow() - 1
5739
        );
5740 3
5741
        $this->debugLog->writeDebugLog('Value adjusted for relative references is %s', $definedNameValue);
5742
5743
        $recursiveCalculator = new self($this->spreadsheet);
5744
        $recursiveCalculator->getDebugLog()->setWriteDebugLog($this->getDebugLog()->getWriteDebugLog());
5745
        $recursiveCalculator->getDebugLog()->setEchoDebugLog($this->getDebugLog()->getEchoDebugLog());
5746
        $result = $recursiveCalculator->_calculateFormulaValue($definedNameValue, $recursiveCalculationCellAddress, $recursiveCalculationCell, true);
5747
        $cellWorksheet->getCell($originalCoordinate);
5748
5749
        if ($this->getDebugLog()->getWriteDebugLog()) {
5750
            $this->debugLog->mergeDebugLog(array_slice($recursiveCalculator->getDebugLog()->getLog(), 3));
5751
            $this->debugLog->writeDebugLog('Evaluation Result for Named %s %s is %s', $definedNameType, $namedRange->getName(), $this->showTypeDetails($result));
5752
        }
5753
5754
        $stack->push('Defined Name', $result, $namedRange->getName());
5755
5756
        return $result;
5757
    }
5758
5759
    public function setSuppressFormulaErrors(bool $suppressFormulaErrors): void
5760
    {
5761
        $this->suppressFormulaErrors = $suppressFormulaErrors;
5762
    }
5763
5764
    public function getSuppressFormulaErrors(): bool
5765
    {
5766
        return $this->suppressFormulaErrors;
5767
    }
5768
5769
    public static function boolToString(mixed $operand1): mixed
5770
    {
5771
        if (is_bool($operand1)) {
5772
            $operand1 = ($operand1) ? self::$localeBoolean['TRUE'] : self::$localeBoolean['FALSE'];
5773
        } elseif ($operand1 === null) {
5774
            $operand1 = '';
5775
        }
5776
5777
        return $operand1;
5778
    }
5779
5780
    private static function isNumericOrBool(mixed $operand): bool
5781
    {
5782
        return is_numeric($operand) || is_bool($operand);
5783
    }
5784
5785
    private static function makeError(mixed $operand = ''): string
5786
    {
5787
        return Information\ErrorValue::isError($operand) ? $operand : ExcelError::VALUE();
5788
    }
5789
}
5790