• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

PHPOffice / PhpSpreadsheet / 21013444139

14 Jan 2026 11:20PM UTC coverage: 96.199% (+0.2%) from 95.962%
21013444139

Pull #4657

github

web-flow
Merge dcaff346a into 48f2fe37d
Pull Request #4657: Handling Unions as Function Arguments

19 of 20 new or added lines in 1 file covered. (95.0%)

359 existing lines in 16 files now uncovered.

46287 of 48116 relevant lines covered (96.2%)

387.01 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

91.85
/src/PhpSpreadsheet/Calculation/Calculation.php
1
<?php
2

3
namespace PhpOffice\PhpSpreadsheet\Calculation;
4

5
use Composer\Pcre\Preg; // many pregs in this program use u modifier, which has side-effects which make it unsuitable for this
6
use PhpOffice\PhpSpreadsheet\Calculation\Engine\BranchPruner;
7
use PhpOffice\PhpSpreadsheet\Calculation\Engine\CyclicReferenceStack;
8
use PhpOffice\PhpSpreadsheet\Calculation\Engine\Logger;
9
use PhpOffice\PhpSpreadsheet\Calculation\Engine\Operands;
10
use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError;
11
use PhpOffice\PhpSpreadsheet\Calculation\Token\Stack;
12
use PhpOffice\PhpSpreadsheet\Cell\AddressRange;
13
use PhpOffice\PhpSpreadsheet\Cell\Cell;
14
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
15
use PhpOffice\PhpSpreadsheet\Cell\DataType;
16
use PhpOffice\PhpSpreadsheet\DefinedName;
17
use PhpOffice\PhpSpreadsheet\NamedRange;
18
use PhpOffice\PhpSpreadsheet\ReferenceHelper;
19
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
20
use PhpOffice\PhpSpreadsheet\Spreadsheet;
21
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
22
use ReflectionClassConstant;
23
use ReflectionMethod;
24
use ReflectionParameter;
25
use Throwable;
26
use TypeError;
27

