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

PHPOffice / PhpSpreadsheet / 18013951085

25 Sep 2025 04:20PM UTC coverage: 95.867% (+0.3%) from 95.602%
18013951085

push

github

web-flow
Merge pull request #4663 from oleibman/tweakcoveralls

Tweak Coveralls

45116 of 47061 relevant lines covered (95.87%)

373.63 hits per line

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

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

3
namespace PhpOffice\PhpSpreadsheet\Calculation;
4

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

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

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

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

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

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

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

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

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

91
    private BranchPruner $branchPruner;
92

93
    private bool $branchPruningEnabled = true;
94

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

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

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

122
    private bool $suppressFormulaErrors = false;
123

124
    private bool $processingAnchorArray = false;
125

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

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

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

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

146
    private string $cyclicFormulaCell = '';
147

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

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

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

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

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

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

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

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

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

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

231
        return null;
121✔
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
210✔
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
1,159✔
248
    {
249
        return $this->debugLog;
1,159✔
250
    }
251

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

260
    /**
261
     * Set the Array Return Type (Array or Value of first element in the array).
262
     *
263
     * @param string $returnType Array return type
264
     *
265
     * @return bool Success or failure
266
     */
267
    public static function setArrayReturnType(string $returnType): bool
580✔
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
580✔
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
374✔
300
    {
301
        if (
302
            ($returnType == self::RETURN_ARRAY_AS_VALUE)
374✔
303
            || ($returnType == self::RETURN_ARRAY_AS_ERROR)
374✔
304
            || ($returnType == self::RETURN_ARRAY_AS_ARRAY)
374✔
305
        ) {
306
            $this->instanceArrayReturnType = $returnType;
373✔
307

308
            return true;
373✔
309
        }
310

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

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

332
    /**
333
     * Enable/disable calculation cache.
334
     */
335
    public function setCalculationCacheEnabled(bool $calculationCacheEnabled): self
8✔
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
220✔
363
    {
364
        $this->calculationCache = [];
220✔
365
    }
366

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

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

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

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

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

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

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

411
    /**
412
     * Wrap string values in quotes.
413
     */
414
    public static function wrapResult(mixed $value): mixed
11,582✔
415
    {
416
        if (is_string($value)) {
11,582✔
417
            //    Error values cannot be "wrapped"
418
            if (preg_match('/^' . self::CALCULATION_REGEXP_ERROR . '$/i', $value, $match)) {
3,997✔
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,196✔
425
        } elseif ((is_float($value)) && ((is_nan($value)) || (is_infinite($value)))) {
9,221✔
426
            //    Convert numeric errors to NaN error
427
            return ExcelError::NAN();
4✔
428
        }
429

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

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

447
        return $value;
10,897✔
448
    }
449

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

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

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

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

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

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

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

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

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

548
        return $result;
7,929✔
549
    }
550

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

576
        //    Parse the formula and return the token stack
577
        return $this->internalParseFormula($formula);
8,133✔
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
2,484✔
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
8,315✔
620
    {
621
        $this->debugLog->writeDebugLog('Testing cache value for cell %s', $cellReference);
8,315✔
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,315✔
625
            $this->debugLog->writeDebugLog('Retrieving value for cell %s from cache', $cellReference);
352✔
626
            // Return the cached result
627

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

630
            return true;
352✔
631
        }
632

633
        return false;
8,315✔
634
    }
635

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

643
    /**
644
     * Parse a cell formula and calculate its value.
645
     *
646
     * @param string $formula The formula to parse and calculate
647
     * @param ?string $cellID The ID (e.g. A3) of the cell that we are calculating
648
     * @param ?Cell $cell Cell to calculate
649
     * @param bool $ignoreQuotePrefix If set to true, evaluate the formyla even if the referenced cell is quote prefixed
650
     */
651
    public function _calculateFormulaValue(string $formula, ?string $cellID = null, ?Cell $cell = null, bool $ignoreQuotePrefix = false): mixed
12,034✔
652
    {
653
        $cellValue = null;
12,034✔
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,034✔
657
            return self::wrapResult((string) $formula);
1✔
658
        }
659

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

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

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

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

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

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

716
        //    Return the calculated value
717
        return $cellValue;
