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

PHPOffice / PhpSpreadsheet / 20985572567

14 Jan 2026 07:07AM UTC coverage: 96.201% (+0.2%) from 95.962%
20985572567

Pull #4657

github

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

11 of 12 new or added lines in 1 file covered. (91.67%)

359 existing lines in 16 files now uncovered.

46284 of 48112 relevant lines covered (96.2%)

386.88 hits per line

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

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

3
namespace PhpOffice\PhpSpreadsheet\Calculation;
4

5
use PhpOffice\PhpSpreadsheet\Calculation\Engine\BranchPruner;
6
use PhpOffice\PhpSpreadsheet\Calculation\Engine\CyclicReferenceStack;
7
use PhpOffice\PhpSpreadsheet\Calculation\Engine\Logger;
8
use PhpOffice\PhpSpreadsheet\Calculation\Engine\Operands;
9
use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError;
10
use PhpOffice\PhpSpreadsheet\Calculation\Token\Stack;
11
use PhpOffice\PhpSpreadsheet\Cell\AddressRange;
12
use PhpOffice\PhpSpreadsheet\Cell\Cell;
13
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
14
use PhpOffice\PhpSpreadsheet\Cell\DataType;
15
use PhpOffice\PhpSpreadsheet\DefinedName;
16
use PhpOffice\PhpSpreadsheet\NamedRange;
17
use PhpOffice\PhpSpreadsheet\ReferenceHelper;
18
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
19
use PhpOffice\PhpSpreadsheet\Spreadsheet;
20
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
21
use ReflectionClassConstant;
22
use ReflectionMethod;
23
use ReflectionParameter;
24
use Throwable;
25
use TypeError;
26

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

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

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

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

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

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

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

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

91
    private BranchPruner $branchPruner;
92

93
    private bool $branchPruningEnabled = true;
94

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

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

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

122
    private bool $suppressFormulaErrors = false;
123

124
    private bool $processingAnchorArray = false;
125

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

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

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

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

146
    private string $cyclicFormulaCell = '';
147

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

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

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

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

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

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

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

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

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

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

231
        return null;
133✔
232
    }
233

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

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

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

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

276
            return true;
588✔
277
        }
278

279
        return false;
1✔
280
    }
281

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

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

308
            return true;
423✔
309
        }
310

311
        return false;
2✔
312
    }
313

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

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

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

340
        return $this;
10✔
341
    }
342

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

630
            return true;
360✔
631
        }
632

633
        return false;
8,620✔
634
    }
635

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

973
        return null;
12,106✔
974
    }
975

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

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

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

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

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

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

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

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

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

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

1080
        $formula = preg_replace_callback(self::UNIONABLE_COMMAS, self::unionForComma(...), $formula) ?? $formula;
12,491✔
1081
        $phpSpreadsheetFunctions = &self::getFunctionsAddress();
12,491✔
1082

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1264
                    continue;
1✔
1265
                }
1266

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

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

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

1289
                if (preg_match('/^' . self::CALCULATION_REGEXP_FUNCTION . '$/miu', $val, $matches)) {
12,487✔
1290
                    $val = (string) preg_replace('/\s/u', '', $val);
12,106✔
1291
                    if (isset($phpSpreadsheetFunctions[strtoupper($matches[1])]) || isset(self::$controlFunctions[strtoupper($matches[1])])) {    // it's a function
12,106✔
1292
                        $valToUpper = strtoupper($val);
12,104✔
1293
                    } else {
1294
                        $valToUpper = 'NAME.ERROR(';
6✔
1295
                    }
1296
                    // here $matches[1] will contain values like "IF"
1297
                    // and $val "IF("
1298

1299
                    $this->branchPruner->functionCall($valToUpper);
12,106✔
1300

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

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

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

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

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

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

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

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

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

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

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

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

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

1570
        return $output;
12,255✔
1571
    }
1572

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

1583
                return $operand[$rowKey];
6✔
1584
            }
1585

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

1593
        return $operand;
1,781✔
1594
    }
1595

1596
    private static int $matchIndex8 = 8;
1597

1598
    private static int $matchIndex9 = 9;
1599

1600
    private static int $matchIndex10 = 10;
1601

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

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

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

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

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

1667
                    continue;
61✔
1668
                }
1669
            }
1670

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

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

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

1701
                    continue;
57✔
1702
                }
1703
            }
1704

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2185
                    //    Reverse the order of the arguments
2186
                    krsort($args);
11,824✔
2187
                    krsort($emptyArguments);
11,824✔
2188

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

2195
                    if (($passByReference) && ($argCount == 0)) {
11,824✔
2196
                        $args[] = $cellID;
9✔
2197
                        $argArrayVals[] = $this->showValue($cellID);
9✔
2198
                    }