28
class Calculation extends CalculationLocale
29
{
30
    /** Constants                */
31
    /** Regular Expressions        */
32
    //    Numeric operand
33
    const CALCULATION_REGEXP_NUMBER = '[-+]?\d*\.?\d+(e[-+]?\d+)?';
34
    //    String operand
35
    const CALCULATION_REGEXP_STRING = '"(?:[^"]|"")*"';
36
    //    Opening bracket
37
    const CALCULATION_REGEXP_OPENBRACE = '\(';
38
    //    Function (allow for the old @ symbol that could be used to prefix a function, but we'll ignore it)
39
    const CALCULATION_REGEXP_FUNCTION = '@?(?:_xlfn\.)?(?:_xlws\.)?((?:__xludf\.)?[\p{L}][\p{L}\p{N}\.]*)[\s]*\(';
40
    //    Cell reference (cell or range of cells, with or without a sheet reference)
41
    const CALCULATION_REGEXP_CELLREF = '((([^\s,!&%^\/\*\+<>=:`-]*)|(\'(?:[^\']|\'[^!])+?\')|(\"(?:[^\"]|\"[^!])+?\"))!)?\$?\b([a-z]{1,3})\$?(\d{1,7})(?![\w.])';
42
    // Used only to detect spill operator #
43
    const CALCULATION_REGEXP_CELLREF_SPILL = '/' . self::CALCULATION_REGEXP_CELLREF . '#/i';
44
    //    Cell reference (with or without a sheet reference) ensuring absolute/relative
45
    const CALCULATION_REGEXP_CELLREF_RELATIVE = '((([^\s\(,!&%^\/\*\+<>=:`-]*)|(\'(?:[^\']|\'[^!])+?\')|(\"(?:[^\"]|\"[^!])+?\"))!)?(\$?\b[a-z]{1,3})(\$?\d{1,7})(?![\w.])';
46
    const CALCULATION_REGEXP_COLUMN_RANGE = '(((([^\s\(,!&%^\/\*\+<>=:`-]*)|(\'(?:[^\']|\'[^!])+?\')|(\".(?:[^\"]|\"[^!])?\"))!)?(\$?[a-z]{1,3})):(?![.*])';
47
    const CALCULATION_REGEXP_ROW_RANGE = '(((([^\s\(,!&%^\/\*\+<>=:`-]*)|(\'(?:[^\']|\'[^!])+?\')|(\"(?:[^\"]|\"[^!])+?\"))!)?(\$?[1-9][0-9]{0,6})):(?![.*])';
48
    //    Cell reference (with or without a sheet reference) ensuring absolute/relative
49
    //    Cell ranges ensuring absolute/relative
50
    const CALCULATION_REGEXP_COLUMNRANGE_RELATIVE = '(\$?[a-z]{1,3}):(\$?[a-z]{1,3})';
51
    const CALCULATION_REGEXP_ROWRANGE_RELATIVE = '(\$?\d{1,7}):(\$?\d{1,7})';
52
    //    Defined Names: Named Range of cells, or Named Formulae
53
    const CALCULATION_REGEXP_DEFINEDNAME = '((([^\s,!&%^\/\*\+<>=-]*)|(\'(?:[^\']|\'[^!])+?\')|(\"(?:[^\"]|\"[^!])+?\"))!)?([_\p{L}][_\p{L}\p{N}\.]*)';
54
    // Structured Reference (Fully Qualified and Unqualified)
55
    const CALCULATION_REGEXP_STRUCTURED_REFERENCE = '([\p{L}_\\\][\p{L}\p{N}\._]+)?(\[(?:[^\d\]+-])?)';
56
    //    Error
57
    const CALCULATION_REGEXP_ERROR = '\#[A-Z][A-Z0_\/]*[!\?]?';
58

59
    /** constants */
60
    const RETURN_ARRAY_AS_ERROR = 'error';
61
    const RETURN_ARRAY_AS_VALUE = 'value';
62
    const RETURN_ARRAY_AS_ARRAY = 'array';
63

64
    /** Preferable to use instance variable instanceArrayReturnType rather than this static property. */
65
    private static string $returnArrayAsType = self::RETURN_ARRAY_AS_VALUE;
66

67
    /** Preferable to use this instance variable rather than static returnArrayAsType */
68
    private ?string $instanceArrayReturnType = null;
69

70
    /**
71
     * Instance of this class.
72
     */
73
    private static ?Calculation $instance = null;
74

75
    /**
76
     * Instance of the spreadsheet this Calculation Engine is using.
77
     */
78
    private ?Spreadsheet $spreadsheet;
79

80
    /**
81
     * Calculation cache.
82
     *
83
     * @var mixed[]
84
     */
85
    private array $calculationCache = [];
86

87
    /**
88
     * Calculation cache enabled.
89
     */
90
    private bool $calculationCacheEnabled = true;
91

92
    private BranchPruner $branchPruner;
93

94
    private bool $branchPruningEnabled = true;
95

96
    /**
97
     * List of operators that can be used within formulae
98
     * The true/false value indicates whether it is a binary operator or a unary operator.
99
     */
100
    private const CALCULATION_OPERATORS = [
101
        '+' => true, '-' => true, '*' => true, '/' => true,
102
        '^' => true, '&' => true, '%' => false, '~' => false,
103
        '>' => true, '<' => true, '=' => true, '>=' => true,
104
        '<=' => true, '<>' => true, '∩' => true, '∪' => true,
105
        ':' => true,
106
    ];
107

108
    /**
109
     * List of binary operators (those that expect two operands).
110
     */
111
    private const BINARY_OPERATORS = [
112
        '+' => true, '-' => true, '*' => true, '/' => true,
113
        '^' => true, '&' => true, '>' => true, '<' => true,
114
        '=' => true, '>=' => true, '<=' => true, '<>' => true,
115
        '∩' => true, '∪' => true, ':' => true,
116
    ];
117

118
    /**
119
     * The debug log generated by the calculation engine.
120
     */
121
    private Logger $debugLog;
122

123
    private bool $suppressFormulaErrors = false;
124

125
    private bool $processingAnchorArray = false;
126

127
    /**
128
     * Error message for any error that was raised/thrown by the calculation engine.
129
     */
130
    public ?string $formulaError = null;
131

132
    /**
133
     * An array of the nested cell references accessed by the calculation engine, used for the debug log.
134
     */
135
    private CyclicReferenceStack $cyclicReferenceStack;
136

137
    /** @var mixed[] */
138
    private array $cellStack = [];
139

140
    /**
141
     * Current iteration counter for cyclic formulae
142
     * If the value is 0 (or less) then cyclic formulae will throw an exception,
143
     * otherwise they will iterate to the limit defined here before returning a result.
144
     */
145
    private int $cyclicFormulaCounter = 1;
146

147
    private string $cyclicFormulaCell = '';
148

149
    /**
150
     * Number of iterations for cyclic formulae.
151
     */
152
    public int $cyclicFormulaCount = 1;
153

154
    /**
155
     * Excel constant string translations to their PHP equivalents
156
     * Constant conversion from text name/value to actual (datatyped) value.
157
     */
158
    private const EXCEL_CONSTANTS = [
159
        'TRUE' => true,
160
        'FALSE' => false,
161
        'NULL' => null,
162
    ];
163

164
    public static function keyInExcelConstants(string $key): bool
20✔
165
    {
166
        return array_key_exists($key, self::EXCEL_CONSTANTS);
20✔
167
    }
168

169
    public static function getExcelConstants(string $key): bool|null
3✔
170
    {
171
        return self::EXCEL_CONSTANTS[$key];
3✔
172
    }
173

174
    /**
175
     *    Internal functions used for special control purposes.
176
     *
177
     * @var array<string, array<string, array<string>|string>>
178
     */
179
    private static array $controlFunctions = [
180
        'MKMATRIX' => [
181
            'argumentCount' => '*',
182
            'functionCall' => [Internal\MakeMatrix::class, 'make'],
183
        ],
184
        'NAME.ERROR' => [
185
            'argumentCount' => '*',
186
            'functionCall' => [ExcelError::class, 'NAME'],
187
        ],
188
        'WILDCARDMATCH' => [
189
            'argumentCount' => '2',
190
            'functionCall' => [Internal\WildcardMatch::class, 'compare'],
191
        ],
192
    ];
193

194
    public function __construct(?Spreadsheet $spreadsheet = null)
11,165✔
195
    {
196
        $this->spreadsheet = $spreadsheet;
11,165✔
197
        $this->cyclicReferenceStack = new CyclicReferenceStack();
11,165✔
198
        $this->debugLog = new Logger($this->cyclicReferenceStack);
11,165✔
199
        $this->branchPruner = new BranchPruner($this->branchPruningEnabled);
11,165✔
200
    }
201

202
    /**
203
     * Get an instance of this class.
204
     *
205
     * @param ?Spreadsheet $spreadsheet Injected spreadsheet for working with a PhpSpreadsheet Spreadsheet object,
206
     *                                    or NULL to create a standalone calculation engine
207
     */
208
    public static function getInstance(?Spreadsheet $spreadsheet = null): self
13,561✔
209
    {
210
        if ($spreadsheet !== null) {
13,561✔
211
            return $spreadsheet->getCalculationEngine();
9,748✔
212
        }
213

214
        if (!self::$instance) {
4,698✔
215
            self::$instance = new self();
15✔
216
        }
217

218
        return self::$instance;
4,698✔
219
    }
220

221
    /**
222
     * Intended for use only via a destructor.
223
     *
224
     * @internal
225
     */
226
    public static function getInstanceOrNull(?Spreadsheet $spreadsheet = null): ?self
138✔
227
    {
228
        if ($spreadsheet !== null) {
138✔
229
            return $spreadsheet->getCalculationEngineOrNull();
89✔
230
        }
231

232
        return null;
133✔
233
    }
234

235
    /**
236
     * Flush the calculation cache for any existing instance of this class
237
     *        but only if a Calculation instance exists.
238
     */
239
    public function flushInstance(): void
209✔
240
    {
241
        $this->clearCalculationCache();
209✔
242
        $this->branchPruner->clearBranchStore();
209✔
243
    }
244

245
    /**
246
     * Get the Logger for this calculation engine instance.
247
     */
248
    public function getDebugLog(): Logger
1,212✔
249
    {
250
        return $this->debugLog;
1,212✔
251
    }
252

253
    /**
254
     * __clone implementation. Cloning should not be allowed in a Singleton!
255
     */
256
    final public function __clone()
1✔
257
    {
258
        throw new Exception('Cloning the calculation engine is not allowed!');
1✔
259
    }
260

261
    /**
262
     * Set the Array Return Type (Array or Value of first element in the array).
263
     *
264
     * @param string $returnType Array return type
265
     *
266
     * @return bool Success or failure
267
     */
268
    public static function setArrayReturnType(string $returnType): bool
588✔
269
    {
270
        if (
271
            ($returnType == self::RETURN_ARRAY_AS_VALUE)
588✔
272
            || ($returnType == self::RETURN_ARRAY_AS_ERROR)
588✔
273
            || ($returnType == self::RETURN_ARRAY_AS_ARRAY)
588✔
274
        ) {
275
            self::$returnArrayAsType = $returnType;
588✔
276

277
            return true;
588✔
278
        }
279

280
        return false;
1✔
281
    }
282

283
    /**
284
     * Return the Array Return Type (Array or Value of first element in the array).
285
     *
286
     * @return string $returnType Array return type
287
     */
288
    public static function getArrayReturnType(): string
588✔
289
    {
290
        return self::$returnArrayAsType;
588✔
291
    }
292

293
    /**
294
     * Set the Instance Array Return Type (Array or Value of first element in the array).
295
     *
296
     * @param string $returnType Array return type
297
     *
298
     * @return bool Success or failure
299
     */
300
    public function setInstanceArrayReturnType(string $returnType): bool
425✔
301
    {
302
        if (
303
            ($returnType == self::RETURN_ARRAY_AS_VALUE)
425✔
304
            || ($returnType == self::RETURN_ARRAY_AS_ERROR)
425✔
305
            || ($returnType == self::RETURN_ARRAY_AS_ARRAY)
425✔
306
        ) {
307
            $this->instanceArrayReturnType = $returnType;
423✔
308

309
            return true;
423✔
310
        }
311

312
        return false;
2✔
313
    }
314

315
    /**
316
     * Return the Array Return Type (Array or Value of first element in the array).
317
     *
318
     * @return string $returnType Array return type for instance if non-null, otherwise static property
319
     */
320
    public function getInstanceArrayReturnType(): string
9,278✔
321
    {
322
        return $this->instanceArrayReturnType ?? self::$returnArrayAsType;
9,278✔
323
    }
324

325
    /**
326
     * Is calculation caching enabled?
327
     */
328
    public function getCalculationCacheEnabled(): bool
3,803✔
329
    {
330
        return $this->calculationCacheEnabled;
3,803✔
331
    }
332

333
    /**
334
     * Enable/disable calculation cache.
335
     */
336
    public function setCalculationCacheEnabled(bool $calculationCacheEnabled): self
10✔
337
    {
338
        $this->calculationCacheEnabled = $calculationCacheEnabled;
10✔
339
        $this->clearCalculationCache();
10✔
340

341
        return $this;
10✔
342
    }
343

344
    /**
345
     * Enable calculation cache.
346
     */
347
    public function enableCalculationCache(): void
×
348
    {
349
        $this->setCalculationCacheEnabled(true);
×
350
    }
351

352
    /**
353
     * Disable calculation cache.
354
     */
355
    public function disableCalculationCache(): void
×
356
    {
357
        $this->setCalculationCacheEnabled(false);
×
358
    }
359

360
    /**
361
     * Clear calculation cache.
362
     */
363
    public function clearCalculationCache(): void
221✔
364
    {
365
        $this->calculationCache = [];
221✔
366
    }
367

368
    /**
369
     * Clear calculation cache for a specified worksheet.
370
     */
371
    public function clearCalculationCacheForWorksheet(string $worksheetName): void
88✔
372
    {
373
        if (isset($this->calculationCache[$worksheetName])) {
88✔
374
            unset($this->calculationCache[$worksheetName]);
×
375
        }
376
    }
377

378
    /**
379
     * Rename calculation cache for a specified worksheet.
380
     */
381
    public function renameCalculationCacheForWorksheet(string $fromWorksheetName, string $toWorksheetName): void
1,473✔
382
    {
383
        if (isset($this->calculationCache[$fromWorksheetName])) {
1,473✔
384
            $this->calculationCache[$toWorksheetName] = &$this->calculationCache[$fromWorksheetName];
×
385
            unset($this->calculationCache[$fromWorksheetName]);
×
386
        }
387
    }
388

389
    public function getBranchPruningEnabled(): bool
10✔
390
    {
391
        return $this->branchPruningEnabled;
10✔
392
    }
393

394
    public function setBranchPruningEnabled(mixed $enabled): self
8,402✔
395
    {
396
        $this->branchPruningEnabled = (bool) $enabled;
8,402✔
397
        $this->branchPruner = new BranchPruner($this->branchPruningEnabled);
8,402✔
398

399
        return $this;
8,402✔
400
    }
401

402
    public function enableBranchPruning(): void
×
403
    {
404
        $this->setBranchPruningEnabled(true);
×
405
    }
406

407
    public function disableBranchPruning(): void
8,392✔
408
    {
409
        $this->setBranchPruningEnabled(false);
8,392✔
410
    }
411

412
    /**
413
     * Wrap string values in quotes.
414
     */
415
    public static function wrapResult(mixed $value): mixed
11,894✔
416
    {
417
        if (is_string($value)) {
11,894✔
418
            //    Error values cannot be "wrapped"
419
            if (Preg::isMatch('/^' . self::CALCULATION_REGEXP_ERROR . '$/i', $value, $match)) {
4,077✔
420
                //    Return Excel errors "as is"
421
                return $value;
1,308✔
422
            }
423

424
            //    Return strings wrapped in quotes
425
            return self::FORMULA_STRING_QUOTE . $value . self::FORMULA_STRING_QUOTE;
3,252✔
426
        } elseif ((is_float($value)) && ((is_nan($value)) || (is_infinite($value)))) {
9,473✔
427
            //    Convert numeric errors to NaN error
428
            return ExcelError::NAN();
4✔
429
        }
430

431
        return $value;
9,470✔
432
    }
433

434
    /**
435
     * Remove quotes used as a wrapper to identify string values.
436
     */
437
    public static function unwrapResult(mixed $value): mixed
12,128✔
438
    {
439
        if (is_string($value)) {
12,128✔
440
            if ((isset($value[0])) && ($value[0] == self::FORMULA_STRING_QUOTE) && (substr($value, -1) == self::FORMULA_STRING_QUOTE)) {
4,164✔
441
                return substr($value, 1, -1);
3,243✔
442
            }
443
            //    Convert numeric errors to NAN error
444
        } elseif ((is_float($value)) && ((is_nan($value)) || (is_infinite($value)))) {
11,283✔
445
            return ExcelError::NAN();
×
446
        }
447

448
        return $value;
11,507✔
449
    }
450

451
    /**
452
     * Calculate cell value (using formula from a cell ID)
453
     * Retained for backward compatibility.
454
     *
455
     * @param ?Cell $cell Cell to calculate
456
     */
457
    public function calculate(?Cell $cell = null): mixed
2✔
458
    {
459
        try {
460
            return $this->calculateCellValue($cell);
2✔
461
        } catch (\Exception $e) {
1✔
462
            throw new Exception($e->getMessage());
1✔
463
        }
464
    }
465

466
    /**
467
     * Calculate the value of a cell formula.
468
     *
469
     * @param ?Cell $cell Cell to calculate
470
     * @param bool $resetLog Flag indicating whether the debug log should be reset or not
471
     */
472
    public function calculateCellValue(?Cell $cell = null, bool $resetLog = true): mixed
8,466✔
473
    {
474
        if ($cell === null) {
8,466✔
475
            return null;
×
476
        }
477

478
        if ($resetLog) {
8,466✔
479
            //    Initialise the logging settings if requested
480
            $this->formulaError = null;
8,454✔
481
            $this->debugLog->clearLog();
8,454✔
482
            $this->cyclicReferenceStack->clear();
8,454✔
483
            $this->cyclicFormulaCounter = 1;
8,454✔
484
        }
485

486
        //    Execute the calculation for the cell formula
487
        $this->cellStack[] = [
8,466✔
488
            'sheet' => $cell->getWorksheet()->getTitle(),
8,466✔
489
            'cell' => $cell->getCoordinate(),
8,466✔
490
        ];
8,466✔
491

492
        $cellAddressAttempted = false;
8,466✔
493
        $cellAddress = null;
8,466✔
494

495
        try {
496
            $value = $cell->getValue();
8,466✔
497
            if (is_string($value) && $cell->getDataType() === DataType::TYPE_FORMULA) {
8,466✔
498
                $value = Preg::replaceCallback(
8,466✔
499
                    self::CALCULATION_REGEXP_CELLREF_SPILL,
8,466✔
500
                    fn (array $matches) => 'ANCHORARRAY(' . substr($matches[0], 0, -1) . ')',
8,466✔
501
                    $value
8,466✔
502
                );
8,466✔
503
            }
504
            $result = self::unwrapResult($this->_calculateFormulaValue($value, $cell->getCoordinate(), $cell)); //* @phpstan-ignore-line
8,466✔
505
            if ($this->spreadsheet === null) {
8,232✔
506
                throw new Exception('null spreadsheet in calculateCellValue');
×
507
            }
508
            $cellAddressAttempted = true;
8,232✔
509
            $cellAddress = array_pop($this->cellStack);
8,232✔
510
            if ($cellAddress === null) {
8,232✔
511
                throw new Exception('null cellAddress in calculateCellValue');
×
512
            }
513
            /** @var array{sheet: string, cell: string} $cellAddress */
514
            $testSheet = $this->spreadsheet->getSheetByName($cellAddress['sheet']);
8,232✔
515
            if ($testSheet === null) {
8,232✔
516
                throw new Exception('worksheet not found in calculateCellValue');
×
517
            }
518
            $testSheet->getCell($cellAddress['cell']);
8,232✔
519
        } catch (\Exception $e) {
244✔
520
            if (!$cellAddressAttempted) {
244✔
521
                $cellAddress = array_pop($this->cellStack);
244✔
522
            }
523
            if ($this->spreadsheet !== null && is_array($cellAddress) && array_key_exists('sheet', $cellAddress)) {
244✔
524
                $sheetName = $cellAddress['sheet'] ?? null;
244✔
525
                $testSheet = is_string($sheetName) ? $this->spreadsheet->getSheetByName($sheetName) : null;
244✔
526
                if ($testSheet !== null && array_key_exists('cell', $cellAddress)) {
244✔
527
                    /** @var array{cell: string} $cellAddress */
528
                    $testSheet->getCell($cellAddress['cell']);
244✔
529
                }
530
            }
531

532
            throw new Exception($e->getMessage(), $e->getCode(), $e);
244✔
533
        }
534

535
        if (is_array($result) && $this->getInstanceArrayReturnType() !== self::RETURN_ARRAY_AS_ARRAY) {
8,232✔
536
            $testResult = Functions::flattenArray($result);
5,066✔
537
            if ($this->getInstanceArrayReturnType() == self::RETURN_ARRAY_AS_ERROR) {
5,066✔
538
                return ExcelError::VALUE();
1✔
539
            }
540
            $result = array_shift($testResult);
5,065✔
541
        }
542

543
        if ($result === null && $cell->getWorksheet()->getSheetView()->getShowZeros()) {
8,231✔
544
            return 0;
18✔
545
        } elseif ((is_float($result)) && ((is_nan($result)) || (is_infinite($result)))) {
8,229✔
546
            return ExcelError::NAN();
×
547
        }
548

549
        return $result;
8,229✔
550
    }
551

552
    /**
553
     * Validate and parse a formula string.
554
     *
555
     * @param string $formula Formula to parse
556
     *
557
     * @return array<mixed>|bool
558
     */
559
    public function parseFormula(string $formula): array|bool
8,437✔
560
    {
561
        $formula = Preg::replaceCallback(
8,437✔
562
            self::CALCULATION_REGEXP_CELLREF_SPILL,
8,437✔
563
            fn (array $matches) => 'ANCHORARRAY(' . substr($matches[0], 0, -1) . ')',
8,437✔
564
            $formula
8,437✔
565
        );
8,437✔
566
        //    Basic validation that this is indeed a formula
567
        //    We return an empty array if not
568
        $formula = trim($formula);
8,437✔
569
        if ((!isset($formula[0])) || ($formula[0] != '=')) {
8,437✔
570
            return [];
1✔
571
        }
572
        $formula = ltrim(substr($formula, 1));
8,437✔
573
        if (!isset($formula[0])) {
8,437✔
574
            return [];
1✔
575
        }
576

577
        //    Parse the formula and return the token stack
578
        return $this->internalParseFormula($formula);
8,436✔
579
    }
580

581
    /**
582
     * Calculate the value of a formula.
583
     *
584
     * @param string $formula Formula to parse
585
     * @param ?string $cellID Address of the cell to calculate
586
     * @param ?Cell $cell Cell to calculate
587
     */
588
    public function calculateFormula(string $formula, ?string $cellID = null, ?Cell $cell = null): mixed
3,793✔
589
    {
590
        //    Initialise the logging settings
591
        $this->formulaError = null;
3,793✔
592
        $this->debugLog->clearLog();
3,793✔
593
        $this->cyclicReferenceStack->clear();
3,793✔
594

595
        $resetCache = $this->getCalculationCacheEnabled();
3,793✔
596
        if ($this->spreadsheet !== null && $cellID === null && $cell === null) {
3,793✔
597
            $cellID = 'A1';
174✔
598
            $cell = $this->spreadsheet->getActiveSheet()->getCell($cellID);
174✔
599
        } else {
600
            //    Disable calculation cacheing because it only applies to cell calculations, not straight formulae
601
            //    But don't actually flush any cache
602
            $this->calculationCacheEnabled = false;
3,619✔
603
        }
604

605
        //    Execute the calculation
606
        try {
607
            $result = self::unwrapResult($this->_calculateFormulaValue($formula, $cellID, $cell));
3,793✔
608
        } catch (\Exception $e) {
3✔
609
            throw new Exception($e->getMessage());
3✔
610
        }
611

612
        if ($this->spreadsheet === null) {
3,790✔
613
            //    Reset calculation cacheing to its previous state
614
            $this->calculationCacheEnabled = $resetCache;
3,603✔
615
        }
616

617
        return $result;
3,790✔
618
    }
619

620
    public function getValueFromCache(string $cellReference, mixed &$cellValue): bool
8,620✔
621
    {
622
        $this->debugLog->writeDebugLog('Testing cache value for cell %s', $cellReference);
8,620✔
623
        // Is calculation cacheing enabled?
624
        // If so, is the required value present in calculation cache?
625
        if (($this->calculationCacheEnabled) && (isset($this->calculationCache[$cellReference]))) {
8,620✔
626
            $this->debugLog->writeDebugLog('Retrieving value for cell %s from cache', $cellReference);
360✔
627
            // Return the cached result
628

629
            $cellValue = $this->calculationCache[$cellReference];
360✔
630

631
            return true;
360✔
632
        }
633

634
        return false;
8,620✔
635
    }
636

637
    public function saveValueToCache(string $cellReference, mixed $cellValue): void
8,385✔
638
    {
639
        if ($this->calculationCacheEnabled) {
8,385✔
640
            $this->calculationCache[$cellReference] = $cellValue;
8,375✔
641
        }
642
    }
643

644
    /**
645
     * Parse a cell formula and calculate its value.
646
     *
647
     * @param string $formula The formula to parse and calculate
648
     * @param ?string $cellID The ID (e.g. A3) of the cell that we are calculating
649
     * @param ?Cell $cell Cell to calculate
650
     * @param bool $ignoreQuotePrefix If set to true, evaluate the formyla even if the referenced cell is quote prefixed
651
     */
652
    public function _calculateFormulaValue(string $formula, ?string $cellID = null, ?Cell $cell = null, bool $ignoreQuotePrefix = false): mixed
12,352✔
653
    {
654
        $cellValue = null;
12,352✔
655

656
        //  Quote-Prefixed cell values cannot be formulae, but are treated as strings
657
        if ($cell !== null && $ignoreQuotePrefix === false && $cell->getStyle()->getQuotePrefix() === true) {
12,352✔
658
            return self::wrapResult((string) $formula);
1✔
659
        }
660

661
        if (preg_match('/^=\s*cmd\s*\|/miu', $formula) !== 0) {
12,352✔
662
            return self::wrapResult($formula);
×
663
        }
664

665
        //    Basic validation that this is indeed a formula
666
        //    We simply return the cell value if not
667
        $formula = trim($formula);
12,352✔
668
        if ($formula === '' || $formula[0] !== '=') {
12,352✔
669
            return self::wrapResult($formula);
2✔
670
        }
671
        $formula = ltrim(substr($formula, 1));
12,352✔
672
        if (!isset($formula[0])) {
12,352✔
673
            return self::wrapResult($formula);
6✔
674
        }
675

676
        $pCellParent = ($cell !== null) ? $cell->getWorksheet() : null;
12,351✔
677
        $wsTitle = ($pCellParent !== null) ? $pCellParent->getTitle() : "\x00Wrk";
12,351✔
678
        $wsCellReference = $wsTitle . '!' . $cellID;
12,351✔
679

680
        if (($cellID !== null) && ($this->getValueFromCache($wsCellReference, $cellValue))) {
12,351✔
681
            return $cellValue;
356✔
682
        }
683
        $this->debugLog->writeDebugLog('Evaluating formula for cell %s', $wsCellReference);
12,351✔
684

685
        if (($wsTitle[0] !== "\x00") && ($this->cyclicReferenceStack->onStack($wsCellReference))) {
12,351✔
686
            if ($this->cyclicFormulaCount <= 0) {
13✔
687
                $this->cyclicFormulaCell = '';
1✔
688

689
                return $this->raiseFormulaError('Cyclic Reference in Formula');
1✔
690
            } elseif ($this->cyclicFormulaCell === $wsCellReference) {
12✔
691
                ++$this->cyclicFormulaCounter;
1✔
692
                if ($this->cyclicFormulaCounter >= $this->cyclicFormulaCount) {
1✔
693
                    $this->cyclicFormulaCell = '';
1✔
694

695
                    return $cellValue;
1✔
696
                }
697
            } elseif ($this->cyclicFormulaCell == '') {
12✔
698
                if ($this->cyclicFormulaCounter >= $this->cyclicFormulaCount) {
12✔
699
                    return $cellValue;
11✔
700
                }
701
                $this->cyclicFormulaCell = $wsCellReference;
1✔
702
            }
703
        }
704

705
        $this->debugLog->writeDebugLog('Formula for cell %s is %s', $wsCellReference, $formula);
12,351✔
706
        //    Parse the formula onto the token stack and calculate the value
707
        $this->cyclicReferenceStack->push($wsCellReference);
12,351✔
708

709
        $cellValue = $this->processTokenStack($this->internalParseFormula($formula, $cell), $cellID, $cell);
12,351✔
710
        $this->cyclicReferenceStack->pop();
12,114✔
711

712
        // Save to calculation cache
713
        if ($cellID !== null) {
12,114✔
714
            $this->saveValueToCache($wsCellReference, $cellValue);
8,385✔
715
        }
716

717
        //    Return the calculated value
718
        return $cellValue;
12,114✔
719
    }
720

721
    /**
722
     * Ensure that paired matrix operands are both matrices and of the same size.
723
     *
724
     * @param mixed $operand1 First matrix operand
725
     *
726
     * @param-out mixed[] $operand1
727
     *
728
     * @param mixed $operand2 Second matrix operand
729
     *
730
     * @param-out mixed[] $operand2
731
     *
732
     * @param int $resize Flag indicating whether the matrices should be resized to match
733
     *                                        and (if so), whether the smaller dimension should grow or the
734
     *                                        larger should shrink.
735
     *                                            0 = no resize
736
     *                                            1 = shrink to fit
737
     *                                            2 = extend to fit
738
     *
739
     * @return mixed[]
740
     */
741
    public static function checkMatrixOperands(mixed &$operand1, mixed &$operand2, int $resize = 1): array
69✔
742
    {
743
        //    Examine each of the two operands, and turn them into an array if they aren't one already
744
        //    Note that this function should only be called if one or both of the operand is already an array
745
        if (!is_array($operand1)) {
69✔
746
            if (is_array($operand2)) {
20✔
747
                [$matrixRows, $matrixColumns] = self::getMatrixDimensions($operand2);
20✔
748
                $operand1 = array_fill(0, $matrixRows, array_fill(0, $matrixColumns, $operand1));
20✔
749
                $resize = 0;
20✔
750
            } else {
751
                $operand1 = [$operand1];
×
752
                $operand2 = [$operand2];
×
753
            }
754
        } elseif (!is_array($operand2)) {
56✔
755
            [$matrixRows, $matrixColumns] = self::getMatrixDimensions($operand1);
18✔
756
            $operand2 = array_fill(0, $matrixRows, array_fill(0, $matrixColumns, $operand2));
18✔
757
            $resize = 0;
18✔
758
        }
759

760
        [$matrix1Rows, $matrix1Columns] = self::getMatrixDimensions($operand1);
69✔
761
        [$matrix2Rows, $matrix2Columns] = self::getMatrixDimensions($operand2);
69✔
762
        if ($resize === 3) {
69✔
763
            $resize = 2;
25✔
764
        } elseif (($matrix1Rows == $matrix2Columns) && ($matrix2Rows == $matrix1Columns)) {
47✔
765
            $resize = 1;
38✔
766
        }
767

768
        if ($resize == 2) {
69✔
769
            //    Given two matrices of (potentially) unequal size, convert the smaller in each dimension to match the larger
770
            self::resizeMatricesExtend($operand1, $operand2, $matrix1Rows, $matrix1Columns, $matrix2Rows, $matrix2Columns);
27✔
771
        } elseif ($resize == 1) {
46✔
772
            //    Given two matrices of (potentially) unequal size, convert the larger in each dimension to match the smaller
773
            /** @var mixed[][] $operand1 */
774
            /** @var mixed[][] $operand2 */
775
            self::resizeMatricesShrink($operand1, $operand2, $matrix1Rows, $matrix1Columns, $matrix2Rows, $matrix2Columns);
38✔
776
        }
777
        [$matrix1Rows, $matrix1Columns] = self::getMatrixDimensions($operand1);
69✔
778
        [$matrix2Rows, $matrix2Columns] = self::getMatrixDimensions($operand2);
69✔
779

780
        return [$matrix1Rows, $matrix1Columns, $matrix2Rows, $matrix2Columns];
69✔
781
    }
782

783
    /**
784
     * Read the dimensions of a matrix, and re-index it with straight numeric keys starting from row 0, column 0.
785
     *
786
     * @param mixed[] $matrix matrix operand
787
     *
788
     * @return int[] An array comprising the number of rows, and number of columns
789
     */
790
    public static function getMatrixDimensions(array &$matrix): array
111✔
791
    {
792
        $matrixRows = count($matrix);
111✔
793
        $matrixColumns = 0;
111✔
794
        foreach ($matrix as $rowKey => $rowValue) {
111✔
795
            if (!is_array($rowValue)) {
109✔
796
                $matrix[$rowKey] = [$rowValue];
4✔
797
                $matrixColumns = max(1, $matrixColumns);
4✔
798
            } else {
799
                $matrix[$rowKey] = array_values($rowValue);
105✔
800
                $matrixColumns = max(count($rowValue), $matrixColumns);
105✔
801
            }
802
        }
803
        $matrix = array_values($matrix);
111✔
804

805
        return [$matrixRows, $matrixColumns];
111✔
806
    }
807

808
    /**
809
     * Ensure that paired matrix operands are both matrices of the same size.
810
     *
811
     * @param mixed[][] $matrix1 First matrix operand
812
     * @param mixed[][] $matrix2 Second matrix operand
813
     * @param int $matrix1Rows Row size of first matrix operand
814
     * @param int $matrix1Columns Column size of first matrix operand
815
     * @param int $matrix2Rows Row size of second matrix operand
816
     * @param int $matrix2Columns Column size of second matrix operand
817
     */
818
    private static function resizeMatricesShrink(array &$matrix1, array &$matrix2, int $matrix1Rows, int $matrix1Columns, int $matrix2Rows, int $matrix2Columns): void
40✔
819
    {
820
        if (($matrix2Columns < $matrix1Columns) || ($matrix2Rows < $matrix1Rows)) {
40✔
821
            if ($matrix2Rows < $matrix1Rows) {
1✔
822
                for ($i = $matrix2Rows; $i < $matrix1Rows; ++$i) {
1✔
823
                    unset($matrix1[$i]);
1✔
824
                }
825
            }
826
            if ($matrix2Columns < $matrix1Columns) {
1✔
827
                for ($i = 0; $i < $matrix1Rows; ++$i) {
1✔
828
                    for ($j = $matrix2Columns; $j < $matrix1Columns; ++$j) {
1✔
829
                        unset($matrix1[$i][$j]);
1✔
830
                    }
831
                }
832
            }
833
        }
834

835
        if (($matrix1Columns < $matrix2Columns) || ($matrix1Rows < $matrix2Rows)) {
40✔
836
            if ($matrix1Rows < $matrix2Rows) {
1✔
837
                for ($i = $matrix1Rows; $i < $matrix2Rows; ++$i) {
1✔
838
                    unset($matrix2[$i]);
1✔
839
                }
840
            }
841
            if ($matrix1Columns < $matrix2Columns) {
1✔
842
                for ($i = 0; $i < $matrix2Rows; ++$i) {
1✔
843
                    for ($j = $matrix1Columns; $j < $matrix2Columns; ++$j) {
1✔
844
                        unset($matrix2[$i][$j]);
1✔
845
                    }
846
                }
847
            }
848
        }
849
    }
850

851
    /**
852
     * Ensure that paired matrix operands are both matrices of the same size.
853
     *
854
     * @param mixed[] $matrix1 First matrix operand
855
     * @param mixed[] $matrix2 Second matrix operand
856
     * @param int $matrix1Rows Row size of first matrix operand
857
     * @param int $matrix1Columns Column size of first matrix operand
858
     * @param int $matrix2Rows Row size of second matrix operand
859
     * @param int $matrix2Columns Column size of second matrix operand
860
     */
861
    private static function resizeMatricesExtend(array &$matrix1, array &$matrix2, int $matrix1Rows, int $matrix1Columns, int $matrix2Rows, int $matrix2Columns): void
29✔
862
    {
863
        if (($matrix2Columns < $matrix1Columns) || ($matrix2Rows < $matrix1Rows)) {
29✔
864
            if ($matrix2Columns < $matrix1Columns) {
17✔
865
                for ($i = 0; $i < $matrix2Rows; ++$i) {
15✔
866
                    /** @var mixed[][] $matrix2 */
867
                    $x = ($matrix2Columns === 1) ? $matrix2[$i][0] : null;
15✔
868
                    for ($j = $matrix2Columns; $j < $matrix1Columns; ++$j) {
15✔
869
                        $matrix2[$i][$j] = $x;
15✔
870
                    }
871
                }
872
            }
873
            if ($matrix2Rows < $matrix1Rows) {
17✔
874
                $x = ($matrix2Rows === 1) ? $matrix2[0] : array_fill(0, $matrix2Columns, null);
3✔
875
                for ($i = $matrix2Rows; $i < $matrix1Rows; ++$i) {
3✔
876
                    $matrix2[$i] = $x;
3✔
877
                }
878
            }
879
        }
880

881
        if (($matrix1Columns < $matrix2Columns) || ($matrix1Rows < $matrix2Rows)) {
29✔
882
            if ($matrix1Columns < $matrix2Columns) {
18✔
883
                for ($i = 0; $i < $matrix1Rows; ++$i) {
1✔
884
                    /** @var mixed[][] $matrix1 */
885
                    $x = ($matrix1Columns === 1) ? $matrix1[$i][0] : null;
1✔
886
                    for ($j = $matrix1Columns; $j < $matrix2Columns; ++$j) {
1✔
887
                        $matrix1[$i][$j] = $x;
1✔
888
                    }
889
                }
890
            }
891
            if ($matrix1Rows < $matrix2Rows) {
18✔
892
                $x = ($matrix1Rows === 1) ? $matrix1[0] : array_fill(0, $matrix2Columns, null);
18✔
893
                for ($i = $matrix1Rows; $i < $matrix2Rows; ++$i) {
18✔
894
                    $matrix1[$i] = $x;
18✔
895
                }
896
            }
897
        }
898
    }
899

900
    /**
901
     * Format details of an operand for display in the log (based on operand type).
902
     *
903
     * @param mixed $value First matrix operand
904
     */
905
    private function showValue(mixed $value): mixed
12,091✔
906
    {
907
        if ($this->debugLog->getWriteDebugLog()) {
12,091✔
908
            $testArray = Functions::flattenArray($value);
3✔
909
            if (count($testArray) == 1) {
3✔
910
                $value = array_pop($testArray);
3✔
911
            }
912

913
            if (is_array($value)) {
3✔
914
                $returnMatrix = [];
2✔
915
                $pad = $rpad = ', ';
2✔
916
                foreach ($value as $row) {
2✔
917
                    if (is_array($row)) {
2✔
918
                        $returnMatrix[] = implode($pad, array_map([$this, 'showValue'], $row));
2✔
919
                        $rpad = '; ';
2✔
920
                    } else {
921
                        $returnMatrix[] = $this->showValue($row);
×
922
                    }
923
                }
924

925
                return '{ ' . implode($rpad, $returnMatrix) . ' }';
2✔
926
            } elseif (is_string($value) && (trim($value, self::FORMULA_STRING_QUOTE) == $value)) {
3✔
927
                return self::FORMULA_STRING_QUOTE . $value . self::FORMULA_STRING_QUOTE;
2✔
928
            } elseif (is_bool($value)) {
3✔
929
                return ($value) ? self::$localeBoolean['TRUE'] : self::$localeBoolean['FALSE'];
×
930
            } elseif ($value === null) {
3✔
931
                return self::$localeBoolean['NULL'];
×
932
            }
933
        }
934

935
        return Functions::flattenSingleValue($value);
12,091✔
936
    }
937

938
    /**
939
     * Format type and details of an operand for display in the log (based on operand type).
940
     *
941
     * @param mixed $value First matrix operand
942
     */
943
    private function showTypeDetails(mixed $value): ?string
12,109✔
944
    {
945
        if ($this->debugLog->getWriteDebugLog()) {
12,109✔
946
            $testArray = Functions::flattenArray($value);
3✔
947
            if (count($testArray) == 1) {
3✔
948
                $value = array_pop($testArray);
3✔
949
            }
950

951
            if ($value === null) {
3✔
952
                return 'a NULL value';
×
953
            } elseif (is_float($value)) {
3✔
954
                $typeString = 'a floating point number';
3✔
955
            } elseif (is_int($value)) {
3✔
956
                $typeString = 'an integer number';
3✔
957
            } elseif (is_bool($value)) {
2✔
958
                $typeString = 'a boolean';
×
959
            } elseif (is_array($value)) {
2✔
960
                $typeString = 'a matrix';
2✔
961
            } else {
962
                /** @var string $value */
963
                if ($value == '') {
×
964
                    return 'an empty string';
×
965
                } elseif ($value[0] == '#') {
×
966
                    return 'a ' . $value . ' error';
×
967
                }
968
                $typeString = 'a string';
×
969
            }
970

971
            return $typeString . ' with a value of ' . StringHelper::convertToString($this->showValue($value));
3✔
972
        }
973

974
        return null;
12,106✔
975
    }
976

977
    private const MATRIX_REPLACE_FROM = [self::FORMULA_OPEN_MATRIX_BRACE, ';', self::FORMULA_CLOSE_MATRIX_BRACE];
978
    private const MATRIX_REPLACE_TO = ['MKMATRIX(MKMATRIX(', '),MKMATRIX(', '))'];
979

980
    /**
981
     * @return false|string False indicates an error
982
     */
983
    private function convertMatrixReferences(string $formula): false|string
12,492✔
984
    {
985
        //    Convert any Excel matrix references to the MKMATRIX() function
986
        if (str_contains($formula, self::FORMULA_OPEN_MATRIX_BRACE)) {
12,492✔
987
            //    If there is the possibility of braces within a quoted string, then we don't treat those as matrix indicators
988
            if (str_contains($formula, self::FORMULA_STRING_QUOTE)) {
825✔
989
                //    So instead we skip replacing in any quoted strings by only replacing in every other array element after we've exploded
990
                //        the formula
991
                $temp = explode(self::FORMULA_STRING_QUOTE, $formula);
252✔
992
                //    Open and Closed counts used for trapping mismatched braces in the formula
993
                $openCount = $closeCount = 0;
252✔
994
                $notWithinQuotes = false;
252✔
995
                foreach ($temp as &$value) {
252✔
996
                    //    Only count/replace in alternating array entries
997
                    $notWithinQuotes = $notWithinQuotes === false;
252✔
998
                    if ($notWithinQuotes === true) {
252✔
999
                        $openCount += substr_count($value, self::FORMULA_OPEN_MATRIX_BRACE);
252✔
1000
                        $closeCount += substr_count($value, self::FORMULA_CLOSE_MATRIX_BRACE);
252✔
1001
                        $value = str_replace(self::MATRIX_REPLACE_FROM, self::MATRIX_REPLACE_TO, $value);
252✔
1002
                    }
1003
                }
1004
                unset($value);
252✔
1005
                //    Then rebuild the formula string
1006
                $formula = implode(self::FORMULA_STRING_QUOTE, $temp);
252✔
1007
            } else {
1008
                //    If there's no quoted strings, then we do a simple count/replace
1009
                $openCount = substr_count($formula, self::FORMULA_OPEN_MATRIX_BRACE);
575✔
1010
                $closeCount = substr_count($formula, self::FORMULA_CLOSE_MATRIX_BRACE);
575✔
1011
                $formula = str_replace(self::MATRIX_REPLACE_FROM, self::MATRIX_REPLACE_TO, $formula);
575✔
1012
            }
1013
            //    Trap for mismatched braces and trigger an appropriate error
1014
            if ($openCount < $closeCount) {
825✔
1015
                if ($openCount > 0) {
×
1016
                    return $this->raiseFormulaError("Formula Error: Mismatched matrix braces '}'");
×
1017
                }
1018

1019
                return $this->raiseFormulaError("Formula Error: Unexpected '}' encountered");
×
1020
            } elseif ($openCount > $closeCount) {
825✔
1021
                if ($closeCount > 0) {
1✔
1022
                    return $this->raiseFormulaError("Formula Error: Mismatched matrix braces '{'");
×
1023
                }
1024

1025
                return $this->raiseFormulaError("Formula Error: Unexpected '{' encountered");
1✔
1026
            }
1027
        }
1028

1029
        return $formula;
12,491✔
1030
    }
1031

1032
    /**
1033
     *    Comparison (Boolean) Operators.
1034
     *    These operators work on two values, but always return a boolean result.
1035
     */
1036
    private const COMPARISON_OPERATORS = ['>' => true, '<' => true, '=' => true, '>=' => true, '<=' => true, '<>' => true];
1037

1038
    /**
1039
     *    Operator Precedence.
1040
     *    This list includes all valid operators, whether binary (including boolean) or unary (such as %).
1041
     *    Array key is the operator, the value is its precedence.
1042
     */
1043
    private const OPERATOR_PRECEDENCE = [
1044
        ':' => 9, //    Range
1045
        '∩' => 8, //    Intersect
1046
        '∪' => 7, //    Union
1047
        '~' => 6, //    Negation
1048
        '%' => 5, //    Percentage
1049
        '^' => 4, //    Exponentiation
1050
        '*' => 3, '/' => 3, //    Multiplication and Division
1051
        '+' => 2, '-' => 2, //    Addition and Subtraction
1052
        '&' => 1, //    Concatenation
1053
        '>' => 0, '<' => 0, '=' => 0, '>=' => 0, '<=' => 0, '<>' => 0, //    Comparison
1054
    ];
1055

1056
    /** @param string[] $matches */
1057
    private static function unionForComma(array $matches): string
4✔
1058
    {
1059
        return $matches[1] . str_replace(',', '∪', $matches[2]);
4✔
1060
    }
1061

1062
    private const UNIONABLE_COMMAS = '/((?:[,(]|^)\s*)' // comma or open paren or start of string, followed by optional whitespace
1063
        . '([(]' // open paren
1064
        . self::CALCULATION_REGEXP_CELLREF // cell address
1065
        . '(?::' . self::CALCULATION_REGEXP_CELLREF . ')?' // optional range address, non-capturing
1066
        . '(?:\s*,\s*' // optioonal whitespace, comma, optional whitespace, non-capturing
1067
        . self::CALCULATION_REGEXP_CELLREF // cell address
1068
        . '(?::' . self::CALCULATION_REGEXP_CELLREF . ')?' // optional range address, non-capturing
1069
        . ')+' // one or more occurrences
1070
        . '\s*[)])/i'; // optional whitespace, end paren
1071

1072
    /**
1073
     * @return array<int, mixed>|false
1074
     */
1075
    private function internalParseFormula(string $formula, ?Cell $cell = null): bool|array
12,492✔
1076
    {
1077
        if (($formula = $this->convertMatrixReferences(trim($formula))) === false) {
12,492✔
1078
            return false;
×
1079
        }
1080

1081
        $formula = Preg::replaceCallback(self::UNIONABLE_COMMAS, self::unionForComma(...), $formula); // @phpstan-ignore-line
12,491✔
1082
        $phpSpreadsheetFunctions = &self::getFunctionsAddress();
12,491✔
1083

1084
        //    If we're using cell caching, then $pCell may well be flushed back to the cache (which detaches the parent worksheet),
1085
        //        so we store the parent worksheet so that we can re-attach it when necessary
1086
        $pCellParent = ($cell !== null) ? $cell->getWorksheet() : null;
12,491✔
1087

1088
        $regexpMatchString = '/^((?<string>' . self::CALCULATION_REGEXP_STRING
12,491✔
1089
                                . ')|(?<function>' . self::CALCULATION_REGEXP_FUNCTION
12,491✔
1090
                                . ')|(?<cellRef>' . self::CALCULATION_REGEXP_CELLREF
12,491✔
1091
                                . ')|(?<colRange>' . self::CALCULATION_REGEXP_COLUMN_RANGE
12,491✔
1092
                                . ')|(?<rowRange>' . self::CALCULATION_REGEXP_ROW_RANGE
12,491✔
1093
                                . ')|(?<number>' . self::CALCULATION_REGEXP_NUMBER
12,491✔
1094
                                . ')|(?<openBrace>' . self::CALCULATION_REGEXP_OPENBRACE
12,491✔
1095
                                . ')|(?<structuredReference>' . self::CALCULATION_REGEXP_STRUCTURED_REFERENCE
12,491✔
1096
                                . ')|(?<definedName>' . self::CALCULATION_REGEXP_DEFINEDNAME
12,491✔
1097
                                . ')|(?<error>' . self::CALCULATION_REGEXP_ERROR
12,491✔
1098
                                . '))/sui';
12,491✔
1099

1100
        //    Start with initialisation
1101
        $index = 0;
12,491✔
1102
        $stack = new Stack($this->branchPruner);
12,491✔
1103
        $output = [];
12,491✔
1104
        $expectingOperator = false; //    We use this test in syntax-checking the expression to determine when a
12,491✔
1105
        //        - is a negation or + is a positive operator rather than an operation
1106
        $expectingOperand = false; //    We use this test in syntax-checking the expression to determine whether an operand
12,491✔
1107
        //        should be null in a function call
1108

1109
        //    The guts of the lexical parser
1110
        //    Loop through the formula extracting each operator and operand in turn
1111
        while (true) {
12,491✔
1112
            // Branch pruning: we adapt the output item to the context (it will
1113
            // be used to limit its computation)
1114
            $this->branchPruner->initialiseForLoop();
12,491✔
1115

1116
            $opCharacter = $formula[$index]; //    Get the first character of the value at the current index position
12,491✔
1117
            if ($opCharacter === "\xe2") { // intersection or union
12,491✔
1118
                $opCharacter .= $formula[++$index];
7✔
1119
                $opCharacter .= $formula[++$index];
7✔
1120
            }
1121

1122
            // Check for two-character operators (e.g. >=, <=, <>)
1123
            if ((isset(self::COMPARISON_OPERATORS[$opCharacter])) && (strlen($formula) > $index) && isset($formula[$index + 1], self::COMPARISON_OPERATORS[$formula[$index + 1]])) {
12,491✔
1124
                $opCharacter .= $formula[++$index];
85✔
1125
            }
1126
            //    Find out if we're currently at the beginning of a number, variable, cell/row/column reference,
1127
            //         function, defined name, structured reference, parenthesis, error or operand
1128
            $isOperandOrFunction = (bool) preg_match($regexpMatchString, substr($formula, $index), $match);
12,491✔
1129

1130
            $expectingOperatorCopy = $expectingOperator;
12,491✔
1131
            if ($opCharacter === '-' && !$expectingOperator) {                //    Is it a negation instead of a minus?
12,491✔
1132
                //    Put a negation on the stack
1133
                $stack->push('Unary Operator', '~');
1,174✔
1134
                ++$index; //        and drop the negation symbol
1,174✔
1135
            } elseif ($opCharacter === '%' && $expectingOperator) {
12,491✔
1136
                //    Put a percentage on the stack
1137
                $stack->push('Unary Operator', '%');
11✔
1138
                ++$index;
11✔
1139
            } elseif ($opCharacter === '+' && !$expectingOperator) {            //    Positive (unary plus rather than binary operator plus) can be discarded?
12,491✔
1140
                ++$index; //    Drop the redundant plus symbol
7✔
1141
            } elseif ((($opCharacter === '~') /*|| ($opCharacter === '∩') || ($opCharacter === '∪')*/) && (!$isOperandOrFunction)) {
12,491✔
1142
                //    We have to explicitly deny a tilde, union or intersect because they are legal
1143
                return $this->raiseFormulaError("Formula Error: Illegal character '~'"); //        on the stack but not in the input expression
×
1144
            } elseif ((isset(self::CALCULATION_OPERATORS[$opCharacter]) || $isOperandOrFunction) && $expectingOperator) {    //    Are we putting an operator on the stack?
12,491✔
1145
                while (self::swapOperands($stack, $opCharacter)) {
1,897✔
1146
                    $output[] = $stack->pop(); //    Swap operands and higher precedence operators from the stack to the output
102✔
1147
                }
1148

1149
                //    Finally put our current operator onto the stack
1150
                $stack->push('Binary Operator', $opCharacter);
1,897✔
1151

1152
                ++$index;
1,897✔
1153
                $expectingOperator = false;
1,897✔
1154
            } elseif ($opCharacter === ')' && $expectingOperator) { //    Are we expecting to close a parenthesis?
12,491✔
1155
                $expectingOperand = false;
12,105✔
1156
                while (($o2 = $stack->pop()) && $o2['value'] !== '(') { //    Pop off the stack back to the last (
12,105✔
1157
                    $output[] = $o2;
1,433✔
1158
                }
1159
                $d = $stack->last(2);
12,105✔
1160

1161
                // Branch pruning we decrease the depth whether is it a function
1162
                // call or a parenthesis
1163
                $this->branchPruner->decrementDepth();
12,105✔
1164

1165
                if (is_array($d) && preg_match('/^' . self::CALCULATION_REGEXP_FUNCTION . '$/miu', StringHelper::convertToString($d['value']), $matches)) {
12,105✔
1166
                    //    Did this parenthesis just close a function?
1167
                    try {
1168
                        $this->branchPruner->closingBrace($d['value']);
12,099✔
1169
                    } catch (Exception $e) {
4✔
1170
                        return $this->raiseFormulaError($e->getMessage(), $e->getCode(), $e);
4✔
1171
                    }
1172

1173
                    $functionName = $matches[1]; //    Get the function name
12,099✔
1174
                    $d = $stack->pop();
12,099✔
1175
                    $argumentCount = $d['value'] ?? 0; //    See how many arguments there were (argument count is the next value stored on the stack)
12,099✔
1176
                    $output[] = $d; //    Dump the argument count on the output
12,099✔
1177
                    $output[] = $stack->pop(); //    Pop the function and push onto the output
12,099✔
1178
                    if (isset(self::$controlFunctions[$functionName])) {
12,099✔
1179
                        $expectedArgumentCount = self::$controlFunctions[$functionName]['argumentCount'];
845✔
1180
                    } elseif (isset($phpSpreadsheetFunctions[$functionName])) {
12,096✔
1181
                        $expectedArgumentCount = $phpSpreadsheetFunctions[$functionName]['argumentCount'];
12,096✔
1182
                    } else {    // did we somehow push a non-function on the stack? this should never happen
1183
                        return $this->raiseFormulaError('Formula Error: Internal error, non-function on stack');
×
1184
                    }
1185
                    //    Check the argument count
1186
                    $argumentCountError = false;
12,099✔
1187
                    $expectedArgumentCountString = null;
12,099✔
1188
                    if (is_numeric($expectedArgumentCount)) {
12,099✔
1189
                        if ($expectedArgumentCount < 0) {
6,191✔
1190
                            if ($argumentCount > abs($expectedArgumentCount + 0)) {
40✔
1191
                                $argumentCountError = true;
×
1192
                                $expectedArgumentCountString = 'no more than ' . abs($expectedArgumentCount + 0);
×
1193
                            }
1194
                        } else {
1195
                            if ($argumentCount != $expectedArgumentCount) {
6,154✔
1196
                                $argumentCountError = true;
146✔
1197
                                $expectedArgumentCountString = $expectedArgumentCount;
146✔
1198
                            }
1199
                        }
1200
                    } elseif (is_string($expectedArgumentCount) && $expectedArgumentCount !== '*') {
6,684✔
1201
                        if (!Preg::isMatch('/(\d*)([-+,])(\d*)/', $expectedArgumentCount, $argMatch)) {
6,195✔
1202
                            $argMatch = ['', '', '', ''];
1✔
1203
                        }
1204
                        switch ($argMatch[2]) {
6,195✔
1205
                            case '+':
6,195✔
1206
                                if ($argumentCount < $argMatch[1]) {
1,194✔
1207
                                    $argumentCountError = true;
27✔
1208
                                    $expectedArgumentCountString = $argMatch[1] . ' or more ';
27✔
1209
                                }
1210

1211
                                break;
1,194✔
1212
                            case '-':
5,169✔
1213
                                if (($argumentCount < $argMatch[1]) || ($argumentCount > $argMatch[3])) {
930✔
1214
                                    $argumentCountError = true;
15✔
1215
                                    $expectedArgumentCountString = 'between ' . $argMatch[1] . ' and ' . $argMatch[3];
15✔
1216
                                }
1217

1218
                                break;
930✔
1219
                            case ',':
4,281✔
1220
                                if (($argumentCount != $argMatch[1]) && ($argumentCount != $argMatch[3])) {
4,281✔
1221
                                    $argumentCountError = true;
39✔
1222
                                    $expectedArgumentCountString = 'either ' . $argMatch[1] . ' or ' . $argMatch[3];
39✔
1223
                                }
1224

1225
                                break;
4,281✔
1226
                        }
1227
                    }
1228
                    if ($argumentCountError) {
12,099✔
1229
                        /** @var int $argumentCount */
1230
                        return $this->raiseFormulaError("Formula Error: Wrong number of arguments for $functionName() function: $argumentCount given, " . $expectedArgumentCountString . ' expected');
227✔
1231
                    }
1232
                }
1233
                ++$index;
11,881✔
1234
            } elseif ($opCharacter === ',') { // Is this the separator for function arguments?
12,491✔
1235
                try {
1236
                    $this->branchPruner->argumentSeparator();
8,179✔
1237
                } catch (Exception $e) {
×
1238
                    return $this->raiseFormulaError($e->getMessage(), $e->getCode(), $e);
×
1239
                }
1240

1241
                while (($o2 = $stack->pop()) && $o2['value'] !== '(') {        //    Pop off the stack back to the last (
8,179✔
1242
                    $output[] = $o2; // pop the argument expression stuff and push onto the output
1,512✔
1243
                }
1244
                //    If we've a comma when we're expecting an operand, then what we actually have is a null operand;
1245
                //        so push a null onto the stack
1246
                if (($expectingOperand) || (!$expectingOperator)) {
8,179✔
1247
                    $output[] = $stack->getStackItem('Empty Argument', null, 'NULL');
120✔
1248
                }
1249
                // make sure there was a function
1250
                $d = $stack->last(2);
8,179✔
1251
                /** @var string */
1252
                $temp = $d['value'] ?? '';
8,179✔
1253
                if (!preg_match('/^' . self::CALCULATION_REGEXP_FUNCTION . '$/miu', $temp, $matches)) {
8,179✔
1254
                    // Can we inject a dummy function at this point so that the braces at least have some context
1255
                    //     because at least the braces are paired up (at this stage in the formula)
1256
                    // MS Excel allows this if the content is cell references; but doesn't allow actual values,
1257
                    //    but at this point, we can't differentiate (so allow both)
1258
                    //return $this->raiseFormulaError('Formula Error: Unexpected ,');
1259

1260
                    $stack->push('Binary Operator', '∪');
1✔
1261

1262
                    ++$index;
1✔
1263
                    $expectingOperator = false;
1✔
1264

1265
                    continue;
1✔
1266
                }
1267

1268
                /** @var array<string, int> $d */
1269
                $d = $stack->pop();
8,178✔
1270
                ++$d['value']; // increment the argument count
8,178✔
1271

1272
                $stack->pushStackItem($d);
8,178✔
1273
                $stack->push('Brace', '('); // put the ( back on, we'll need to pop back to it again
8,178✔
1274

1275
                $expectingOperator = false;
8,178✔
1276
                $expectingOperand = true;
8,178✔
1277
                ++$index;
8,178✔
1278
            } elseif ($opCharacter === '(' && !$expectingOperator) {
12,491✔
1279
                // Branch pruning: we go deeper
1280
                $this->branchPruner->incrementDepth();
41✔
1281
                $stack->push('Brace', '(', null);
41✔
1282
                ++$index;
41✔
1283
            } elseif ($isOperandOrFunction && !$expectingOperatorCopy) {
12,491✔
1284
                // do we now have a function/variable/number?
1285
                $expectingOperator = true;
12,487✔
1286
                $expectingOperand = false;
12,487✔
1287
                $val = $match[1] ?? ''; //* @phpstan-ignore-line
12,487✔
1288
                $length = strlen($val);
12,487✔
1289

1290
                if (preg_match('/^' . self::CALCULATION_REGEXP_FUNCTION . '$/miu', $val, $matches)) {
12,487✔
1291
                    // $val is known to be valid unicode from statement above, so Preg::replace is okay even with u modifier
1292
                    $val = Preg::replace('/\s/u', '', $val);
12,106✔
1293
                    if (isset($phpSpreadsheetFunctions[strtoupper($matches[1])]) || isset(self::$controlFunctions[strtoupper($matches[1])])) {    // it's a function
12,106✔
1294
                        $valToUpper = strtoupper($val);
12,104✔
1295
                    } else {
1296
                        $valToUpper = 'NAME.ERROR(';
6✔
1297
                    }
1298
                    // here $matches[1] will contain values like "IF"
1299
                    // and $val "IF("
1300

1301
                    $this->branchPruner->functionCall($valToUpper);
12,106✔
1302

1303
                    $stack->push('Function', $valToUpper);
12,106✔
1304
                    // tests if the function is closed right after opening
1305
                    $ax = preg_match('/^\s*\)/u', substr($formula, $index + $length));
12,106✔
1306
                    if ($ax) {
12,106✔
1307
                        $stack->push('Operand Count for Function ' . $valToUpper . ')', 0);
328✔
1308
                        $expectingOperator = true;
328✔
1309
                    } else {
1310
                        $stack->push('Operand Count for Function ' . $valToUpper . ')', 1);
11,924✔
1311
                        $expectingOperator = false;
11,924✔
1312
                    }
1313
                    $stack->push('Brace', '(');
12,106✔
1314
                } elseif (preg_match('/^' . self::CALCULATION_REGEXP_CELLREF . '$/miu', $val, $matches)) {
12,281✔
1315
                    //    Watch for this case-change when modifying to allow cell references in different worksheets...
1316
                    //    Should only be applied to the actual cell column, not the worksheet name
1317
                    //    If the last entry on the stack was a : operator, then we have a cell range reference
1318
                    $testPrevOp = $stack->last(1);
7,323✔
1319
                    if ($testPrevOp !== null && $testPrevOp['value'] === ':') {
7,323✔
1320
                        //    If we have a worksheet reference, then we're playing with a 3D reference
1321
                        if ($matches[2] === '') {
1,307✔
1322
                            //    Otherwise, we 'inherit' the worksheet reference from the start cell reference
1323
                            //    The start of the cell range reference should be the last entry in $output
1324
                            $rangeStartCellRef = $output[count($output) - 1]['value'] ?? '';
1,303✔
1325
                            if ($rangeStartCellRef === ':') {
1,303✔
1326
                                // Do we have chained range operators?
1327
                                $rangeStartCellRef = $output[count($output) - 2]['value'] ?? '';
5✔
1328
                            }
1329
                            /** @var string $rangeStartCellRef */
1330
                            preg_match('/^' . self::CALCULATION_REGEXP_CELLREF . '$/miu', $rangeStartCellRef, $rangeStartMatches);
1,303✔
1331
                            if (array_key_exists(2, $rangeStartMatches)) {
1,303✔
1332
                                if ($rangeStartMatches[2] > '') {
1,298✔
1333
                                    $val = $rangeStartMatches[2] . '!' . $val;
1,281✔
1334
                                }
1335
                            } else {
1336
                                $val = ExcelError::REF();
5✔
1337
                            }
1338
                        } else {
1339
                            $rangeStartCellRef = $output[count($output) - 1]['value'] ?? '';
4✔
1340
                            if ($rangeStartCellRef === ':') {
4✔
1341
                                // Do we have chained range operators?
1342
                                $rangeStartCellRef = $output[count($output) - 2]['value'] ?? '';
×
1343
                            }
1344
                            /** @var string $rangeStartCellRef */
1345
                            preg_match('/^' . self::CALCULATION_REGEXP_CELLREF . '$/miu', $rangeStartCellRef, $rangeStartMatches);
4✔
1346
                            if (isset($rangeStartMatches[2]) && $rangeStartMatches[2] !== $matches[2]) {
4✔
1347
                                return $this->raiseFormulaError('3D Range references are not yet supported');
2✔
1348
                            }
1349
                        }
1350
                    } elseif (!str_contains($val, '!') && $pCellParent !== null) {
7,318✔
1351
                        $worksheet = $pCellParent->getTitle();
7,101✔
1352
                        $val = "'{$worksheet}'!{$val}";
7,101✔
1353
                    }
1354
                    // unescape any apostrophes or double quotes in worksheet name
1355
                    $val = str_replace(["''", '""'], ["'", '"'], $val);
7,323✔
1356
                    $outputItem = $stack->getStackItem('Cell Reference', $val, $val);
7,323✔
1357

1358
                    $output[] = $outputItem;
7,323✔
1359
                } elseif (preg_match('/^' . self::CALCULATION_REGEXP_STRUCTURED_REFERENCE . '$/miu', $val, $matches)) {
6,478✔
1360
                    try {
1361
                        $structuredReference = Operands\StructuredReference::fromParser($formula, $index, $matches);
76✔
1362
                    } catch (Exception $e) {
×
1363
                        return $this->raiseFormulaError($e->getMessage(), $e->getCode(), $e);
×
1364
                    }
1365

1366
                    $val = $structuredReference->value();
76✔
1367
                    $length = strlen($val);
76✔
1368
                    $outputItem = $stack->getStackItem(Operands\StructuredReference::NAME, $structuredReference, null);
76✔
1369

1370
                    $output[] = $outputItem;
76✔
1371
                    $expectingOperator = true;
76✔
1372
                } else {
1373
                    // it's a variable, constant, string, number or boolean
1374
                    $localeConstant = false;
6,411✔
1375
                    $stackItemType = 'Value';
6,411✔
1376
                    $stackItemReference = null;
6,411✔
1377

1378
                    //    If the last entry on the stack was a : operator, then we may have a row or column range reference
1379
                    $testPrevOp = $stack->last(1);
6,411✔
1380
                    if ($testPrevOp !== null && $testPrevOp['value'] === ':') {
6,411✔
1381
                        $stackItemType = 'Cell Reference';
38✔
1382

1383
                        if (
1384
                            !is_numeric($val)
38✔
1385
                            && ((ctype_alpha($val) === false || strlen($val) > 3))
38✔
1386
                            && (preg_match('/^' . self::CALCULATION_REGEXP_DEFINEDNAME . '$/mui', $val) !== false)
38✔
1387
                            && ($this->spreadsheet === null || $this->spreadsheet->getNamedRange($val) !== null)
38✔
1388
                        ) {
1389
                            $namedRange = ($this->spreadsheet === null) ? null : $this->spreadsheet->getNamedRange($val);
10✔
1390
                            if ($namedRange !== null) {
10✔
1391
                                $stackItemType = 'Defined Name';
4✔
1392
                                $address = str_replace('$', '', $namedRange->getValue());
4✔
1393
                                $stackItemReference = $val;
4✔
1394
                                if (str_contains($address, ':')) {
4✔
1395
                                    // We'll need to manipulate the stack for an actual named range rather than a named cell
1396
                                    $fromTo = explode(':', $address);
3✔
1397
                                    $to = array_pop($fromTo);
3✔
1398
                                    foreach ($fromTo as $from) {
3✔
1399
                                        $output[] = $stack->getStackItem($stackItemType, $from, $stackItemReference);
3✔
1400
                                        $output[] = $stack->getStackItem('Binary Operator', ':');
3✔
1401
                                    }
1402
                                    $address = $to;
3✔
1403
                                }
1404
                                $val = $address;
4✔
1405
                            }
1406
                        } elseif ($val === ExcelError::REF()) {
34✔
1407
                            $stackItemReference = $val;
3✔
1408
                        } else {
1409
                            /** @var non-empty-string $startRowColRef */
1410
                            $startRowColRef = $output[count($output) - 1]['value'] ?? '';
31✔
1411
                            [$rangeWS1, $startRowColRef] = Worksheet::extractSheetTitle($startRowColRef, true);
31✔
1412
                            $rangeSheetRef = $rangeWS1;
31✔
1413
                            if ($rangeWS1 !== '') {
31✔
1414
                                $rangeWS1 .= '!';
19✔
1415
                            }
1416
                            if (str_starts_with($rangeSheetRef, "'")) {
31✔
1417
                                $rangeSheetRef = Worksheet::unApostrophizeTitle($rangeSheetRef);
18✔
1418
                            }
1419
                            [$rangeWS2, $val] = Worksheet::extractSheetTitle($val, true);
31✔
1420
                            if ($rangeWS2 !== '') {
31✔
1421
                                $rangeWS2 .= '!';
×
1422
                            } else {
1423
                                $rangeWS2 = $rangeWS1;
31✔
1424
                            }
1425

1426
                            $refSheet = $pCellParent;
31✔
1427
                            if ($pCellParent !== null && $rangeSheetRef !== '' && $rangeSheetRef !== $pCellParent->getTitle()) {
31✔
1428
                                $refSheet = $pCellParent->getParentOrThrow()->getSheetByName($rangeSheetRef);
4✔
1429
                            }
1430

1431
                            if (ctype_digit($val) && $val <= 1048576) {
31✔
1432
                                //    Row range
1433
                                $stackItemType = 'Row Reference';
10✔
1434
                                $valx = $val;
10✔
1435
                                $endRowColRef = ($refSheet !== null) ? $refSheet->getHighestDataColumn($valx) : AddressRange::MAX_COLUMN; //    Max 16,384 columns for Excel2007
10✔
1436
                                $val = "{$rangeWS2}{$endRowColRef}{$val}";
10✔
1437
                            } elseif (ctype_alpha($val) && strlen($val) <= 3) {
21✔
1438
                                //    Column range
1439
                                $stackItemType = 'Column Reference';
15✔
1440
                                $endRowColRef = ($refSheet !== null) ? $refSheet->getHighestDataRow($val) : AddressRange::MAX_ROW; //    Max 1,048,576 rows for Excel2007
15✔
1441
                                $val = "{$rangeWS2}{$val}{$endRowColRef}";
15✔
1442
                            }
1443
                            $stackItemReference = $val;
31✔
1444
                        }
1445
                    } elseif ($opCharacter === self::FORMULA_STRING_QUOTE) {
6,406✔
1446
                        //    UnEscape any quotes within the string
1447
                        $val = self::wrapResult(str_replace('""', self::FORMULA_STRING_QUOTE, StringHelper::convertToString(self::unwrapResult($val))));
2,864✔
1448
                    } elseif (isset(self::EXCEL_CONSTANTS[trim(strtoupper($val))])) {
4,759✔
1449
                        $stackItemType = 'Constant';
566✔
1450
                        $excelConstant = trim(strtoupper($val));
566✔
1451
                        $val = self::EXCEL_CONSTANTS[$excelConstant];
566✔
1452
                        $stackItemReference = $excelConstant;
566✔
1453
                    } elseif (($localeConstant = array_search(trim(strtoupper($val)), self::$localeBoolean)) !== false) {
4,467✔
1454
                        $stackItemType = 'Constant';
39✔
1455
                        $val = self::EXCEL_CONSTANTS[$localeConstant];
39✔
1456
                        $stackItemReference = $localeConstant;
39✔
1457
                    } elseif (
1458
                        preg_match('/^' . self::CALCULATION_REGEXP_ROW_RANGE . '/miu', substr($formula, $index), $rowRangeReference)
4,448✔
1459
                    ) {
1460
                        $val = $rowRangeReference[1];
10✔
1461
                        $length = strlen($rowRangeReference[1]);
10✔
1462
                        $stackItemType = 'Row Reference';
10✔
1463
                        // unescape any apostrophes or double quotes in worksheet name
1464
                        $val = str_replace(["''", '""'], ["'", '"'], $val);
10✔
1465
                        $column = 'A';
10✔
1466
                        if (($testPrevOp !== null && $testPrevOp['value'] === ':') && $pCellParent !== null) {
10✔
1467
                            $column = $pCellParent->getHighestDataColumn($val);
×
1468
                        }
1469
                        $val = "{$rowRangeReference[2]}{$column}{$rowRangeReference[7]}";
10✔
1470
                        $stackItemReference = $val;
10✔
1471
                    } elseif (
1472
                        preg_match('/^' . self::CALCULATION_REGEXP_COLUMN_RANGE . '/miu', substr($formula, $index), $columnRangeReference)
4,441✔
1473
                    ) {
1474
                        $val = $columnRangeReference[1];
15✔
1475
                        $length = strlen($val);
15✔
1476
                        $stackItemType = 'Column Reference';
15✔
1477
                        // unescape any apostrophes or double quotes in worksheet name
1478
                        $val = str_replace(["''", '""'], ["'", '"'], $val);
15✔
1479
                        $row = '1';
15✔
1480
                        if (($testPrevOp !== null && $testPrevOp['value'] === ':') && $pCellParent !== null) {
15✔
1481
                            $row = $pCellParent->getHighestDataRow($val);
×
1482
                        }
1483
                        $val = "{$val}{$row}";
15✔
1484
                        $stackItemReference = $val;
15✔
1485
                    } elseif (preg_match('/^' . self::CALCULATION_REGEXP_DEFINEDNAME . '.*/miu', $val, $match)) {
4,426✔
1486
                        $stackItemType = 'Defined Name';
166✔
1487
                        $stackItemReference = $val;
166✔
1488
                    } elseif (is_numeric($val)) {
4,291✔
1489
                        if ((str_contains((string) $val, '.')) || (stripos((string) $val, 'e') !== false) || ($val > PHP_INT_MAX) || ($val < -PHP_INT_MAX)) {
4,285✔
1490
                            $val = (float) $val;
1,693✔
1491
                        } else {
1492
                            $val = (int) $val;
3,521✔
1493
                        }
1494
                    }
1495

1496
                    $details = $stack->getStackItem($stackItemType, $val, $stackItemReference);
6,411✔
1497
                    if ($localeConstant) {
6,411✔
1498
                        $details['localeValue'] = $localeConstant;
39✔
1499
                    }
1500
                    $output[] = $details;
6,411✔
1501
                }
1502
                $index += $length;
12,487✔
1503
            } elseif ($opCharacter === '$') { // absolute row or column range
95✔
1504
                ++$index;
6✔
1505
            } elseif ($opCharacter === ')') { // miscellaneous error checking
89✔
1506
                if ($expectingOperand) {
83✔
1507
                    $output[] = $stack->getStackItem('Empty Argument', null, 'NULL');
83✔
1508
                    $expectingOperand = false;
83✔
1509
                    $expectingOperator = true;
83✔
1510
                } else {
1511
                    return $this->raiseFormulaError("Formula Error: Unexpected ')'");
×
1512
                }
1513
            } elseif (isset(self::CALCULATION_OPERATORS[$opCharacter]) && !$expectingOperator) {
6✔
1514
                return $this->raiseFormulaError("Formula Error: Unexpected operator '$opCharacter'");
×
1515
            } else {    // I don't even want to know what you did to get here
1516
                return $this->raiseFormulaError('Formula Error: An unexpected error occurred');
6✔
1517
            }
1518
            //    Test for end of formula string
1519
            if ($index == strlen($formula)) {
12,487✔
1520
                //    Did we end with an operator?.
1521
                //    Only valid for the % unary operator
1522
                if ((isset(self::CALCULATION_OPERATORS[$opCharacter])) && ($opCharacter != '%')) {
12,259✔
1523
                    return $this->raiseFormulaError("Formula Error: Operator '$opCharacter' has no operands");
1✔
1524
                }
1525

1526
                break;
12,258✔
1527
            }
1528
            //    Ignore white space
1529
            while (($formula[$index] === "\n") || ($formula[$index] === "\r")) {
12,454✔
1530
                ++$index;
×
1531
            }
1532

1533
            if ($formula[$index] === ' ') {
12,454✔
1534
                while ($formula[$index] === ' ') {
2,129✔
1535
                    ++$index;
2,129✔
1536
                }
1537

1538
                //    If we're expecting an operator, but only have a space between the previous and next operands (and both are
1539
                //        Cell References, Defined Names or Structured References) then we have an INTERSECTION operator
1540
                $countOutputMinus1 = count($output) - 1;
2,129✔
1541
                if (
1542
                    ($expectingOperator)
2,129✔
1543
                    && array_key_exists($countOutputMinus1, $output)
2,129✔
1544
                    && is_array($output[$countOutputMinus1])
2,129✔
1545
                    && array_key_exists('type', $output[$countOutputMinus1])
2,129✔
1546
                    && (
1547
                        (preg_match('/^' . self::CALCULATION_REGEXP_CELLREF . '.*/miu', substr($formula, $index), $match))
2,129✔
1548
                            && ($output[$countOutputMinus1]['type'] === 'Cell Reference')
2,129✔
1549
                        || (preg_match('/^' . self::CALCULATION_REGEXP_DEFINEDNAME . '.*/miu', substr($formula, $index), $match))
2,129✔
1550
                            && ($output[$countOutputMinus1]['type'] === 'Defined Name' || $output[$countOutputMinus1]['type'] === 'Value')
2,129✔
1551
                        || (preg_match('/^' . self::CALCULATION_REGEXP_STRUCTURED_REFERENCE . '.*/miu', substr($formula, $index), $match))
2,129✔
1552
                            && ($output[$countOutputMinus1]['type'] === Operands\StructuredReference::NAME || $output[$countOutputMinus1]['type'] === 'Value')
2,129✔
1553
                    )
1554
                ) {
1555
                    while (self::swapOperands($stack, $opCharacter)) {
20✔
1556
                        $output[] = $stack->pop(); //    Swap operands and higher precedence operators from the stack to the output
13✔
1557
                    }
1558
                    $stack->push('Binary Operator', '∩'); //    Put an Intersect Operator on the stack
20✔
1559
                    $expectingOperator = false;
20✔
1560
                }
1561
            }
1562
        }
1563

1564
        while (($op = $stack->pop()) !== null) {
12,258✔
1565
            // pop everything off the stack and push onto output
1566
            if ($op['value'] == '(') {
758✔
1567
                return $this->raiseFormulaError("Formula Error: Expecting ')'"); // if there are any opening braces on the stack, then braces were unbalanced
5✔
1568
            }
1569
            $output[] = $op;
755✔
1570
        }
1571

1572
        return $output;
12,255✔
1573
    }
1574

1575
    /** @param mixed[] $operandData */
1576
    private static function dataTestReference(array &$operandData): mixed
1,781✔
1577
    {
1578
        $operand = $operandData['value'];
1,781✔
1579
        if (($operandData['reference'] === null) && (is_array($operand))) {
1,781✔
1580
            $rKeys = array_keys($operand);
46✔
1581
            $rowKey = array_shift($rKeys);
46✔
1582
            if (is_array($operand[$rowKey]) === false) {
46✔
1583
                $operandData['value'] = $operand[$rowKey];
6✔
1584

1585
                return $operand[$rowKey];
6✔
1586
            }
1587

1588
            $cKeys = array_keys(array_keys($operand[$rowKey]));
44✔
1589
            $colKey = array_shift($cKeys);
44✔
1590
            if (ctype_upper("$colKey")) {
44✔
1591
                $operandData['reference'] = $colKey . $rowKey;
×
1592
            }
1593
        }
1594

1595
        return $operand;
1,781✔
1596
    }
1597

1598
    private static int $matchIndex8 = 8;
1599

1600
    private static int $matchIndex9 = 9;
1601

1602
    private static int $matchIndex10 = 10;
1603

1604
    /**
1605
     * @param array<mixed>|false $tokens
1606
     *
1607
     * @return array<int, mixed>|false|string
1608
     */
1609
    private function processTokenStack(false|array $tokens, ?string $cellID = null, ?Cell $cell = null)
12,122✔
1610
    {
1611
        if ($tokens === false) {
12,122✔
1612
            return false;
2✔
1613
        }
1614
        $phpSpreadsheetFunctions = &self::getFunctionsAddress();
12,121✔
1615

1616
        //    If we're using cell caching, then $pCell may well be flushed back to the cache (which detaches the parent cell collection),
1617
        //        so we store the parent cell collection so that we can re-attach it when necessary
1618
        $pCellWorksheet = ($cell !== null) ? $cell->getWorksheet() : null;
12,121✔
1619
        $originalCoordinate = $cell?->getCoordinate();
12,121✔
1620
        $pCellParent = ($cell !== null) ? $cell->getParent() : null;
12,121✔
1621
        $stack = new Stack($this->branchPruner);
12,121✔
1622

1623
        // Stores branches that have been pruned
1624
        $fakedForBranchPruning = [];
12,121✔
1625
        // help us to know when pruning ['branchTestId' => true/false]
1626
        $branchStore = [];
12,121✔
1627
        //    Loop through each token in turn
1628
        foreach ($tokens as $tokenIdx => $tokenData) {
12,121✔
1629
            /** @var mixed[] $tokenData */
1630
            $this->processingAnchorArray = false;
12,121✔
1631
            if ($tokenData['type'] === 'Cell Reference' && isset($tokens[$tokenIdx + 1]) && $tokens[$tokenIdx + 1]['type'] === 'Operand Count for Function ANCHORARRAY()') { //* @phpstan-ignore-line
12,121✔
1632
                $this->processingAnchorArray = true;
6✔
1633
            }
1634
            $token = $tokenData['value'];
12,121✔
1635
            // Branch pruning: skip useless resolutions
1636
            /** @var ?string */
1637
            $storeKey = $tokenData['storeKey'] ?? null;
12,121✔
1638
            if ($this->branchPruningEnabled && isset($tokenData['onlyIf'])) {
12,121✔
1639
                /** @var string */
1640
                $onlyIfStoreKey = $tokenData['onlyIf'];
84✔
1641
                $storeValue = $branchStore[$onlyIfStoreKey] ?? null;
84✔
1642
                $storeValueAsBool = ($storeValue === null)
84✔
1643
                    ? true : (bool) Functions::flattenSingleValue($storeValue);
84✔
1644
                if (is_array($storeValue)) {
84✔
1645
                    $wrappedItem = end($storeValue);
57✔
1646
                    $storeValue = is_array($wrappedItem) ? end($wrappedItem) : $wrappedItem;
57✔
1647
                }
1648

1649
                if (
1650
                    (isset($storeValue) || $tokenData['reference'] === 'NULL')
84✔
1651
                    && (!$storeValueAsBool || Information\ErrorValue::isError($storeValue) || ($storeValue === 'Pruned branch'))
84✔
1652
                ) {
1653
                    // If branching value is not true, we don't need to compute
1654
                    /** @var string $onlyIfStoreKey */
1655
                    if (!isset($fakedForBranchPruning['onlyIf-' . $onlyIfStoreKey])) {
61✔
1656
                        /** @var string $token */
1657
                        $stack->push('Value', 'Pruned branch (only if ' . $onlyIfStoreKey . ') ' . $token);
59✔
1658
                        $fakedForBranchPruning['onlyIf-' . $onlyIfStoreKey] = true;
59✔
1659
                    }
1660

1661
                    if (isset($storeKey)) {
61✔
1662
                        // We are processing an if condition
1663
                        // We cascade the pruning to the depending branches
1664
                        $branchStore[$storeKey] = 'Pruned branch';
3✔
1665
                        $fakedForBranchPruning['onlyIfNot-' . $storeKey] = true;
3✔
1666
                        $fakedForBranchPruning['onlyIf-' . $storeKey] = true;
3✔
1667
                    }
1668

1669
                    continue;
61✔
1670
                }
1671
            }
1672

1673
            if ($this->branchPruningEnabled && isset($tokenData['onlyIfNot'])) {
12,121✔
1674
                /** @var string */
1675
                $onlyIfNotStoreKey = $tokenData['onlyIfNot'];
79✔
1676
                $storeValue = $branchStore[$onlyIfNotStoreKey] ?? null;
79✔
1677
                $storeValueAsBool = ($storeValue === null)
79✔
1678
                    ? true : (bool) Functions::flattenSingleValue($storeValue);
79✔
1679
                if (is_array($storeValue)) {
79✔
1680
                    $wrappedItem = end($storeValue);
52✔
1681
                    $storeValue = is_array($wrappedItem) ? end($wrappedItem) : $wrappedItem;
52✔
1682
                }
1683

1684
                if (
1685
                    (isset($storeValue) || $tokenData['reference'] === 'NULL')
79✔
1686
                    && ($storeValueAsBool || Information\ErrorValue::isError($storeValue) || ($storeValue === 'Pruned branch'))
79✔
1687
                ) {
1688
                    // If branching value is true, we don't need to compute
1689
                    if (!isset($fakedForBranchPruning['onlyIfNot-' . $onlyIfNotStoreKey])) {
57✔
1690
                        /** @var string $token */
1691
                        $stack->push('Value', 'Pruned branch (only if not ' . $onlyIfNotStoreKey . ') ' . $token);
57✔
1692
                        $fakedForBranchPruning['onlyIfNot-' . $onlyIfNotStoreKey] = true;
57✔
1693
                    }
1694

1695
                    if (isset($storeKey)) {
57✔
1696
                        // We are processing an if condition
1697
                        // We cascade the pruning to the depending branches
1698
                        $branchStore[$storeKey] = 'Pruned branch';
10✔
1699
                        $fakedForBranchPruning['onlyIfNot-' . $storeKey] = true;
10✔
1700
                        $fakedForBranchPruning['onlyIf-' . $storeKey] = true;
10✔
1701
                    }
1702

1703
                    continue;
57✔
1704
                }
1705
            }
1706

1707
            if ($token instanceof Operands\StructuredReference) {
12,121✔
1708
                if ($cell === null) {
17✔
1709
                    return $this->raiseFormulaError('Structured References must exist in a Cell context');
×
1710
                }
1711

1712
                try {
1713
                    $cellRange = $token->parse($cell);
17✔
1714
                    if (str_contains($cellRange, ':')) {
17✔
1715
                        $this->debugLog->writeDebugLog('Evaluating Structured Reference %s as Cell Range %s', $token->value(), $cellRange);
8✔
1716
                        $rangeValue = self::getInstance($cell->getWorksheet()->getParent())->_calculateFormulaValue("={$cellRange}", $cellRange, $cell);
8✔
1717
                        $stack->push('Value', $rangeValue);
8✔
1718
                        $this->debugLog->writeDebugLog('Evaluated Structured Reference %s as value %s', $token->value(), $this->showValue($rangeValue));
8✔
1719
                    } else {
1720
                        $this->debugLog->writeDebugLog('Evaluating Structured Reference %s as Cell %s', $token->value(), $cellRange);
10✔
1721
                        $cellValue = $cell->getWorksheet()->getCell($cellRange)->getCalculatedValue(false);
10✔
1722
                        $stack->push('Cell Reference', $cellValue, $cellRange);
10✔
1723
                        $this->debugLog->writeDebugLog('Evaluated Structured Reference %s as value %s', $token->value(), $this->showValue($cellValue));
17✔
1724
                    }
1725
                } catch (Exception $e) {
2✔
1726
                    if ($e->getCode() === Exception::CALCULATION_ENGINE_PUSH_TO_STACK) {
2✔
1727
                        $stack->push('Error', ExcelError::REF(), null);
2✔
1728
                        $this->debugLog->writeDebugLog('Evaluated Structured Reference %s as error value %s', $token->value(), ExcelError::REF());
2✔
1729
                    } else {
1730
                        return $this->raiseFormulaError($e->getMessage(), $e->getCode(), $e);
×
1731
                    }
1732
                }
1733
            } elseif (!is_numeric($token) && !is_object($token) && isset($token, self::BINARY_OPERATORS[$token])) { //* @phpstan-ignore-line
12,120✔
1734
                // 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
1735
                //    We must have two operands, error if we don't
1736
                $operand2Data = $stack->pop();
1,781✔
1737
                if ($operand2Data === null) {
1,781✔
1738
                    return $this->raiseFormulaError('Internal error - Operand value missing from stack');
×
1739
                }
1740
                $operand1Data = $stack->pop();
1,781✔
1741
                if ($operand1Data === null) {
1,781✔
1742
                    return $this->raiseFormulaError('Internal error - Operand value missing from stack');
×
1743
                }
1744

1745
                $operand1 = self::dataTestReference($operand1Data);
1,781✔
1746
                $operand2 = self::dataTestReference($operand2Data);
1,781✔
1747

1748
                //    Log what we're doing
1749
                if ($token == ':') {
1,781✔
1750
                    $this->debugLog->writeDebugLog('Evaluating Range %s %s %s', $this->showValue($operand1Data['reference']), $token, $this->showValue($operand2Data['reference']));
1,296✔
1751
                } else {
1752
                    $this->debugLog->writeDebugLog('Evaluating %s %s %s', $this->showValue($operand1), $token, $this->showValue($operand2));
766✔
1753
                }
1754

1755
                //    Process the operation in the appropriate manner
1756
                switch ($token) {
1757
                    // Comparison (Boolean) Operators
1758
                    case '>': // Greater than
1,781✔
1759
                    case '<': // Less than
1,766✔
1760
                    case '>=': // Greater than or Equal to
1,749✔
1761
                    case '<=': // Less than or Equal to
1,741✔
1762
                    case '=': // Equality
1,723✔
1763
                    case '<>': // Inequality
1,570✔
1764
                        $result = $this->executeBinaryComparisonOperation($operand1, $operand2, (string) $token, $stack);
414✔
1765
                        if (isset($storeKey)) {
414✔
1766
                            $branchStore[$storeKey] = $result;
71✔
1767
                        }
1768

1769
                        break;
414✔
1770
                    // Binary Operators
1771
                    case ':': // Range
1,560✔
1772
                        if ($operand1Data['type'] === 'Error') {
1,296✔
1773
                            $stack->push($operand1Data['type'], $operand1Data['value'], null);
6✔
1774

1775
                            break;
6✔
1776
                        }
1777
                        if ($operand2Data['type'] === 'Error') {
1,291✔
1778
                            $stack->push($operand2Data['type'], $operand2Data['value'], null);
4✔
1779

1780
                            break;
4✔
1781
                        }
1782
                        if ($operand1Data['type'] === 'Defined Name') {
1,287✔
1783
                            /** @var array{reference: string} $operand1Data */
1784
                            if (preg_match('/$' . self::CALCULATION_REGEXP_DEFINEDNAME . '^/mui', $operand1Data['reference']) !== false && $this->spreadsheet !== null) {
3✔
1785
                                /** @var string[] $operand1Data */
1786
                                $definedName = $this->spreadsheet->getNamedRange($operand1Data['reference']);
3✔
1787
                                if ($definedName !== null) {
3✔
1788
                                    $operand1Data['reference'] = $operand1Data['value'] = str_replace('$', '', $definedName->getValue());
3✔
1789
                                }
1790
                            }
1791
                        }
1792
                        /** @var array{reference?: ?string} $operand1Data */
1793
                        if (str_contains($operand1Data['reference'] ?? '', '!')) {
1,287✔
1794
                            [$sheet1, $operand1Data['reference']] = Worksheet::extractSheetTitle($operand1Data['reference'], true, true);
1,279✔
1795
                        } else {
1796
                            $sheet1 = ($pCellWorksheet !== null) ? $pCellWorksheet->getTitle() : '';
12✔
1797
                        }
1798
                        //$sheet1 ??= ''; // phpstan level 10 says this is unneeded
1799

1800
                        /** @var string */
1801
                        $op2ref = $operand2Data['reference'];
1,287✔
1802
                        [$sheet2, $operand2Data['reference']] = Worksheet::extractSheetTitle($op2ref, true, true);
1,287✔
1803
                        if (empty($sheet2)) {
1,287✔
1804
                            $sheet2 = $sheet1;
7✔
1805
                        }
1806

1807
                        if ($sheet1 === $sheet2) {
1,287✔
1808
                            /** @var array{reference: ?string, value: string|string[]} $operand1Data */
1809
                            if ($operand1Data['reference'] === null && $cell !== null) {
1,284✔
1810
                                if (is_array($operand1Data['value'])) {
×
1811
                                    $operand1Data['reference'] = $cell->getCoordinate();
×
1812
                                } elseif ((trim($operand1Data['value']) != '') && (is_numeric($operand1Data['value']))) {
×
1813
                                    $operand1Data['reference'] = $cell->getColumn() . $operand1Data['value'];
×
1814
                                } elseif (trim($operand1Data['value']) == '') {
×
1815
                                    $operand1Data['reference'] = $cell->getCoordinate();
×
1816
                                } else {
1817
                                    $operand1Data['reference'] = $operand1Data['value'] . $cell->getRow();
×
1818
                                }
1819
                            }
1820
                            /** @var array{reference: ?string, value: string|string[]} $operand2Data */
1821
                            if ($operand2Data['reference'] === null && $cell !== null) {
1,284✔
1822
                                if (is_array($operand2Data['value'])) {
3✔
1823
                                    $operand2Data['reference'] = $cell->getCoordinate();
2✔
1824
                                } elseif ((trim($operand2Data['value']) != '') && (is_numeric($operand2Data['value']))) {
1✔
1825
                                    $operand2Data['reference'] = $cell->getColumn() . $operand2Data['value'];
×
1826
                                } elseif (trim($operand2Data['value']) == '') {
1✔
1827
                                    $operand2Data['reference'] = $cell->getCoordinate();
×
1828
                                } else {
1829
                                    $operand2Data['reference'] = $operand2Data['value'] . $cell->getRow();
1✔
1830
                                }
1831
                            }
1832

1833
                            $oData = array_merge(explode(':', $operand1Data['reference'] ?? ''), explode(':', $operand2Data['reference'] ?? ''));
1,284✔
1834
                            $oCol = $oRow = [];
1,284✔
1835
                            $breakNeeded = false;
1,284✔
1836
                            foreach ($oData as $oDatum) {
1,284✔
1837
                                try {
1838
                                    $oCR = Coordinate::coordinateFromString($oDatum);
1,284✔
1839
                                    $oCol[] = Coordinate::columnIndexFromString($oCR[0]) - 1;
1,284✔
1840
                                    $oRow[] = $oCR[1];
1,284✔
1841
                                } catch (\Exception) {
1✔
1842
                                    $stack->push('Error', ExcelError::REF(), null);
1✔
1843
                                    $breakNeeded = true;
1✔
1844

1845
                                    break;
1✔
1846
                                }
1847
                            }
1848
                            if ($breakNeeded) {
1,284✔
1849
                                break;
1✔
1850
                            }
1851
                            $cellRef = Coordinate::stringFromColumnIndex(min($oCol) + 1) . min($oRow) . ':' . Coordinate::stringFromColumnIndex(max($oCol) + 1) . max($oRow); // @phpstan-ignore-line
1,283✔
1852
                            if ($pCellParent !== null && $this->spreadsheet !== null) {
1,283✔
1853
                                $cellValue = $this->extractCellRange($cellRef, $this->spreadsheet->getSheetByName($sheet1), false);
1,283✔
1854
                            } else {
1855
                                return $this->raiseFormulaError('Unable to access Cell Reference');
×
1856
                            }
1857

1858
                            $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($cellValue));
1,283✔
1859
                            $stack->push('Cell Reference', $cellValue, $cellRef);
1,283✔
1860
                        } else {
1861
                            $this->debugLog->writeDebugLog('Evaluation Result is a #REF! Error');
4✔
1862
                            $stack->push('Error', ExcelError::REF(), null);
4✔
1863
                        }
1864

1865
                        break;
1,286✔
1866
                    case '+':            //    Addition
421✔
1867
                    case '-':            //    Subtraction
339✔
1868
                    case '*':            //    Multiplication
299✔
1869
                    case '/':            //    Division
170✔
1870
                    case '^':            //    Exponential
55✔
1871
                        $result = $this->executeNumericBinaryOperation($operand1, $operand2, $token, $stack);
383✔
1872
                        if (isset($storeKey)) {
383✔
1873
                            $branchStore[$storeKey] = $result;
6✔
1874
                        }
1875

1876
                        break;
383✔
1877
                    case '&':            //    Concatenation
51✔
1878
                        //    If either of the operands is a matrix, we need to treat them both as matrices
1879
                        //        (converting the other operand to a matrix if need be); then perform the required
1880
                        //        matrix operation
1881
                        $operand1 = self::boolToString($operand1);
28✔
1882
                        $operand2 = self::boolToString($operand2);
28✔
1883
                        if (is_array($operand1) || is_array($operand2)) {
28✔
1884
                            if (is_string($operand1)) {
17✔
1885
                                $operand1 = self::unwrapResult($operand1);
8✔
1886
                            }
1887
                            if (is_string($operand2)) {
17✔
1888
                                $operand2 = self::unwrapResult($operand2);
6✔
1889
                            }
1890
                            //    Ensure that both operands are arrays/matrices
1891
                            [$rows, $columns] = self::checkMatrixOperands($operand1, $operand2, 2);
17✔
1892

1893
                            for ($row = 0; $row < $rows; ++$row) {
17✔
1894
                                for ($column = 0; $column < $columns; ++$column) {
17✔
1895
                                    /** @var mixed[][] $operand1 */
1896
                                    $op1x = self::boolToString($operand1[$row][$column]);
17✔
1897
                                    /** @var mixed[][] $operand2 */
1898
                                    $op2x = self::boolToString($operand2[$row][$column]);
17✔
1899
                                    if (Information\ErrorValue::isError($op1x)) {
17✔
1900
                                        // no need to do anything
1901
                                    } elseif (Information\ErrorValue::isError($op2x)) {
17✔
1902
                                        $operand1[$row][$column] = $op2x;
1✔
1903
                                    } else {
1904
                                        /** @var string $op1x */
1905
                                        /** @var string $op2x */
1906
                                        $operand1[$row][$column]
16✔
1907
                                            = StringHelper::substring(
16✔
1908
                                                $op1x . $op2x,
16✔
1909
                                                0,
16✔
1910
                                                DataType::MAX_STRING_LENGTH
16✔
1911
                                            );
16✔
1912
                                    }
1913
                                }
1914
                            }
1915
                            $result = $operand1;
17✔
1916
                        } else {
1917
                            if (Information\ErrorValue::isError($operand1)) {
13✔
1918
                                $result = $operand1;
×
1919
                            } elseif (Information\ErrorValue::isError($operand2)) {
13✔
1920
                                $result = $operand2;
×
1921
                            } else {
1922
                                $result = str_replace('""', self::FORMULA_STRING_QUOTE, self::unwrapResult($operand1) . self::unwrapResult($operand2)); //* @phpstan-ignore-line
13✔
1923
                                $result = StringHelper::substring(
13✔
1924
                                    $result,
13✔
1925
                                    0,
13✔
1926
                                    DataType::MAX_STRING_LENGTH
13✔
1927
                                );
13✔
1928
                                $result = self::FORMULA_STRING_QUOTE . $result . self::FORMULA_STRING_QUOTE;
13✔
1929
                            }
1930
                        }
1931
                        $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($result));
28✔
1932
                        $stack->push('Value', $result);
28✔
1933

1934
                        if (isset($storeKey)) {
28✔
1935
                            $branchStore[$storeKey] = $result;
×
1936
                        }
1937

1938
                        break;
28✔
1939
                    case '∩':            //    Intersect
23✔
1940
                        /** @var mixed[][] $operand1 */
1941
                        /** @var mixed[][] $operand2 */
1942
                        $rowIntersect = array_intersect_key($operand1, $operand2);
17✔
1943
                        $cellIntersect = $oCol = $oRow = [];
17✔
1944
                        foreach (array_keys($rowIntersect) as $row) {
17✔
1945
                            $oRow[] = $row;
17✔
1946
                            foreach ($rowIntersect[$row] as $col => $data) {
17✔
1947
                                $oCol[] = Coordinate::columnIndexFromString($col) - 1;
17✔
1948
                                $cellIntersect[$row] = array_intersect_key($operand1[$row], $operand2[$row]);
17✔
1949
                            }
1950
                        }
1951
                        if (count(Functions::flattenArray($cellIntersect)) === 0) {
17✔
1952
                            $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($cellIntersect));
2✔
1953
                            $stack->push('Error', ExcelError::null(), null);
2✔
1954
                        } else {
1955
                            $cellRef = Coordinate::stringFromColumnIndex(min($oCol) + 1) . min($oRow) . ':' // @phpstan-ignore-line
15✔
1956
                                . Coordinate::stringFromColumnIndex(max($oCol) + 1) . max($oRow); // @phpstan-ignore-line
15✔
1957
                            $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($cellIntersect));
15✔
1958
                            $stack->push('Value', $cellIntersect, $cellRef);
15✔
1959
                        }
1960

1961
                        break;
17✔
1962
                    case '∪':            //    union
8✔
1963
                        /** @var mixed[][] $operand1 */
1964
                        /** @var mixed[][] $operand2 */
1965
                        $cellUnion = array_merge($operand1, $operand2);
8✔
1966
                        $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($cellUnion));