11,800✔
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
68✔
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
110✔
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
40✔
818
    {
819
        if (($matrix2Columns < $matrix1Columns) || ($matrix2Rows < $matrix1Rows)) {
40✔
820
            if ($matrix2Rows < $matrix1Rows) {
1✔
821
                for ($i = $matrix2Rows; $i < $matrix1Rows; ++$i) {
1✔
822
                    unset($matrix1[$i]);
1✔
823
                }
824
            }
825
            if ($matrix2Columns < $matrix1Columns) {
1✔
826
                for ($i = 0; $i < $matrix1Rows; ++$i) {
1✔
827
                    for ($j = $matrix2Columns; $j < $matrix1Columns; ++$j) {
1✔
828
                        unset($matrix1[$i][$j]);
1✔
829
                    }
830
                }
831
            }
832
        }
833

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

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

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

899
    /**
900
     * Format details of an operand for display in the log (based on operand type).
901
     *
902
     * @param mixed $value First matrix operand
903
     */
904
    private function showValue(mixed $value): mixed
11,778✔
905
    {
906
        if ($this->debugLog->getWriteDebugLog()) {
11,778✔
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,778✔
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
11,795✔
943
    {
944
        if ($this->debugLog->getWriteDebugLog()) {
11,795✔
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,792✔
974
    }
975

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

979
    /**
980
     * @return false|string False indicates an error
981
     */
982
    private function convertMatrixReferences(string $formula): false|string
12,175✔
983
    {
984
        //    Convert any Excel matrix references to the MKMATRIX() function
985
        if (str_contains($formula, self::FORMULA_OPEN_MATRIX_BRACE)) {
12,175✔
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,175✔
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
12,175✔
1059
    {
1060
        if (($formula = $this->convertMatrixReferences(trim($formula))) === false) {
12,175✔
1061
            return false;
×
1062
        }
1063
        $phpSpreadsheetFunctions = &self::getFunctionsAddress();
12,175✔
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,175✔
1068

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

1081
        //    Start with initialisation
1082
        $index = 0;
12,175✔
1083
        $stack = new Stack($this->branchPruner);
12,175✔
1084
        $output = [];
12,175✔
1085
        $expectingOperator = false; //    We use this test in syntax-checking the expression to determine when a
12,175✔
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,175✔
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,175✔
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,175✔
1096

1097
            $opCharacter = $formula[$index]; //    Get the first character of the value at the current index position
12,175✔
1098
            if ($opCharacter === "\xe2") { // intersection or union
12,175✔
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,175✔
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,175✔
1110

1111
            $expectingOperatorCopy = $expectingOperator;
12,175✔
1112
            if ($opCharacter === '-' && !$expectingOperator) {                //    Is it a negation instead of a minus?
12,175✔
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,175✔
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,175✔
1121
                ++$index; //    Drop the redundant plus symbol
7✔
1122
            } elseif ((($opCharacter === '~') /*|| ($opCharacter === '∩') || ($opCharacter === '∪')*/) && (!$isOperandOrFunction)) {
12,175✔
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,175✔
1126
                while (self::swapOperands($stack, $opCharacter)) {
1,846✔
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,846✔
1132

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

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

1146
                if (is_array($d) && preg_match('/^' . self::CALCULATION_REGEXP_FUNCTION . '$/miu', StringHelper::convertToString($d['value']), $matches)) {
11,790✔
1147
                    //    Did this parenthesis just close a function?
1148
                    try {
1149
                        $this->branchPruner->closingBrace($d['value']);
11,785✔
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,785✔
1155
                    $d = $stack->pop();
11,785✔
1156
                    $argumentCount = $d['value'] ?? 0; //    See how many arguments there were (argument count is the next value stored on the stack)
11,785✔
1157
                    $output[] = $d; //    Dump the argument count on the output
11,785✔
1158
                    $output[] = $stack->pop(); //    Pop the function and push onto the output
11,785✔
1159
                    if (isset(self::$controlFunctions[$functionName])) {
11,785✔
1160
                        $expectedArgumentCount = self::$controlFunctions[$functionName]['argumentCount'];
819✔
1161
                    } elseif (isset($phpSpreadsheetFunctions[$functionName])) {
11,782✔
1162
                        $expectedArgumentCount = $phpSpreadsheetFunctions[$functionName]['argumentCount'];
11,782✔
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,785✔
1168
                    $expectedArgumentCountString = null;
11,785✔
1169
                    if (is_numeric($expectedArgumentCount)) {
11,785✔
1170
                        if ($expectedArgumentCount < 0) {
5,937✔
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,900✔
1177
                                $argumentCountError = true;
142✔
1178
                                $expectedArgumentCountString = $expectedArgumentCount;
142✔
1179
                            }
1180
                        }
1181
                    } elseif (is_string($expectedArgumentCount) && $expectedArgumentCount !== '*') {
6,611✔
1182
                        if (1 !== preg_match('/(\d*)([-+,])(\d*)/', $expectedArgumentCount, $argMatch)) {
6,134✔
1183
                            $argMatch = ['', '', '', ''];
1✔
1184
                        }
1185
                        switch ($argMatch[2]) {
6,134✔
1186
                            case '+':
6,134✔
1187
                                if ($argumentCount < $argMatch[1]) {
1,176✔
1188
                                    $argumentCountError = true;
27✔
1189
                                    $expectedArgumentCountString = $argMatch[1] . ' or more ';
27✔
1190
                                }
1191

1192
                                break;
1,176✔
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,785✔
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,570✔
1215
            } elseif ($opCharacter === ',') { // Is this the separator for function arguments?
12,175✔
1216
                try {
1217
                    $this->branchPruner->argumentSeparator();
8,034✔
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,034✔
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,034✔
1228
                    $output[] = $stack->getStackItem('Empty Argument', null, 'NULL');
120✔
1229
                }
1230
                // make sure there was a function
1231
                $d = $stack->last(2);
8,034✔
1232
                /** @var string */
1233
                $temp = $d['value'] ?? '';
8,034✔
1234
                if (!preg_match('/^' . self::CALCULATION_REGEXP_FUNCTION . '$/miu', $temp, $matches)) {
8,034✔
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 ,');
×
1240
                    /* The following code may be a better choice, but, with
1241
                       the other changes for this PR, I can no longer come up
1242
                       with a test case that gets here
1243
                    $stack->push('Binary Operator', '∪');
1244

1245
                    ++$index;
1246
                    $expectingOperator = false;
1247

1248
                    continue;*/
1249
                }
1250

1251
                /** @var array<string, int> $d */
1252
                $d = $stack->pop();
8,034✔
1253
                ++$d['value']; // increment the argument count
8,034✔
1254

1255
                $stack->pushStackItem($d);
8,034✔
1256
                $stack->push('Brace', '('); // put the ( back on, we'll need to pop back to it again
8,034✔
1257

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

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

1283
                    $this->branchPruner->functionCall($valToUpper);
11,792✔
1284

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

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

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

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

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

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

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

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

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

1508
                break;
11,946✔
1509
            }
1510
            //    Ignore white space
1511
            while (($formula[$index] === "\n") || ($formula[$index] === "\r")) {
12,138✔
1512
                ++$index;
×
1513
            }
1514

1515
            if ($formula[$index] === ' ') {
12,138✔
1516
                while ($formula[$index] === ' ') {
2,072✔
1517
                    ++$index;
2,072✔
1518
                }
1519

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

1546
        while (($op = $stack->pop()) !== null) {
11,946✔
1547
            // pop everything off the stack and push onto output
1548
            if ($op['value'] == '(') {
755✔
1549
                return $this->raiseFormulaError("Formula Error: Expecting ')'"); // if there are any opening braces on the stack, then braces were unbalanced
5✔
1550
            }
1551
            $output[] = $op;
752✔
1552
        }
1553

1554
        return $output;
11,943✔
1555
    }
1556

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

1567
                return $operand[$rowKey];
6✔
1568
            }
1569

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

1577
        return $operand;
1,730✔
1578
    }
1579

1580
    private static int $matchIndex8 = 8;
1581

1582
    private static int $matchIndex9 = 9;
1583

1584
    private static int $matchIndex10 = 10;
1585

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

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

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

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

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

1651
                    continue;
60✔
1652
                }
1653
            }
1654

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

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

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

1685
                    continue;
56✔
1686
                }
1687
            }
1688

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

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

1727
                $operand1 = self::dataTestReference($operand1Data);
1,730✔
1728
                $operand2 = self::dataTestReference($operand2Data);
1,730✔
1729

1730
                //    Log what we're doing
1731
                if ($token == ':') {
1,730✔
1732
                    $this->debugLog->writeDebugLog('Evaluating Range %s %s %s', $this->showValue($operand1Data['reference']), $token, $this->showValue($operand2Data['reference']));
1,250✔
1733
                } else {
1734
                    $this->debugLog->writeDebugLog('Evaluating %s %s %s', $this->showValue($operand1), $token, $this->showValue($operand2));
758✔
1735
                }
1736

1737
                //    Process the operation in the appropriate manner
1738
                switch ($token) {
1739
                    // Comparison (Boolean) Operators
1740
                    case '>': // Greater than
1,730✔
1741
                    case '<': // Less than
1,715✔
1742
                    case '>=': // Greater than or Equal to
1,698✔
1743
                    case '<=': // Less than or Equal to
1,690✔
1744
                    case '=': // Equality
1,672✔
1745
                    case '<>': // Inequality
1,519✔
1746
                        $result = $this->executeBinaryComparisonOperation($operand1, $operand2, (string) $token, $stack);
413✔
1747
                        if (isset($storeKey)) {
413✔
1748
                            $branchStore[$storeKey] = $result;
70✔
1749
                        }
1750

1751
                        break;
413✔
1752
                    // Binary Operators
1753
                    case ':': // Range
1,509✔
1754
                        if ($operand1Data['type'] === 'Error') {
1,250✔
1755
                            $stack->push($operand1Data['type'], $operand1Data['value'], null);
6✔
1756

1757
                            break;
6✔
1758
                        }
1759
                        if ($operand2Data['type'] === 'Error') {
1,245✔
1760
                            $stack->push($operand2Data['type'], $operand2Data['value'], null);
4✔
1761

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

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

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

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

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

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

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

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

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

1916
                        if (isset($storeKey)) {
27✔
1917
                            $branchStore[$storeKey] = $result;
×
1918
                        }
1919

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

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

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

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

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

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

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

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

2169
                    //    Reverse the order of the arguments
2170
                    krsort($args);
11,513✔
2171
                    krsort($emptyArguments);
11,513✔
2172

2173
                    if ($argCount > 0 && is_array($functionCall)) {
11,513✔
2174
                        /** @var string[] */
2175
                        $functionCallCopy = $functionCall;
11,495✔
2176
                        $args = $this->addDefaultArgumentValues($functionCallCopy, $args, $emptyArguments);
11,495✔
2177
                    }
2178

2179
                    if (($passByReference) && ($argCount == 0)) {
11,513✔
2180
                        $args[] = $cellID;
9✔
2181
                        $argArrayVals[] = $this->showValue($cellID);
9✔
2182
                    }
2183

2184
                    if ($functionName !== 'MKMATRIX') {
11,513✔
2185
                        if ($this->debugLog->getWriteDebugLog()) {
11,512✔
2186
                            krsort($argArrayVals);
2✔
2187
                            $this->debugLog->writeDebugLog('Evaluating %s ( %s )', self::localeFunc($functionName), implode(self::$localeArgumentSeparator . ' ', Functions::flattenArray($argArrayVals)));
2✔
2188
                        }
2189
                    }
2190

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

2198
                    if (!is_array($functionCall)) {
11,513✔
2199
                        foreach ($args as &$arg) {
54✔
2200
                            $arg = Functions::flattenSingleValue($arg);
1✔
2201
                        }
2202
                        unset($arg);
54✔
2203
                    }
2204

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

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

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

2295
        return $output;
11,798✔
2296
    }
2297

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

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

2327
                    return false;
6✔
2328
                }
2329
            }
2330
        }
2331

2332
        //    return a true if the value of the operand is one that we can use in normal binary mathematical operations
2333
        return true;
1,463✔
2334
    }
2335

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

2378
        return $result;
56✔
2379
    }
2380

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

2389
        $result = BinaryComparison::compare($operand1, $operand2, $operation);
413✔
2390

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

2396
        return $result;
413✔
2397
    }
2398

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

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

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

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

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

2455
                            break;
3✔
2456
                        case '-':
34✔
2457
                            $operand1[$row][$column] = $operand1Val - $operand2Val;
3✔
2458

2459
                            break;
3✔
2460
                        case '*':
32✔
2461
                            $operand1[$row][$column] = $operand1Val * $operand2Val;
25✔
2462

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

2471
                            break;
5✔
2472
                        case '^':
2✔
2473
                            $operand1[$row][$column] = $operand1Val ** $operand2Val;
2✔
2474

2475
                            break;
2✔
2476

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

2492
                    break;
162✔
2493
                //    Subtraction
2494
                case '-':
1,360✔
2495
                    $result = $operand1 - $operand2;
51✔
2496

2497
                    break;
51✔
2498
                //    Multiplication
2499
                case '*':
1,325✔
2500
                    $result = $operand1 * $operand2;
1,247✔
2501

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

2510
                        return false;
61✔
2511
                    }
2512
                    $result = $operand1 / $operand2;
61✔
2513

2514
                    break;
61✔
2515
                //    Power
2516
                case '^':
3✔
2517
                    $result = $operand1 ** $operand2;
3✔
2518

2519
                    break;
3✔
2520

2521
                default:
2522
                    throw new Exception('Unsupported numeric binary operation');
×
2523
            }