2199

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

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

2214
                    if (!is_array($functionCall)) {
11,824✔
2215
                        foreach ($args as &$arg) {
54✔
2216
                            $arg = Functions::flattenSingleValue($arg);
1✔
2217
                        }
2218
                        unset($arg);
54✔
2219
                    }
2220

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

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

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

2311
        return $output;
12,112✔
2312
    }
2313

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

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

2343
                    return false;
6✔
2344
                }
2345
            }
2346
        }
2347

2348
        //    return a true if the value of the operand is one that we can use in normal binary mathematical operations
2349
        return true;
1,482✔
2350
    }
2351

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

2394
        return $result;
56✔
2395
    }
2396

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

2405
        $result = BinaryComparison::compare($operand1, $operand2, $operation);
414✔
2406

2407
        //    Log the result details
2408
        $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($result));
414✔
2409
        //    And push the result onto the stack
2410
        $stack->push('Value', $result);
414✔
2411

2412
        return $result;
414✔
2413
    }
2414

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

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

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

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

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

2471
                            break;
4✔
2472
                        case '-':
35✔
2473
                            $operand1[$row][$column] = $operand1Val - $operand2Val;
4✔
2474

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

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

2487
                            break;
5✔
2488
                        case '^':
2✔
2489
                            $operand1[$row][$column] = $operand1Val ** $operand2Val;
2✔
2490

2491
                            break;
2✔
2492

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

2508
                    break;
163✔
2509
                //    Subtraction
2510
                case '-':
1,378✔
2511
                    $result = $operand1 - $operand2;
51✔
2512

2513
                    break;
51✔
2514
                //    Multiplication
2515
                case '*':
1,343✔
2516
                    $result = $operand1 * $operand2;
1,265✔
2517

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

2526
                        return false;
62✔
2527
                    }
2528
                    $result = $operand1 / $operand2;
61✔
2529

2530
                    break;
61✔
2531
                //    Power
2532
                case '^':
3✔
2533
                    $result = $operand1 ** $operand2;
3✔
2534

2535
                    break;
3✔
2536

2537
                default:
2538
                    throw new Exception('Unsupported numeric binary operation');
×
2539
            }
2540
        }
2541

2542
        //    Log the result details
2543
        $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($result));
1,433✔
2544
        //    And push the result onto the stack
2545
        $stack->push('Value', $result);
1,433✔
2546

2547
        return $result;
1,433✔
2548
    }
2549

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

2566
        return false;
2✔
2567
    }
2568

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

2584
        if ($worksheet !== null) {
7,257✔
2585
            $worksheetName = $worksheet->getTitle();
7,256✔
2586

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

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

2641
        return $returnValue;
7,257✔
2642
    }
2643

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

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

2664
            // Named range?
2665
            $namedRange = ($worksheet === null) ? null : DefinedName::resolveName($range, $worksheet);
1✔
2666
            if ($namedRange === null) {
1✔
2667
                return ExcelError::REF();
1✔
2668
            }
2669

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

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

2705
        return $returnValue;
1✔
2706
    }
2707

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

2719
        return !$notImplemented;
3✔
2720
    }
2721

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

2737
        return $returnValue;
2✔
2738
    }
2739

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

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

2764
                    $args[$argumentId] = $this->getArgumentDefaultValue($methodArguments[$reflectedArgumentId]);
135✔
2765
                }
2766
            }
2767
        }
2768

2769
        return $args;
11,806✔
2770
    }
2771

2772
    private function getArgumentDefaultValue(ReflectionParameter $methodArgument): mixed
135✔
2773
    {
2774
        $defaultValue = null;
135✔
2775

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

2786
                    return $constantReflector->getValue();
2✔
2787
                }
2788

2789
                return constant($constantName);
×
2790
            }
2791
        }
2792

2793
        return $defaultValue;
134✔
2794
    }
2795

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

2811
                $reflectionMethod = new ReflectionMethod($className, $methodName);
280✔
2812
                $argumentCount = count($reflectionMethod->getParameters());
280✔
2813
                while (count($args) < $argumentCount - 1) {
280✔
2814
                    $args[] = null;
57✔
2815
                }
2816
            }
2817

2818
            $args[] = $cell;
280✔
2819
        }
2820

2821
        return $args;
11,824✔
2822
    }
2823

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

2832
            return $result;
×
2833
        }
2834

2835
        $definedNameValue = $namedRange->getValue();
137✔
2836
        $definedNameType = $namedRange->isFormula() ? 'Formula' : 'Range';