8✔
1967
                        $stack->push('Value', $cellUnion, 'A1');
8✔
1968

1969
                        break;
8✔
1970
                }
1971
            } elseif (($token === '~') || ($token === '%')) {
12,113✔
1972
                // if the token is a unary operator, pop one value off the stack, do the operation, and push it back on
1973
                if (($arg = $stack->pop()) === null) {
1,169✔
1974
                    return $this->raiseFormulaError('Internal error - Operand value missing from stack');
×
1975
                }
1976
                $arg = $arg['value'];
1,169✔
1977
                if ($token === '~') {
1,169✔
1978
                    $this->debugLog->writeDebugLog('Evaluating Negation of %s', $this->showValue($arg));
1,165✔
1979
                    $multiplier = -1;
1,165✔
1980
                } else {
1981
                    $this->debugLog->writeDebugLog('Evaluating Percentile of %s', $this->showValue($arg));
6✔
1982
                    $multiplier = 0.01;
6✔
1983
                }
1984
                if (is_array($arg)) {
1,169✔
1985
                    $operand2 = $multiplier;
4✔
1986
                    $result = $arg;
4✔
1987
                    [$rows, $columns] = self::checkMatrixOperands($result, $operand2, 0);
4✔
1988
                    for ($row = 0; $row < $rows; ++$row) {
4✔
1989
                        for ($column = 0; $column < $columns; ++$column) {
4✔
1990
                            /** @var mixed[][] $result */
1991
                            if (self::isNumericOrBool($result[$row][$column])) {
4✔
1992
                                /** @var float|int|numeric-string */
1993
                                $temp = $result[$row][$column];
4✔
1994
                                $result[$row][$column] = $temp * $multiplier;
4✔
1995
                            } else {
1996
                                $result[$row][$column] = self::makeError($result[$row][$column]);
2✔
1997
                            }
1998
                        }
1999
                    }
2000

2001
                    $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($result));
4✔
2002
                    $stack->push('Value', $result);
4✔
2003
                    if (isset($storeKey)) {
4✔
2004
                        $branchStore[$storeKey] = $result;
×
2005
                    }
2006
                } else {
2007
                    $this->executeNumericBinaryOperation($multiplier, $arg, '*', $stack);
1,168✔
2008
                }
