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

PHPOffice / PhpSpreadsheet / 17242911923

26 Aug 2025 03:29PM UTC coverage: 95.096% (-0.006%) from 95.102%
17242911923

Pull #4596

github

web-flow
Merge 81759448e into 3c28bf455
Pull Request #4596: WIP Some Additional Support for Intersection and Union

25 of 30 new or added lines in 2 files covered. (83.33%)

76 existing lines in 1 file now uncovered.

40119 of 42188 relevant lines covered (95.1%)

346.88 hits per line

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

87.48
/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
164
    {
165
        return array_key_exists($key, self::EXCEL_CONSTANTS);
20✔
166
    }
167

168
    public static function getExcelConstants(string $key): bool|null
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)
194
    {
195
        $this->spreadsheet = $spreadsheet;
10,664✔
196
        $this->cyclicReferenceStack = new CyclicReferenceStack();
10,664✔
197
        $this->debugLog = new Logger($this->cyclicReferenceStack);
10,664✔
198
        $this->branchPruner = new BranchPruner($this->branchPruningEnabled);
10,664✔
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
208
    {
209
        if ($spreadsheet !== null) {
13,130✔
210
            return $spreadsheet->getCalculationEngine();
9,363✔
211
        }
212

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

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

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

231
        return null;
130✔
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
239
    {
240
        $this->clearCalculationCache();
210✔
241
        $this->branchPruner->clearBranchStore();
210✔
242
    }
243

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

252
    /**
253
     * __clone implementation. Cloning should not be allowed in a Singleton!
254
     */
255
    final public function __clone()
256
    {
257
        throw new Exception('Cloning the calculation engine is not allowed!');
×
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
268
    {
269
        if (
270
            ($returnType == self::RETURN_ARRAY_AS_VALUE)
580✔
271
            || ($returnType == self::RETURN_ARRAY_AS_ERROR)
580✔
272
            || ($returnType == self::RETURN_ARRAY_AS_ARRAY)
580✔
273
        ) {
274
            self::$returnArrayAsType = $returnType;
580✔
275

276
            return true;
580✔
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
288
    {
289
        return self::$returnArrayAsType;
580✔
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
300
    {
301
        if (
302
            ($returnType == self::RETURN_ARRAY_AS_VALUE)
373✔
303
            || ($returnType == self::RETURN_ARRAY_AS_ERROR)
373✔
304
            || ($returnType == self::RETURN_ARRAY_AS_ARRAY)
373✔
305
        ) {
306
            $this->instanceArrayReturnType = $returnType;
373✔
307

308
            return true;
373✔
309
        }
310

311
        return false;
×
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
320
    {
321
        return $this->instanceArrayReturnType ?? self::$returnArrayAsType;
8,903✔
322
    }
323

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

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

340
        return $this;
8✔
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
363
    {
364
        $this->calculationCache = [];
220✔
365
    }
366

367
    /**
368
     * Clear calculation cache for a specified worksheet.
369
     */
370
    public function clearCalculationCacheForWorksheet(string $worksheetName): void
371
    {
372
        if (isset($this->calculationCache[$worksheetName])) {
86✔
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
381
    {
382
        if (isset($this->calculationCache[$fromWorksheetName])) {
1,430✔
383
            $this->calculationCache[$toWorksheetName] = &$this->calculationCache[$fromWorksheetName];
×
384
            unset($this->calculationCache[$fromWorksheetName]);
×
385
        }
386
    }
387

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

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

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

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

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

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

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

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

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

447
        return $value;
10,887✔
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
457
    {
458
        try {
459
            return $this->calculateCellValue($cell);
×
460
        } catch (\Exception $e) {
×
461
            throw new Exception($e->getMessage());
×
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
472
    {
473
        if ($cell === null) {
8,150✔
474
            return null;
×
475
        }
476

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

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

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

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

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

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

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

548
        return $result;
7,919✔
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
559
    {
560
        $formula = preg_replace_callback(
8,123✔
561
            self::CALCULATION_REGEXP_CELLREF_SPILL,
8,123✔
562
            fn (array $matches) => 'ANCHORARRAY(' . substr($matches[0], 0, -1) . ')',
8,123✔
563
            $formula
8,123✔
564
        ) ?? $formula;
8,123✔
565
        //    Basic validation that this is indeed a formula
566
        //    We return an empty array if not
567
        $formula = trim($formula);
8,123✔
568
        if ((!isset($formula[0])) || ($formula[0] != '=')) {
8,123✔
569
            return [];
×
570
        }
571
        $formula = ltrim(substr($formula, 1));
8,123✔
572
        if (!isset($formula[0])) {
8,123✔
573
            return [];
×
574
        }
575

576
        //    Parse the formula and return the token stack
577
        return $this->internalParseFormula($formula);
8,123✔
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
588
    {
589
        //    Initialise the logging settings
590
        $this->formulaError = null;
2,484✔
591
        $this->debugLog->clearLog();
2,484✔
592
        $this->cyclicReferenceStack->clear();
2,484✔
593

594
        $resetCache = $this->getCalculationCacheEnabled();
2,484✔
595
        if ($this->spreadsheet !== null && $cellID === null && $cell === null) {
2,484✔
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;
2,310✔
602
        }
603

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

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

616
        return $result;
2,483✔
617
    }
618

619
    public function getValueFromCache(string $cellReference, mixed &$cellValue): bool
620
    {
621
        $this->debugLog->writeDebugLog('Testing cache value for cell %s', $cellReference);
8,304✔
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,304✔
625
            $this->debugLog->writeDebugLog('Retrieving value for cell %s from cache', $cellReference);
346✔
626
            // Return the cached result
627

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

630
            return true;
346✔
631
        }
632

633
        return false;
8,304✔
634
    }
635

636
    public function saveValueToCache(string $cellReference, mixed $cellValue): void
637
    {
638
        if ($this->calculationCacheEnabled) {
8,074✔
639
            $this->calculationCache[$cellReference] = $cellValue;
8,065✔
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
652
    {
653
        $cellValue = null;
12,023✔
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,023✔
657
            return self::wrapResult((string) $formula);
1✔
658
        }
659

660
        if (preg_match('/^=\s*cmd\s*\|/miu', $formula) !== 0) {
12,023✔
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,023✔
667
        if ($formula === '' || $formula[0] !== '=') {
12,023✔
668
            return self::wrapResult($formula);
2✔
669
        }
670
        $formula = ltrim(substr($formula, 1));
12,023✔
671
        if (!isset($formula[0])) {
12,023✔
672
            return self::wrapResult($formula);
6✔
673
        }
674

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

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

684
        if (($wsTitle[0] !== "\x00") && ($this->cyclicReferenceStack->onStack($wsCellReference))) {
12,022✔
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,022✔
705
        //    Parse the formula onto the token stack and calculate the value
706
        $this->cyclicReferenceStack->push($wsCellReference);
12,022✔
707

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

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

716
        //    Return the calculated value
717
        return $cellValue;
11,790✔
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
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)) {
68✔
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)) {
55✔
754
            [$matrixRows, $matrixColumns] = self::getMatrixDimensions($operand1);
17✔
755
            $operand2 = array_fill(0, $matrixRows, array_fill(0, $matrixColumns, $operand2));
17✔
756
            $resize = 0;
17✔
757
        }
758

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

767
        if ($resize == 2) {
68✔
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) {
45✔
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);
68✔
777
        [$matrix2Rows, $matrix2Columns] = self::getMatrixDimensions($operand2);
68✔
778

779
        return [$matrix1Rows, $matrix1Columns, $matrix2Rows, $matrix2Columns];
68✔
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
790
    {
791
        $matrixRows = count($matrix);
110✔
792
        $matrixColumns = 0;
110✔
793
        foreach ($matrix as $rowKey => $rowValue) {
110✔
794
            if (!is_array($rowValue)) {
108✔
795
                $matrix[$rowKey] = [$rowValue];
4✔
796
                $matrixColumns = max(1, $matrixColumns);
4✔
797
            } else {
798
                $matrix[$rowKey] = array_values($rowValue);
104✔
799
                $matrixColumns = max(count($rowValue), $matrixColumns);
104✔
800
            }
801
        }
802
        $matrix = array_values($matrix);
110✔
803

804
        return [$matrixRows, $matrixColumns];
110✔
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
818
    {
819
        if (($matrix2Columns < $matrix1Columns) || ($matrix2Rows < $matrix1Rows)) {
38✔
820
            if ($matrix2Rows < $matrix1Rows) {
×
821
                for ($i = $matrix2Rows; $i < $matrix1Rows; ++$i) {
×
822
                    unset($matrix1[$i]);
×
823
                }
824
            }
825
            if ($matrix2Columns < $matrix1Columns) {
×
826
                for ($i = 0; $i < $matrix1Rows; ++$i) {
×
827
                    for ($j = $matrix2Columns; $j < $matrix1Columns; ++$j) {
×
828
                        unset($matrix1[$i][$j]);
×
829
                    }
830
                }
831
            }
832
        }
833

834
        if (($matrix1Columns < $matrix2Columns) || ($matrix1Rows < $matrix2Rows)) {
38✔
835
            if ($matrix1Rows < $matrix2Rows) {
×
836
                for ($i = $matrix1Rows; $i < $matrix2Rows; ++$i) {
×
837
                    unset($matrix2[$i]);
×
838
                }
839
            }
840
            if ($matrix1Columns < $matrix2Columns) {
×
841
                for ($i = 0; $i < $matrix2Rows; ++$i) {
×
842
                    for ($j = $matrix1Columns; $j < $matrix2Columns; ++$j) {
×
843
                        unset($matrix2[$i][$j]);
×
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
861
    {
862
        if (($matrix2Columns < $matrix1Columns) || ($matrix2Rows < $matrix1Rows)) {
28✔
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)) {
28✔
881
            if ($matrix1Columns < $matrix2Columns) {
17✔
882
                for ($i = 0; $i < $matrix1Rows; ++$i) {
×
883
                    /** @var mixed[][] $matrix1 */
884
                    $x = ($matrix1Columns === 1) ? $matrix1[$i][0] : null;
×
885
                    for ($j = $matrix1Columns; $j < $matrix2Columns; ++$j) {
×
886
                        $matrix1[$i][$j] = $x;
×
887
                    }
888
                }
889
            }
890
            if ($matrix1Rows < $matrix2Rows) {
17✔
891
                $x = ($matrix1Rows === 1) ? $matrix1[0] : array_fill(0, $matrix1Columns, null);
17✔
892
                for ($i = $matrix1Rows; $i < $matrix2Rows; ++$i) {
17✔
893
                    $matrix1[$i] = $x;
17✔
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
905
    {
906
        if ($this->debugLog->getWriteDebugLog()) {
11,768✔
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);
11,768✔
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
943
    {
944
        if ($this->debugLog->getWriteDebugLog()) {
11,785✔
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;
11,782✔
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
983
    {
984
        //    Convert any Excel matrix references to the MKMATRIX() function
985
        if (str_contains($formula, self::FORMULA_OPEN_MATRIX_BRACE)) {
12,164✔
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)) {
798✔
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);
247✔
991
                //    Open and Closed counts used for trapping mismatched braces in the formula
992
                $openCount = $closeCount = 0;
247✔
993
                $notWithinQuotes = false;
247✔
994
                foreach ($temp as &$value) {
247✔
995
                    //    Only count/replace in alternating array entries
996
                    $notWithinQuotes = $notWithinQuotes === false;
247✔
997
                    if ($notWithinQuotes === true) {
247✔
998
                        $openCount += substr_count($value, self::FORMULA_OPEN_MATRIX_BRACE);
247✔
999
                        $closeCount += substr_count($value, self::FORMULA_CLOSE_MATRIX_BRACE);
247✔
1000
                        $value = str_replace(self::MATRIX_REPLACE_FROM, self::MATRIX_REPLACE_TO, $value);
247✔
1001
                    }
1002
                }
1003
                unset($value);
247✔
1004
                //    Then rebuild the formula string
1005
                $formula = implode(self::FORMULA_STRING_QUOTE, $temp);
247✔
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);
553✔
1009
                $closeCount = substr_count($formula, self::FORMULA_CLOSE_MATRIX_BRACE);
553✔
1010
                $formula = str_replace(self::MATRIX_REPLACE_FROM, self::MATRIX_REPLACE_TO, $formula);
553✔
1011
            }
1012
            //    Trap for mismatched braces and trigger an appropriate error
1013
            if ($openCount < $closeCount) {
798✔
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) {
798✔
1020
                if ($closeCount > 0) {
×
1021
                    return $this->raiseFormulaError("Formula Error: Mismatched matrix braces '{'");
×
1022
                }
1023

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

1028
        return $formula;
12,164✔
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
    /**
1056
     * @return array<int, mixed>|false
1057
     */
1058
    private function internalParseFormula(string $formula, ?Cell $cell = null): bool|array
1059
    {
1060
        if (($formula = $this->convertMatrixReferences(trim($formula))) === false) {
12,164✔
1061
            return false;
×
1062
        }
1063
        $phpSpreadsheetFunctions = &self::getFunctionsAddress();
12,164✔
1064

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

1069
        $regexpMatchString = '/^((?<string>' . self::CALCULATION_REGEXP_STRING
12,164✔
1070
                                . ')|(?<function>' . self::CALCULATION_REGEXP_FUNCTION
12,164✔
1071
                                . ')|(?<cellRef>' . self::CALCULATION_REGEXP_CELLREF
12,164✔
1072
                                . ')|(?<colRange>' . self::CALCULATION_REGEXP_COLUMN_RANGE
12,164✔
1073
                                . ')|(?<rowRange>' . self::CALCULATION_REGEXP_ROW_RANGE
12,164✔
1074
                                . ')|(?<number>' . self::CALCULATION_REGEXP_NUMBER
12,164✔
1075
                                . ')|(?<openBrace>' . self::CALCULATION_REGEXP_OPENBRACE
12,164✔
1076
                                . ')|(?<structuredReference>' . self::CALCULATION_REGEXP_STRUCTURED_REFERENCE
12,164✔
1077
                                . ')|(?<definedName>' . self::CALCULATION_REGEXP_DEFINEDNAME
12,164✔
1078
                                . ')|(?<error>' . self::CALCULATION_REGEXP_ERROR
12,164✔
1079
                                . '))/sui';
12,164✔
1080

1081
        //    Start with initialisation
1082
        $index = 0;
12,164✔
1083
        $stack = new Stack($this->branchPruner);
12,164✔
1084
        $output = [];
12,164✔
1085
        $expectingOperator = false; //    We use this test in syntax-checking the expression to determine when a
12,164✔
1086
        //        - is a negation or + is a positive operator rather than an operation
1087
        $expectingOperand = false; //    We use this test in syntax-checking the expression to determine whether an operand
12,164✔
1088
        //        should be null in a function call
1089

1090
        //    The guts of the lexical parser
1091
        //    Loop through the formula extracting each operator and operand in turn
1092
        while (true) {
12,164✔
1093
            // Branch pruning: we adapt the output item to the context (it will
1094
            // be used to limit its computation)
1095
            $this->branchPruner->initialiseForLoop();
12,164✔
1096

1097
            $opCharacter = $formula[$index]; //    Get the first character of the value at the current index position
12,164✔
1098
            if ($opCharacter === "\xe2") { // intersection or union
12,164✔
1099
                $opCharacter .= $formula[++$index];
3✔
1100
                $opCharacter .= $formula[++$index];
3✔
1101
            }
1102

1103
            // Check for two-character operators (e.g. >=, <=, <>)
1104
            if ((isset(self::COMPARISON_OPERATORS[$opCharacter])) && (strlen($formula) > $index) && isset($formula[$index + 1], self::COMPARISON_OPERATORS[$formula[$index + 1]])) {
12,164✔
1105
                $opCharacter .= $formula[++$index];
85✔
1106
            }
1107
            //    Find out if we're currently at the beginning of a number, variable, cell/row/column reference,
1108
            //         function, defined name, structured reference, parenthesis, error or operand
1109
            $isOperandOrFunction = (bool) preg_match($regexpMatchString, substr($formula, $index), $match);
12,164✔
1110

1111
            $expectingOperatorCopy = $expectingOperator;
12,164✔
1112
            if ($opCharacter === '-' && !$expectingOperator) {                //    Is it a negation instead of a minus?
12,164✔
1113
                //    Put a negation on the stack
1114
                $stack->push('Unary Operator', '~');
1,156✔
1115
                ++$index; //        and drop the negation symbol
1,156✔
1116
            } elseif ($opCharacter === '%' && $expectingOperator) {
12,164✔
1117
                //    Put a percentage on the stack
1118
                $stack->push('Unary Operator', '%');
11✔
1119
                ++$index;
11✔
1120
            } elseif ($opCharacter === '+' && !$expectingOperator) {            //    Positive (unary plus rather than binary operator plus) can be discarded?
12,164✔
1121
                ++$index; //    Drop the redundant plus symbol
7✔
1122
            } elseif ((($opCharacter === '~') /*|| ($opCharacter === '∩') || ($opCharacter === '∪')*/) && (!$isOperandOrFunction)) {
12,164✔
1123
                //    We have to explicitly deny a tilde, union or intersect because they are legal
1124
                return $this->raiseFormulaError("Formula Error: Illegal character '~'"); //        on the stack but not in the input expression
×
1125
            } elseif ((isset(self::CALCULATION_OPERATORS[$opCharacter]) || $isOperandOrFunction) && $expectingOperator) {    //    Are we putting an operator on the stack?
12,164✔
1126
                while (self::swapOperands($stack, $opCharacter)) {
1,844✔
1127
                    $output[] = $stack->pop(); //    Swap operands and higher precedence operators from the stack to the output
100✔
1128
                }
1129

1130
                //    Finally put our current operator onto the stack
1131
                $stack->push('Binary Operator', $opCharacter);
1,844✔
1132

1133
                ++$index;
1,844✔
1134
                $expectingOperator = false;
1,844✔
1135
            } elseif ($opCharacter === ')' && $expectingOperator) { //    Are we expecting to close a parenthesis?
12,164✔
1136
                $expectingOperand = false;
11,781✔
1137
                while (($o2 = $stack->pop()) && $o2['value'] !== '(') { //    Pop off the stack back to the last (
11,781✔
1138
                    $output[] = $o2;
1,401✔
1139
                }
1140
                $d = $stack->last(2);
11,781✔
1141

1142
                // Branch pruning we decrease the depth whether is it a function
1143
                // call or a parenthesis
1144
                $this->branchPruner->decrementDepth();
11,781✔
1145

1146
                if (is_array($d) && preg_match('/^' . self::CALCULATION_REGEXP_FUNCTION . '$/miu', StringHelper::convertToString($d['value']), $matches)) {
11,781✔
1147
                    //    Did this parenthesis just close a function?
1148
                    try {
1149
                        $this->branchPruner->closingBrace($d['value']);
11,776✔
1150
                    } catch (Exception $e) {
4✔
1151
                        return $this->raiseFormulaError($e->getMessage(), $e->getCode(), $e);
4✔
1152
                    }
1153

1154
                    $functionName = $matches[1]; //    Get the function name
11,776✔
1155
                    $d = $stack->pop();
11,776✔
1156
                    $argumentCount = $d['value'] ?? 0; //    See how many arguments there were (argument count is the next value stored on the stack)
11,776✔
1157
                    $output[] = $d; //    Dump the argument count on the output
11,776✔
1158
                    $output[] = $stack->pop(); //    Pop the function and push onto the output
11,776✔
1159
                    if (isset(self::$controlFunctions[$functionName])) {
11,776✔
1160
                        $expectedArgumentCount = self::$controlFunctions[$functionName]['argumentCount'];
819✔
1161
                    } elseif (isset($phpSpreadsheetFunctions[$functionName])) {
11,773✔
1162
                        $expectedArgumentCount = $phpSpreadsheetFunctions[$functionName]['argumentCount'];
11,773✔
1163
                    } else {    // did we somehow push a non-function on the stack? this should never happen
1164
                        return $this->raiseFormulaError('Formula Error: Internal error, non-function on stack');
×
1165
                    }
1166
                    //    Check the argument count
1167
                    $argumentCountError = false;
11,776✔
1168
                    $expectedArgumentCountString = null;
11,776✔
1169
                    if (is_numeric($expectedArgumentCount)) {
11,776✔
1170
                        if ($expectedArgumentCount < 0) {
5,929✔
1171
                            if ($argumentCount > abs($expectedArgumentCount + 0)) {
39✔
1172
                                $argumentCountError = true;
×
1173
                                $expectedArgumentCountString = 'no more than ' . abs($expectedArgumentCount + 0);
×
1174
                            }
1175
                        } else {
1176
                            if ($argumentCount != $expectedArgumentCount) {
5,892✔
1177
                                $argumentCountError = true;
142✔
1178
                                $expectedArgumentCountString = $expectedArgumentCount;
142✔
1179
                            }
1180
                        }
1181
                    } elseif (is_string($expectedArgumentCount) && $expectedArgumentCount !== '*') {
6,610✔
1182
                        if (1 !== preg_match('/(\d*)([-+,])(\d*)/', $expectedArgumentCount, $argMatch)) {
6,133✔
1183
                            $argMatch = ['', '', '', ''];
1✔
1184
                        }
1185
                        switch ($argMatch[2]) {
6,133✔
1186
                            case '+':
6,133✔
1187
                                if ($argumentCount < $argMatch[1]) {
1,175✔
1188
                                    $argumentCountError = true;
27✔
1189
                                    $expectedArgumentCountString = $argMatch[1] . ' or more ';
27✔
1190
                                }
1191

1192
                                break;
1,175✔
1193
                            case '-':
5,125✔
1194
                                if (($argumentCount < $argMatch[1]) || ($argumentCount > $argMatch[3])) {
905✔
1195
                                    $argumentCountError = true;
15✔
1196
                                    $expectedArgumentCountString = 'between ' . $argMatch[1] . ' and ' . $argMatch[3];
15✔
1197
                                }
1198

1199
                                break;
905✔
1200
                            case ',':
4,261✔
1201
                                if (($argumentCount != $argMatch[1]) && ($argumentCount != $argMatch[3])) {
4,261✔
1202
                                    $argumentCountError = true;
39✔
1203
                                    $expectedArgumentCountString = 'either ' . $argMatch[1] . ' or ' . $argMatch[3];
39✔
1204
                                }
1205

1206
                                break;
4,261✔
1207
                        }
1208
                    }
1209
                    if ($argumentCountError) {
11,776✔
1210
                        /** @var int $argumentCount */
1211
                        return $this->raiseFormulaError("Formula Error: Wrong number of arguments for $functionName() function: $argumentCount given, " . $expectedArgumentCountString . ' expected');
223✔
1212
                    }
1213
                }
1214
                ++$index;
11,561✔
1215
            } elseif ($opCharacter === ',') { // Is this the separator for function arguments?
12,164✔
1216
                try {
1217
                    $this->branchPruner->argumentSeparator();
8,028✔
1218
                } catch (Exception $e) {
×
1219
                    return $this->raiseFormulaError($e->getMessage(), $e->getCode(), $e);
×
1220
                }
1221

1222
                while (($o2 = $stack->pop()) && $o2['value'] !== '(') {        //    Pop off the stack back to the last (
8,028✔
1223
                    $output[] = $o2; // pop the argument expression stuff and push onto the output
1,473✔
1224
                }
1225
                //    If we've a comma when we're expecting an operand, then what we actually have is a null operand;
1226
                //        so push a null onto the stack
1227
                if (($expectingOperand) || (!$expectingOperator)) {
8,028✔
1228
                    $output[] = $stack->getStackItem('Empty Argument', null, 'NULL');
120✔
1229
                }
1230
                // make sure there was a function
1231
                $d = $stack->last(2);
8,028✔
1232
                /** @var string */
1233
                $temp = $d['value'] ?? '';
8,028✔
1234
                if (!preg_match('/^' . self::CALCULATION_REGEXP_FUNCTION . '$/miu', $temp, $matches)) {
8,028✔
1235
                    // Can we inject a dummy function at this point so that the braces at least have some context
1236
                    //     because at least the braces are paired up (at this stage in the formula)
1237
                    // MS Excel allows this if the content is cell references; but doesn't allow actual values,
1238
                    //    but at this point, we can't differentiate (so allow both)
1239
                    //return $this->raiseFormulaError('Formula Error: Unexpected ,');
NEW
1240
                    $stack->push('Binary Operator', '∪');
×
1241

NEW
1242
                    ++$index;
×
NEW
1243
                    $expectingOperator = false;
×
1244

NEW
1245
                    continue;
×
1246
                }
1247

1248
                /** @var array<string, int> $d */
1249
                $d = $stack->pop();
8,028✔
1250
                ++$d['value']; // increment the argument count
8,028✔
1251

1252
                $stack->pushStackItem($d);
8,028✔
1253
                $stack->push('Brace', '('); // put the ( back on, we'll need to pop back to it again
8,028✔
1254

1255
                $expectingOperator = false;
8,028✔
1256
                $expectingOperand = true;
8,028✔
1257
                ++$index;
8,028✔
1258
            } elseif ($opCharacter === '(' && !$expectingOperator) {
12,164✔
1259
                // Branch pruning: we go deeper
1260
                $this->branchPruner->incrementDepth();
36✔
1261
                $stack->push('Brace', '(', null);
36✔
1262
                ++$index;
36✔
1263
            } elseif ($isOperandOrFunction && !$expectingOperatorCopy) {
12,164✔
1264
                // do we now have a function/variable/number?
1265
                $expectingOperator = true;
12,160✔
1266
                $expectingOperand = false;
12,160✔
1267
                $val = $match[1] ?? ''; //* @phpstan-ignore-line
12,160✔
1268
                $length = strlen($val);
12,160✔
1269

1270
                if (preg_match('/^' . self::CALCULATION_REGEXP_FUNCTION . '$/miu', $val, $matches)) {
12,160✔
1271
                    $val = (string) preg_replace('/\s/u', '', $val);
11,782✔
1272
                    if (isset($phpSpreadsheetFunctions[strtoupper($matches[1])]) || isset(self::$controlFunctions[strtoupper($matches[1])])) {    // it's a function
11,782✔
1273
                        $valToUpper = strtoupper($val);
11,780✔
1274
                    } else {
1275
                        $valToUpper = 'NAME.ERROR(';
6✔
1276
                    }
1277
                    // here $matches[1] will contain values like "IF"
1278
                    // and $val "IF("
1279

1280
                    $this->branchPruner->functionCall($valToUpper);
11,782✔
1281

1282
                    $stack->push('Function', $valToUpper);
11,782✔
1283
                    // tests if the function is closed right after opening
1284
                    $ax = preg_match('/^\s*\)/u', substr($formula, $index + $length));
11,782✔
1285
                    if ($ax) {
11,782✔
1286
                        $stack->push('Operand Count for Function ' . $valToUpper . ')', 0);
324✔
1287
                        $expectingOperator = true;
324✔
1288
                    } else {
1289
                        $stack->push('Operand Count for Function ' . $valToUpper . ')', 1);
11,604✔
1290
                        $expectingOperator = false;
11,604✔
1291
                    }
1292
                    $stack->push('Brace', '(');
11,782✔
1293
                } elseif (preg_match('/^' . self::CALCULATION_REGEXP_CELLREF . '$/miu', $val, $matches)) {
11,959✔
1294
                    //    Watch for this case-change when modifying to allow cell references in different worksheets...
1295
                    //    Should only be applied to the actual cell column, not the worksheet name
1296
                    //    If the last entry on the stack was a : operator, then we have a cell range reference
1297
                    $testPrevOp = $stack->last(1);
7,059✔
1298
                    if ($testPrevOp !== null && $testPrevOp['value'] === ':') {
7,059✔
1299
                        //    If we have a worksheet reference, then we're playing with a 3D reference
1300
                        if ($matches[2] === '') {
1,260✔
1301
                            //    Otherwise, we 'inherit' the worksheet reference from the start cell reference
1302
                            //    The start of the cell range reference should be the last entry in $output
1303
                            $rangeStartCellRef = $output[count($output) - 1]['value'] ?? '';
1,256✔
1304
                            if ($rangeStartCellRef === ':') {
1,256✔
1305
                                // Do we have chained range operators?
1306
                                $rangeStartCellRef = $output[count($output) - 2]['value'] ?? '';
5✔
1307
                            }
1308
                            /** @var string $rangeStartCellRef */
1309
                            preg_match('/^' . self::CALCULATION_REGEXP_CELLREF . '$/miu', $rangeStartCellRef, $rangeStartMatches);
1,256✔
1310
                            if (array_key_exists(2, $rangeStartMatches)) {
1,256✔
1311
                                if ($rangeStartMatches[2] > '') {
1,251✔
1312
                                    $val = $rangeStartMatches[2] . '!' . $val;
1,234✔
1313
                                }
1314
                            } else {
1315
                                $val = ExcelError::REF();
5✔
1316
                            }
1317
                        } else {
1318
                            $rangeStartCellRef = $output[count($output) - 1]['value'] ?? '';
4✔
1319
                            if ($rangeStartCellRef === ':') {
4✔
1320
                                // Do we have chained range operators?
UNCOV
1321
                                $rangeStartCellRef = $output[count($output) - 2]['value'] ?? '';
×
1322
                            }
1323
                            /** @var string $rangeStartCellRef */
1324
                            preg_match('/^' . self::CALCULATION_REGEXP_CELLREF . '$/miu', $rangeStartCellRef, $rangeStartMatches);
4✔
1325
                            if (isset($rangeStartMatches[2]) && $rangeStartMatches[2] !== $matches[2]) {
4✔
1326
                                return $this->raiseFormulaError('3D Range references are not yet supported');
2✔
1327
                            }
1328
                        }
1329
                    } elseif (!str_contains($val, '!') && $pCellParent !== null) {
7,054✔
1330
                        $worksheet = $pCellParent->getTitle();
6,838✔
1331
                        $val = "'{$worksheet}'!{$val}";
6,838✔
1332
                    }
1333
                    // unescape any apostrophes or double quotes in worksheet name
1334
                    $val = str_replace(["''", '""'], ["'", '"'], $val);
7,059✔
1335
                    $outputItem = $stack->getStackItem('Cell Reference', $val, $val);
7,059✔
1336

1337
                    $output[] = $outputItem;
7,059✔
1338
                } elseif (preg_match('/^' . self::CALCULATION_REGEXP_STRUCTURED_REFERENCE . '$/miu', $val, $matches)) {
6,379✔
1339
                    try {
1340
                        $structuredReference = Operands\StructuredReference::fromParser($formula, $index, $matches);
76✔
UNCOV
1341
                    } catch (Exception $e) {
×
UNCOV
1342
                        return $this->raiseFormulaError($e->getMessage(), $e->getCode(), $e);
×
1343
                    }
1344

1345
                    $val = $structuredReference->value();
76✔
1346
                    $length = strlen($val);
76✔
1347
                    $outputItem = $stack->getStackItem(Operands\StructuredReference::NAME, $structuredReference, null);
76✔
1348

1349
                    $output[] = $outputItem;
76✔
1350
                    $expectingOperator = true;
76✔
1351
                } else {
1352
                    // it's a variable, constant, string, number or boolean
1353
                    $localeConstant = false;
6,312✔
1354
                    $stackItemType = 'Value';
6,312✔
1355
                    $stackItemReference = null;
6,312✔
1356

1357
                    //    If the last entry on the stack was a : operator, then we may have a row or column range reference
1358
                    $testPrevOp = $stack->last(1);
6,312✔
1359
                    if ($testPrevOp !== null && $testPrevOp['value'] === ':') {
6,312✔
1360
                        $stackItemType = 'Cell Reference';
38✔
1361

1362
                        if (
1363
                            !is_numeric($val)
38✔
1364
                            && ((ctype_alpha($val) === false || strlen($val) > 3))
38✔
1365
                            && (preg_match('/^' . self::CALCULATION_REGEXP_DEFINEDNAME . '$/mui', $val) !== false)
38✔
1366
                            && ($this->spreadsheet === null || $this->spreadsheet->getNamedRange($val) !== null)
38✔
1367
                        ) {
1368
                            $namedRange = ($this->spreadsheet === null) ? null : $this->spreadsheet->getNamedRange($val);
10✔
1369
                            if ($namedRange !== null) {
10✔
1370
                                $stackItemType = 'Defined Name';
4✔
1371
                                $address = str_replace('$', '', $namedRange->getValue());
4✔
1372
                                $stackItemReference = $val;
4✔
1373
                                if (str_contains($address, ':')) {
4✔
1374
                                    // We'll need to manipulate the stack for an actual named range rather than a named cell
1375
                                    $fromTo = explode(':', $address);
3✔
1376
                                    $to = array_pop($fromTo);
3✔
1377
                                    foreach ($fromTo as $from) {
3✔
1378
                                        $output[] = $stack->getStackItem($stackItemType, $from, $stackItemReference);
3✔
1379
                                        $output[] = $stack->getStackItem('Binary Operator', ':');
3✔
1380
                                    }
1381
                                    $address = $to;
3✔
1382
                                }
1383
                                $val = $address;
4✔
1384
                            }
1385
                        } elseif ($val === ExcelError::REF()) {
34✔
1386
                            $stackItemReference = $val;
3✔
1387
                        } else {
1388
                            /** @var non-empty-string $startRowColRef */
1389
                            $startRowColRef = $output[count($output) - 1]['value'] ?? '';
31✔
1390
                            [$rangeWS1, $startRowColRef] = Worksheet::extractSheetTitle($startRowColRef, true);
31✔
1391
                            $rangeSheetRef = $rangeWS1;
31✔
1392
                            if ($rangeWS1 !== '') {
31✔
1393
                                $rangeWS1 .= '!';
19✔
1394
                            }
1395
                            if (str_starts_with($rangeSheetRef, "'")) {
31✔
1396
                                $rangeSheetRef = Worksheet::unApostrophizeTitle($rangeSheetRef);
18✔
1397
                            }
1398
                            [$rangeWS2, $val] = Worksheet::extractSheetTitle($val, true);
31✔
1399
                            if ($rangeWS2 !== '') {
31✔
UNCOV
1400
                                $rangeWS2 .= '!';
×
1401
                            } else {
1402
                                $rangeWS2 = $rangeWS1;
31✔
1403
                            }
1404

1405
                            $refSheet = $pCellParent;
31✔
1406
                            if ($pCellParent !== null && $rangeSheetRef !== '' && $rangeSheetRef !== $pCellParent->getTitle()) {
31✔
1407
                                $refSheet = $pCellParent->getParentOrThrow()->getSheetByName($rangeSheetRef);
4✔
1408
                            }
1409

1410
                            if (ctype_digit($val) && $val <= 1048576) {
31✔
1411
                                //    Row range
1412
                                $stackItemType = 'Row Reference';
10✔
1413
                                $valx = $val;
10✔
1414
                                $endRowColRef = ($refSheet !== null) ? $refSheet->getHighestDataColumn($valx) : AddressRange::MAX_COLUMN; //    Max 16,384 columns for Excel2007
10✔
1415
                                $val = "{$rangeWS2}{$endRowColRef}{$val}";
10✔
1416
                            } elseif (ctype_alpha($val) && strlen($val) <= 3) {
21✔
1417
                                //    Column range
1418
                                $stackItemType = 'Column Reference';
15✔
1419
                                $endRowColRef = ($refSheet !== null) ? $refSheet->getHighestDataRow($val) : AddressRange::MAX_ROW; //    Max 1,048,576 rows for Excel2007
15✔
1420
                                $val = "{$rangeWS2}{$val}{$endRowColRef}";
15✔
1421
                            }
1422
                            $stackItemReference = $val;
31✔
1423
                        }
1424
                    } elseif ($opCharacter === self::FORMULA_STRING_QUOTE) {
6,307✔
1425
                        //    UnEscape any quotes within the string
1426
                        $val = self::wrapResult(str_replace('""', self::FORMULA_STRING_QUOTE, StringHelper::convertToString(self::unwrapResult($val))));
2,829✔
1427
                    } elseif (isset(self::EXCEL_CONSTANTS[trim(strtoupper($val))])) {
4,687✔
1428
                        $stackItemType = 'Constant';
559✔
1429
                        $excelConstant = trim(strtoupper($val));
559✔
1430
                        $val = self::EXCEL_CONSTANTS[$excelConstant];
559✔
1431
                        $stackItemReference = $excelConstant;
559✔
1432
                    } elseif (($localeConstant = array_search(trim(strtoupper($val)), self::$localeBoolean)) !== false) {
4,398✔
1433
                        $stackItemType = 'Constant';
39✔
1434
                        $val = self::EXCEL_CONSTANTS[$localeConstant];
39✔
1435
                        $stackItemReference = $localeConstant;
39✔
1436
                    } elseif (
1437
                        preg_match('/^' . self::CALCULATION_REGEXP_ROW_RANGE . '/miu', substr($formula, $index), $rowRangeReference)
4,379✔
1438
                    ) {
1439
                        $val = $rowRangeReference[1];
10✔
1440
                        $length = strlen($rowRangeReference[1]);
10✔
1441
                        $stackItemType = 'Row Reference';
10✔
1442
                        // unescape any apostrophes or double quotes in worksheet name
1443
                        $val = str_replace(["''", '""'], ["'", '"'], $val);
10✔
1444
                        $column = 'A';
10✔
1445
                        if (($testPrevOp !== null && $testPrevOp['value'] === ':') && $pCellParent !== null) {
10✔
UNCOV
1446
                            $column = $pCellParent->getHighestDataColumn($val);
×
1447
                        }
1448
                        $val = "{$rowRangeReference[2]}{$column}{$rowRangeReference[7]}";
10✔
1449
                        $stackItemReference = $val;
10✔
1450
                    } elseif (
1451
                        preg_match('/^' . self::CALCULATION_REGEXP_COLUMN_RANGE . '/miu', substr($formula, $index), $columnRangeReference)
4,372✔
1452
                    ) {
1453
                        $val = $columnRangeReference[1];
15✔
1454
                        $length = strlen($val);
15✔
1455
                        $stackItemType = 'Column Reference';
15✔
1456
                        // unescape any apostrophes or double quotes in worksheet name
1457
                        $val = str_replace(["''", '""'], ["'", '"'], $val);
15✔
1458
                        $row = '1';
15✔
1459
                        if (($testPrevOp !== null && $testPrevOp['value'] === ':') && $pCellParent !== null) {
15✔
UNCOV
1460
                            $row = $pCellParent->getHighestDataRow($val);
×
1461
                        }
1462
                        $val = "{$val}{$row}";
15✔
1463
                        $stackItemReference = $val;
15✔
1464
                    } elseif (preg_match('/^' . self::CALCULATION_REGEXP_DEFINEDNAME . '.*/miu', $val, $match)) {
4,357✔
1465
                        $stackItemType = 'Defined Name';
166✔
1466
                        $stackItemReference = $val;
166✔
1467
                    } elseif (is_numeric($val)) {
4,221✔
1468
                        if ((str_contains((string) $val, '.')) || (stripos((string) $val, 'e') !== false) || ($val > PHP_INT_MAX) || ($val < -PHP_INT_MAX)) {
4,215✔
1469
                            $val = (float) $val;
1,681✔
1470
                        } else {
1471
                            $val = (int) $val;
3,457✔
1472
                        }
1473
                    }
1474

1475
                    $details = $stack->getStackItem($stackItemType, $val, $stackItemReference);
6,312✔
1476
                    if ($localeConstant) {
6,312✔
1477
                        $details['localeValue'] = $localeConstant;
39✔
1478
                    }
1479
                    $output[] = $details;
6,312✔
1480
                }
1481
                $index += $length;
12,160✔
1482
            } elseif ($opCharacter === '$') { // absolute row or column range
95✔
1483
                ++$index;
6✔
1484
            } elseif ($opCharacter === ')') { // miscellaneous error checking
89✔
1485
                if ($expectingOperand) {
83✔
1486
                    $output[] = $stack->getStackItem('Empty Argument', null, 'NULL');
83✔
1487
                    $expectingOperand = false;
83✔
1488
                    $expectingOperator = true;
83✔
1489
                } else {
UNCOV
1490
                    return $this->raiseFormulaError("Formula Error: Unexpected ')'");
×
1491
                }
1492
            } elseif (isset(self::CALCULATION_OPERATORS[$opCharacter]) && !$expectingOperator) {
6✔
1493
                return $this->raiseFormulaError("Formula Error: Unexpected operator '$opCharacter'");
×
1494
            } else {    // I don't even want to know what you did to get here
1495
                return $this->raiseFormulaError('Formula Error: An unexpected error occurred');
6✔
1496
            }
1497
            //    Test for end of formula string
1498
            if ($index == strlen($formula)) {
12,160✔
1499
                //    Did we end with an operator?.
1500
                //    Only valid for the % unary operator
1501
                if ((isset(self::CALCULATION_OPERATORS[$opCharacter])) && ($opCharacter != '%')) {
11,936✔
1502
                    return $this->raiseFormulaError("Formula Error: Operator '$opCharacter' has no operands");
1✔
1503
                }
1504

1505
                break;
11,935✔
1506
            }
1507
            //    Ignore white space
1508
            while (($formula[$index] === "\n") || ($formula[$index] === "\r")) {
12,128✔
UNCOV
1509
                ++$index;
×
1510
            }
1511

1512
            if ($formula[$index] === ' ') {
12,128✔
1513
                while ($formula[$index] === ' ') {
2,072✔
1514
                    ++$index;
2,072✔
1515
                }
1516

1517
                //    If we're expecting an operator, but only have a space between the previous and next operands (and both are
1518
                //        Cell References, Defined Names or Structured References) then we have an INTERSECTION operator
1519
                $countOutputMinus1 = count($output) - 1;
2,072✔
1520
                if (
1521
                    ($expectingOperator)
2,072✔
1522
                    && array_key_exists($countOutputMinus1, $output)
2,072✔
1523
                    && is_array($output[$countOutputMinus1])
2,072✔
1524
                    && array_key_exists('type', $output[$countOutputMinus1])
2,072✔
1525
                    && (
1526
                        (preg_match('/^' . self::CALCULATION_REGEXP_CELLREF . '.*/miu', substr($formula, $index), $match))
2,072✔
1527
                            && ($output[$countOutputMinus1]['type'] === 'Cell Reference')
2,072✔
1528
                        || (preg_match('/^' . self::CALCULATION_REGEXP_DEFINEDNAME . '.*/miu', substr($formula, $index), $match))
2,072✔
1529
                            && ($output[$countOutputMinus1]['type'] === 'Defined Name' || $output[$countOutputMinus1]['type'] === 'Value')
2,072✔
1530
                        || (preg_match('/^' . self::CALCULATION_REGEXP_STRUCTURED_REFERENCE . '.*/miu', substr($formula, $index), $match))
2,072✔
1531
                            && ($output[$countOutputMinus1]['type'] === Operands\StructuredReference::NAME || $output[$countOutputMinus1]['type'] === 'Value')
2,072✔
1532
                    )
1533
                ) {
1534
                    while (self::swapOperands($stack, $opCharacter)) {
20✔
1535
                        $output[] = $stack->pop(); //    Swap operands and higher precedence operators from the stack to the output
13✔
1536
                    }
1537
                    $stack->push('Binary Operator', '∩'); //    Put an Intersect Operator on the stack
20✔
1538
                    $expectingOperator = false;
20✔
1539
                }
1540
            }
1541
        }
1542

1543
        while (($op = $stack->pop()) !== null) {
11,935✔
1544
            // pop everything off the stack and push onto output
1545
            if ($op['value'] == '(') {
753✔
1546
                return $this->raiseFormulaError("Formula Error: Expecting ')'"); // if there are any opening braces on the stack, then braces were unbalanced
4✔
1547
            }
1548
            $output[] = $op;
751✔
1549
        }
1550

1551
        return $output;
11,933✔
1552
    }
1553

1554
    /** @param mixed[] $operandData */
1555
    private static function dataTestReference(array &$operandData): mixed
1556
    {
1557
        $operand = $operandData['value'];
1,728✔
1558
        if (($operandData['reference'] === null) && (is_array($operand))) {
1,728✔
1559
            $rKeys = array_keys($operand);
45✔
1560
            $rowKey = array_shift($rKeys);
45✔
1561
            if (is_array($operand[$rowKey]) === false) {
45✔
1562
                $operandData['value'] = $operand[$rowKey];
6✔
1563

1564
                return $operand[$rowKey];
6✔
1565
            }
1566

1567
            $cKeys = array_keys(array_keys($operand[$rowKey]));
43✔
1568
            $colKey = array_shift($cKeys);
43✔
1569
            if (ctype_upper("$colKey")) {
43✔
UNCOV
1570
                $operandData['reference'] = $colKey . $rowKey;
×
1571
            }
1572
        }
1573

1574
        return $operand;
1,728✔
1575
    }
1576

1577
    private static int $matchIndex8 = 8;
1578

1579
    private static int $matchIndex9 = 9;
1580

1581
    private static int $matchIndex10 = 10;
1582

1583
    /**
1584
     * @param array<mixed>|false $tokens
1585
     *
1586
     * @return array<int, mixed>|false|string
1587
     */
1588
    private function processTokenStack(false|array $tokens, ?string $cellID = null, ?Cell $cell = null)
1589
    {
1590
        if ($tokens === false) {
11,799✔
1591
            return false;
2✔
1592
        }
1593
        $phpSpreadsheetFunctions = &self::getFunctionsAddress();
11,798✔
1594

1595
        //    If we're using cell caching, then $pCell may well be flushed back to the cache (which detaches the parent cell collection),
1596
        //        so we store the parent cell collection so that we can re-attach it when necessary
1597
        $pCellWorksheet = ($cell !== null) ? $cell->getWorksheet() : null;
11,798✔
1598
        $originalCoordinate = $cell?->getCoordinate();
11,798✔
1599
        $pCellParent = ($cell !== null) ? $cell->getParent() : null;
11,798✔
1600
        $stack = new Stack($this->branchPruner);
11,798✔
1601

1602
        // Stores branches that have been pruned
1603
        $fakedForBranchPruning = [];
11,798✔
1604
        // help us to know when pruning ['branchTestId' => true/false]
1605
        $branchStore = [];
11,798✔
1606
        //    Loop through each token in turn
1607
        foreach ($tokens as $tokenIdx => $tokenData) {
11,798✔
1608
            /** @var mixed[] $tokenData */
1609
            $this->processingAnchorArray = false;
11,798✔
1610
            if ($tokenData['type'] === 'Cell Reference' && isset($tokens[$tokenIdx + 1]) && $tokens[$tokenIdx + 1]['type'] === 'Operand Count for Function ANCHORARRAY()') { //* @phpstan-ignore-line
11,798✔
1611
                $this->processingAnchorArray = true;
6✔
1612
            }
1613
            $token = $tokenData['value'];
11,798✔
1614
            // Branch pruning: skip useless resolutions
1615
            /** @var ?string */
1616
            $storeKey = $tokenData['storeKey'] ?? null;
11,798✔
1617
            if ($this->branchPruningEnabled && isset($tokenData['onlyIf'])) {
11,798✔
1618
                /** @var string */
1619
                $onlyIfStoreKey = $tokenData['onlyIf'];
83✔
1620
                $storeValue = $branchStore[$onlyIfStoreKey] ?? null;
83✔
1621
                $storeValueAsBool = ($storeValue === null)
83✔
1622
                    ? true : (bool) Functions::flattenSingleValue($storeValue);
83✔
1623
                if (is_array($storeValue)) {
83✔
1624
                    $wrappedItem = end($storeValue);
57✔
1625
                    $storeValue = is_array($wrappedItem) ? end($wrappedItem) : $wrappedItem;
57✔
1626
                }
1627

1628
                if (
1629
                    (isset($storeValue) || $tokenData['reference'] === 'NULL')
83✔
1630
                    && (!$storeValueAsBool || Information\ErrorValue::isError($storeValue) || ($storeValue === 'Pruned branch'))
83✔
1631
                ) {
1632
                    // If branching value is not true, we don't need to compute
1633
                    /** @var string $onlyIfStoreKey */
1634
                    if (!isset($fakedForBranchPruning['onlyIf-' . $onlyIfStoreKey])) {
60✔
1635
                        /** @var string $token */
1636
                        $stack->push('Value', 'Pruned branch (only if ' . $onlyIfStoreKey . ') ' . $token);
58✔
1637
                        $fakedForBranchPruning['onlyIf-' . $onlyIfStoreKey] = true;
58✔
1638
                    }
1639

1640
                    if (isset($storeKey)) {
60✔
1641
                        // We are processing an if condition
1642
                        // We cascade the pruning to the depending branches
1643
                        $branchStore[$storeKey] = 'Pruned branch';
3✔
1644
                        $fakedForBranchPruning['onlyIfNot-' . $storeKey] = true;
3✔
1645
                        $fakedForBranchPruning['onlyIf-' . $storeKey] = true;
3✔
1646
                    }
1647

1648
                    continue;
60✔
1649
                }
1650
            }
1651

1652
            if ($this->branchPruningEnabled && isset($tokenData['onlyIfNot'])) {
11,798✔
1653
                /** @var string */
1654
                $onlyIfNotStoreKey = $tokenData['onlyIfNot'];
78✔
1655
                $storeValue = $branchStore[$onlyIfNotStoreKey] ?? null;
78✔
1656
                $storeValueAsBool = ($storeValue === null)
78✔
1657
                    ? true : (bool) Functions::flattenSingleValue($storeValue);
78✔
1658
                if (is_array($storeValue)) {
78✔
1659
                    $wrappedItem = end($storeValue);
52✔
1660
                    $storeValue = is_array($wrappedItem) ? end($wrappedItem) : $wrappedItem;
52✔
1661
                }
1662

1663
                if (
1664
                    (isset($storeValue) || $tokenData['reference'] === 'NULL')
78✔
1665
                    && ($storeValueAsBool || Information\ErrorValue::isError($storeValue) || ($storeValue === 'Pruned branch'))
78✔
1666
                ) {
1667
                    // If branching value is true, we don't need to compute
1668
                    if (!isset($fakedForBranchPruning['onlyIfNot-' . $onlyIfNotStoreKey])) {
56✔
1669
                        /** @var string $token */
1670
                        $stack->push('Value', 'Pruned branch (only if not ' . $onlyIfNotStoreKey . ') ' . $token);
56✔
1671
                        $fakedForBranchPruning['onlyIfNot-' . $onlyIfNotStoreKey] = true;
56✔
1672
                    }
1673

1674
                    if (isset($storeKey)) {
56✔
1675
                        // We are processing an if condition
1676
                        // We cascade the pruning to the depending branches
1677
                        $branchStore[$storeKey] = 'Pruned branch';
10✔
1678
                        $fakedForBranchPruning['onlyIfNot-' . $storeKey] = true;
10✔
1679
                        $fakedForBranchPruning['onlyIf-' . $storeKey] = true;
10✔
1680
                    }
1681

1682
                    continue;
56✔
1683
                }
1684
            }
1685

1686
            if ($token instanceof Operands\StructuredReference) {
11,798✔
1687
                if ($cell === null) {
17✔
UNCOV
1688
                    return $this->raiseFormulaError('Structured References must exist in a Cell context');
×
1689
                }
1690

1691
                try {
1692
                    $cellRange = $token->parse($cell);
17✔
1693
                    if (str_contains($cellRange, ':')) {
17✔
1694
                        $this->debugLog->writeDebugLog('Evaluating Structured Reference %s as Cell Range %s', $token->value(), $cellRange);
8✔
1695
                        $rangeValue = self::getInstance($cell->getWorksheet()->getParent())->_calculateFormulaValue("={$cellRange}", $cellRange, $cell);
8✔
1696
                        $stack->push('Value', $rangeValue);
8✔
1697
                        $this->debugLog->writeDebugLog('Evaluated Structured Reference %s as value %s', $token->value(), $this->showValue($rangeValue));
8✔
1698
                    } else {
1699
                        $this->debugLog->writeDebugLog('Evaluating Structured Reference %s as Cell %s', $token->value(), $cellRange);
10✔
1700
                        $cellValue = $cell->getWorksheet()->getCell($cellRange)->getCalculatedValue(false);
10✔
1701
                        $stack->push('Cell Reference', $cellValue, $cellRange);
10✔
1702
                        $this->debugLog->writeDebugLog('Evaluated Structured Reference %s as value %s', $token->value(), $this->showValue($cellValue));
17✔
1703
                    }
1704
                } catch (Exception $e) {
2✔
1705
                    if ($e->getCode() === Exception::CALCULATION_ENGINE_PUSH_TO_STACK) {
2✔
1706
                        $stack->push('Error', ExcelError::REF(), null);
2✔
1707
                        $this->debugLog->writeDebugLog('Evaluated Structured Reference %s as error value %s', $token->value(), ExcelError::REF());
2✔
1708
                    } else {
UNCOV
1709
                        return $this->raiseFormulaError($e->getMessage(), $e->getCode(), $e);
×
1710
                    }
1711
                }
1712
            } elseif (!is_numeric($token) && !is_object($token) && isset(self::BINARY_OPERATORS[$token])) {
11,797✔
1713
                // 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
1714
                //    We must have two operands, error if we don't
1715
                $operand2Data = $stack->pop();
1,728✔
1716
                if ($operand2Data === null) {
1,728✔
UNCOV
1717
                    return $this->raiseFormulaError('Internal error - Operand value missing from stack');
×
1718
                }
1719
                $operand1Data = $stack->pop();
1,728✔
1720
                if ($operand1Data === null) {
1,728✔
UNCOV
1721
                    return $this->raiseFormulaError('Internal error - Operand value missing from stack');
×
1722
                }
1723

1724
                $operand1 = self::dataTestReference($operand1Data);
1,728✔
1725
                $operand2 = self::dataTestReference($operand2Data);
1,728✔
1726

1727
                //    Log what we're doing
1728
                if ($token == ':') {
1,728✔
1729
                    $this->debugLog->writeDebugLog('Evaluating Range %s %s %s', $this->showValue($operand1Data['reference']), $token, $this->showValue($operand2Data['reference']));
1,249✔
1730
                } else {
1731
                    $this->debugLog->writeDebugLog('Evaluating %s %s %s', $this->showValue($operand1), $token, $this->showValue($operand2));
757✔
1732
                }
1733

1734
                //    Process the operation in the appropriate manner
1735
                switch ($token) {
1736
                    // Comparison (Boolean) Operators
1737
                    case '>': // Greater than
1,728✔
1738
                    case '<': // Less than
1,713✔
1739
                    case '>=': // Greater than or Equal to
1,696✔
1740
                    case '<=': // Less than or Equal to
1,688✔
1741
                    case '=': // Equality
1,670✔
1742
                    case '<>': // Inequality
1,517✔
1743
                        $result = $this->executeBinaryComparisonOperation($operand1, $operand2, (string) $token, $stack);
413✔
1744
                        if (isset($storeKey)) {
413✔
1745
                            $branchStore[$storeKey] = $result;
70✔
1746
                        }
1747

1748
                        break;
413✔
1749
                    // Binary Operators
1750
                    case ':': // Range
1,507✔
1751
                        if ($operand1Data['type'] === 'Error') {
1,249✔
1752
                            $stack->push($operand1Data['type'], $operand1Data['value'], null);
6✔
1753

1754
                            break;
6✔
1755
                        }
1756
                        if ($operand2Data['type'] === 'Error') {
1,244✔
1757
                            $stack->push($operand2Data['type'], $operand2Data['value'], null);
4✔
1758

1759
                            break;
4✔
1760
                        }
1761
                        if ($operand1Data['type'] === 'Defined Name') {
1,240✔
1762
                            /** @var array{reference: string} $operand1Data */
1763
                            if (preg_match('/$' . self::CALCULATION_REGEXP_DEFINEDNAME . '^/mui', $operand1Data['reference']) !== false && $this->spreadsheet !== null) {
3✔
1764
                                /** @var string[] $operand1Data */
1765
                                $definedName = $this->spreadsheet->getNamedRange($operand1Data['reference']);
3✔
1766
                                if ($definedName !== null) {
3✔
1767
                                    $operand1Data['reference'] = $operand1Data['value'] = str_replace('$', '', $definedName->getValue());
3✔
1768
                                }
1769
                            }
1770
                        }
1771
                        /** @var array{reference?: ?string} $operand1Data */
1772
                        if (str_contains($operand1Data['reference'] ?? '', '!')) {
1,240✔
1773
                            [$sheet1, $operand1Data['reference']] = Worksheet::extractSheetTitle($operand1Data['reference'], true, true);
1,232✔
1774
                        } else {
1775
                            $sheet1 = ($pCellWorksheet !== null) ? $pCellWorksheet->getTitle() : '';
12✔
1776
                        }
1777
                        //$sheet1 ??= ''; // phpstan level 10 says this is unneeded
1778

1779
                        /** @var string */
1780
                        $op2ref = $operand2Data['reference'];
1,240✔
1781
                        [$sheet2, $operand2Data['reference']] = Worksheet::extractSheetTitle($op2ref, true, true);
1,240✔
1782
                        if (empty($sheet2)) {
1,240✔
1783
                            $sheet2 = $sheet1;
7✔
1784
                        }
1785

1786
                        if ($sheet1 === $sheet2) {
1,240✔
1787
                            /** @var array{reference: ?string, value: string|string[]} $operand1Data */
1788
                            if ($operand1Data['reference'] === null && $cell !== null) {
1,237✔
UNCOV
1789
                                if (is_array($operand1Data['value'])) {
×
UNCOV
1790
                                    $operand1Data['reference'] = $cell->getCoordinate();
×
UNCOV
1791
                                } elseif ((trim($operand1Data['value']) != '') && (is_numeric($operand1Data['value']))) {
×
1792
                                    $operand1Data['reference'] = $cell->getColumn() . $operand1Data['value'];
×
1793
                                } elseif (trim($operand1Data['value']) == '') {
×
1794
                                    $operand1Data['reference'] = $cell->getCoordinate();
×
1795
                                } else {
1796
                                    $operand1Data['reference'] = $operand1Data['value'] . $cell->getRow();
×
1797
                                }
1798
                            }
1799
                            /** @var array{reference: ?string, value: string|string[]} $operand2Data */
1800
                            if ($operand2Data['reference'] === null && $cell !== null) {
1,237✔
1801
                                if (is_array($operand2Data['value'])) {
3✔
1802
                                    $operand2Data['reference'] = $cell->getCoordinate();
2✔
1803
                                } elseif ((trim($operand2Data['value']) != '') && (is_numeric($operand2Data['value']))) {
1✔
UNCOV
1804
                                    $operand2Data['reference'] = $cell->getColumn() . $operand2Data['value'];
×
1805
                                } elseif (trim($operand2Data['value']) == '') {
1✔
UNCOV
1806
                                    $operand2Data['reference'] = $cell->getCoordinate();
×
1807
                                } else {
1808
                                    $operand2Data['reference'] = $operand2Data['value'] . $cell->getRow();
1✔
1809
                                }
1810
                            }
1811

1812
                            $oData = array_merge(explode(':', $operand1Data['reference'] ?? ''), explode(':', $operand2Data['reference'] ?? ''));
1,237✔
1813
                            $oCol = $oRow = [];
1,237✔
1814
                            $breakNeeded = false;
1,237✔
1815
                            foreach ($oData as $oDatum) {
1,237✔
1816
                                try {
1817
                                    $oCR = Coordinate::coordinateFromString($oDatum);
1,237✔
1818
                                    $oCol[] = Coordinate::columnIndexFromString($oCR[0]) - 1;
1,237✔
1819
                                    $oRow[] = $oCR[1];
1,237✔
1820
                                } catch (\Exception) {
1✔
1821
                                    $stack->push('Error', ExcelError::REF(), null);
1✔
1822
                                    $breakNeeded = true;
1✔
1823

1824
                                    break;
1✔
1825
                                }
1826
                            }
1827
                            if ($breakNeeded) {
1,237✔
1828
                                break;
1✔
1829
                            }
1830
                            $cellRef = Coordinate::stringFromColumnIndex(min($oCol) + 1) . min($oRow) . ':' . Coordinate::stringFromColumnIndex(max($oCol) + 1) . max($oRow); // @phpstan-ignore-line
1,236✔
1831
                            if ($pCellParent !== null && $this->spreadsheet !== null) {
1,236✔
1832
                                $cellValue = $this->extractCellRange($cellRef, $this->spreadsheet->getSheetByName($sheet1), false);
1,236✔
1833
                            } else {
UNCOV
1834
                                return $this->raiseFormulaError('Unable to access Cell Reference');
×
1835
                            }
1836

1837
                            $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($cellValue));
1,236✔
1838
                            $stack->push('Cell Reference', $cellValue, $cellRef);
1,236✔
1839
                        } else {
1840
                            $this->debugLog->writeDebugLog('Evaluation Result is a #REF! Error');
4✔
1841
                            $stack->push('Error', ExcelError::REF(), null);
4✔
1842
                        }
1843

1844
                        break;
1,239✔
1845
                    case '+':            //    Addition
412✔
1846
                    case '-':            //    Subtraction
332✔
1847
                    case '*':            //    Multiplication
292✔
1848
                    case '/':            //    Division
163✔
1849
                    case '^':            //    Exponential
49✔
1850
                        $result = $this->executeNumericBinaryOperation($operand1, $operand2, $token, $stack);
380✔
1851
                        if (isset($storeKey)) {
380✔
1852
                            $branchStore[$storeKey] = $result;
5✔
1853
                        }
1854

1855
                        break;
380✔
1856
                    case '&':            //    Concatenation
45✔
1857
                        //    If either of the operands is a matrix, we need to treat them both as matrices
1858
                        //        (converting the other operand to a matrix if need be); then perform the required
1859
                        //        matrix operation
1860
                        $operand1 = self::boolToString($operand1);
27✔
1861
                        $operand2 = self::boolToString($operand2);
27✔
1862
                        if (is_array($operand1) || is_array($operand2)) {
27✔
1863
                            if (is_string($operand1)) {
17✔
1864
                                $operand1 = self::unwrapResult($operand1);
8✔
1865
                            }
1866
                            if (is_string($operand2)) {
17✔
1867
                                $operand2 = self::unwrapResult($operand2);
6✔
1868
                            }
1869
                            //    Ensure that both operands are arrays/matrices
1870
                            [$rows, $columns] = self::checkMatrixOperands($operand1, $operand2, 2);
17✔
1871

1872
                            for ($row = 0; $row < $rows; ++$row) {
17✔
1873
                                for ($column = 0; $column < $columns; ++$column) {
17✔
1874
                                    /** @var mixed[][] $operand1 */
1875
                                    $op1x = self::boolToString($operand1[$row][$column]);
17✔
1876
                                    /** @var mixed[][] $operand2 */
1877
                                    $op2x = self::boolToString($operand2[$row][$column]);
17✔
1878
                                    if (Information\ErrorValue::isError($op1x)) {
17✔
1879
                                        // no need to do anything
1880
                                    } elseif (Information\ErrorValue::isError($op2x)) {
17✔
1881
                                        $operand1[$row][$column] = $op2x;
1✔
1882
                                    } else {
1883
                                        /** @var string $op1x */
1884
                                        /** @var string $op2x */
1885
                                        $operand1[$row][$column]
16✔
1886
                                            = StringHelper::substring(
16✔
1887
                                                $op1x . $op2x,
16✔
1888
                                                0,
16✔
1889
                                                DataType::MAX_STRING_LENGTH
16✔
1890
                                            );
16✔
1891
                                    }
1892
                                }
1893
                            }
1894
                            $result = $operand1;
17✔
1895
                        } else {
1896
                            if (Information\ErrorValue::isError($operand1)) {
12✔
UNCOV
1897
                                $result = $operand1;
×
1898
                            } elseif (Information\ErrorValue::isError($operand2)) {
12✔
UNCOV
1899
                                $result = $operand2;
×
1900
                            } else {
1901
                                $result = str_replace('""', self::FORMULA_STRING_QUOTE, self::unwrapResult($operand1) . self::unwrapResult($operand2)); //* @phpstan-ignore-line
12✔
1902
                                $result = StringHelper::substring(
12✔
1903
                                    $result,
12✔
1904
                                    0,
12✔
1905
                                    DataType::MAX_STRING_LENGTH
12✔
1906
                                );
12✔
1907
                                $result = self::FORMULA_STRING_QUOTE . $result . self::FORMULA_STRING_QUOTE;
12✔
1908
                            }
1909
                        }
1910
                        $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($result));
27✔
1911
                        $stack->push('Value', $result);
27✔
1912

1913
                        if (isset($storeKey)) {
27✔
UNCOV
1914
                            $branchStore[$storeKey] = $result;
×
1915
                        }
1916

1917
                        break;
27✔
1918
                    case '∩':            //    Intersect
18✔
1919
                        /** @var mixed[][] $operand1 */
1920
                        /** @var mixed[][] $operand2 */
1921
                        $rowIntersect = array_intersect_key($operand1, $operand2);
17✔
1922
                        $cellIntersect = $oCol = $oRow = [];
17✔
1923
                        foreach (array_keys($rowIntersect) as $row) {
17✔
1924
                            $oRow[] = $row;
17✔
1925
                            foreach ($rowIntersect[$row] as $col => $data) {
17✔
1926
                                $oCol[] = Coordinate::columnIndexFromString($col) - 1;
17✔
1927
                                $cellIntersect[$row] = array_intersect_key($operand1[$row], $operand2[$row]);
17✔
1928
                            }
1929
                        }
1930
                        if (count(Functions::flattenArray($cellIntersect)) === 0) {
17✔
1931
                            $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($cellIntersect));
2✔
1932
                            $stack->push('Error', ExcelError::null(), null);
2✔
1933
                        } else {
1934
                            $cellRef = Coordinate::stringFromColumnIndex(min($oCol) + 1) . min($oRow) . ':' // @phpstan-ignore-line
15✔
1935
                                . Coordinate::stringFromColumnIndex(max($oCol) + 1) . max($oRow); // @phpstan-ignore-line
15✔
1936
                            $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($cellIntersect));
15✔
1937
                            $stack->push('Value', $cellIntersect, $cellRef);
15✔
1938
                        }
1939

1940
                        break;
17✔
1941
                    case '∪':            //    union
3✔
1942
                        /** @var mixed[][] $operand1 */
1943
                        /** @var mixed[][] $operand2 */
1944
                        $cellUnion = array_merge($operand1, $operand2);
3✔
1945
                        $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($cellUnion));
3✔
1946
                        $stack->push('Value', $cellUnion, 'A1');
3✔
1947

1948
                        break;
3✔
1949
                }
1950
            } elseif (($token === '~') || ($token === '%')) {
11,790✔
1951
                // if the token is a unary operator, pop one value off the stack, do the operation, and push it back on
1952
                if (($arg = $stack->pop()) === null) {
1,151✔
UNCOV
1953
                    return $this->raiseFormulaError('Internal error - Operand value missing from stack');
×
1954
                }
1955
                $arg = $arg['value'];
1,151✔
1956
                if ($token === '~') {
1,151✔
1957
                    $this->debugLog->writeDebugLog('Evaluating Negation of %s', $this->showValue($arg));
1,147✔
1958
                    $multiplier = -1;
1,147✔
1959
                } else {
1960
                    $this->debugLog->writeDebugLog('Evaluating Percentile of %s', $this->showValue($arg));
6✔
1961
                    $multiplier = 0.01;
6✔
1962
                }
1963
                if (is_array($arg)) {
1,151✔
1964
                    $operand2 = $multiplier;
4✔
1965
                    $result = $arg;
4✔
1966
                    [$rows, $columns] = self::checkMatrixOperands($result, $operand2, 0);
4✔
1967
                    for ($row = 0; $row < $rows; ++$row) {
4✔
1968
                        for ($column = 0; $column < $columns; ++$column) {
4✔
1969
                            /** @var mixed[][] $result */
1970
                            if (self::isNumericOrBool($result[$row][$column])) {
4✔
1971
                                /** @var float|int|numeric-string */
1972
                                $temp = $result[$row][$column];
4✔
1973
                                $result[$row][$column] = $temp * $multiplier;
4✔
1974
                            } else {
1975
                                $result[$row][$column] = self::makeError($result[$row][$column]);
2✔
1976
                            }
1977
                        }
1978
                    }
1979

1980
                    $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($result));
4✔
1981
                    $stack->push('Value', $result);
4✔
1982
                    if (isset($storeKey)) {
4✔
UNCOV
1983
                        $branchStore[$storeKey] = $result;
×
1984
                    }
1985
                } else {
1986
                    $this->executeNumericBinaryOperation($multiplier, $arg, '*', $stack);
1,150✔
1987
                }
1988
            } elseif (preg_match('/^' . self::CALCULATION_REGEXP_CELLREF . '$/i', StringHelper::convertToString($token ?? ''), $matches)) {
11,790✔
1989
                $cellRef = null;
6,954✔
1990

1991
                /* Phpstan says matches[8/9/10] is never set,
1992
                   and code coverage report seems to confirm.
1993
                   Appease PhpStan for now;
1994
                   probably delete this block later.
1995
                */
1996
                if (isset($matches[self::$matchIndex8])) {
6,954✔
UNCOV
1997
                    if ($cell === null) {
×
1998
                        // We can't access the range, so return a REF error
UNCOV
1999
                        $cellValue = ExcelError::REF();
×
2000
                    } else {
UNCOV
2001
                        $cellRef = $matches[6] . $matches[7] . ':' . $matches[self::$matchIndex9] . $matches[self::$matchIndex10];
×
2002
                        if ($matches[2] > '') {
×
UNCOV
2003
                            $matches[2] = trim($matches[2], "\"'");
×
2004
                            if ((str_contains($matches[2], '[')) || (str_contains($matches[2], ']'))) {
×
2005
                                //    It's a Reference to an external spreadsheet (not currently supported)
2006
                                return $this->raiseFormulaError('Unable to access External Workbook');
×
2007
                            }
UNCOV
2008
                            $matches[2] = trim($matches[2], "\"'");
×
2009
                            $this->debugLog->writeDebugLog('Evaluating Cell Range %s in worksheet %s', $cellRef, $matches[2]);
×
UNCOV
2010
                            if ($pCellParent !== null && $this->spreadsheet !== null) {
×
2011
                                $cellValue = $this->extractCellRange($cellRef, $this->spreadsheet->getSheetByName($matches[2]), false);
×
2012
                            } else {
2013
                                return $this->raiseFormulaError('Unable to access Cell Reference');
×
2014
                            }
UNCOV
2015
                            $this->debugLog->writeDebugLog('Evaluation Result for cells %s in worksheet %s is %s', $cellRef, $matches[2], $this->showTypeDetails($cellValue));
×
2016
                        } else {
UNCOV
2017
                            $this->debugLog->writeDebugLog('Evaluating Cell Range %s in current worksheet', $cellRef);
×
2018
                            if ($pCellParent !== null) {
×
UNCOV
2019
                                $cellValue = $this->extractCellRange($cellRef, $pCellWorksheet, false);
×
2020
                            } else {
2021
                                return $this->raiseFormulaError('Unable to access Cell Reference');
×
2022
                            }
UNCOV
2023
                            $this->debugLog->writeDebugLog('Evaluation Result for cells %s is %s', $cellRef, $this->showTypeDetails($cellValue));
×
2024
                        }
2025
                    }
2026
                } else {
2027
                    if ($cell === null) {
6,954✔
2028
                        // We can't access the cell, so return a REF error
UNCOV
2029
                        $cellValue = ExcelError::REF();
×
2030
                    } else {
2031
                        $cellRef = $matches[6] . $matches[7];
6,954✔
2032
                        if ($matches[2] > '') {
6,954✔
2033
                            $matches[2] = trim($matches[2], "\"'");
6,947✔
2034
                            if ((str_contains($matches[2], '[')) || (str_contains($matches[2], ']'))) {
6,947✔
2035
                                //    It's a Reference to an external spreadsheet (not currently supported)
2036
                                return $this->raiseFormulaError('Unable to access External Workbook');
1✔
2037
                            }
2038
                            $this->debugLog->writeDebugLog('Evaluating Cell %s in worksheet %s', $cellRef, $matches[2]);
6,947✔
2039
                            if ($pCellParent !== null && $this->spreadsheet !== null) {
6,947✔
2040
                                $cellSheet = $this->spreadsheet->getSheetByName($matches[2]);
6,947✔
2041
                                if ($cellSheet && !$cellSheet->cellExists($cellRef)) {
6,947✔
2042
                                    $cellSheet->setCellValue($cellRef, null);
327✔
2043
                                }
2044
                                if ($cellSheet && $cellSheet->cellExists($cellRef)) {
6,947✔
2045
                                    $cellValue = $this->extractCellRange($cellRef, $this->spreadsheet->getSheetByName($matches[2]), false);
6,939✔
2046
                                    $cell->attach($pCellParent);
6,939✔
2047
                                } else {
2048
                                    $cellRef = ($cellSheet !== null) ? "'{$matches[2]}'!{$cellRef}" : $cellRef;
21✔
2049
                                    $cellValue = ($cellSheet !== null) ? null : ExcelError::REF();
21✔
2050
                                }
2051
                            } else {
UNCOV
2052
                                return $this->raiseFormulaError('Unable to access Cell Reference');
×
2053
                            }
2054
                            $this->debugLog->writeDebugLog('Evaluation Result for cell %s in worksheet %s is %s', $cellRef, $matches[2], $this->showTypeDetails($cellValue));
6,947✔
2055
                        } else {
2056
                            $this->debugLog->writeDebugLog('Evaluating Cell %s in current worksheet', $cellRef);
11✔
2057
                            if ($pCellParent !== null && $pCellParent->has($cellRef)) {
11✔
2058
                                $cellValue = $this->extractCellRange($cellRef, $pCellWorksheet, false);
11✔
2059
                                $cell->attach($pCellParent);
11✔
2060
                            } else {
2061
                                $cellValue = null;
2✔
2062
                            }
2063
                            $this->debugLog->writeDebugLog('Evaluation Result for cell %s is %s', $cellRef, $this->showTypeDetails($cellValue));
11✔
2064
                        }
2065
                    }
2066
                }
2067

2068
                if ($this->getInstanceArrayReturnType() === self::RETURN_ARRAY_AS_ARRAY && !$this->processingAnchorArray && is_array($cellValue)) {
6,954✔
2069
                    while (is_array($cellValue)) {
173✔
2070
                        $cellValue = array_shift($cellValue);
173✔
2071
                    }
2072
                    if (is_string($cellValue)) {
173✔
2073
                        $cellValue = preg_replace('/"/', '""', $cellValue);
124✔
2074
                    }
2075
                    $this->debugLog->writeDebugLog('Scalar Result for cell %s is %s', $cellRef, $this->showTypeDetails($cellValue));
173✔
2076
                }
2077
                $this->processingAnchorArray = false;
6,954✔
2078
                $stack->push('Cell Value', $cellValue, $cellRef);
6,954✔
2079
                if (isset($storeKey)) {
6,954✔
2080
                    $branchStore[$storeKey] = $cellValue;
58✔
2081
                }
2082
            } elseif (preg_match('/^' . self::CALCULATION_REGEXP_FUNCTION . '$/miu', StringHelper::convertToString($token ?? ''), $matches)) {
11,707✔
2083
                // if the token is a function, pop arguments off the stack, hand them to the function, and push the result back on
2084
                if ($cell !== null && $pCellParent !== null) {
11,504✔
2085
                    $cell->attach($pCellParent);
7,925✔
2086
                }
2087

2088
                $functionName = $matches[1];
11,504✔
2089
                /** @var array<string, int> $argCount */
2090
                $argCount = $stack->pop();
11,504✔
2091
                $argCount = $argCount['value'];
11,504✔
2092
                if ($functionName !== 'MKMATRIX') {
11,504✔
2093
                    $this->debugLog->writeDebugLog('Evaluating Function %s() with %s argument%s', self::localeFunc($functionName), (($argCount == 0) ? 'no' : $argCount), (($argCount == 1) ? '' : 's'));
11,503✔
2094
                }
2095
                if ((isset($phpSpreadsheetFunctions[$functionName])) || (isset(self::$controlFunctions[$functionName]))) {    // function
11,504✔
2096
                    $passByReference = false;
11,504✔
2097
                    $passCellReference = false;
11,504✔
2098
                    $functionCall = null;
11,504✔
2099
                    if (isset($phpSpreadsheetFunctions[$functionName])) {
11,504✔
2100
                        $functionCall = $phpSpreadsheetFunctions[$functionName]['functionCall'];
11,501✔
2101
                        $passByReference = isset($phpSpreadsheetFunctions[$functionName]['passByReference']);
11,501✔
2102
                        $passCellReference = isset($phpSpreadsheetFunctions[$functionName]['passCellReference']);
11,501✔
2103
                    } elseif (isset(self::$controlFunctions[$functionName])) {
818✔
2104
                        $functionCall = self::$controlFunctions[$functionName]['functionCall'];
818✔
2105
                        $passByReference = isset(self::$controlFunctions[$functionName]['passByReference']);
818✔
2106
                        $passCellReference = isset(self::$controlFunctions[$functionName]['passCellReference']);
818✔
2107
                    }
2108

2109
                    // get the arguments for this function
2110
                    $args = $argArrayVals = [];
11,504✔
2111
                    $emptyArguments = [];
11,504✔
2112
                    for ($i = 0; $i < $argCount; ++$i) {
11,504✔
2113
                        $arg = $stack->pop();
11,486✔
2114
                        $a = $argCount - $i - 1;
11,486✔
2115
                        if (
2116
                            ($passByReference)
11,486✔
2117
                            && (isset($phpSpreadsheetFunctions[$functionName]['passByReference'][$a])) //* @phpstan-ignore-line
11,486✔
2118
                            && ($phpSpreadsheetFunctions[$functionName]['passByReference'][$a])
11,486✔
2119
                        ) {
2120
                            /** @var mixed[] $arg */
2121
                            if ($arg['reference'] === null) {
81✔
2122
                                $nextArg = $cellID;
19✔
2123
                                if ($functionName === 'ISREF' && ($arg['type'] ?? '') === 'Value') {
19✔
2124
                                    if (array_key_exists('value', $arg)) {
5✔
2125
                                        $argValue = $arg['value'];
5✔
2126
                                        if (is_scalar($argValue)) {
5✔
2127
                                            $nextArg = $argValue;
2✔
2128
                                        } elseif (empty($argValue)) {
3✔
2129
                                            $nextArg = '';
1✔
2130
                                        }
2131
                                    }
2132
                                } elseif (($arg['type'] ?? '') === 'Error') {
14✔
2133
                                    $argValue = $arg['value'];
13✔
2134
                                    if (is_scalar($argValue)) {
13✔
2135
                                        $nextArg = $argValue;
13✔
UNCOV
2136
                                    } elseif (empty($argValue)) {
×
UNCOV
2137
                                        $nextArg = '';
×
2138
                                    }
2139
                                }
2140
                                $args[] = $nextArg;
19✔
2141
                                if ($functionName !== 'MKMATRIX') {
19✔
2142
                                    $argArrayVals[] = $this->showValue($cellID);
19✔
2143
                                }
2144
                            } else {
2145
                                $args[] = $arg['reference'];
66✔
2146
                                if ($functionName !== 'MKMATRIX') {
66✔
2147
                                    $argArrayVals[] = $this->showValue($arg['reference']);
66✔
2148
                                }
2149
                            }
2150
                        } else {
2151
                            /** @var mixed[] $arg */
2152
                            if ($arg['type'] === 'Empty Argument' && in_array($functionName, ['MIN', 'MINA', 'MAX', 'MAXA', 'IF'], true)) {
11,430✔
2153
                                $emptyArguments[] = false;
15✔
2154
                                $args[] = $arg['value'] = 0;
15✔
2155
                                $this->debugLog->writeDebugLog('Empty Argument reevaluated as 0');
15✔
2156
                            } else {
2157
                                $emptyArguments[] = $arg['type'] === 'Empty Argument';
11,430✔
2158
                                $args[] = self::unwrapResult($arg['value']);
11,430✔
2159
                            }
2160
                            if ($functionName !== 'MKMATRIX') {
11,430✔
2161
                                $argArrayVals[] = $this->showValue($arg['value']);
11,429✔
2162
                            }
2163
                        }
2164
                    }
2165

2166
                    //    Reverse the order of the arguments
2167
                    krsort($args);
11,504✔
2168
                    krsort($emptyArguments);
11,504✔
2169

2170
                    if ($argCount > 0 && is_array($functionCall)) {
11,504✔
2171
                        /** @var string[] */
2172
                        $functionCallCopy = $functionCall;
11,486✔
2173
                        $args = $this->addDefaultArgumentValues($functionCallCopy, $args, $emptyArguments);
11,486✔
2174
                    }
2175

2176
                    if (($passByReference) && ($argCount == 0)) {
11,504✔
2177
                        $args[] = $cellID;
9✔
2178
                        $argArrayVals[] = $this->showValue($cellID);
9✔
2179
                    }
2180

2181
                    if ($functionName !== 'MKMATRIX') {
11,504✔
2182
                        if ($this->debugLog->getWriteDebugLog()) {
11,503✔
2183
                            krsort($argArrayVals);
2✔
2184
                            $this->debugLog->writeDebugLog('Evaluating %s ( %s )', self::localeFunc($functionName), implode(self::$localeArgumentSeparator . ' ', Functions::flattenArray($argArrayVals)));
2✔
2185
                        }
2186
                    }
2187

2188
                    //    Process the argument with the appropriate function call
2189
                    if ($pCellWorksheet !== null && $originalCoordinate !== null) {
11,504✔
2190
                        $pCellWorksheet->getCell($originalCoordinate);
7,925✔
2191
                    }
2192
                    /** @var array<string>|string $functionCall */
2193
                    $args = $this->addCellReference($args, $passCellReference, $functionCall, $cell);
11,504✔
2194

2195
                    if (!is_array($functionCall)) {
11,504✔
2196
                        foreach ($args as &$arg) {
53✔
UNCOV
2197
                            $arg = Functions::flattenSingleValue($arg);
×
2198
                        }
2199
                        unset($arg);
53✔
2200
                    }
2201

2202
                    /** @var callable $functionCall */
2203
                    try {
2204
                        $result = call_user_func_array($functionCall, $args);
11,504✔
2205
                    } catch (TypeError $e) {
13✔
UNCOV
2206
                        if (!$this->suppressFormulaErrors) {
×
UNCOV
2207
                            throw $e;
×
2208
                        }
2209
                        $result = false;
×
2210
                    }
2211
                    if ($functionName !== 'MKMATRIX') {
11,498✔
2212
                        $this->debugLog->writeDebugLog('Evaluation Result for %s() function call is %s', self::localeFunc($functionName), $this->showTypeDetails($result));
11,495✔
2213
                    }
2214
                    $stack->push('Value', self::wrapResult($result));
11,498✔
2215
                    if (isset($storeKey)) {
11,498✔
2216
                        $branchStore[$storeKey] = $result;
22✔
2217
                    }
2218
                }
2219
            } else {
2220
                // if the token is a number, boolean, string or an Excel error, push it onto the stack
2221
                /** @var ?string $token */
2222
                if (isset(self::EXCEL_CONSTANTS[strtoupper($token ?? '')])) {
11,707✔
UNCOV
2223
                    $excelConstant = strtoupper("$token");
×
UNCOV
2224
                    $stack->push('Constant Value', self::EXCEL_CONSTANTS[$excelConstant]);
×
UNCOV
2225
                    if (isset($storeKey)) {
×
2226
                        $branchStore[$storeKey] = self::EXCEL_CONSTANTS[$excelConstant];
×
2227
                    }
2228
                    $this->debugLog->writeDebugLog('Evaluating Constant %s as %s', $excelConstant, $this->showTypeDetails(self::EXCEL_CONSTANTS[$excelConstant]));
×
2229
                } elseif ((is_numeric($token)) || ($token === null) || (is_bool($token)) || ($token == '') || ($token[0] == self::FORMULA_STRING_QUOTE) || ($token[0] == '#')) { //* @phpstan-ignore-line
11,707✔
2230
                    /** @var array{type: string, reference: ?string} $tokenData */
2231
                    $stack->push($tokenData['type'], $token, $tokenData['reference']);
11,668✔
2232
                    if (isset($storeKey)) {
11,668✔
2233
                        $branchStore[$storeKey] = $token;
73✔
2234
                    }
2235
                } elseif (preg_match('/^' . self::CALCULATION_REGEXP_DEFINEDNAME . '$/miu', $token, $matches)) {
160✔
2236
                    // if the token is a named range or formula, evaluate it and push the result onto the stack
2237
                    $definedName = $matches[6];
160✔
2238
                    if (str_starts_with($definedName, '_xleta')) {
160✔
2239
                        return Functions::NOT_YET_IMPLEMENTED;
1✔
2240
                    }
2241
                    if ($cell === null || $pCellWorksheet === null) {
159✔
UNCOV
2242
                        return $this->raiseFormulaError("undefined name '$token'");
×
2243
                    }
2244
                    $specifiedWorksheet = trim($matches[2], "'");
159✔
2245

2246
                    $this->debugLog->writeDebugLog('Evaluating Defined Name %s', $definedName);
159✔
2247
                    $namedRange = DefinedName::resolveName($definedName, $pCellWorksheet, $specifiedWorksheet);
159✔
2248
                    // If not Defined Name, try as Table.
2249
                    if ($namedRange === null && $this->spreadsheet !== null) {
159✔
2250
                        $table = $this->spreadsheet->getTableByName($definedName);
37✔
2251
                        if ($table !== null) {
37✔
2252
                            $tableRange = Coordinate::getRangeBoundaries($table->getRange());
3✔
2253
                            if ($table->getShowHeaderRow()) {
3✔
2254
                                ++$tableRange[0][1];
3✔
2255
                            }
2256
                            if ($table->getShowTotalsRow()) {
3✔
UNCOV
2257
                                --$tableRange[1][1];
×
2258
                            }
2259
                            $tableRangeString
3✔
2260
                                = '$' . $tableRange[0][0]
3✔
2261
                                . '$' . $tableRange[0][1]
3✔
2262
                                . ':'
3✔
2263
                                . '$' . $tableRange[1][0]
3✔
2264
                                . '$' . $tableRange[1][1];
3✔
2265
                            $namedRange = new NamedRange($definedName, $table->getWorksheet(), $tableRangeString);
3✔
2266
                        }
2267
                    }
2268
                    if ($namedRange === null) {
159✔
2269
                        $result = ExcelError::NAME();
34✔
2270
                        $stack->push('Error', $result, null);
34✔
2271
                        $this->debugLog->writeDebugLog("Error $result");
34✔
2272
                    } else {
2273
                        $result = $this->evaluateDefinedName($cell, $namedRange, $pCellWorksheet, $stack, $specifiedWorksheet !== '');
137✔
2274
                    }
2275

2276
                    if (isset($storeKey)) {
159✔
2277
                        $branchStore[$storeKey] = $result;
1✔
2278
                    }
2279
                } else {
UNCOV
2280
                    return $this->raiseFormulaError("undefined name '$token'");
×
2281
                }
2282
            }
2283
        }
2284
        // when we're out of tokens, the stack should have a single element, the final result
2285
        if ($stack->count() != 1) {
11,788✔
2286
            return $this->raiseFormulaError('internal error');
1✔
2287
        }
2288
        /** @var array<string, array<int, mixed>|false|string> */
2289
        $output = $stack->pop();
11,788✔
2290
        $output = $output['value'];
11,788✔
2291

2292
        return $output;
11,788✔
2293
    }
2294

2295
    private function validateBinaryOperand(mixed &$operand, Stack &$stack): bool
2296
    {
2297
        if (is_array($operand)) {
1,464✔
2298
            if ((count($operand, COUNT_RECURSIVE) - count($operand)) == 1) {
226✔
2299
                do {
2300
                    $operand = array_pop($operand);
191✔
2301
                } while (is_array($operand));
191✔
2302
            }
2303
        }
2304
        //    Numbers, matrices and booleans can pass straight through, as they're already valid
2305
        if (is_string($operand)) {
1,464✔
2306
            //    We only need special validations for the operand if it is a string
2307
            //    Start by stripping off the quotation marks we use to identify true excel string values internally
2308
            if ($operand > '' && $operand[0] == self::FORMULA_STRING_QUOTE) {
16✔
2309
                $operand = StringHelper::convertToString(self::unwrapResult($operand));
5✔
2310
            }
2311
            //    If the string is a numeric value, we treat it as a numeric, so no further testing
2312
            if (!is_numeric($operand)) {
16✔
2313
                //    If not a numeric, test to see if the value is an Excel error, and so can't be used in normal binary operations
2314
                if ($operand > '' && $operand[0] == '#') {
15✔
2315
                    $stack->push('Value', $operand);
6✔
2316
                    $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($operand));
6✔
2317

2318
                    return false;
6✔
2319
                } elseif (Engine\FormattedNumber::convertToNumberIfFormatted($operand) === false) {
11✔
2320
                    //    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
2321
                    $stack->push('Error', '#VALUE!');
6✔
2322
                    $this->debugLog->writeDebugLog('Evaluation Result is a %s', $this->showTypeDetails('#VALUE!'));
6✔
2323

2324
                    return false;
6✔
2325
                }
2326
            }
2327
        }
2328

2329
        //    return a true if the value of the operand is one that we can use in normal binary mathematical operations
2330
        return true;
1,462✔
2331
    }
2332

2333
    /** @return mixed[] */
2334
    private function executeArrayComparison(mixed $operand1, mixed $operand2, string $operation, Stack &$stack, bool $recursingArrays): array
2335
    {
2336
        $result = [];
56✔
2337
        if (!is_array($operand2) && is_array($operand1)) {
56✔
2338
            // Operand 1 is an array, Operand 2 is a scalar
2339
            foreach ($operand1 as $x => $operandData) {
53✔
2340
                $this->debugLog->writeDebugLog('Evaluating Comparison %s %s %s', $this->showValue($operandData), $operation, $this->showValue($operand2));
53✔
2341
                $this->executeBinaryComparisonOperation($operandData, $operand2, $operation, $stack);
53✔
2342
                /** @var array<string, mixed> $r */
2343
                $r = $stack->pop();
53✔
2344
                $result[$x] = $r['value'];
53✔
2345
            }
2346
        } elseif (is_array($operand2) && !is_array($operand1)) {
10✔
2347
            // Operand 1 is a scalar, Operand 2 is an array
2348
            foreach ($operand2 as $x => $operandData) {
1✔
2349
                $this->debugLog->writeDebugLog('Evaluating Comparison %s %s %s', $this->showValue($operand1), $operation, $this->showValue($operandData));
1✔
2350
                $this->executeBinaryComparisonOperation($operand1, $operandData, $operation, $stack);
1✔
2351
                /** @var array<string, mixed> $r */
2352
                $r = $stack->pop();
1✔
2353
                $result[$x] = $r['value'];
1✔
2354
            }
2355
        } elseif (is_array($operand2) && is_array($operand1)) {
9✔
2356
            // Operand 1 and Operand 2 are both arrays
2357
            if (!$recursingArrays) {
9✔
2358
                self::checkMatrixOperands($operand1, $operand2, 2);
9✔
2359
            }
2360
            foreach ($operand1 as $x => $operandData) {
9✔
2361
                $this->debugLog->writeDebugLog('Evaluating Comparison %s %s %s', $this->showValue($operandData), $operation, $this->showValue($operand2[$x]));
9✔
2362
                $this->executeBinaryComparisonOperation($operandData, $operand2[$x], $operation, $stack, true);
9✔
2363
                /** @var array<string, mixed> $r */
2364
                $r = $stack->pop();
9✔
2365
                $result[$x] = $r['value'];
9✔
2366
            }
2367
        } else {
UNCOV
2368
            throw new Exception('Neither operand is an arra');
×
2369
        }
2370
        //    Log the result details
2371
        $this->debugLog->writeDebugLog('Comparison Evaluation Result is %s', $this->showTypeDetails($result));
56✔
2372
        //    And push the result onto the stack
2373
        $stack->push('Array', $result);
56✔
2374

2375
        return $result;
56✔
2376
    }
2377

2378
    /** @return bool|mixed[] */
2379
    private function executeBinaryComparisonOperation(mixed $operand1, mixed $operand2, string $operation, Stack &$stack, bool $recursingArrays = false): array|bool
2380
    {
2381
        //    If we're dealing with matrix operations, we want a matrix result
2382
        if ((is_array($operand1)) || (is_array($operand2))) {
413✔
2383
            return $this->executeArrayComparison($operand1, $operand2, $operation, $stack, $recursingArrays);
56✔
2384
        }
2385

2386
        $result = BinaryComparison::compare($operand1, $operand2, $operation);
413✔
2387

2388
        //    Log the result details
2389
        $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($result));
413✔
2390
        //    And push the result onto the stack
2391
        $stack->push('Value', $result);
413✔
2392

2393
        return $result;
413✔
2394
    }
2395

2396
    private function executeNumericBinaryOperation(mixed $operand1, mixed $operand2, string $operation, Stack &$stack): mixed
2397
    {
2398
        //    Validate the two operands
2399
        if (
2400
            ($this->validateBinaryOperand($operand1, $stack) === false)
1,464✔
2401
            || ($this->validateBinaryOperand($operand2, $stack) === false)
1,464✔
2402
        ) {
2403
            return false;
10✔
2404
        }
2405

2406
        if (
2407
            (Functions::getCompatibilityMode() != Functions::COMPATIBILITY_OPENOFFICE)
1,457✔
2408
            && ((is_string($operand1) && !is_numeric($operand1) && $operand1 !== '')
1,457✔
2409
                || (is_string($operand2) && !is_numeric($operand2) && $operand2 !== ''))
1,457✔
2410
        ) {
UNCOV
2411
            $result = ExcelError::VALUE();
×
2412
        } elseif (is_array($operand1) || is_array($operand2)) {
1,457✔
2413
            //    Ensure that both operands are arrays/matrices
2414
            if (is_array($operand1)) {
37✔
2415
                foreach ($operand1 as $key => $value) {
31✔
2416
                    $operand1[$key] = Functions::flattenArray($value);
31✔
2417
                }
2418
            }
2419
            if (is_array($operand2)) {
37✔
2420
                foreach ($operand2 as $key => $value) {
31✔
2421
                    $operand2[$key] = Functions::flattenArray($value);
31✔
2422
                }
2423
            }
2424
            [$rows, $columns] = self::checkMatrixOperands($operand1, $operand2, 3);
37✔
2425

2426
            for ($row = 0; $row < $rows; ++$row) {
37✔
2427
                for ($column = 0; $column < $columns; ++$column) {
37✔
2428
                    /** @var mixed[][] $operand1 */
2429
                    if (($operand1[$row][$column] ?? null) === null) {
37✔
2430
                        $operand1[$row][$column] = 0;
2✔
2431
                    } elseif (!self::isNumericOrBool($operand1[$row][$column])) {
37✔
2432
                        $operand1[$row][$column] = self::makeError($operand1[$row][$column]);
1✔
2433

2434
                        continue;
1✔
2435
                    }
2436
                    /** @var mixed[][] $operand2 */
2437
                    if (($operand2[$row][$column] ?? null) === null) {
37✔
2438
                        $operand2[$row][$column] = 0;
2✔
2439
                    } elseif (!self::isNumericOrBool($operand2[$row][$column])) {
37✔
UNCOV
2440
                        $operand1[$row][$column] = self::makeError($operand2[$row][$column]);
×
2441

UNCOV
2442
                        continue;
×
2443
                    }
2444
                    /** @var float|int */
2445
                    $operand1Val = $operand1[$row][$column];
37✔
2446
                    /** @var float|int */
2447
                    $operand2Val = $operand2[$row][$column];
37✔
2448
                    switch ($operation) {
2449
                        case '+':
37✔
2450
                            $operand1[$row][$column] = $operand1Val + $operand2Val;
3✔
2451

2452
                            break;
3✔
2453
                        case '-':
34✔
2454
                            $operand1[$row][$column] = $operand1Val - $operand2Val;
3✔
2455

2456
                            break;
3✔
2457
                        case '*':
32✔
2458
                            $operand1[$row][$column] = $operand1Val * $operand2Val;
25✔
2459

2460
                            break;
25✔
2461
                        case '/':
7✔
2462
                            if ($operand2Val == 0) {
5✔
2463
                                $operand1[$row][$column] = ExcelError::DIV0();
3✔
2464
                            } else {
2465
                                $operand1[$row][$column] = $operand1Val / $operand2Val;
4✔
2466
                            }
2467

2468
                            break;
5✔
2469
                        case '^':
2✔
2470
                            $operand1[$row][$column] = $operand1Val ** $operand2Val;
2✔
2471

2472
                            break;
2✔
2473

2474
                        default:
UNCOV
2475
                            throw new Exception('Unsupported numeric binary operation');
×
2476
                    }
2477
                }
2478
            }
2479
            $result = $operand1;
37✔
2480
        } else {
2481
            //    If we're dealing with non-matrix operations, execute the necessary operation
2482
            /** @var float|int $operand1 */
2483
            /** @var float|int $operand2 */
2484
            switch ($operation) {
2485
                //    Addition
2486
                case '+':
1,439✔
2487
                    $result = $operand1 + $operand2;
161✔
2488

2489
                    break;
161✔
2490
                //    Subtraction
2491
                case '-':
1,360✔
2492
                    $result = $operand1 - $operand2;
51✔
2493

2494
                    break;
51✔
2495
                //    Multiplication
2496
                case '*':
1,325✔
2497
                    $result = $operand1 * $operand2;
1,247✔
2498

2499
                    break;
1,247✔
2500
                //    Division
2501
                case '/':
114✔
2502
                    if ($operand2 == 0) {
112✔
2503
                        //    Trap for Divide by Zero error
2504
                        $stack->push('Error', ExcelError::DIV0());
61✔
2505
                        $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails(ExcelError::DIV0()));
61✔
2506

2507
                        return false;
61✔
2508
                    }
2509
                    $result = $operand1 / $operand2;
61✔
2510

2511
                    break;
61✔
2512
                //    Power
2513
                case '^':
3✔
2514
                    $result = $operand1 ** $operand2;
3✔
2515

2516
                    break;
3✔
2517

2518
                default:
UNCOV
2519
                    throw new Exception('Unsupported numeric binary operation');
×
2520
            }
2521
        }
2522

2523
        //    Log the result details
2524
        $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($result));
1,413✔
2525
        //    And push the result onto the stack
2526
        $stack->push('Value', $result);
1,413✔
2527

2528
        return $result;
1,413✔
2529
    }
2530

2531
    /**
2532
     * Trigger an error, but nicely, if need be.
2533
     *
2534
     * @return false
2535
     */
2536
    protected function raiseFormulaError(string $errorMessage, int $code = 0, ?Throwable $exception = null): bool
2537
    {
2538
        $this->formulaError = $errorMessage;
239✔
2539
        $this->cyclicReferenceStack->clear();
239✔
2540
        $suppress = $this->suppressFormulaErrors;
239✔
2541
        $suppressed = $suppress ? ' $suppressed' : '';
239✔
2542
        $this->debugLog->writeDebugLog("Raise Error$suppressed $errorMessage");
239✔
2543
        if (!$suppress) {
239✔
2544
            throw new Exception($errorMessage, $code, $exception);
238✔
2545
        }
2546

2547
        return false;
2✔
2548
    }
2549

2550
    /**
2551
     * Extract range values.
2552
     *
2553
     * @param string $range String based range representation
2554
     * @param ?Worksheet $worksheet Worksheet
2555
     * @param bool $resetLog Flag indicating whether calculation log should be reset or not
2556
     *
2557
     * @return mixed[] Array of values in range if range contains more than one element. Otherwise, a single value is returned.
2558
     */
2559
    public function extractCellRange(string &$range = 'A1', ?Worksheet $worksheet = null, bool $resetLog = true, bool $createCell = false): array
2560
    {
2561
        // Return value
2562
        /** @var mixed[][] */
2563
        $returnValue = [];
6,993✔
2564

2565
        if ($worksheet !== null) {
6,993✔
2566
            $worksheetName = $worksheet->getTitle();
6,992✔
2567

2568
            if (str_contains($range, '!')) {
6,992✔
2569
                [$worksheetName, $range] = Worksheet::extractSheetTitle($range, true, true);
10✔
2570
                $worksheet = ($this->spreadsheet === null) ? null : $this->spreadsheet->getSheetByName($worksheetName);
10✔
2571
            }
2572

2573
            // Extract range
2574
            $aReferences = Coordinate::extractAllCellReferencesInRange($range);
6,992✔
2575
            $range = "'" . $worksheetName . "'" . '!' . $range;
6,992✔
2576
            $currentCol = '';
6,992✔
2577
            $currentRow = 0;
6,992✔
2578
            if (!isset($aReferences[1])) {
6,992✔
2579
                //    Single cell in range
2580
                sscanf($aReferences[0], '%[A-Z]%d', $currentCol, $currentRow);
6,988✔
2581
                if ($createCell && $worksheet !== null && !$worksheet->cellExists($aReferences[0])) {
6,988✔
2582
                    $worksheet->setCellValue($aReferences[0], null);
2✔
2583
                }
2584
                if ($worksheet !== null && $worksheet->cellExists($aReferences[0])) {
6,988✔
2585
                    $temp = $worksheet->getCell($aReferences[0])->getCalculatedValue($resetLog);
6,988✔
2586
                    if ($this->getInstanceArrayReturnType() === self::RETURN_ARRAY_AS_ARRAY) {
6,988✔
2587
                        while (is_array($temp)) {
175✔
2588
                            $temp = array_shift($temp);
8✔
2589
                        }
2590
                    }
2591
                    $returnValue[$currentRow][$currentCol] = $temp;
6,988✔
2592
                } else {
UNCOV
2593
                    $returnValue[$currentRow][$currentCol] = null;
×
2594
                }
2595
            } else {
2596
                // Extract cell data for all cells in the range
2597
                foreach ($aReferences as $reference) {
1,237✔
2598
                    // Extract range
2599
                    sscanf($reference, '%[A-Z]%d', $currentCol, $currentRow);
1,237✔
2600
                    if ($createCell && $worksheet !== null && !$worksheet->cellExists($reference)) {
1,237✔
2601
                        $worksheet->setCellValue($reference, null);
4✔
2602
                    }
2603
                    if ($worksheet !== null && $worksheet->cellExists($reference)) {
1,237✔
2604
                        $temp = $worksheet->getCell($reference)->getCalculatedValue($resetLog);
1,235✔
2605
                        if ($this->getInstanceArrayReturnType() === self::RETURN_ARRAY_AS_ARRAY) {
1,235✔
2606
                            while (is_array($temp)) {
152✔
2607
                                $temp = array_shift($temp);
1✔
2608
                            }
2609
                        }
2610
                        $returnValue[$currentRow][$currentCol] = $temp;
1,235✔
2611
                    } else {
2612
                        $returnValue[$currentRow][$currentCol] = null;
137✔
2613
                    }
2614
                }
2615
            }
2616
        }
2617

2618
        return $returnValue;
6,993✔
2619
    }
2620

2621
    /**
2622
     * Extract range values.
2623
     *
2624
     * @param string $range String based range representation
2625
     * @param null|Worksheet $worksheet Worksheet
2626
     * @param bool $resetLog Flag indicating whether calculation log should be reset or not
2627
     *
2628
     * @return mixed[]|string Array of values in range if range contains more than one element. Otherwise, a single value is returned.
2629
     */
2630
    public function extractNamedRange(string &$range = 'A1', ?Worksheet $worksheet = null, bool $resetLog = true): string|array
2631
    {
2632
        // Return value
UNCOV
2633
        $returnValue = [];
×
2634

UNCOV
2635
        if ($worksheet !== null) {
×
2636
            if (str_contains($range, '!')) {
×
UNCOV
2637
                [$worksheetName, $range] = Worksheet::extractSheetTitle($range, true, true);
×
2638
                $worksheet = ($this->spreadsheet === null) ? null : $this->spreadsheet->getSheetByName($worksheetName);
×
2639
            }
2640

2641
            // Named range?
UNCOV
2642
            $namedRange = ($worksheet === null) ? null : DefinedName::resolveName($range, $worksheet);
×
UNCOV
2643
            if ($namedRange === null) {
×
UNCOV
2644
                return ExcelError::REF();
×
2645
            }
2646

2647
            $worksheet = $namedRange->getWorksheet();
×
UNCOV
2648
            $range = $namedRange->getValue();
×
UNCOV
2649
            $splitRange = Coordinate::splitRange($range);
×
2650
            //    Convert row and column references
2651
            if ($worksheet !== null && ctype_alpha($splitRange[0][0])) {
×
2652
                $range = $splitRange[0][0] . '1:' . $splitRange[0][1] . $worksheet->getHighestRow();
×
UNCOV
2653
            } elseif ($worksheet !== null && ctype_digit($splitRange[0][0])) {
×
2654
                $range = 'A' . $splitRange[0][0] . ':' . $worksheet->getHighestColumn() . $splitRange[0][1];
×
2655
            }
2656

2657
            // Extract range
UNCOV
2658
            $aReferences = Coordinate::extractAllCellReferencesInRange($range);
×
UNCOV
2659
            if (!isset($aReferences[1])) {
×
2660
                //    Single cell (or single column or row) in range
2661
                [$currentCol, $currentRow] = Coordinate::coordinateFromString($aReferences[0]);
×
2662
                /** @var mixed[][] $returnValue */
UNCOV
2663
                if ($worksheet !== null && $worksheet->cellExists($aReferences[0])) {
×
2664
                    $returnValue[$currentRow][$currentCol] = $worksheet->getCell($aReferences[0])->getCalculatedValue($resetLog);
×
2665
                } else {
2666
                    $returnValue[$currentRow][$currentCol] = null;
×
2667
                }
2668
            } else {
2669
                // Extract cell data for all cells in the range
UNCOV
2670
                foreach ($aReferences as $reference) {
×
2671
                    // Extract range
UNCOV
2672
                    [$currentCol, $currentRow] = Coordinate::coordinateFromString($reference);
×
2673
                    if ($worksheet !== null && $worksheet->cellExists($reference)) {
×
UNCOV
2674
                        $returnValue[$currentRow][$currentCol] = $worksheet->getCell($reference)->getCalculatedValue($resetLog);
×
2675
                    } else {
2676
                        $returnValue[$currentRow][$currentCol] = null;
×
2677
                    }
2678
                }
2679
            }
2680
        }
2681

UNCOV
2682
        return $returnValue;
×
2683
    }
2684

2685
    /**
2686
     * Is a specific function implemented?
2687
     *
2688
     * @param string $function Function Name
2689
     */
2690
    public function isImplemented(string $function): bool
2691
    {
2692
        $function = strtoupper($function);
3✔
2693
        $phpSpreadsheetFunctions = &self::getFunctionsAddress();
3✔
2694
        $notImplemented = !isset($phpSpreadsheetFunctions[$function]) || (is_array($phpSpreadsheetFunctions[$function]['functionCall']) && $phpSpreadsheetFunctions[$function]['functionCall'][1] === 'DUMMY');
3✔
2695

2696
        return !$notImplemented;
3✔
2697
    }
2698

2699
    /**
2700
     * Get a list of implemented Excel function names.
2701
     *
2702
     * @return string[]
2703
     */
2704
    public function getImplementedFunctionNames(): array
2705
    {
2706
        $returnValue = [];
2✔
2707
        $phpSpreadsheetFunctions = &self::getFunctionsAddress();
2✔
2708
        foreach ($phpSpreadsheetFunctions as $functionName => $function) {
2✔
2709
            if ($this->isImplemented($functionName)) {
2✔
2710
                $returnValue[] = $functionName;
2✔
2711
            }
2712
        }
2713

2714
        return $returnValue;
2✔
2715
    }
2716

2717
    /**
2718
     * @param string[] $functionCall
2719
     * @param mixed[] $args
2720
     * @param mixed[] $emptyArguments
2721
     *
2722
     * @return mixed[]
2723
     */
2724
    private function addDefaultArgumentValues(array $functionCall, array $args, array $emptyArguments): array
2725
    {
2726
        $reflector = new ReflectionMethod($functionCall[0], $functionCall[1]);
11,486✔
2727
        $methodArguments = $reflector->getParameters();
11,486✔
2728

2729
        if (count($methodArguments) > 0) {
11,486✔
2730
            // Apply any defaults for empty argument values
2731
            foreach ($emptyArguments as $argumentId => $isArgumentEmpty) {
11,479✔
2732
                if ($isArgumentEmpty === true) {
11,423✔
2733
                    $reflectedArgumentId = count($args) - (int) $argumentId - 1;
148✔
2734
                    if (
2735
                        !array_key_exists($reflectedArgumentId, $methodArguments)
148✔
2736
                        || $methodArguments[$reflectedArgumentId]->isVariadic()
148✔
2737
                    ) {
2738
                        break;
13✔
2739
                    }
2740

2741
                    $args[$argumentId] = $this->getArgumentDefaultValue($methodArguments[$reflectedArgumentId]);
135✔
2742
                }
2743
            }
2744
        }
2745

2746
        return $args;
11,486✔
2747
    }
2748

2749
    private function getArgumentDefaultValue(ReflectionParameter $methodArgument): mixed
2750
    {
2751
        $defaultValue = null;
135✔
2752

2753
        if ($methodArgument->isDefaultValueAvailable()) {
135✔
2754
            $defaultValue = $methodArgument->getDefaultValue();
63✔
2755
            if ($methodArgument->isDefaultValueConstant()) {
63✔
2756
                $constantName = $methodArgument->getDefaultValueConstantName() ?? '';
2✔
2757
                // read constant value
2758
                if (str_contains($constantName, '::')) {
2✔
2759
                    [$className, $constantName] = explode('::', $constantName);
2✔
2760
                    $constantReflector = new ReflectionClassConstant($className, $constantName);
2✔
2761

2762
                    return $constantReflector->getValue();
2✔
2763
                }
2764

UNCOV
2765
                return constant($constantName);
×
2766
            }
2767
        }
2768

2769
        return $defaultValue;
134✔
2770
    }
2771

2772
    /**
2773
     * Add cell reference if needed while making sure that it is the last argument.
2774
     *
2775
     * @param mixed[] $args
2776
     * @param string|string[] $functionCall
2777
     *
2778
     * @return mixed[]
2779
     */
2780
    private function addCellReference(array $args, bool $passCellReference, array|string $functionCall, ?Cell $cell = null): array
2781
    {
2782
        if ($passCellReference) {
11,504✔
2783
            if (is_array($functionCall)) {
240✔
2784
                $className = $functionCall[0];
240✔
2785
                $methodName = $functionCall[1];
240✔
2786

2787
                $reflectionMethod = new ReflectionMethod($className, $methodName);
240✔
2788
                $argumentCount = count($reflectionMethod->getParameters());
240✔
2789
                while (count($args) < $argumentCount - 1) {
240✔
2790
                    $args[] = null;
56✔
2791
                }
2792
            }
2793

2794
            $args[] = $cell;
240✔
2795
        }
2796

2797
        return $args;
11,504✔
2798
    }
2799

2800
    private function evaluateDefinedName(Cell $cell, DefinedName $namedRange, Worksheet $cellWorksheet, Stack $stack, bool $ignoreScope = false): mixed
2801
    {
2802
        $definedNameScope = $namedRange->getScope();
137✔
2803
        if ($definedNameScope !== null && $definedNameScope !== $cellWorksheet && !$ignoreScope) {
137✔
2804
            // The defined name isn't in our current scope, so #REF
UNCOV
2805
            $result = ExcelError::REF();
×
UNCOV
2806
            $stack->push('Error', $result, $namedRange->getName());
×
2807

2808
            return $result;
×
2809
        }
2810

2811
        $definedNameValue = $namedRange->getValue();
137✔
2812
        $definedNameType = $namedRange->isFormula() ? 'Formula' : 'Range';
137✔
2813
        if ($definedNameType === 'Range') {
137✔
2814
            if (preg_match('/^(.*!)?(.*)$/', $definedNameValue, $matches) === 1) {
132✔
2815
                $matches2 = trim($matches[2]);
132✔
2816
                $matches2 = preg_replace('/ +/', ' ∩ ', $matches2) ?? $matches2;
132✔
2817
                $matches2 = preg_replace('/,/', ' ∪ ', $matches2) ?? $matches2;
132✔
2818
                $definedNameValue = $matches[1] . $matches2;
132✔
2819
            }
2820
        }
2821
        $definedNameWorksheet = $namedRange->getWorksheet();
137✔
2822

2823
        if ($definedNameValue[0] !== '=') {
137✔
2824
            $definedNameValue = '=' . $definedNameValue;
114✔
2825
        }
2826

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

2829
        $originalCoordinate = $cell->getCoordinate();
137✔
2830
        $recursiveCalculationCell = ($definedNameType !== 'Formula' && $definedNameWorksheet !== null && $definedNameWorksheet !== $cellWorksheet)
137✔
2831
            ? $definedNameWorksheet->getCell('A1')
20✔
2832
            : $cell;
126✔
2833
        $recursiveCalculationCellAddress = $recursiveCalculationCell->getCoordinate();
137✔
2834

2835
        // Adjust relative references in ranges and formulae so that we execute the calculation for the correct rows and columns
2836
        $definedNameValue = ReferenceHelper::getInstance()
137✔
2837
            ->updateFormulaReferencesAnyWorksheet(
137✔
2838
                $definedNameValue,
137✔
2839
                Coordinate::columnIndexFromString(
137✔
2840
                    $cell->getColumn()
137✔
2841
                ) - 1,
137✔
2842
                $cell->getRow() - 1
137✔
2843
            );
137✔
2844

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

2847
        $recursiveCalculator = new self($this->spreadsheet);
137✔
2848
        $recursiveCalculator->getDebugLog()->setWriteDebugLog($this->getDebugLog()->getWriteDebugLog());
137✔
2849
        $recursiveCalculator->getDebugLog()->setEchoDebugLog($this->getDebugLog()->getEchoDebugLog());
137✔
2850
        $result = $recursiveCalculator->_calculateFormulaValue($definedNameValue, $recursiveCalculationCellAddress, $recursiveCalculationCell, true);
137✔
2851
        $cellWorksheet->getCell($originalCoordinate);
137✔
2852

2853
        if ($this->getDebugLog()->getWriteDebugLog()) {
137✔
UNCOV
2854
            $this->debugLog->mergeDebugLog(array_slice($recursiveCalculator->getDebugLog()->getLog(), 3));
×
UNCOV
2855
            $this->debugLog->writeDebugLog('Evaluation Result for Named %s %s is %s', $definedNameType, $namedRange->getName(), $this->showTypeDetails($result));
×
2856
        }
2857

2858
        $y = $namedRange->getWorksheet()?->getTitle();
137✔
2859
        $x = $namedRange->getLocalOnly();
137✔
2860
        if ($x && $y !== null) {
137✔
2861
            $stack->push('Defined Name', $result, "'$y'!" . $namedRange->getName());
20✔
2862
        } else {
2863
            $stack->push('Defined Name', $result, $namedRange->getName());
118✔
2864
        }
2865

2866
        return $result;
137✔
2867
    }
2868

2869
    public function setSuppressFormulaErrors(bool $suppressFormulaErrors): self
2870
    {
2871
        $this->suppressFormulaErrors = $suppressFormulaErrors;
10✔
2872

2873
        return $this;
10✔
2874
    }
2875

2876
    public function getSuppressFormulaErrors(): bool
2877
    {
2878
        return $this->suppressFormulaErrors;
12✔
2879
    }
2880

2881
    public static function boolToString(mixed $operand1): mixed
2882
    {
2883
        if (is_bool($operand1)) {
31✔
2884
            $operand1 = ($operand1) ? self::$localeBoolean['TRUE'] : self::$localeBoolean['FALSE'];
1✔
2885
        } elseif ($operand1 === null) {
31✔
UNCOV
2886
            $operand1 = '';
×
2887
        }
2888

2889
        return $operand1;
31✔
2890
    }
2891

2892
    private static function isNumericOrBool(mixed $operand): bool
2893
    {
2894
        return is_numeric($operand) || is_bool($operand);
41✔
2895
    }
2896

2897
    private static function makeError(mixed $operand = ''): string
2898
    {
2899
        return (is_string($operand) && Information\ErrorValue::isError($operand)) ? $operand : ExcelError::VALUE();
3✔
2900
    }
2901

2902
    private static function swapOperands(Stack $stack, string $opCharacter): bool
2903
    {
2904
        $retVal = false;
1,847✔
2905
        if ($stack->count() > 0) {
1,847✔
2906
            $o2 = $stack->last();
1,363✔
2907
            if ($o2) {
1,363✔
2908
                if (isset(self::CALCULATION_OPERATORS[$o2['value']])) {
1,363✔
2909
                    $retVal = (self::OPERATOR_PRECEDENCE[$opCharacter] ?? 0) <= self::OPERATOR_PRECEDENCE[$o2['value']];
123✔
2910
                }
2911
            }
2912
        }
2913

2914
        return $retVal;
1,847✔
2915
    }
2916

2917
    public function getSpreadsheet(): ?Spreadsheet
2918
    {
2919
        return $this->spreadsheet;
2✔
2920
    }
2921
}
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