137✔
2837
        if ($definedNameType === 'Range') {
137✔
2838
            if (preg_match('/^(.*!)?(.*)$/', $definedNameValue, $matches) === 1) {
132✔
2839
                $matches2 = trim($matches[2]);
132✔
2840
                $matches2 = preg_replace('/ +/', ' ∩ ', $matches2) ?? $matches2;
132✔
2841
                $matches2 = preg_replace('/,/', ' ∪ ', $matches2) ?? $matches2;
132✔
2842
                $definedNameValue = $matches[1] . $matches2;
132✔
2843
            }
2844
        }
2845
        $definedNameWorksheet = $namedRange->getWorksheet();
137✔
2846

2847
        if ($definedNameValue[0] !== '=') {
137✔
2848
            $definedNameValue = '=' . $definedNameValue;
114✔
2849
        }
2850

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

2853
        $originalCoordinate = $cell->getCoordinate();
137✔
2854
        $recursiveCalculationCell = ($definedNameType !== 'Formula' && $definedNameWorksheet !== null && $definedNameWorksheet !== $cellWorksheet)
137✔
2855
            ? $definedNameWorksheet->getCell('A1')
20✔
2856
            : $cell;
126✔
2857
        $recursiveCalculationCellAddress = $recursiveCalculationCell->getCoordinate();
137✔
2858

2859
        // Adjust relative references in ranges and formulae so that we execute the calculation for the correct rows and columns
2860
        $definedNameValue = ReferenceHelper::getInstance()
137✔
2861
            ->updateFormulaReferencesAnyWorksheet(
137✔
2862
                $definedNameValue,
137✔
2863
                Coordinate::columnIndexFromString(
137✔
2864
                    $cell->getColumn()
137✔
2865
                ) - 1,
137✔
2866
                $cell->getRow() - 1
137✔
2867
            );
137✔
2868

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

2871
        $recursiveCalculator = new self($this->spreadsheet);
137✔
2872
        $recursiveCalculator->getDebugLog()->setWriteDebugLog($this->getDebugLog()->getWriteDebugLog());
137✔
2873
        $recursiveCalculator->getDebugLog()->setEchoDebugLog($this->getDebugLog()->getEchoDebugLog());
137✔
2874
        $result = $recursiveCalculator->_calculateFormulaValue($definedNameValue, $recursiveCalculationCellAddress, $recursiveCalculationCell, true);
137✔
2875
        $cellWorksheet->getCell($originalCoordinate);
137✔
2876

2877
        if ($this->getDebugLog()->getWriteDebugLog()) {
137✔
2878
            $this->debugLog->mergeDebugLog(array_slice($recursiveCalculator->getDebugLog()->getLog(), 3));
×
2879
            $this->debugLog->writeDebugLog('Evaluation Result for Named %s %s is %s', $definedNameType, $namedRange->getName(), $this->showTypeDetails($result));
×
2880
        }
2881

2882
        $y = $namedRange->getWorksheet()?->getTitle();
137✔
2883
        $x = $namedRange->getLocalOnly();
137✔
2884
        if ($x && $y !== null) {
137✔
2885
            $stack->push('Defined Name', $result, "'$y'!" . $namedRange->getName());
20✔
2886
        } else {
2887
            $stack->push('Defined Name', $result, $namedRange->getName());
118✔
2888
        }
2889

2890
        return $result;
137✔
2891
    }
2892

2893
    public function setSuppressFormulaErrors(bool $suppressFormulaErrors): self
12✔
2894
    {
2895
        $this->suppressFormulaErrors = $suppressFormulaErrors;
12✔
2896

2897
        return $this;
12✔
2898
    }
2899

2900
    public function getSuppressFormulaErrors(): bool
14✔
2901
    {
2902
        return $this->suppressFormulaErrors;
14✔
2903
    }
2904

2905
    public static function boolToString(mixed $operand1): mixed
33✔
2906
    {
2907
        if (is_bool($operand1)) {
33✔
2908
            $operand1 = ($operand1) ? self::$localeBoolean['TRUE'] : self::$localeBoolean['FALSE'];
1✔
2909
        } elseif ($operand1 === null) {
33✔
2910
            $operand1 = '';
1✔
2911
        }
2912

2913
        return $operand1;
33✔
2914
    }
2915

2916
    private static function isNumericOrBool(mixed $operand): bool
42✔
2917
    {
2918
        return is_numeric($operand) || is_bool($operand);
42✔
2919
    }
2920

2921
    private static function makeError(mixed $operand = ''): string
3✔
2922
    {
2923
        return (is_string($operand) && Information\ErrorValue::isError($operand)) ? $operand : ExcelError::VALUE();
3✔
2924
    }
2925

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

2939
        return $retVal;
1,900✔
2940
    }
2941

2942
    public function getSpreadsheet(): ?Spreadsheet
2✔
2943
    {
2944
        return $this->spreadsheet;
2✔
2945
    }
2946
}
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