2009
            } elseif (Preg::isMatch('/^' . self::CALCULATION_REGEXP_CELLREF . '$/i', StringHelper::convertToString($token ?? ''), $matches)) {
12,113✔
2010
                $cellRef = null;
7,218✔
2011

2012
                /* Phpstan says matches[8/9/10] is never set,
2013
                   and code coverage report seems to confirm.
2014
                   Appease PhpStan for now;
2015
                   probably delete this block later.
2016
                */
2017
                if (isset($matches[self::$matchIndex8])) {
7,218✔
2018
                    if ($cell === null) {
×
2019
                        // We can't access the range, so return a REF error
2020
                        $cellValue = ExcelError::REF();
×
2021
                    } else {
2022
                        $cellRef = $matches[6] . $matches[7] . ':' . $matches[self::$matchIndex9] . $matches[self::$matchIndex10];
×
NEW
2023
                        $matches[2] = (string) $matches[2];
×
2024
                        if ($matches[2] > '') {
×
2025
                            $matches[2] = trim($matches[2], "\"'");
×
2026
                            if ((str_contains($matches[2], '[')) || (str_contains($matches[2], ']'))) {
×
2027
                                //    It's a Reference to an external spreadsheet (not currently supported)
2028
                                return $this->raiseFormulaError('Unable to access External Workbook');
×
2029
                            }
2030
                            $matches[2] = trim($matches[2], "\"'");
×
2031
                            $this->debugLog->writeDebugLog('Evaluating Cell Range %s in worksheet %s', $cellRef, $matches[2]);
×
2032
                            if ($pCellParent !== null && $this->spreadsheet !== null) {
×
2033
                                $cellValue = $this->extractCellRange($cellRef, $this->spreadsheet->getSheetByName($matches[2]), false);
×
2034
                            } else {
2035
                                return $this->raiseFormulaError('Unable to access Cell Reference');
×
2036
                            }
2037
                            $this->debugLog->writeDebugLog('Evaluation Result for cells %s in worksheet %s is %s', $cellRef, $matches[2], $this->showTypeDetails($cellValue));
×
2038
                        } else {
2039
                            $this->debugLog->writeDebugLog('Evaluating Cell Range %s in current worksheet', $cellRef);
×
2040
                            if ($pCellParent !== null) {
×
2041
                                $cellValue = $this->extractCellRange($cellRef, $pCellWorksheet, false);
×
2042
                            } else {
2043
                                return $this->raiseFormulaError('Unable to access Cell Reference');
×
2044
                            }
2045
                            $this->debugLog->writeDebugLog('Evaluation Result for cells %s is %s', $cellRef, $this->showTypeDetails($cellValue));
×
2046
                        }
2047
                    }
2048
                } else {
2049
                    if ($cell === null) {
7,218✔
2050
                        // We can't access the cell, so return a REF error
2051
                        $cellValue = ExcelError::REF();
×
2052
                    } else {
2053
                        $cellRef = $matches[6] . $matches[7];
7,218✔
2054
                        $matches[2] = (string) $matches[2];
7,218✔
2055
                        if ($matches[2] > '') {
7,218✔
2056
                            $matches[2] = trim($matches[2], "\"'");
7,211✔
2057
                            if ((str_contains($matches[2], '[')) || (str_contains($matches[2], ']'))) {
7,211✔
2058
                                //    It's a Reference to an external spreadsheet (not currently supported)
2059
                                return $this->raiseFormulaError('Unable to access External Workbook');
1✔
2060
                            }
2061
                            $this->debugLog->writeDebugLog('Evaluating Cell %s in worksheet %s', $cellRef, $matches[2]);
7,211✔
2062
                            if ($pCellParent !== null && $this->spreadsheet !== null) {
7,211✔
2063
                                $cellSheet = $this->spreadsheet->getSheetByName($matches[2]);
7,211✔
2064
                                if ($cellSheet && !$cellSheet->cellExists($cellRef)) {
7,211✔
2065
                                    $cellSheet->setCellValue($cellRef, null);
338✔
2066
                                }
2067
                                if ($cellSheet && $cellSheet->cellExists($cellRef)) {
7,211✔
2068
                                    $cellValue = $this->extractCellRange($cellRef, $this->spreadsheet->getSheetByName($matches[2]), false);
7,203✔
2069
                                    $cell->attach($pCellParent);
7,203✔
2070
                                } else {
2071
                                    $cellRef = ($cellSheet !== null) ? "'{$matches[2]}'!{$cellRef}" : $cellRef;
21✔
2072
                                    $cellValue = ($cellSheet !== null) ? null : ExcelError::REF();
21✔
2073
                                }
2074
                            } else {
2075
                                return $this->raiseFormulaError('Unable to access Cell Reference');
×
2076
                            }
2077
                            $this->debugLog->writeDebugLog('Evaluation Result for cell %s in worksheet %s is %s', $cellRef, $matches[2], $this->showTypeDetails($cellValue));
7,211✔
2078
                        } else {
2079
                            $this->debugLog->writeDebugLog('Evaluating Cell %s in current worksheet', $cellRef);
11✔
2080
                            if ($pCellParent !== null && $pCellParent->has($cellRef)) {
11✔
2081
                                $cellValue = $this->extractCellRange($cellRef, $pCellWorksheet, false);
11✔
2082
                                $cell->attach($pCellParent);
11✔
2083
                            } else {
2084
                                $cellValue = null;
2✔
2085
                            }
2086
                            $this->debugLog->writeDebugLog('Evaluation Result for cell %s is %s', $cellRef, $this->showTypeDetails($cellValue));
11✔
2087
                        }
2088
                    }
2089
                }
2090

2091
                if ($this->getInstanceArrayReturnType() === self::RETURN_ARRAY_AS_ARRAY && !$this->processingAnchorArray && is_array($cellValue)) {
7,218✔
2092
                    while (is_array($cellValue)) {
213✔
2093
                        $cellValue = array_shift($cellValue);
213✔
2094
                    }
2095
                    if (is_string($cellValue)) {
213✔
2096
                        $cellValue = Preg::replace('/"/', '""', $cellValue);
139✔
2097
                    }
2098
                    $this->debugLog->writeDebugLog('Scalar Result for cell %s is %s', $cellRef, $this->showTypeDetails($cellValue));
213✔
2099
                }
2100
                $this->processingAnchorArray = false;
7,218✔
2101
                $stack->push('Cell Value', $cellValue, $cellRef);
7,218✔
2102
                if (isset($storeKey)) {
7,218✔
2103
                    $branchStore[$storeKey] = $cellValue;
59✔
2104
                }
2105
            } elseif (preg_match('/^' . self::CALCULATION_REGEXP_FUNCTION . '$/miu', StringHelper::convertToString($token ?? ''), $matches)) {
12,029✔
2106
                // if the token is a function, pop arguments off the stack, hand them to the function, and push the result back on
2107
                if ($cell !== null && $pCellParent !== null) {
11,824✔
2108
                    $cell->attach($pCellParent);
8,233✔
2109
                }
2110

2111
                $functionName = $matches[1];
11,824✔
2112
                /** @var array<string, int> $argCount */
2113
                $argCount = $stack->pop();
11,824✔
2114
                $argCount = $argCount['value'];
11,824✔
2115
                if ($functionName !== 'MKMATRIX') {
11,824✔
2116
                    $this->debugLog->writeDebugLog('Evaluating Function %s() with %s argument%s', self::localeFunc($functionName), (($argCount == 0) ? 'no' : $argCount), (($argCount == 1) ? '' : 's'));
11,823✔
2117
                }
2118
                if ((isset($phpSpreadsheetFunctions[$functionName])) || (isset(self::$controlFunctions[$functionName]))) {    // function
11,824✔
2119
                    $passByReference = false;
11,824✔
2120
                    $passCellReference = false;
11,824✔
2121
                    $functionCall = null;
11,824✔
2122
                    if (isset($phpSpreadsheetFunctions[$functionName])) {
11,824✔
2123
                        $functionCall = $phpSpreadsheetFunctions[$functionName]['functionCall'];
11,821✔
2124
                        $passByReference = isset($phpSpreadsheetFunctions[$functionName]['passByReference']);
11,821✔
2125
                        $passCellReference = isset($phpSpreadsheetFunctions[$functionName]['passCellReference']);
11,821✔
2126
                    } elseif (isset(self::$controlFunctions[$functionName])) {
844✔
2127
                        $functionCall = self::$controlFunctions[$functionName]['functionCall'];
844✔
2128
                        $passByReference = isset(self::$controlFunctions[$functionName]['passByReference']);
844✔
2129
                        $passCellReference = isset(self::$controlFunctions[$functionName]['passCellReference']);
844✔
2130
                    }
2131

2132
                    // get the arguments for this function
2133
                    $args = $argArrayVals = [];
11,824✔
2134
                    $emptyArguments = [];
11,824✔
2135
                    for ($i = 0; $i < $argCount; ++$i) {
11,824✔
2136
                        $arg = $stack->pop();
11,806✔
2137
                        $a = $argCount - $i - 1;
11,806✔
2138
                        if (
2139
                            ($passByReference)
11,806✔
2140
                            && (isset($phpSpreadsheetFunctions[$functionName]['passByReference'][$a])) //* @phpstan-ignore-line
11,806✔
2141
                            && ($phpSpreadsheetFunctions[$functionName]['passByReference'][$a])
11,806✔
2142
                        ) {
2143
                            /** @var mixed[] $arg */
2144
                            if ($arg['reference'] === null) {
82✔
2145
                                $nextArg = $cellID;
19✔
2146
                                if ($functionName === 'ISREF' && ($arg['type'] ?? '') === 'Value') {
19✔
2147
                                    if (array_key_exists('value', $arg)) {
5✔
2148
                                        $argValue = $arg['value'];
5✔
2149
                                        if (is_scalar($argValue)) {
5✔
2150
                                            $nextArg = $argValue;
2✔
2151
                                        } elseif (empty($argValue)) {
3✔
2152
                                            $nextArg = '';
1✔
2153
                                        }
2154
                                    }
2155
                                } elseif (($arg['type'] ?? '') === 'Error') {
14✔
2156
                                    $argValue = $arg['value'];
13✔
2157
                                    if (is_scalar($argValue)) {
13✔
2158
                                        $nextArg = $argValue;
13✔
2159
                                    } elseif (empty($argValue)) {
×
2160
                                        $nextArg = '';
×
2161
                                    }
2162
                                }
2163
                                $args[] = $nextArg;
19✔
2164
                                if ($functionName !== 'MKMATRIX') {
19✔
2165
                                    $argArrayVals[] = $this->showValue($cellID);
19✔
2166
                                }
2167
                            } else {
2168
                                $args[] = $arg['reference'];
67✔
2169
                                if ($functionName !== 'MKMATRIX') {
67✔
2170
                                    $argArrayVals[] = $this->showValue($arg['reference']);
67✔
2171
                                }
2172
                            }
2173
                        } else {
2174
                            /** @var mixed[] $arg */
2175
                            if ($arg['type'] === 'Empty Argument' && in_array($functionName, ['MIN', 'MINA', 'MAX', 'MAXA', 'IF'], true)) {
11,750✔
2176
                                $emptyArguments[] = false;
15✔
2177
                                $args[] = $arg['value'] = 0;
15✔
2178
                                $this->debugLog->writeDebugLog('Empty Argument reevaluated as 0');
15✔
2179
                            } else {
2180
                                $emptyArguments[] = $arg['type'] === 'Empty Argument';
11,750✔
2181
                                $args[] = self::unwrapResult($arg['value']);
11,750✔
2182
                            }
2183
                            if ($functionName !== 'MKMATRIX') {
11,750✔
2184
                                $argArrayVals[] = $this->showValue($arg['value']);
11,749✔
2185
                            }
2186
                        }
2187
                    }
2188

2189
                    //    Reverse the order of the arguments
2190
                    krsort($args);
11,824✔
2191
                    krsort($emptyArguments);
11,824✔
2192

2193
                    if ($argCount > 0 && is_array($functionCall)) {
11,824✔
2194
                        /** @var string[] */
2195
                        $functionCallCopy = $functionCall;
11,806✔
2196
                        $args = $this->addDefaultArgumentValues($functionCallCopy, $args, $emptyArguments);
11,806✔
2197
                    }
2198

2199
                    if (($passByReference) && ($argCount == 0)) {
11,824✔
2200
                        $args[] = $cellID;
9✔
2201
                        $argArrayVals[] = $this->showValue($cellID);
9✔
2202
                    }
2203

2204
                    if ($functionName !== 'MKMATRIX') {
11,824✔
2205
                        if ($this->debugLog->getWriteDebugLog()) {
11,823✔
2206
                            krsort($argArrayVals);
2✔
2207
                            $this->debugLog->writeDebugLog('Evaluating %s ( %s )', self::localeFunc($functionName), implode(self::$localeArgumentSeparator . ' ', Functions::flattenArray($argArrayVals)));
2✔
2208
                        }
2209
                    }
2210

2211
                    //    Process the argument with the appropriate function call
2212
                    if ($pCellWorksheet !== null && $originalCoordinate !== null) {
11,824✔
2213
                        $pCellWorksheet->getCell($originalCoordinate);
8,233✔
2214
                    }
2215
                    /** @var array<string>|string $functionCall */
2216
                    $args = $this->addCellReference($args, $passCellReference, $functionCall, $cell);
11,824✔
2217

2218
                    if (!is_array($functionCall)) {
11,824✔
2219
                        foreach ($args as &$arg) {
54✔
2220
                            $arg = Functions::flattenSingleValue($arg);
1✔
2221
                        }
2222
                        unset($arg);
54✔
2223
                    }
2224

2225
                    /** @var callable $functionCall */
2226
                    try {
2227
                        $result = call_user_func_array($functionCall, $args);
11,824✔
2228
                    } catch (TypeError $e) {
12✔
2229
                        if (!$this->suppressFormulaErrors) {
×
2230
                            throw $e;
×
2231
                        }
2232
                        $result = false;
×
2233
                    }
2234
                    if ($functionName !== 'MKMATRIX') {
11,819✔
2235
                        $this->debugLog->writeDebugLog('Evaluation Result for %s() function call is %s', self::localeFunc($functionName), $this->showTypeDetails($result));
11,816✔
2236
                    }
2237
                    $stack->push('Value', self::wrapResult($result));
11,819✔
2238
                    if (isset($storeKey)) {
11,819✔
2239
                        $branchStore[$storeKey] = $result;
23✔
2240
                    }
2241
                }
2242
            } else {
2243
                // if the token is a number, boolean, string or an Excel error, push it onto the stack
2244
                /** @var ?string $token */
2245
                if (isset(self::EXCEL_CONSTANTS[strtoupper($token ?? '')])) {
12,029✔
2246
                    $excelConstant = strtoupper("$token");
×
2247
                    $stack->push('Constant Value', self::EXCEL_CONSTANTS[$excelConstant]);
×
2248
                    if (isset($storeKey)) {
×
2249
                        $branchStore[$storeKey] = self::EXCEL_CONSTANTS[$excelConstant];
×
2250
                    }
2251
                    $this->debugLog->writeDebugLog('Evaluating Constant %s as %s', $excelConstant, $this->showTypeDetails(self::EXCEL_CONSTANTS[$excelConstant]));
×
2252
                } elseif ((is_numeric($token)) || ($token === null) || (is_bool($token)) || ($token == '') || ($token[0] == self::FORMULA_STRING_QUOTE) || ($token[0] == '#')) { //* @phpstan-ignore-line
12,029✔
2253
                    /** @var array{type: string, reference: ?string} $tokenData */
2254
                    $stack->push($tokenData['type'], $token, $tokenData['reference']);
11,990✔
2255
                    if (isset($storeKey)) {
11,990✔
2256
                        $branchStore[$storeKey] = $token;
74✔
2257
                    }
2258
                } elseif (preg_match('/^' . self::CALCULATION_REGEXP_DEFINEDNAME . '$/miu', $token, $matches)) {
161✔
2259
                    // if the token is a named range or formula, evaluate it and push the result onto the stack
2260
                    $definedName = $matches[6];
161✔
2261
                    if (str_starts_with($definedName, '_xleta')) {
161✔
2262
                        return Functions::NOT_YET_IMPLEMENTED;
1✔
2263
                    }
2264
                    if ($cell === null || $pCellWorksheet === null) {
160✔
2265
                        return $this->raiseFormulaError("undefined name '$token'");
×
2266
                    }
2267
                    $specifiedWorksheet = trim($matches[2], "'");
160✔
2268

2269
                    $this->debugLog->writeDebugLog('Evaluating Defined Name %s', $definedName);
160✔
2270
                    $namedRange = DefinedName::resolveName($definedName, $pCellWorksheet, $specifiedWorksheet);
160✔
2271
                    // If not Defined Name, try as Table.
2272
                    if ($namedRange === null && $this->spreadsheet !== null) {
160✔
2273
                        $table = $this->spreadsheet->getTableByName($definedName);
38✔
2274
                        if ($table !== null) {
38✔
2275
                            $tableRange = Coordinate::getRangeBoundaries($table->getRange());
3✔
2276
                            if ($table->getShowHeaderRow()) {
3✔
2277
                                ++$tableRange[0][1];
3✔
2278
                            }
2279
                            if ($table->getShowTotalsRow()) {
3✔
2280
                                --$tableRange[1][1];
×
2281
                            }
2282
                            $tableRangeString
3✔
2283
                                = '$' . $tableRange[0][0]
3✔
2284
                                . '$' . $tableRange[0][1]
3✔
2285
                                . ':'
3✔
2286
                                . '$' . $tableRange[1][0]
3✔
2287
                                . '$' . $tableRange[1][1];
3✔
2288
                            $namedRange = new NamedRange($definedName, $table->getWorksheet(), $tableRangeString);
3✔
2289
                        }
2290
                    }
2291
                    if ($namedRange === null) {
160✔
2292
                        $result = ExcelError::NAME();
35✔
2293
                        $stack->push('Error', $result, null);
35✔
2294
                        $this->debugLog->writeDebugLog("Error $result");
35✔
2295
                    } else {
2296
                        $result = $this->evaluateDefinedName($cell, $namedRange, $pCellWorksheet, $stack, $specifiedWorksheet !== '');
137✔
2297
                    }
2298

2299
                    if (isset($storeKey)) {
160✔
2300
                        $branchStore[$storeKey] = $result;
1✔
2301
                    }
2302
                } else {
2303
                    return $this->raiseFormulaError("undefined name '$token'");
×
2304
                }
2305
            }
