Completed
Push — master ( d93a30...6a259d )
by Mark
41s queued 30s
created

Calculation::flushInstance()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

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