Completed
Push — master ( fe79f7...a3187a )
by Mark
36s queued 32s
created

Calculation::getTRUE()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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