2306
        }
2307
        // when we're out of tokens, the stack should have a single element, the final result
2308
        if ($stack->count() != 1) {
12,112✔
2309
            return $this->raiseFormulaError('internal error');
1✔
2310
        }
2311
        /** @var array<string, array<int, mixed>|false|string> */
2312
        $output = $stack->pop();
12,112✔
2313
        $output = $output['value'];
12,112✔
2314

2315
        return $output;
12,112✔
2316
    }
2317

2318
    private function validateBinaryOperand(mixed &$operand, Stack &$stack): bool
1,484✔
2319
    {
2320
        if (is_array($operand)) {
1,484✔
2321
            if ((count($operand, COUNT_RECURSIVE) - count($operand)) == 1) {
228✔
2322
                do {
2323
                    $operand = array_pop($operand);
193✔
2324
                } while (is_array($operand));
193✔
2325
            }
2326
        }
2327
        //    Numbers, matrices and booleans can pass straight through, as they're already valid
2328
        if (is_string($operand)) {
1,484✔
2329
            //    We only need special validations for the operand if it is a string
2330
            //    Start by stripping off the quotation marks we use to identify true excel string values internally
2331
            if ($operand > '' && $operand[0] == self::FORMULA_STRING_QUOTE) {
17✔
2332
                $operand = StringHelper::convertToString(self::unwrapResult($operand));
5✔
2333
            }
2334
            //    If the string is a numeric value, we treat it as a numeric, so no further testing
2335
            if (!is_numeric($operand)) {
17✔
2336
                //    If not a numeric, test to see if the value is an Excel error, and so can't be used in normal binary operations
2337
                if ($operand > '' && $operand[0] == '#') {
15✔
2338
                    $stack->push('Value', $operand);
6✔
2339
                    $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($operand));
6✔
2340

2341
                    return false;
6✔
2342
                } elseif (Engine\FormattedNumber::convertToNumberIfFormatted($operand) === false) {
11✔
2343
                    //    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
2344
                    $stack->push('Error', '#VALUE!');
6✔
2345
                    $this->debugLog->writeDebugLog('Evaluation Result is a %s', $this->showTypeDetails('#VALUE!'));
6✔
2346

2347
                    return false;
6✔
2348
                }
2349
            }
2350
        }