2524
        }
2525

2526
        //    Log the result details
2527
        $this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($result));
1,414✔
2528
        //    And push the result onto the stack
2529
        $stack->push('Value', $result);
1,414✔
2530

2531
        return $result;
1,414✔
2532
    }
2533

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

2550
        return false;
2✔
2551
    }
2552

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

2568
        if ($worksheet !== null) {
6,997✔
2569
            $worksheetName = $worksheet->getTitle();
6,996✔
2570

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

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

2621
        return $returnValue;
6,997✔
2622
    }
2623

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

2638
        if ($worksheet !== null) {
1✔
2639
            if (str_contains($range, '!')) {
1✔
2640
                [$worksheetName, $range] = Worksheet::extractSheetTitle($range, true, true);
1✔
2641
                $worksheet = ($this->spreadsheet === null) ? null : $this->spreadsheet->getSheetByName($worksheetName);
1✔
2642
            }
2643

2644
            // Named range?
2645
            $namedRange = ($worksheet === null) ? null : DefinedName::resolveName($range, $worksheet);
1✔
2646
            if ($namedRange === null) {
1✔
2647
                return ExcelError::REF();
1✔
2648
            }
2649

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

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

2685
        return $returnValue;
1✔
2686
    }
2687

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

2699
        return !$notImplemented;
