Proyectos de Subversion Moodle

Rev

| Ultima modificación | Ver Log |

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