Cell   F
last analyzed

Complexity

Total Complexity 178

Size/Duplication

Total Lines 975
Duplicated Lines 0 %

Test Coverage

Coverage 93.78%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 178
eloc 371
dl 0
loc 975
ccs 377
cts 402
cp 0.9378
rs 2
c 1
b 0
f 0

52 Methods

Rating   Name   Duplication   Size   Complexity  
A detach() 0 3 1
A attach() 0 3 1
A getValue() 0 3 1
A getCoordinate() 0 13 3
A getRow() 0 8 2
A getColumn() 0 8 2
A getFormattedValue() 0 11 1
A updateInCollection() 0 9 2
A getDataType() 0 3 1
A getStyle() 0 3 1
A setDataValidation() 0 9 2
A getOldCalculatedValue() 0 3 1
A compareCells() 0 11 4
A rebindParent() 0 5 1
A getAppliedStyle() 0 13 3
A __clone() 0 8 4
A getDataValidation() 0 7 2
A setValueBinder() 0 3 1
A getParent() 0 3 1
A isInRange() 0 11 4
A isFormula() 0 3 2
A isHiddenOnFormulaBar() 0 12 3
A setFormulaAttributes() 0 5 1
A isInMergeRange() 0 3 1
A getWorksheetOrNull() 0 10 2
A isLocked() 0 9 2
A getValueBinder() 0 7 2
A getHyperlink() 0 7 2
A getWorksheet() 0 14 3
A setHyperlink() 0 9 2
A getXfIndex() 0 3 1
A isMergeRangeValueCell() 0 10 2
A getIgnoredErrors() 0 3 1
A hasValidValue() 0 5 1
A hasHyperlink() 0 7 2
A getFormulaAttributes() 0 3 1
A hasDataValidation() 0 7 2
A setXfIndex() 0 5 1
A setDataType() 0 5 1
A setCalculatedValue() 0 7 4
A getMergeRange() 0 9 3
A __construct() 0 21 4
A getValueString() 0 3 1
A getCalculatedValueString() 0 8 2
A convertDateTimeInt() 0 15 6
A __toString() 0 5 1
F setValueExplicit() 0 77 21
A setCalculateDateTimeType() 0 5 1
A getCalculateDateTimeType() 0 3 1
A updateIfCellIsTableHeader() 0 17 6
F getCalculatedValue() 0 175 56
A setValue() 0 9 2

How to fix   Complexity   

Complex Class