3✔
2700
    }
2701

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

2717
        return $returnValue;
2✔
2718
    }
2719

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

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

2744
                    $args[$argumentId] = $this->getArgumentDefaultValue($methodArguments[$reflectedArgumentId]);
135✔
2745
                }
2746
            }
2747
        }
2748

2749
        return $args;
11,495✔
2750
    }
2751

2752
    private function getArgumentDefaultValue(ReflectionParameter $methodArgument): mixed
135✔
2753
    {
2754
        $defaultValue = null;
135✔
2755

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

2765
                    return $constantReflector->getValue();
2✔
2766
                }
2767

2768
                return constant($constantName);
×
2769
            }
2770
        }
2771

2772
        return $defaultValue;
134✔
2773
    }
2774

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

2790
                $reflectionMethod = new ReflectionMethod($className, $methodName);
241✔
2791
                $argumentCount = count($reflectionMethod->getParameters());
241✔
2792
                while (count($args) < $argumentCount - 1) {
241✔
2793
                    $args[] = null;
56✔
2794
                }
2795
            }
2796

2797
            $args[] = $cell;
241✔
2798
        }
2799

2800
        return $args;
11,513✔
2801
    }
2802

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

2811
            return $result;
×
2812
        }
2813

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

2826
        if ($definedNameValue[0] !== '=') {
137✔
2827
            $definedNameValue = '=' . $definedNameValue;
114✔
2828
        }