2351

2352
        //    return a true if the value of the operand is one that we can use in normal binary mathematical operations
2353
        return true;
1,482✔
2354
    }
2355

2356
    /** @return mixed[] */
2357
    private function executeArrayComparison(mixed $operand1, mixed $operand2, string $operation, Stack &$stack, bool $recursingArrays): array
56✔
2358
    {
2359
        $result = [];
56✔
2360
        if (!is_array($operand2) && is_array($operand1)) {
56✔
2361
            // Operand 1 is an array, Operand 2 is a scalar
2362
            foreach ($operand1 as $x => $operandData) {
53✔
2363
                $this->debugLog->writeDebugLog('Evaluating Comparison %s %s %s', $this->showValue($operandData), $operation, $this->showValue($operand2));
53✔
2364
                $this->executeBinaryComparisonOperation($operandData, $operand2, $operation, $stack);
53✔
2365
                /** @var array<string, mixed> $r */
2366
                $r = $stack->pop();
53✔
2367
                $result[$x] = $r['value'];
53✔
2368
            }
2369
        } elseif (is_array($operand2) && !is_array($operand1)) {
10✔
2370
            // Operand 1 is a scalar, Operand 2 is an array
2371
            foreach ($operand2 as $x => $operandData) {
1✔
2372
                $this->debugLog->writeDebugLog('Evaluating Comparison %s %s %s', $this->showValue($operand1), $operation, $this->showValue($operandData));
1✔
2373
                $this->executeBinaryComparisonOperation($operand1, $operandData, $operation, $stack);
1✔
2374
                /** @var array<string, mixed> $r */
2375
                $r = $stack->pop();
1✔
2376
                $result[$x] = $r['value'];
1✔
2377
            }
2378
        } elseif (is_array($operand2) && is_array($operand1)) {
9✔
2379
            // Operand 1 and Operand 2 are both arrays
2380
            if (!$recursingArrays) {
9✔
2381
                self::checkMatrixOperands($operand1, $operand2, 2);
9✔
2382
            }
2383
            foreach ($operand1 as $x => $operandData) {
9✔
2384
                $this->debugLog->writeDebugLog('Evaluating Comparison %s %s %s', $this->showValue($operandData), $operation, $this->showValue($operand2[$x]));
9✔
2385
                $this->executeBinaryComparisonOperation($operandData, $operand2[$x], $operation, $stack, true);
9✔
2386
                /** @var array<string, mixed> $r */
2387
                $r = $stack->pop();
9✔
2388
                $result[$x] = $r['value'];
9✔
2389
            }
2390
        } else {
2391
            throw new Exception('Neither operand is an arra');
×
2392
        }
2393
        //    Log the result details
2394
        $this->debugLog->writeDebugLog('Comparison Evaluation Result is %s', $this->showTypeDetails($result));
56✔
2395
        //    And push the result onto the stack
2396
        $stack->push('Array', $result);
56✔
2397

2398
        return $result;
56✔
2399
    }