Complex classes like Cell often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Cell, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace PhpOffice\PhpSpreadsheet\Cell;
4
5
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
6
use PhpOffice\PhpSpreadsheet\Calculation\Exception as CalculationException;
7
use PhpOffice\PhpSpreadsheet\Calculation\Functions;
8
use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError;
9
use PhpOffice\PhpSpreadsheet\Collection\Cells;
10
use PhpOffice\PhpSpreadsheet\Exception as SpreadsheetException;
11
use PhpOffice\PhpSpreadsheet\RichText\RichText;
12
use PhpOffice\PhpSpreadsheet\Shared\Date as SharedDate;
13
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
14
use PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\CellStyleAssessor;
15
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
16
use PhpOffice\PhpSpreadsheet\Style\Protection;
17
use PhpOffice\PhpSpreadsheet\Style\Style;
18
use PhpOffice\PhpSpreadsheet\Worksheet\Table;
19
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
20
use Stringable;
21
22
class Cell implements Stringable
23
{
24
    /**
25
     * Value binder to use.
26
     */
27
    private static ?IValueBinder $valueBinder = null;
28
29
    /**
30
     * Value of the cell.
31
     */
32
    private mixed $value;
33
34
    /**
35
     *    Calculated value of the cell (used for caching)
36
     *    This returns the value last calculated by MS Excel or whichever spreadsheet program was used to
37
     *        create the original spreadsheet file.
38
     *    Note that this value is not guaranteed to reflect the actual calculated value because it is
39
     *        possible that auto-calculation was disabled in the original spreadsheet, and underlying data
40
     *        values used by the formula have changed since it was last calculated.
41
     *
42
     * @var mixed
43
     */
44
    private $calculatedValue;
45
46
    /**
47
     * Type of the cell data.
48
     */
49
    private string $dataType;
50
51
    /**
52
     * The collection of cells that this cell belongs to (i.e. The Cell Collection for the parent Worksheet).
53
     */
54
    private ?Cells $parent;
55
56
    /**
57
     * Index to the cellXf reference for the styling of this cell.
58
     */
59
    private int $xfIndex = 0;
60
61
    /**
62
     * Attributes of the formula.
63
     *
64
     * @var null|array<string, string>
65
     */
66
    private ?array $formulaAttributes = null;
67
68
    private IgnoredErrors $ignoredErrors;
69
70
    /**
71
     * Update the cell into the cell collection.
72
     *
73
     * @throws SpreadsheetException
74
     */
75 10126
    public function updateInCollection(): self
76
    {
77 10126
        $parent = $this->parent;
78 10126
        if ($parent === null) {
79 2
            throw new SpreadsheetException('Cannot update when cell is not bound to a worksheet');
80
        }
81 10124
        $parent->update($this);
82
83 10124
        return $this;
84
    }
85
86 10033
    public function detach(): void
87
    {
88 10033
        $this->parent = null;
89
    }
90
91 8881
    public function attach(Cells $parent): void
92
    {
93 8881
        $this->parent = $parent;
94
    }
95
96
    /**
97
     * Create a new Cell.
98
     *
99
     * @throws SpreadsheetException
100
     */
101 10165
    public function __construct(mixed $value, ?string $dataType, Worksheet $worksheet)
102
    {
103
        // Initialise cell value
104 10165
        $this->value = $value;
105
106
        // Set worksheet cache
107 10165
        $this->parent = $worksheet->getCellCollection();
108
109
        // Set datatype?
110 10165
        if ($dataType !== null) {
111 10165
            if ($dataType == DataType::TYPE_STRING2) {
112
                $dataType = DataType::TYPE_STRING;
113
            }
114 10165
            $this->dataType = $dataType;
115
        } else {
116
            $valueBinder = $worksheet->getParent()?->getValueBinder() ?? self::getValueBinder();
117
            if ($valueBinder->bindValue($this, $value) === false) {
118
                throw new SpreadsheetException('Value could not be bound to cell.');
119
            }
120
        }
121 10165
        $this->ignoredErrors = new IgnoredErrors();
122
    }
123
124
    /**
125
     * Get cell coordinate column.
126
     *
127
     * @throws SpreadsheetException
128
     */
129 8171
    public function getColumn(): string
130
    {
131 8171
        $parent = $this->parent;
132 8171
        if ($parent === null) {
133 1
            throw new SpreadsheetException('Cannot get column when cell is not bound to a worksheet');
134
        }
135
136 8170
        return $parent->getCurrentColumn();
137
    }
138
139
    /**
140
     * Get cell coordinate row.
141
     *
142
     * @throws SpreadsheetException
143
     */
144 654
    public function getRow(): int
145
    {
146 654
        $parent = $this->parent;
147 654
        if ($parent === null) {
148 1
            throw new SpreadsheetException('Cannot get row when cell is not bound to a worksheet');
149
        }
150
151 653
        return $parent->getCurrentRow();
152
    }
153
154
    /**
155
     * Get cell coordinate.
156
     *
157
     * @throws SpreadsheetException
158
     */
159 10137
    public function getCoordinate(): string
160
    {
161 10137
        $parent = $this->parent;
162 10137
        if ($parent !== null) {
163 10137
            $coordinate = $parent->getCurrentCoordinate();
164
        } else {
165 2
            $coordinate = null;
166
        }
167 10137
        if ($coordinate === null) {
168 2
            throw new SpreadsheetException('Coordinate no longer exists');
169
        }
170
171 10137
        return $coordinate;
172
    }
173
174
    /**
175
     * Get cell value.
176
     */
177 9464
    public function getValue(): mixed
178
    {
179 9464
        return $this->value;
180
    }
181
182 656
    public function getValueString(): string
183
    {
184 656
        return StringHelper::convertToString($this->value, false);
185
    }
186
187
    /**
188
     * Get cell value with formatting.
189
     */
190 100
    public function getFormattedValue(): string
191
    {
192 100
        $currentCalendar = SharedDate::getExcelCalendar();
193 100
        SharedDate::setExcelCalendar($this->getWorksheet()->getParent()?->getExcelCalendar());
194 100
        $formattedValue = (string) NumberFormat::toFormattedString(
195 100
            $this->getCalculatedValueString(),
196 100
            (string) $this->getStyle()->getNumberFormat()->getFormatCode(true)
197 100
        );
198 100
        SharedDate::setExcelCalendar($currentCalendar);
199
200 100
        return $formattedValue;
201
    }
202
203 10071
    protected static function updateIfCellIsTableHeader(?Worksheet $workSheet, self $cell, mixed $oldValue, mixed $newValue): void
204
    {
205 10071
        $oldValue = StringHelper::convertToString($oldValue, false);
206 10071
        $newValue = StringHelper::convertToString($newValue, false);
207 10071
        if (StringHelper::strToLower($oldValue) === StringHelper::strToLower($newValue) || $workSheet === null) {
208 936
            return;
209
        }
210
211 10048
        foreach ($workSheet->getTableCollection() as $table) {
212
            /** @var Table $table */
213 10
            if ($cell->isInRange($table->getRange())) {
214 7
                $rangeRowsColumns = Coordinate::getRangeBoundaries($table->getRange());
215 7
                if ($cell->getRow() === (int) $rangeRowsColumns[0][1]) {
216 4
                    Table\Column::updateStructuredReferences($workSheet, $oldValue, $newValue);
217
                }
218
219 7
                return;
220
            }
221
        }
222
    }
223
224
    /**
225
     * Set cell value.
226
     *
227
     *    Sets the value for a cell, automatically determining the datatype using the value binder
228
     *
229
     * @param mixed $value Value
230
     * @param null|IValueBinder $binder Value Binder to override the currently set Value Binder
231
     *
232
     * @throws SpreadsheetException
233
     */
234 9651
    public function setValue(mixed $value, ?IValueBinder $binder = null): self
235
    {
236
        // Cells?->Worksheet?->Spreadsheet
237 9651
        $binder ??= $this->parent?->getParent()?->getParent()?->getValueBinder() ?? self::getValueBinder();
238 9651
        if (!$binder->bindValue($this, $value)) {
239
            throw new SpreadsheetException('Value could not be bound to cell.');
240
        }
241
242 9650
        return $this;
243
    }
244
245
    /**
246
     * Set the value for a cell, with the explicit data type passed to the method (bypassing any use of the value binder).
247
     *
248
     * @param mixed $value Value
249
     * @param string $dataType Explicit data type, see DataType::TYPE_*
250
     *        Note that PhpSpreadsheet does not validate that the value and datatype are consistent, in using this
251
     *             method, then it is your responsibility as an end-user developer to validate that the value and
252
     *             the datatype match.
253
     *       If you do mismatch value and datatype, then the value you enter may be changed to match the datatype
254
     *          that you specify.
255
     *
256
     * @throws SpreadsheetException
257
     */
258 10077
    public function setValueExplicit(mixed $value, string $dataType = DataType::TYPE_STRING): self
259
    {
260 10077
        $oldValue = $this->value;
261 10077
        $quotePrefix = false;
262
263
        // set the value according to data type
264
        switch ($dataType) {
265 263
            case DataType::TYPE_NULL:
266 618
                $this->value = null;
267
268 618
                break;
269 263
            case DataType::TYPE_STRING2:
270 4
                $dataType = DataType::TYPE_STRING;
271
                // no break
272 263
            case DataType::TYPE_STRING:
273
                // Synonym for string
274 5168
                if (is_string($value) && strlen($value) > 1 && $value[0] === '=') {
275 40
                    $quotePrefix = true;
276
                }
277
                // no break
278 242
            case DataType::TYPE_INLINE:
279
                // Rich text
280 5184
                $value2 = StringHelper::convertToString($value, true);
281 5182
                $this->value = DataType::checkString(($value instanceof RichText) ? $value : $value2);
282
283 5182
                break;
284 241
            case DataType::TYPE_NUMERIC:
285 7198
                if ($value !== null && !is_bool($value) && !is_numeric($value)) {
286 2
                    throw new SpreadsheetException('Invalid numeric value for datatype Numeric');
287
                }
288 7197
                $this->value = 0 + $value;
289
290 7197
                break;
291 187
            case DataType::TYPE_FORMULA:
292 8433
                $this->value = StringHelper::convertToString($value, true);
293
294 8432
                break;
295 18
            case DataType::TYPE_BOOL:
296 613
                $this->value = (bool) $value;
297
298 613
                break;
299
            case DataType::TYPE_ISO_DATE:
300 6
                $this->value = SharedDate::convertIsoDate($value);
301 5
                $dataType = DataType::TYPE_NUMERIC;
302
303 5
                break;
304
            case DataType::TYPE_ERROR:
305 21
                $this->value = DataType::checkErrorCode($value);
306
307 21
                break;
308
            default:
309 1
                throw new SpreadsheetException('Invalid datatype: ' . $dataType);
310
        }
311
312
        // set the datatype
313 10072
        $this->dataType = $dataType;
314
315 10072
        $this->updateInCollection();
316 10071
        $cellCoordinate = $this->getCoordinate();
317 10071
        self::updateIfCellIsTableHeader($this->getParent()?->getParent(), $this, $oldValue, $value);
318 10071
        $worksheet = $this->getWorksheet();
319 10071
        $spreadsheet = $worksheet->getParent();
320 10071
        if (isset($spreadsheet) && $spreadsheet->getIndex($worksheet, true) >= 0) {
321 10067
            $originalSelected = $worksheet->getSelectedCells();
322 10067
            $activeSheetIndex = $spreadsheet->getActiveSheetIndex();
323 10067
            $style = $this->getStyle();
324 10067
            $oldQuotePrefix = $style->getQuotePrefix();
325 10067
            if ($oldQuotePrefix !== $quotePrefix) {
326 40
                $style->setQuotePrefix($quotePrefix);
327
            }
328 10067
            $worksheet->setSelectedCells($originalSelected);
329 10067
            if ($activeSheetIndex >= 0) {
330 10067
                $spreadsheet->setActiveSheetIndex($activeSheetIndex);
331
            }
332
        }
333
334 10071
        return $this->getParent()?->get($cellCoordinate) ?? $this;
335
    }
336
337
    public const CALCULATE_DATE_TIME_ASIS = 0;
338
    public const CALCULATE_DATE_TIME_FLOAT = 1;
339
    public const CALCULATE_TIME_FLOAT = 2;
340
341
    private static int $calculateDateTimeType = self::CALCULATE_DATE_TIME_ASIS;
342
343 45
    public static function getCalculateDateTimeType(): int
344
    {
345 45
        return self::$calculateDateTimeType;
346
    }
347
348
    /** @throws CalculationException */
349 45
    public static function setCalculateDateTimeType(int $calculateDateTimeType): void
350
    {
351 45
        self::$calculateDateTimeType = match ($calculateDateTimeType) {
352 45
            self::CALCULATE_DATE_TIME_ASIS, self::CALCULATE_DATE_TIME_FLOAT, self::CALCULATE_TIME_FLOAT => $calculateDateTimeType,
353 1
            default => throw new CalculationException("Invalid value $calculateDateTimeType for calculated date time type"),
354 45
        };
355
    }
356
357
    /**
358
     * Convert date, time, or datetime from int to float if desired.
359
     */
360 8838
    private function convertDateTimeInt(mixed $result): mixed
361
    {
362 8838
        if (is_int($result)) {
363 5052
            if (self::$calculateDateTimeType === self::CALCULATE_TIME_FLOAT) {
364 4
                if (SharedDate::isDateTime($this, $result, false)) {
365 2
                    $result = (float) $result;
366
                }
367 5048
            } elseif (self::$calculateDateTimeType === self::CALCULATE_DATE_TIME_FLOAT) {
368 4
                if (SharedDate::isDateTime($this, $result, true)) {
369 3
                    $result = (float) $result;
370
                }
371
            }
372
        }
373
374 8838
        return $result;
375
    }
376
377
    /**
378
     * Get calculated cell value converted to string.
379
     */
380 866
    public function getCalculatedValueString(): string
381
    {
382 866
        $value = $this->getCalculatedValue();
383 866
        while (is_array($value)) {
384 12
            $value = array_shift($value);
385
        }
386
387 866
        return StringHelper::convertToString($value, false);
388
    }
389
390
    /**
391
     * Get calculated cell value.
392
     *
393
     * @param bool $resetLog Whether the calculation engine logger should be reset or not
394
     *
395
     * @throws CalculationException
396
     */
397 9084
    public function getCalculatedValue(bool $resetLog = true): mixed
398
    {
399 9084
        $title = 'unknown';
400 9084
        $oldAttributes = $this->formulaAttributes;
401 9084
        $oldAttributesT = $oldAttributes['t'] ?? '';
402 9084
        $coordinate = $this->getCoordinate();
403 9084
        $oldAttributesRef = $oldAttributes['ref'] ?? $coordinate;
404 9084
        $originalValue = $this->value;
405 9084
        $originalDataType = $this->dataType;
406 9084
        $this->formulaAttributes = [];
407 9084
        $spill = false;
408
409 9084
        if ($this->dataType === DataType::TYPE_FORMULA) {
410
            try {
411 8080
                $currentCalendar = SharedDate::getExcelCalendar();
412 8080
                SharedDate::setExcelCalendar($this->getWorksheet()->getParent()?->getExcelCalendar());
413 8080
                $thisworksheet = $this->getWorksheet();
414 8080
                $index = $thisworksheet->getParentOrThrow()->getActiveSheetIndex();
415 8080
                $selected = $thisworksheet->getSelectedCells();
416 8080
                $title = $thisworksheet->getTitle();
417 8080
                $calculation = Calculation::getInstance($thisworksheet->getParent());
418 8080
                $result = $calculation->calculateCellValue($this, $resetLog);
419 7832
                $result = $this->convertDateTimeInt($result);
420 7832
                $thisworksheet->setSelectedCells($selected);
421 7832
                $thisworksheet->getParentOrThrow()->setActiveSheetIndex($index);
422 7832
                if (is_array($result) && $calculation->getInstanceArrayReturnType() !== Calculation::RETURN_ARRAY_AS_ARRAY) {
423
                    while (is_array($result)) {
424
                        $result = array_shift($result);
425
                    }
426
                }
427
                if (
428 7832
                    !is_array($result)
429 7832
                    && $calculation->getInstanceArrayReturnType() === Calculation::RETURN_ARRAY_AS_ARRAY
430 7832
                    && $oldAttributesT === 'array'
431 7832
                    && ($oldAttributesRef === $coordinate || $oldAttributesRef === "$coordinate:$coordinate")
432
                ) {
433 8
                    $result = [$result];
434
                }
435
                // if return_as_array for formula like '=sheet!cell'
436 7832
                if (is_array($result) && count($result) === 1) {
437 29
                    $resultKey = array_keys($result)[0];
438 29
                    $resultValue = $result[$resultKey];
439 29
                    if (is_int($resultKey) && is_array($resultValue) && count($resultValue) === 1) {
440 4
                        $resultKey2 = array_keys($resultValue)[0];
441 4
                        $resultValue2 = $resultValue[$resultKey2];
442 4
                        if (is_string($resultKey2) && !is_array($resultValue2) && preg_match('/[a-zA-Z]{1,3}/', $resultKey2) === 1) {
443
                            $result = $resultValue2;
444
                        }
445
                    }
446
                }
447 7832
                $newColumn = $this->getColumn();
448 7832
                if (is_array($result)) {
449 109
                    $this->formulaAttributes['t'] = 'array';
450 109
                    $this->formulaAttributes['ref'] = $maxCoordinate = $coordinate;
451 109
                    $newRow = $row = $this->getRow();
452 109
                    $column = $this->getColumn();
453 109
                    foreach ($result as $resultRow) {
454 109
                        if (is_array($resultRow)) {
455 108
                            $newColumn = $column;
456 108
                            foreach ($resultRow as $resultValue) {
457 108
                                if ($row !== $newRow || $column !== $newColumn) {
458 104
                                    $maxCoordinate = $newColumn . $newRow;
459 104
                                    if ($thisworksheet->getCell($newColumn . $newRow)->getValue() !== null) {
460 42
                                        if (!Coordinate::coordinateIsInsideRange($oldAttributesRef, $newColumn . $newRow)) {
461 3
                                            $spill = true;
462
463 3
                                            break;
464
                                        }
465
                                    }
466
                                }
467 108
                                ++$newColumn;
468
                            }
469 108
                            ++$newRow;
470
                        } else {
471 11
                            if ($row !== $newRow || $column !== $newColumn) {
472 3
                                $maxCoordinate = $newColumn . $newRow;
473 3
                                if ($thisworksheet->getCell($newColumn . $newRow)->getValue() !== null) {
474 3
                                    if (!Coordinate::coordinateIsInsideRange($oldAttributesRef, $newColumn . $newRow)) {
475
                                        $spill = true;
476
                                    }
477
                                }
478
                            }
479 11
                            ++$newColumn;
480
                        }
481 109
                        if ($spill) {
482 3
                            break;
483
                        }
484
                    }
485 109
                    if (!$spill) {
486 107
                        $this->formulaAttributes['ref'] .= ":$maxCoordinate";
487
                    }
488 109
                    $thisworksheet->getCell($column . $row);
489
                }
490 7832
                if (is_array($result)) {
491 109
                    if ($oldAttributes !== null && $calculation->getInstanceArrayReturnType() === Calculation::RETURN_ARRAY_AS_ARRAY) {
492 44
                        if (($oldAttributesT) === 'array') {
493 43
                            $thisworksheet = $this->getWorksheet();
494 43
                            $coordinate = $this->getCoordinate();
495 43
                            $ref = $oldAttributesRef;
496 43
                            if (preg_match('/^([A-Z]{1,3})([0-9]{1,7})(:([A-Z]{1,3})([0-9]{1,7}))?$/', $ref, $matches) === 1) {
497 43
                                if (isset($matches[3])) {
498 42
                                    $minCol = $matches[1];
499 42
                                    $minRow = (int) $matches[2];
500
                                    // https://github.com/phpstan/phpstan/issues/11602
501 42
                                    $maxCol = $matches[4]; // @phpstan-ignore-line
502 42
                                    ++$maxCol;
503 42
                                    $maxRow = (int) $matches[5]; // @phpstan-ignore-line
504 42
                                    for ($row = $minRow; $row <= $maxRow; ++$row) {
505 42
                                        for ($col = $minCol; $col !== $maxCol; ++$col) {
506 42
                                            if ("$col$row" !== $coordinate) {
507 41
                                                $thisworksheet->getCell("$col$row")->setValue(null);
508
                                            }
509
                                        }
510
                                    }
511
                                }
512
                            }
513 43
                            $thisworksheet->getCell($coordinate);
514
                        }
515
                    }
516
                }
517 7832
                if ($spill) {
518 3
                    $result = ExcelError::SPILL();
519
                }
520 7832
                if (is_array($result)) {
521 107
                    $newRow = $row = $this->getRow();
522 107
                    $newColumn = $column = $this->getColumn();
523 107
                    foreach ($result as $resultRow) {
524 107
                        if (is_array($resultRow)) {
525 106
                            $newColumn = $column;
526 106
                            foreach ($resultRow as $resultValue) {
527 106
                                if ($row !== $newRow || $column !== $newColumn) {
528 102
                                    $thisworksheet->getCell($newColumn . $newRow)->setValue($resultValue);
529
                                }
530 106
                                ++$newColumn;
531
                            }
532 106
                            ++$newRow;
533
                        } else {
534 11
                            if ($row !== $newRow || $column !== $newColumn) {
535 3
                                $thisworksheet->getCell($newColumn . $newRow)->setValue($resultRow);
536
                            }
537 11
                            ++$newColumn;
538
                        }
539
                    }
540 107
                    $thisworksheet->getCell($column . $row);
541 107
                    $this->value = $originalValue;
542 7832
                    $this->dataType = $originalDataType;
543
                }
544 269
            } catch (SpreadsheetException $ex) {
545 269
                SharedDate::setExcelCalendar($currentCalendar);
546 269
                if (($ex->getMessage() === 'Unable to access External Workbook') && ($this->calculatedValue !== null)) {
547 1
                    return $this->calculatedValue; // Fallback for calculations referencing external files.
548 269
                } elseif (preg_match('/[Uu]ndefined (name|offset: 2|array key 2)/', $ex->getMessage()) === 1) {
549 31
                    return ExcelError::NAME();
550
                }
551
552 238
                throw new CalculationException(
553 238
                    $title . '!' . $this->getCoordinate() . ' -> ' . $ex->getMessage(),
554 238
                    $ex->getCode(),
555 238
                    $ex
556 238
                );
557
            }
558 7832
            SharedDate::setExcelCalendar($currentCalendar);
559
560 7832
            if ($result === Functions::NOT_YET_IMPLEMENTED) {
561 14
                $this->formulaAttributes = $oldAttributes;
562
563 14
                return $this->calculatedValue; // Fallback if calculation engine does not support the formula.
564
            }
565
566 7823
            return $result;
567 7726
        } elseif ($this->value instanceof RichText) {
568 20
            return $this->value->getPlainText();
569
        }
570
571 7721
        return $this->convertDateTimeInt($this->value);
572
    }
573
574
    /**
575
     * Set old calculated value (cached).
576
     *
577
     * @param mixed $originalValue Value
578
     */
579 443
    public function setCalculatedValue(mixed $originalValue, bool $tryNumeric = true): self
580
    {
581 443
        if ($originalValue !== null) {
582 443
            $this->calculatedValue = ($tryNumeric && is_numeric($originalValue)) ? (0 + $originalValue) : $originalValue;
583
        }
584
585 443
        return $this->updateInCollection();
586
    }
587
588
    /**
589
     *    Get old calculated value (cached)
590
     *    This returns the value last calculated by MS Excel or whichever spreadsheet program was used to
591
     *        create the original spreadsheet file.
592
     *    Note that this value is not guaranteed to reflect the actual calculated value because it is
593
     *        possible that auto-calculation was disabled in the original spreadsheet, and underlying data
594
     *        values used by the formula have changed since it was last calculated.
595
     */
596 20
    public function getOldCalculatedValue(): mixed
597
    {
598 20
        return $this->calculatedValue;
599
    }
600
601
    /**
602
     * Get cell data type.
603
     */
604 9083
    public function getDataType(): string
605
    {
606 9083
        return $this->dataType;
607
    }
608
609
    /**
610
     * Set cell data type.
611
     *
612
     * @param string $dataType see DataType::TYPE_*
613
     */
614 2
    public function setDataType(string $dataType): self
615
    {
616 2
        $this->setValueExplicit($this->value, $dataType);
617
618 2
        return $this;
619
    }
620
621
    /**
622
     * Identify if the cell contains a formula.
623
     */
624 73
    public function isFormula(): bool
625
    {
626 73
        return $this->dataType === DataType::TYPE_FORMULA && $this->getStyle()->getQuotePrefix() === false;
627
    }
628
629
    /**
630
     *    Does this cell contain Data validation rules?
631
     *
632
     * @throws SpreadsheetException
633
     */
634 24
    public function hasDataValidation(): bool
635
    {
636 24
        if (!isset($this->parent)) {
637 1
            throw new SpreadsheetException('Cannot check for data validation when cell is not bound to a worksheet');
638
        }
639
640 23
        return $this->getWorksheet()->dataValidationExists($this->getCoordinate());
641
    }
642
643
    /**
644
     * Get Data validation rules.
645
     *
646
     * @throws SpreadsheetException
647
     */
648 29
    public function getDataValidation(): DataValidation
649
    {
650 29
        if (!isset($this->parent)) {
651 1
            throw new SpreadsheetException('Cannot get data validation for cell that is not bound to a worksheet');
652
        }
653
654 28
        return $this->getWorksheet()->getDataValidation($this->getCoordinate());
655
    }
656
657
    /**
658
     * Set Data validation rules.
659
     *
660
     * @throws SpreadsheetException
661
     */
662 3
    public function setDataValidation(?DataValidation $dataValidation = null): self
663
    {
664 3
        if (!isset($this->parent)) {
665 1
            throw new SpreadsheetException('Cannot set data validation for cell that is not bound to a worksheet');
666
        }
667
668 2
        $this->getWorksheet()->setDataValidation($this->getCoordinate(), $dataValidation);
669
670 2
        return $this->updateInCollection();
671
    }
672
673
    /**
674
     * Does this cell contain valid value?
675
     */
676 12
    public function hasValidValue(): bool
677
    {
678 12
        $validator = new DataValidator();
679
680 12
        return $validator->isValid($this);
681
    }
682
683
    /**
684
     * Does this cell contain a Hyperlink?
685
     *
686
     * @throws SpreadsheetException
687
     */
688 1
    public function hasHyperlink(): bool
689
    {
690 1
        if (!isset($this->parent)) {
691 1
            throw new SpreadsheetException('Cannot check for hyperlink when cell is not bound to a worksheet');
692
        }
693
694
        return $this->getWorksheet()->hyperlinkExists($this->getCoordinate());
695
    }
696
697
    /**
698
     * Get Hyperlink.
699
     *
700
     * @throws SpreadsheetException
701
     */
702 92
    public function getHyperlink(): Hyperlink
703
    {
704 92
        if (!isset($this->parent)) {
705 1
            throw new SpreadsheetException('Cannot get hyperlink for cell that is not bound to a worksheet');
706
        }
707
708 91
        return $this->getWorksheet()->getHyperlink($this->getCoordinate());
709
    }
710
711
    /**
712
     * Set Hyperlink.
713
     *
714
     * @throws SpreadsheetException
715
     */
716 2
    public function setHyperlink(?Hyperlink $hyperlink = null): self
717
    {
718 2
        if (!isset($this->parent)) {
719 1
            throw new SpreadsheetException('Cannot set hyperlink for cell that is not bound to a worksheet');
720
        }
721
722 1
        $this->getWorksheet()->setHyperlink($this->getCoordinate(), $hyperlink);
723
724 1
        return $this->updateInCollection();
725
    }
726
727
    /**
728
     * Get cell collection.
729
     */
730 10074
    public function getParent(): ?Cells
731
    {
732 10074
        return $this->parent;
733
    }
734
735
    /**
736
     * Get parent worksheet.
737
     *
738
     * @throws SpreadsheetException
739
     */
740 10084
    public function getWorksheet(): Worksheet
741
    {
742 10084
        $parent = $this->parent;
743 10084
        if ($parent !== null) {
744 10084
            $worksheet = $parent->getParent();
745
        } else {
746 1
            $worksheet = null;
747
        }
748
749 10084
        if ($worksheet === null) {
750 1
            throw new SpreadsheetException('Worksheet no longer exists');
751
        }
752
753 10084
        return $worksheet;
754
    }
755
756 9
    public function getWorksheetOrNull(): ?Worksheet
757
    {
758 9
        $parent = $this->parent;
759 9
        if ($parent !== null) {
760 9
            $worksheet = $parent->getParent();
761
        } else {
762
            $worksheet = null;
763
        }
764
765 9
        return $worksheet;
766
    }
767
768
    /**
769
     * Is this cell in a merge range.
770
     */
771 7
    public function isInMergeRange(): bool
772
    {
773 7
        return (bool) $this->getMergeRange();
774
    }
775
776
    /**
777
     * Is this cell the master (top left cell) in a merge range (that holds the actual data value).
778
     */
779 56
    public function isMergeRangeValueCell(): bool
780
    {
781 56
        if ($mergeRange = $this->getMergeRange()) {
782 22
            $mergeRange = Coordinate::splitRange($mergeRange);
783 22
            [$startCell] = $mergeRange[0];
784
785 22
            return $this->getCoordinate() === $startCell;
786
        }
787
788 36
        return false;
789
    }
790
791
    /**
792
     * If this cell is in a merge range, then return the range.
793
     *
794
     * @return false|string
795
     */
796 59
    public function getMergeRange()
797
    {
798 59
        foreach ($this->getWorksheet()->getMergeCells() as $mergeRange) {
799 22
            if ($this->isInRange($mergeRange)) {
800 22
                return $mergeRange;
801
            }
802
        }
803
804 39
        return false;
805
    }
806
807
    /**
808
     * Get cell style.
809
     */
810 10076
    public function getStyle(): Style
811
    {
812 10076
        return $this->getWorksheet()->getStyle($this->getCoordinate());
813
    }
814
815
    /**
816
     * Get cell style.
817
     */
818 6
    public function getAppliedStyle(): Style
819
    {
820 6
        if ($this->getWorksheet()->conditionalStylesExists($this->getCoordinate()) === false) {
821 2
            return $this->getStyle();
822
        }
823 4
        $range = $this->getWorksheet()->getConditionalRange($this->getCoordinate());
824 4
        if ($range === null) {
825
            return $this->getStyle();
826
        }
827
828 4
        $matcher = new CellStyleAssessor($this, $range);
829
830 4
        return $matcher->matchConditions($this->getWorksheet()->getConditionalStyles($this->getCoordinate()));
831
    }
832
833
    /**
834
     * Re-bind parent.
835
     */
836
    public function rebindParent(Worksheet $parent): self
837
    {
838
        $this->parent = $parent->getCellCollection();
839
840
        return $this->updateInCollection();
841
    }
842
843
    /**
844
     *    Is cell in a specific range?
845
     *
846
     * @param string $range Cell range (e.g. A1:A1)
847
     */
848 230
    public function isInRange(string $range): bool
849
    {
850 230
        [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($range);
851
852
        // Translate properties
853 230
        $myColumn = Coordinate::columnIndexFromString($this->getColumn());
854 230
        $myRow = $this->getRow();
855
856
        // Verify if cell is in range
857 230
        return ($rangeStart[0] <= $myColumn) && ($rangeEnd[0] >= $myColumn)
858 230
            && ($rangeStart[1] <= $myRow) && ($rangeEnd[1] >= $myRow);
859
    }
860
861
    /**
862
     * Compare 2 cells.
863
     *
864
     * @param Cell $a Cell a
865
     * @param Cell $b Cell b
866
     *
867
     * @return int Result of comparison (always -1 or 1, never zero!)
868
     */
869
    public static function compareCells(self $a, self $b): int
870
    {
871
        if ($a->getRow() < $b->getRow()) {
872
            return -1;
873
        } elseif ($a->getRow() > $b->getRow()) {
874
            return 1;
875
        } elseif (Coordinate::columnIndexFromString($a->getColumn()) < Coordinate::columnIndexFromString($b->getColumn())) {
876
            return -1;
877
        }
878
879
        return 1;
880
    }
881
882
    /**
883
     * Get value binder to use.
884
     */
885 9652
    public static function getValueBinder(): IValueBinder
886
    {
887 9652
        if (self::$valueBinder === null) {
888 254
            self::$valueBinder = new DefaultValueBinder();
889
        }
890
891 9652
        return self::$valueBinder;
892
    }
893
894
    /**
895
     * Set value binder to use.
896
     */
897 160
    public static function setValueBinder(IValueBinder $binder): void
898
    {
899 160
        self::$valueBinder = $binder;
900
    }
901
902
    /**
903
     * Implement PHP __clone to create a deep clone, not just a shallow copy.
904
     */
905 17
    public function __clone()
906
    {
907 17
        $vars = get_object_vars($this);
908 17
        foreach ($vars as $propertyName => $propertyValue) {
909 17
            if ((is_object($propertyValue)) && ($propertyName !== 'parent')) {
910 17
                $this->$propertyName = clone $propertyValue;
911
            } else {
912 17
                $this->$propertyName = $propertyValue;
913
            }
914
        }
915
    }
916
917
    /**
918
     * Get index to cellXf.
919
     */
920 10121
    public function getXfIndex(): int
921
    {
922 10121
        return $this->xfIndex;
923
    }
924
925
    /**
926
     * Set index to cellXf.
927
     */
928 1799
    public function setXfIndex(int $indexValue): self
929
    {
930 1799
        $this->xfIndex = $indexValue;
931
932 1799
        return $this->updateInCollection();
933
    }
934
935
    /**
936
     * Set the formula attributes.
937
     *
938
     * @param $attributes null|array<string, string>
939
     *
940
     * @return $this
941
     */
942 285
    public function setFormulaAttributes(?array $attributes): self
943
    {
944 285
        $this->formulaAttributes = $attributes;
945
946 285
        return $this;
947
    }
948
949
    /**
950
     * Get the formula attributes.
951
     *
952
     * @return null|array<string, string>
953
     */
954 168
    public function getFormulaAttributes(): mixed
955
    {
956 168
        return $this->formulaAttributes;
957
    }
958
959
    /**
960
     * Convert to string.
961
     */
962 2
    public function __toString(): string
963
    {
964 2
        $retVal = $this->value;
965
966 2
        return StringHelper::convertToString($retVal, false);
967
    }
968
969 353
    public function getIgnoredErrors(): IgnoredErrors
970
    {
971 353
        return $this->ignoredErrors;
972
    }
973
974 3
    public function isLocked(): bool
975
    {
976 3
        $protected = $this->parent?->getParent()?->getProtection()?->getSheet();
977 3
        if ($protected !== true) {
978 1
            return false;
979
        }
980 3
        $locked = $this->getStyle()->getProtection()->getLocked();
981
982 3
        return $locked !== Protection::PROTECTION_UNPROTECTED;
983
    }
984
985 2
    public function isHiddenOnFormulaBar(): bool
986
    {
987 2
        if ($this->getDataType() !== DataType::TYPE_FORMULA) {
988 2
            return false;
989
        }
990 2
        $protected = $this->parent?->getParent()?->getProtection()?->getSheet();
991 2
        if ($protected !== true) {
992 2
            return false;
993
        }
994 2
        $hidden = $this->getStyle()->getProtection()->getHidden();
995
996 2
        return $hidden !== Protection::PROTECTION_UNPROTECTED;
997
    }
998
}
999