2829

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

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

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

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

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

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

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

2869
        return $result;
137✔
2870
    }
2871

2872
    public function setSuppressFormulaErrors(bool $suppressFormulaErrors): self
10✔
2873
    {
2874
        $this->suppressFormulaErrors = $suppressFormulaErrors;
10✔
2875

2876
        return $this;
10✔
2877
    }
2878

2879
    public function getSuppressFormulaErrors(): bool
12✔
2880
    {
2881
        return $this->suppressFormulaErrors;
12✔
2882
    }
2883

2884
    public static function boolToString(mixed $operand1): mixed
32✔
2885
    {
2886
        if (is_bool($operand1)) {
32✔
2887
            $operand1 = ($operand1) ? self::$localeBoolean['TRUE'] : self::$localeBoolean['FALSE'];
1✔
2888
        } elseif ($operand1 === null) {
32✔
2889
            $operand1 = '';
1✔
2890
        }
2891

2892
        return $operand1;
32✔
2893
    }
2894

2895
    private static function isNumericOrBool(mixed $operand): bool
41✔
2896
    {
2897
        return is_numeric($operand) || is_bool($operand);
41✔
2898
    }
2899

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

2905
    private static function swapOperands(Stack $stack, string $opCharacter): bool
1,849✔
2906
    {
2907
        $retVal = false;
1,849✔
2908
        if ($stack->count() > 0) {
1,849✔
2909
            $o2 = $stack->last();
1,364✔
2910
            if ($o2) {
1,364✔
2911
                /** @var array{value: string} $o2 */
2912
                if (isset(self::CALCULATION_OPERATORS[$o2['value']])) {
1,364✔
2913
                    $retVal = (self::OPERATOR_PRECEDENCE[$opCharacter] ?? 0) <= self::OPERATOR_PRECEDENCE[$o2['value']];
123✔
2914
                }
2915
            }
2916
        }
2917

2918
        return $retVal;
1,849✔
2919
    }
2920

2921
    public function getSpreadsheet(): ?Spreadsheet
2✔
2922
    {
2923
        return $this->spreadsheet;
2✔
2924
    }
2925
}
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