2400

2401
    /** @return array<mixed>|bool|string */
2402
    private function executeBinaryComparisonOperation(mixed $operand1, mixed $operand2, string $operation, Stack &$stack, bool $recursingArrays = false): array|bool|string
414✔
2403
    {
2404
        //    If we're dealing with matrix operations, we want a matrix result
2405
        if ((is_array($operand1)) || (is_array($operand2))) {
414✔
2406
            return $this->executeArrayComparison($operand1, $operand2, $operation, $stack, $recursingArrays);
56✔
2407
        }
2408

2409
        $result = BinaryComparison::compare($operand1, $operand2, $operation);
414✔
2410

2411
        //    Log the result details
2412
        $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($result));
414✔
2413
        //    And push the result onto the stack
2414
        $stack->push('Value', $result);
414✔
2415

2416
        return $result;
414✔
2417
    }
2418

2419
    private function executeNumericBinaryOperation(mixed $operand1, mixed $operand2, string $operation, Stack &$stack): mixed
1,484✔
2420
    {
2421
        //    Validate the two operands
2422
        if (
2423
            ($this->validateBinaryOperand($operand1, $stack) === false)
1,484✔
2424
            || ($this->validateBinaryOperand($operand2, $stack) === false)
1,484✔
2425
        ) {
2426
            return false;
10✔
2427
        }
2428

2429
        if (
2430
            (Functions::getCompatibilityMode() != Functions::COMPATIBILITY_OPENOFFICE)
1,477✔
2431
            && ((is_string($operand1) && !is_numeric($operand1) && $operand1 !== '')
1,477✔
2432
                || (is_string($operand2) && !is_numeric($operand2) && $operand2 !== ''))
1,477✔
2433
        ) {
2434
            $result = ExcelError::VALUE();
×
2435
        } elseif (is_array($operand1) || is_array($operand2)) {
1,477✔
2436
            //    Ensure that both operands are arrays/matrices
2437
            if (is_array($operand1)) {
38✔
2438
                foreach ($operand1 as $key => $value) {
32✔
2439
                    $operand1[$key] = Functions::flattenArray($value);
32✔
2440
                }
2441
            }
2442
            if (is_array($operand2)) {
38✔
2443
                foreach ($operand2 as $key => $value) {
31✔
2444
                    $operand2[$key] = Functions::flattenArray($value);
31✔
2445
                }
2446
            }
2447
            [$rows, $columns] = self::checkMatrixOperands($operand1, $operand2, 3);
38✔
2448

2449
            for ($row = 0; $row < $rows; ++$row) {
38✔
2450
                for ($column = 0; $column < $columns; ++$column) {
38✔
2451
                    /** @var mixed[][] $operand1 */
2452
                    if (($operand1[$row][$column] ?? null) === null) {
38✔
2453
                        $operand1[$row][$column] = 0;
2✔
2454
                    } elseif (!self::isNumericOrBool($operand1[$row][$column])) {
38✔
2455
                        $operand1[$row][$column] = self::makeError($operand1[$row][$column]);
1✔
2456

2457
                        continue;
1✔
2458
                    }
2459
                    /** @var mixed[][] $operand2 */
2460
                    if (($operand2[$row][$column] ?? null) === null) {
38✔
2461
                        $operand2[$row][$column] = 0;
2✔
2462
                    } elseif (!self::isNumericOrBool($operand2[$row][$column])) {
38✔
2463
                        $operand1[$row][$column] = self::makeError($operand2[$row][$column]);
×
2464

2465
                        continue;
×
2466
                    }
2467
                    /** @var float|int */
2468
                    $operand1Val = $operand1[$row][$column];
38✔
2469
                    /** @var float|int */
2470
                    $operand2Val = $operand2[$row][$column];
38✔
2471
                    switch ($operation) {
2472
                        case '+':
38✔
2473
                            $operand1[$row][$column] = $operand1Val + $operand2Val;
4✔
2474

2475
                            break;
4✔
2476
                        case '-':
35✔
2477
                            $operand1[$row][$column] = $operand1Val - $operand2Val;
4✔
2478

2479
                            break;
4✔
2480
                        case '*':
32✔
2481
                            $operand1[$row][$column] = $operand1Val * $operand2Val;
25✔
2482

2483
                            break;
25✔
2484
                        case '/':
7✔
2485
                            if ($operand2Val == 0) {
5✔
2486
                                $operand1[$row][$column] = ExcelError::DIV0();
3✔
2487
                            } else {
2488
                                $operand1[$row][$column] = $operand1Val / $operand2Val;
4✔
2489
                            }
2490

2491
                            break;
5✔
2492
                        case '^':
2✔
2493
                            $operand1[$row][$column] = $operand1Val ** $operand2Val;
2✔
2494

2495
                            break;
2✔
2496

2497
                        default:
2498
                            throw new Exception('Unsupported numeric binary operation');
×
2499
                    }
2500
                }
2501
            }
2502
            $result = $operand1;
38✔
2503
        } else {
2504
            //    If we're dealing with non-matrix operations, execute the necessary operation
2505
            /** @var float|int $operand1 */
2506
            /** @var float|int $operand2 */
2507
            switch ($operation) {
2508
                //    Addition
2509
                case '+':
1,459✔
2510
                    $result = $operand1 + $operand2;
163✔
2511

2512
                    break;
163✔
2513
                //    Subtraction
2514
                case '-':
1,378✔
2515
                    $result = $operand1 - $operand2;
51✔
2516

2517
                    break;
51✔
2518
                //    Multiplication
2519
                case '*':
1,343✔
2520
                    $result = $operand1 * $operand2;
1,265✔
2521

2522
                    break;
1,265✔
2523
                //    Division
2524
                case '/':
115✔
2525
                    if ($operand2 == 0) {
113✔
2526
                        //    Trap for Divide by Zero error
2527
                        $stack->push('Error', ExcelError::DIV0());
62✔
2528
                        $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails(ExcelError::DIV0()));
62✔
2529

2530
                        return false;
62✔
2531
                    }
2532
                    $result = $operand1 / $operand2;
61✔
2533

2534
                    break;
61✔
2535
                //    Power
2536
                case '^':
3✔
2537
                    $result = $operand1 ** $operand2;
3✔
2538

2539
                    break;
3✔
2540

2541
                default:
2542
                    throw new Exception('Unsupported numeric binary operation');
×
2543
            }
2544
        }
2545

2546
        //    Log the result details
2547
        $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($result));
1,433✔
2548
        //    And push the result onto the stack
2549
        $stack->push('Value', $result);
1,433✔
2550

2551
        return $result;
1,433✔
2552
    }
2553

2554
    /**
2555
     * Trigger an error, but nicely, if need be.
2556
     *
2557
     * @return false
2558
     */
2559
    protected function raiseFormulaError(string $errorMessage, int $code = 0, ?Throwable $exception = null): bool
245✔
2560
    {
2561
        $this->formulaError = $errorMessage;
245✔
2562
        $this->cyclicReferenceStack->clear();
245✔
2563
        $suppress = $this->suppressFormulaErrors;
245✔
2564
        $suppressed = $suppress ? ' $suppressed' : '';
245✔
2565
        $this->debugLog->writeDebugLog("Raise Error$suppressed $errorMessage");
245✔
2566
        if (!$suppress) {
245✔
2567
            throw new Exception($errorMessage, $code, $exception);
244✔
2568
        }
2569

2570
        return false;
2✔
2571
    }
2572

2573
    /**
2574
     * Extract range values.
2575
     *
2576
     * @param string $range String based range representation
2577
     * @param ?Worksheet $worksheet Worksheet
2578
     * @param bool $resetLog Flag indicating whether calculation log should be reset or not
2579
     *
2580
     * @return mixed[] Array of values in range if range contains more than one element. Otherwise, a single value is returned.
2581
     */
2582
    public function extractCellRange(string &$range = 'A1', ?Worksheet $worksheet = null, bool $resetLog = true, bool $createCell = false): array
7,257✔
2583
    {
2584
        // Return value
2585
        /** @var mixed[][] */
2586
        $returnValue = [];
7,257✔
2587

2588
        if ($worksheet !== null) {
7,257✔
2589
            $worksheetName = $worksheet->getTitle();
7,256✔
2590

2591
            if (str_contains($range, '!')) {
7,256✔
2592
                [$worksheetName, $range] = Worksheet::extractSheetTitle($range, true, true);
10✔
2593
                $worksheet = ($this->spreadsheet === null) ? null : $this->spreadsheet->getSheetByName($worksheetName);
10✔
2594
            }
2595

2596
            // Extract range
2597
            $aReferences = Coordinate::extractAllCellReferencesInRange($range);
7,256✔
2598
            $range = "'" . $worksheetName . "'" . '!' . $range;
7,256✔
2599
            $currentCol = '';
7,256✔
2600
            $currentRow = 0;
7,256✔
2601
            if (!isset($aReferences[1])) {
7,256✔
2602
                //    Single cell in range
2603
                sscanf($aReferences[0], '%[A-Z]%d', $currentCol, $currentRow);
7,252✔
2604
                /** @var string $currentCol */
2605
                /** @var int $currentRow */
2606
                if ($createCell && $worksheet !== null && !$worksheet->cellExists($aReferences[0])) {
7,252✔
2607
                    $worksheet->setCellValue($aReferences[0], null);
2✔
2608
                }
2609
                if ($worksheet !== null && $worksheet->cellExists($aReferences[0])) {
7,252✔
2610
                    $temp = $worksheet->getCell($aReferences[0])->getCalculatedValue($resetLog);
7,252✔
2611
                    if ($this->getInstanceArrayReturnType() === self::RETURN_ARRAY_AS_ARRAY) {
7,252✔
2612
                        while (is_array($temp)) {
215✔
2613
                            $temp = array_shift($temp);
8✔
2614
                        }
2615
                    }
2616
                    $returnValue[$currentRow][$currentCol] = $temp;
7,252✔
2617
                } else {
2618
                    $returnValue[$currentRow][$currentCol] = null;
×
2619
                }
2620
            } else {
2621
                // Extract cell data for all cells in the range
2622
                foreach ($aReferences as $reference) {
1,282✔
2623
                    // Extract range
2624
                    sscanf($reference, '%[A-Z]%d', $currentCol, $currentRow);
1,282✔
2625
                    /** @var string $currentCol */
2626
                    /** @var int $currentRow */
2627
                    if ($createCell && $worksheet !== null && !$worksheet->cellExists($reference)) {
1,282✔
2628
                        $worksheet->setCellValue($reference, null);
4✔
2629
                    }
2630
                    if ($worksheet !== null && $worksheet->cellExists($reference)) {
1,282✔
2631
                        $temp = $worksheet->getCell($reference)->getCalculatedValue($resetLog);
1,280✔
2632
                        if ($this->getInstanceArrayReturnType() === self::RETURN_ARRAY_AS_ARRAY) {
1,280✔
2633
                            while (is_array($temp)) {
190✔
2634
                                $temp = array_shift($temp);
1✔
2635
                            }
2636
                        }
2637
                        $returnValue[$currentRow][$currentCol] = $temp;
1,280✔
2638
                    } else {
2639
                        $returnValue[$currentRow][$currentCol] = null;
137✔
2640
                    }
2641
                }
2642
            }
2643
        }
2644

2645
        return $returnValue;
7,257✔
2646
    }
2647

2648
    /**
2649
     * Extract range values.
2650
     *
2651
     * @param string $range String based range representation
2652
     * @param null|Worksheet $worksheet Worksheet
2653
     * @param bool $resetLog Flag indicating whether calculation log should be reset or not
2654
     *
2655
     * @return mixed[]|string Array of values in range if range contains more than one element. Otherwise, a single value is returned.
2656
     */
2657
    public function extractNamedRange(string &$range = 'A1', ?Worksheet $worksheet = null, bool $resetLog = true): string|array
1✔
2658
    {
2659
        // Return value
2660
        $returnValue = [];
1✔
2661

2662
        if ($worksheet !== null) {
1✔
2663
            if (str_contains($range, '!')) {
1✔
2664
                [$worksheetName, $range] = Worksheet::extractSheetTitle($range, true, true);
1✔
2665
                $worksheet = ($this->spreadsheet === null) ? null : $this->spreadsheet->getSheetByName($worksheetName);
1✔
2666
            }
2667

2668
            // Named range?
2669
            $namedRange = ($worksheet === null) ? null : DefinedName::resolveName($range, $worksheet);
1✔
2670
            if ($namedRange === null) {
1✔
2671
                return ExcelError::REF();
1✔
2672
            }
2673

2674
            $worksheet = $namedRange->getWorksheet();
1✔
2675
            $range = $namedRange->getValue();
1✔
2676
            $splitRange = Coordinate::splitRange($range);
1✔
2677
            //    Convert row and column references
2678
            if ($worksheet !== null && ctype_alpha($splitRange[0][0])) {
1✔
2679
                $range = $splitRange[0][0] . '1:' . $splitRange[0][1] . $worksheet->getHighestRow();
×
2680
            } elseif ($worksheet !== null && ctype_digit($splitRange[0][0])) {
1✔
2681
                $range = 'A' . $splitRange[0][0] . ':' . $worksheet->getHighestColumn() . $splitRange[0][1];
×
2682
            }
2683

2684
            // Extract range
2685
            $aReferences = Coordinate::extractAllCellReferencesInRange($range);
1✔
2686
            if (!isset($aReferences[1])) {
1✔
2687
                //    Single cell (or single column or row) in range
2688
                [$currentCol, $currentRow] = Coordinate::coordinateFromString($aReferences[0]);
1✔
2689
                /** @var mixed[][] $returnValue */
2690
                if ($worksheet !== null && $worksheet->cellExists($aReferences[0])) {
1✔
2691
                    $returnValue[$currentRow][$currentCol] = $worksheet->getCell($aReferences[0])->getCalculatedValue($resetLog);
1✔
2692
                } else {
2693
                    $returnValue[$currentRow][$currentCol] = null;
1✔
2694
                }
2695
            } else {
2696
                // Extract cell data for all cells in the range
2697
                foreach ($aReferences as $reference) {
1✔
2698
                    // Extract range
2699
                    [$currentCol, $currentRow] = Coordinate::coordinateFromString($reference);
1✔
2700
                    if ($worksheet !== null && $worksheet->cellExists($reference)) {
1✔
2701
                        $returnValue[$currentRow][$currentCol] = $worksheet->getCell($reference)->getCalculatedValue($resetLog);
1✔
2702
                    } else {
2703
                        $returnValue[$currentRow][$currentCol] = null;
1✔
2704
                    }
2705
                }
2706
            }
2707
        }
2708

2709
        return $returnValue;
1✔
2710
    }
2711

2712
    /**
2713
     * Is a specific function implemented?
2714
     *
2715
     * @param string $function Function Name
2716
     */
2717
    public function isImplemented(string $function): bool
3✔
2718
    {
2719
        $function = strtoupper($function);
3✔
2720
        $phpSpreadsheetFunctions = &self::getFunctionsAddress();
3✔
2721
        $notImplemented = !isset($phpSpreadsheetFunctions[$function]) || (is_array($phpSpreadsheetFunctions[$function]['functionCall']) && $phpSpreadsheetFunctions[$function]['functionCall'][1] === 'DUMMY');
3✔
2722

2723
        return !$notImplemented;
3✔
2724
    }
2725

2726
    /**
2727
     * Get a list of implemented Excel function names.
2728
     *
2729
     * @return string[]
2730
     */
2731
    public function getImplementedFunctionNames(): array
2✔
2732
    {
2733
        $returnValue = [];
2✔
2734
        $phpSpreadsheetFunctions = &self::getFunctionsAddress();
2✔
2735
        foreach ($phpSpreadsheetFunctions as $functionName => $function) {
2✔
2736
            if ($this->isImplemented($functionName)) {
2✔
2737
                $returnValue[] = $functionName;
2✔
2738
            }
2739
        }
2740

2741
        return $returnValue;
2✔
2742
    }
2743

2744
    /**
2745
     * @param string[] $functionCall
2746
     * @param mixed[] $args
2747
     * @param mixed[] $emptyArguments
2748
     *
2749
     * @return mixed[]
2750
     */
2751
    private function addDefaultArgumentValues(array $functionCall, array $args, array $emptyArguments): array
11,806✔
2752
    {
2753
        $reflector = new ReflectionMethod($functionCall[0], $functionCall[1]);
11,806✔
2754
        $methodArguments = $reflector->getParameters();
11,806✔
2755

2756
        if (count($methodArguments) > 0) {
11,806✔
2757
            // Apply any defaults for empty argument values
2758
            foreach ($emptyArguments as $argumentId => $isArgumentEmpty) {
11,806✔
2759
                if ($isArgumentEmpty === true) {
11,750✔
2760
                    $reflectedArgumentId = count($args) - (int) $argumentId - 1;
148✔
2761
                    if (
2762
                        !array_key_exists($reflectedArgumentId, $methodArguments)
148✔
2763
                        || $methodArguments[$reflectedArgumentId]->isVariadic()
148✔
2764
                    ) {
2765
                        break;
13✔
2766
                    }
2767

2768
                    $args[$argumentId] = $this->getArgumentDefaultValue($methodArguments[$reflectedArgumentId]);
135✔
2769
                }
2770
            }
2771
        }
2772

2773
        return $args;
11,806✔
2774
    }
2775

2776
    private function getArgumentDefaultValue(ReflectionParameter $methodArgument): mixed
135✔
2777
    {
2778
        $defaultValue = null;
135✔
2779

2780
        if ($methodArgument->isDefaultValueAvailable()) {
135✔
2781
            $defaultValue = $methodArgument->getDefaultValue();
63✔
2782
            if ($methodArgument->isDefaultValueConstant()) {
63✔
2783
                $constantName = $methodArgument->getDefaultValueConstantName() ?? '';
2✔
2784
                // read constant value
2785
                if (str_contains($constantName, '::')) {
2✔
2786
                    [$className, $constantName] = explode('::', $constantName);
2✔
2787
                    /** @var class-string $className */
2788
                    $constantReflector = new ReflectionClassConstant($className, $constantName);
2✔
2789

2790
                    return $constantReflector->getValue();
2✔
2791
                }
2792

2793
                return constant($constantName);
×
2794
            }
2795
        }
2796

2797
        return $defaultValue;
134✔
2798
    }
2799

2800
    /**
2801
     * Add cell reference if needed while making sure that it is the last argument.
2802
     *
2803
     * @param mixed[] $args
2804
     * @param string|string[] $functionCall
2805
     *
2806
     * @return mixed[]
2807
     */
2808
    private function addCellReference(array $args, bool $passCellReference, array|string $functionCall, ?Cell $cell = null): array
11,824✔
2809
    {
2810
        if ($passCellReference) {
11,824✔
2811
            if (is_array($functionCall)) {
280✔
2812
                $className = $functionCall[0];
280✔
2813
                $methodName = $functionCall[1];
280✔
2814

2815
                $reflectionMethod = new ReflectionMethod($className, $methodName);
280✔
2816
                $argumentCount = count($reflectionMethod->getParameters());
280✔
2817
                while (count($args) < $argumentCount - 1) {
280✔
2818
                    $args[] = null;
57✔
2819
                }
2820
            }
2821

2822
            $args[] = $cell;
280✔
2823
        }
2824

2825
        return $args;
11,824✔
2826
    }
2827

2828
    private function evaluateDefinedName(Cell $cell, DefinedName $namedRange, Worksheet $cellWorksheet, Stack $stack, bool $ignoreScope = false): mixed
137✔
2829
    {
2830
        $definedNameScope = $namedRange->getScope();
137✔
2831
        if ($definedNameScope !== null && $definedNameScope !== $cellWorksheet && !$ignoreScope) {
137✔
2832
            // The defined name isn't in our current scope, so #REF
2833
            $result = ExcelError::REF();
×
2834
            $stack->push('Error', $result, $namedRange->getName());
×
2835

2836
            return $result;
×
2837
        }
2838

2839
        $definedNameValue = $namedRange->getValue();
137✔
2840
        $definedNameType = $namedRange->isFormula() ? 'Formula' : 'Range';
137✔
2841
        if ($definedNameType === 'Range') {
137✔
2842
            if (Preg::isMatch('/^(.*!)?(.*)$/', $definedNameValue, $matches)) {
132✔
2843
                $matches2 = Preg::replace(
132✔
2844
                    ['/ +/', '/,/'],
132✔
2845
                    [' ∩ ', ' ∪ '],
132✔
2846
                    trim($matches[2])
132✔
2847
                );
132✔
2848
                $definedNameValue = $matches[1] . $matches2;
132✔
2849
            }
2850
        }
2851
        $definedNameWorksheet = $namedRange->getWorksheet();
137✔
2852

2853
        if ($definedNameValue[0] !== '=') {
137✔
2854
            $definedNameValue = '=' . $definedNameValue;
114✔
2855
        }
2856

2857
        $this->debugLog->writeDebugLog('Defined Name is a %s with a value of %s', $definedNameType, $definedNameValue);
137✔
2858

2859
        $originalCoordinate = $cell->getCoordinate();
137✔
2860
        $recursiveCalculationCell = ($definedNameType !== 'Formula' && $definedNameWorksheet !== null && $definedNameWorksheet !== $cellWorksheet)
137✔
2861
            ? $definedNameWorksheet->getCell('A1')
20✔
2862
            : $cell;
126✔
2863
        $recursiveCalculationCellAddress = $recursiveCalculationCell->getCoordinate();
137✔
2864

2865
        // Adjust relative references in ranges and formulae so that we execute the calculation for the correct rows and columns
2866
        $definedNameValue = ReferenceHelper::getInstance()
137✔
2867
            ->updateFormulaReferencesAnyWorksheet(
137✔
2868
                $definedNameValue,
137✔
2869
                Coordinate::columnIndexFromString(
137✔
2870
                    $cell->getColumn()
137✔
2871
                ) - 1,
137✔
2872
                $cell->getRow() - 1
137✔
2873
            );
137✔
2874

2875
        $this->debugLog->writeDebugLog('Value adjusted for relative references is %s', $definedNameValue);
137✔
2876

2877
        $recursiveCalculator = new self($this->spreadsheet);
137✔
2878
        $recursiveCalculator->getDebugLog()->setWriteDebugLog($this->getDebugLog()->getWriteDebugLog());
137✔
2879
        $recursiveCalculator->getDebugLog()->setEchoDebugLog($this->getDebugLog()->getEchoDebugLog());
137✔
2880
        $result = $recursiveCalculator->_calculateFormulaValue($definedNameValue, $recursiveCalculationCellAddress, $recursiveCalculationCell, true);
137✔
2881
        $cellWorksheet->getCell($originalCoordinate);
137✔
2882

2883
        if ($this->getDebugLog()->getWriteDebugLog()) {
137✔
2884
            $this->debugLog->mergeDebugLog(array_slice($recursiveCalculator->getDebugLog()->getLog(), 3));
×
2885
            $this->debugLog->writeDebugLog('Evaluation Result for Named %s %s is %s', $definedNameType, $namedRange->getName(), $this->showTypeDetails($result));
×
2886
        }
2887

2888
        $y = $namedRange->getWorksheet()?->getTitle();
137✔
2889
        $x = $namedRange->getLocalOnly();
137✔
2890
        if ($x && $y !== null) {
137✔
2891
            $stack->push('Defined Name', $result, "'$y'!" . $namedRange->getName());
20✔
2892
        } else {
2893
            $stack->push('Defined Name', $result, $namedRange->getName());
118✔
2894
        }
2895

2896
        return $result;
137✔
2897
    }
2898

2899
    public function setSuppressFormulaErrors(bool $suppressFormulaErrors): self
12✔
2900
    {
2901
        $this->suppressFormulaErrors = $suppressFormulaErrors;
12✔
2902

2903
        return $this;
12✔
2904
    }
2905

2906
    public function getSuppressFormulaErrors(): bool
14✔
2907
    {
2908
        return $this->suppressFormulaErrors;
14✔
2909
    }
2910

2911
    public static function boolToString(mixed $operand1): mixed
33✔
2912
    {
2913
        if (is_bool($operand1)) {
33✔
2914
            $operand1 = ($operand1) ? self::$localeBoolean['TRUE'] : self::$localeBoolean['FALSE'];
1✔
2915
        } elseif ($operand1 === null) {
33✔
2916
            $operand1 = '';
1✔
2917
        }
2918

2919
        return $operand1;
33✔
2920
    }
2921

2922
    private static function isNumericOrBool(mixed $operand): bool
42✔
2923
    {
2924
        return is_numeric($operand) || is_bool($operand);
42✔
2925
    }
2926

2927
    private static function makeError(mixed $operand = ''): string
3✔
2928
    {
2929
        return (is_string($operand) && Information\ErrorValue::isError($operand)) ? $operand : ExcelError::VALUE();
3✔
2930
    }
2931

2932
    private static function swapOperands(Stack $stack, string $opCharacter): bool
1,900✔
2933
    {
2934
        $retVal = false;
1,900✔
2935
        if ($stack->count() > 0) {
1,900✔
2936
            $o2 = $stack->last();
1,412✔
2937
            if ($o2) {
1,412✔
2938
                /** @var array{value: string} $o2 */
2939
                if (isset(self::CALCULATION_OPERATORS[$o2['value']])) {
1,412✔
2940
                    $retVal = (self::OPERATOR_PRECEDENCE[$opCharacter] ?? 0) <= self::OPERATOR_PRECEDENCE[$o2['value']];
125✔
2941
                }
2942
            }
2943
        }
2944

2945
        return $retVal;
1,900✔
2946
    }
2947

2948
    public function getSpreadsheet(): ?Spreadsheet
2✔
2949
    {
2950
        return $this->spreadsheet;
2✔
2951
    }
2952
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc