Cell   F
last analyzed

Complexity

Total Complexity 178

Size/Duplication

Total Lines 977
Duplicated Lines 0 %

Test Coverage

Coverage 93.81%

Importance

Changes 0
Metric Value
wmc 178
eloc 373
c 0
b 0
f 0
dl 0
loc 977
ccs 379
cts 404
cp 0.9381
rs 2

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 __construct() 0 21 4
A getValueString() 0 3 1
A getCalculatedValueString() 0 8 2
A convertDateTimeInt() 0 15 6
A setCalculateDateTimeType() 0 5 1
A getCalculateDateTimeType() 0 3 1
A updateIfCellIsTableHeader() 0 17 6
A setValue() 0 9 2
F setValueExplicit() 0 77 21
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 __toString() 0 5 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
F getCalculatedValue() 0 179 56
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

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 10145
    public function updateInCollection(): self
76
    {
77 10145
        $parent = $this->parent;
78 10145
        if ($parent === null) {
79 2
            throw new SpreadsheetException('Cannot update when cell is not bound to a worksheet');
80
        }
81 10143
        $parent->update($this);
82
83 10143
        return $this;
84
    }
85
86 10051
    public function detach(): void
87
    {
88 10051
        $this->parent = null;
89
    }
90
91 8895
    public function attach(Cells $parent): void
92
    {
93 8895
        $this->parent = $parent;
94
    }
95
96
    /**
97
     * Create a new Cell.
98
     *
99
     * @throws SpreadsheetException
100
     */
101 10184
    public function __construct(mixed $value, ?string $dataType, Worksheet $worksheet)
102
    {
103
        // Initialise cell value
104 10184
        $this->value = $value;
105
106
        // Set worksheet cache
107 10184
        $this->parent = $worksheet->getCellCollection();
108
109
        // Set datatype?
110 10184
        if ($dataType !== null) {
111 10184
            if ($dataType == DataType::TYPE_STRING2) {
112
                $dataType = DataType::TYPE_STRING;
113
            }
114 10184
            $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 10184
        $this->ignoredErrors = new IgnoredErrors();
122
    }
123
124
    /**
125
     * Get cell coordinate column.
126
     *
127
     * @throws SpreadsheetException
128
     */
129 8186
    public function getColumn(): string
130
    {
131 8186
        $parent = $this->parent;
132 8186
        if ($parent === null) {
133 1
            throw new SpreadsheetException('Cannot get column when cell is not bound to a worksheet');
134
        }
135
136 8185
        return $parent->getCurrentColumn();
137
    }
138
139
    /**
140
     * Get cell coordinate row.
141
     *
142
     * @throws SpreadsheetException
143
     */
144 662
    public function getRow(): int
145
    {
146 662
        $parent = $this->parent;
147 662
        if ($parent === null) {
148 1
            throw new SpreadsheetException('Cannot get row when cell is not bound to a worksheet');
149
        }
150
151 661
        return $parent->getCurrentRow();
152
    }
153
154
    /**
155
     * Get cell coordinate.
156
     *
157
     * @throws SpreadsheetException
158
     */
159 10156
    public function getCoordinate(): string
160
    {
161 10156
        $parent = $this->parent;
162 10156
        if ($parent !== null) {
163 10156
            $coordinate = $parent->getCurrentCoordinate();
164
        } else {
165 2
            $coordinate = null;
166
        }
167 10156
        if ($coordinate === null) {
168 2
            throw new SpreadsheetException('Coordinate no longer exists');
169
        }
170
171 10156
        return $coordinate;
172
    }
173
174
    /**
175
     * Get cell value.
176
     */
177 9483
    public function getValue(): mixed
178
    {
179 9483
        return $this->value;
180
    }
181
182 664
    public function getValueString(): string
183
    {
184 664
        return StringHelper::convertToString($this->value, false);
185
    }
186
187
    /**
188
     * Get cell value with formatting.
189
     */
190 103
    public function getFormattedValue(): string
191
    {
192 103
        $currentCalendar = SharedDate::getExcelCalendar();
193 103
        SharedDate::setExcelCalendar($this->getWorksheet()->getParent()?->getExcelCalendar());
194 103
        $formattedValue = (string) NumberFormat::toFormattedString(
195 103
            $this->getCalculatedValueString(),
196 103
            (string) $this->getStyle()->getNumberFormat()->getFormatCode(true)
197 103
        );
198 103
        SharedDate::setExcelCalendar($currentCalendar);
199
200 103
        return $formattedValue;
201
    }
202
203 10090
    protected static function updateIfCellIsTableHeader(?Worksheet $workSheet, self $cell, mixed $oldValue, mixed $newValue): void
204
    {
205 10090
        $oldValue = StringHelper::convertToString($oldValue, false);
206 10090
        $newValue = StringHelper::convertToString($newValue, false);
207 10090
        if (StringHelper::strToLower($oldValue) === StringHelper::strToLower($newValue) || $workSheet === null) {
208 941
            return;
209
        }
210
211 10067
        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 9666
    public function setValue(mixed $value, ?IValueBinder $binder = null): self
235
    {
236
        // Cells?->Worksheet?->Spreadsheet
237 9666
        $binder ??= $this->parent?->getParent()?->getParent()?->getValueBinder() ?? self::getValueBinder();
238 9666
        if (!$binder->bindValue($this, $value)) {
239
            throw new SpreadsheetException('Value could not be bound to cell.');
240
        }
241
242 9665
        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 10096
    public function setValueExplicit(mixed $value, string $dataType = DataType::TYPE_STRING): self
259
    {
260 10096
        $oldValue = $this->value;
261 10096
        $quotePrefix = false;
262
263
        // set the value according to data type
264
        switch ($dataType) {
265 263
            case DataType::TYPE_NULL:
266 623
                $this->value = null;
267
268 623
                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 5177
                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 5193
                $value2 = StringHelper::convertToString($value, true);
281 5191
                $this->value = DataType::checkString(($value instanceof RichText) ? $value : $value2);
282
283 5191
                break;
284 241
            case DataType::TYPE_NUMERIC:
285 7203
                if ($value !== null && !is_bool($value) && !is_numeric($value)) {
286 2
                    throw new SpreadsheetException('Invalid numeric value for datatype Numeric');
287
                }
288 7202
                $this->value = 0 + $value;
289
290 7202
                break;
291 187
            case DataType::TYPE_FORMULA:
292 8441
                $this->value = StringHelper::convertToString($value, true);
293
294 8440
                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 10091
        $this->dataType = $dataType;
314
315 10091
        $this->updateInCollection();
316 10090
        $cellCoordinate = $this->getCoordinate();
317 10090
        self::updateIfCellIsTableHeader($this->getParent()?->getParent(), $this, $oldValue, $value);
318 10090
        $worksheet = $this->getWorksheet();
319 10090
        $spreadsheet = $worksheet->getParent();
320 10090
        if (isset($spreadsheet) && $spreadsheet->getIndex($worksheet, true) >= 0) {
321 10086
            $originalSelected = $worksheet->getSelectedCells();
322 10086
            $activeSheetIndex = $spreadsheet->getActiveSheetIndex();
323 10086
            $style = $this->getStyle();
324 10086
            $oldQuotePrefix = $style->getQuotePrefix();
325 10086
            if ($oldQuotePrefix !== $quotePrefix) {
326 40
                $style->setQuotePrefix($quotePrefix);
327
            }
328 10086
            $worksheet->setSelectedCells($originalSelected);
329 10086
            if ($activeSheetIndex >= 0) {
330 10086
                $spreadsheet->setActiveSheetIndex($activeSheetIndex);
331
            }
332
        }
333
334 10090
        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 8849
    private function convertDateTimeInt(mixed $result): mixed
361
    {
362 8849
        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 8849
        return $result;
375
    }
376
377
    /**
378
     * Get calculated cell value converted to string.
379
     */
380 867
    public function getCalculatedValueString(): string
381
    {
382 867
        $value = $this->getCalculatedValue();
383 867
        while (is_array($value)) {
384 12
            $value = array_shift($value);
385
        }
386
387 867
        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 9095
    public function getCalculatedValue(bool $resetLog = true): mixed
398
    {
399 9095
        $title = 'unknown';
400 9095
        $oldAttributes = $this->formulaAttributes;
401 9095
        $oldAttributesT = $oldAttributes['t'] ?? '';
402 9095
        $coordinate = $this->getCoordinate();
403 9095
        $oldAttributesRef = $oldAttributes['ref'] ?? $coordinate;
404 9095
        $originalValue = $this->value;
405 9095
        $originalDataType = $this->dataType;
406 9095
        $this->formulaAttributes = [];
407 9095
        $spill = false;
408
409 9095
        if ($this->dataType === DataType::TYPE_FORMULA) {
410
            try {
411 8088
                $currentCalendar = SharedDate::getExcelCalendar();
412 8088
                SharedDate::setExcelCalendar($this->getWorksheet()->getParent()?->getExcelCalendar());
413 8088
                $thisworksheet = $this->getWorksheet();
414 8088
                $index = $thisworksheet->getParentOrThrow()->getActiveSheetIndex();
415 8088
                $selected = $thisworksheet->getSelectedCells();
416 8088
                $title = $thisworksheet->getTitle();
417 8088
                $calculation = Calculation::getInstance($thisworksheet->getParent());
418 8088
                $result = $calculation->calculateCellValue($this, $resetLog);
419 7840
                $result = $this->convertDateTimeInt($result);
420 7840
                $thisworksheet->setSelectedCells($selected);
421 7840
                $thisworksheet->getParentOrThrow()->setActiveSheetIndex($index);
422 7840
                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 7840
                    !is_array($result)
429 7840
                    && $calculation->getInstanceArrayReturnType() === Calculation::RETURN_ARRAY_AS_ARRAY
430 7840
                    && $oldAttributesT === 'array'
431 7840
                    && ($oldAttributesRef === $coordinate || $oldAttributesRef === "$coordinate:$coordinate")
432
                ) {
433 8
                    $result = [$result];
434
                }
435
                // if return_as_array for formula like '=sheet!cell'
436 7840
                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 7840
                $newColumn = $this->getColumn();
448 7840
                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
                                /** @var string $newColumn */
468 108
                                ++$newColumn;
469
                            }
470 108
                            ++$newRow;
471
                        } else {
472 11
                            if ($row !== $newRow || $column !== $newColumn) {
473 3
                                $maxCoordinate = $newColumn . $newRow;
474 3
                                if ($thisworksheet->getCell($newColumn . $newRow)->getValue() !== null) {
475 3
                                    if (!Coordinate::coordinateIsInsideRange($oldAttributesRef, $newColumn . $newRow)) {
476
                                        $spill = true;
477
                                    }
478
                                }
479
                            }
480 11
                            ++$newColumn;
481
                        }
482 109
                        if ($spill) {
483 3
                            break;
484
                        }
485
                    }
486 109
                    if (!$spill) {
487 107
                        $this->formulaAttributes['ref'] .= ":$maxCoordinate";
488
                    }
489 109
                    $thisworksheet->getCell($column . $row);
490
                }
491 7840
                if (is_array($result)) {
492 109
                    if ($oldAttributes !== null && $calculation->getInstanceArrayReturnType() === Calculation::RETURN_ARRAY_AS_ARRAY) {
493 44
                        if (($oldAttributesT) === 'array') {
494 43
                            $thisworksheet = $this->getWorksheet();
495 43
                            $coordinate = $this->getCoordinate();
496 43
                            $ref = $oldAttributesRef;
497 43
                            if (preg_match('/^([A-Z]{1,3})([0-9]{1,7})(:([A-Z]{1,3})([0-9]{1,7}))?$/', $ref, $matches) === 1) {
498 43
                                if (isset($matches[3])) {
499 42
                                    $minCol = $matches[1];
500 42
                                    $minRow = (int) $matches[2];
501 42
                                    $maxCol = $matches[4];
502 42
                                    ++$maxCol;
503 42
                                    $maxRow = (int) $matches[5];
504 42
                                    for ($row = $minRow; $row <= $maxRow; ++$row) {
505 42
                                        for ($col = $minCol; $col !== $maxCol; ++$col) {
506
                                            /** @var string $col */
507 42
                                            if ("$col$row" !== $coordinate) {
508 41
                                                $thisworksheet->getCell("$col$row")->setValue(null);
509
                                            }
510
                                        }
511
                                    }
512
                                }
513
                            }
514 43
                            $thisworksheet->getCell($coordinate);
515
                        }
516
                    }
517
                }
518 7840
                if ($spill) {
519 3
                    $result = ExcelError::SPILL();
520
                }
521 7840
                if (is_array($result)) {
522 107
                    $newRow = $row = $this->getRow();
523 107
                    $newColumn = $column = $this->getColumn();
524 107
                    foreach ($result as $resultRow) {
525 107
                        if (is_array($resultRow)) {
526 106
                            $newColumn = $column;
527 106
                            foreach ($resultRow as $resultValue) {
528 106
                                if ($row !== $newRow || $column !== $newColumn) {
529 102
                                    $thisworksheet
530 102
                                        ->getCell($newColumn . $newRow)
531 102
                                        ->setValue($resultValue);
532
                                }
533
                                /** @var string $newColumn */
534 106
                                ++$newColumn;
535
                            }
536 106
                            ++$newRow;
537
                        } else {
538 11
                            if ($row !== $newRow || $column !== $newColumn) {
539 3
                                $thisworksheet->getCell($newColumn . $newRow)->setValue($resultRow);
540
                            }
541 11
                            ++$newColumn;
542
                        }
543
                    }
544 107
                    $thisworksheet->getCell($column . $row);
545 107
                    $this->value = $originalValue;
546 7840
                    $this->dataType = $originalDataType;
547
                }
548 269
            } catch (SpreadsheetException $ex) {
549 269
                SharedDate::setExcelCalendar($currentCalendar);
550 269
                if (($ex->getMessage() === 'Unable to access External Workbook') && ($this->calculatedValue !== null)) {
551 1
                    return $this->calculatedValue; // Fallback for calculations referencing external files.
552 269
                } elseif (preg_match('/[Uu]ndefined (name|offset: 2|array key 2)/', $ex->getMessage()) === 1) {
553 31
                    return ExcelError::NAME();
554
                }
555
556 238
                throw new CalculationException(
557 238
                    $title . '!' . $this->getCoordinate() . ' -> ' . $ex->getMessage(),
558 238
                    $ex->getCode(),
559 238
                    $ex
560 238
                );
561
            }
562 7840
            SharedDate::setExcelCalendar($currentCalendar);
563
564 7840
            if ($result === Functions::NOT_YET_IMPLEMENTED) {
565 14
                $this->formulaAttributes = $oldAttributes;
566
567 14
                return $this->calculatedValue; // Fallback if calculation engine does not support the formula.
568
            }
569
570 7831
            return $result;
571 7729
        } elseif ($this->value instanceof RichText) {
572 20
            return $this->value->getPlainText();
573
        }
574
575 7724
        return $this->convertDateTimeInt($this->value);
576
    }
577
578
    /**
579
     * Set old calculated value (cached).
580
     *
581
     * @param mixed $originalValue Value
582
     */
583 448
    public function setCalculatedValue(mixed $originalValue, bool $tryNumeric = true): self
584
    {
585 448
        if ($originalValue !== null) {
586 448
            $this->calculatedValue = ($tryNumeric && is_numeric($originalValue)) ? (0 + $originalValue) : $originalValue;
587
        }
588
589 448
        return $this->updateInCollection();
590
    }
591
592
    /**
593
     *    Get old calculated value (cached)
594
     *    This returns the value last calculated by MS Excel or whichever spreadsheet program was used to
595
     *        create the original spreadsheet file.
596
     *    Note that this value is not guaranteed to reflect the actual calculated value because it is
597
     *        possible that auto-calculation was disabled in the original spreadsheet, and underlying data
598
     *        values used by the formula have changed since it was last calculated.
599
     */
600 20
    public function getOldCalculatedValue(): mixed
601
    {
602 20
        return $this->calculatedValue;
603
    }
604
605
    /**
606
     * Get cell data type.
607
     */
608 9100
    public function getDataType(): string
609
    {
610 9100
        return $this->dataType;
611
    }
612
613
    /**
614
     * Set cell data type.
615
     *
616
     * @param string $dataType see DataType::TYPE_*
617
     */
618 2
    public function setDataType(string $dataType): self
619
    {
620 2
        $this->setValueExplicit($this->value, $dataType);
621
622 2
        return $this;
623
    }
624
625
    /**
626
     * Identify if the cell contains a formula.
627
     */
628 73
    public function isFormula(): bool
629
    {
630 73
        return $this->dataType === DataType::TYPE_FORMULA && $this->getStyle()->getQuotePrefix() === false;
631
    }
632
633
    /**
634
     *    Does this cell contain Data validation rules?
635
     *
636
     * @throws SpreadsheetException
637
     */
638 24
    public function hasDataValidation(): bool
639
    {
640 24
        if (!isset($this->parent)) {
641 1
            throw new SpreadsheetException('Cannot check for data validation when cell is not bound to a worksheet');
642
        }
643
644 23
        return $this->getWorksheet()->dataValidationExists($this->getCoordinate());
645
    }
646
647
    /**
648
     * Get Data validation rules.
649
     *
650
     * @throws SpreadsheetException
651
     */
652 29
    public function getDataValidation(): DataValidation
653
    {
654 29
        if (!isset($this->parent)) {
655 1
            throw new SpreadsheetException('Cannot get data validation for cell that is not bound to a worksheet');
656
        }
657
658 28
        return $this->getWorksheet()->getDataValidation($this->getCoordinate());
659
    }
660
661
    /**
662
     * Set Data validation rules.
663
     *
664
     * @throws SpreadsheetException
665
     */
666 3
    public function setDataValidation(?DataValidation $dataValidation = null): self
667
    {
668 3
        if (!isset($this->parent)) {
669 1
            throw new SpreadsheetException('Cannot set data validation for cell that is not bound to a worksheet');
670
        }
671
672 2
        $this->getWorksheet()->setDataValidation($this->getCoordinate(), $dataValidation);
673
674 2
        return $this->updateInCollection();
675
    }
676
677
    /**
678
     * Does this cell contain valid value?
679
     */
680 12
    public function hasValidValue(): bool
681
    {
682 12
        $validator = new DataValidator();
683
684 12
        return $validator->isValid($this);
685
    }
686
687
    /**
688
     * Does this cell contain a Hyperlink?
689
     *
690
     * @throws SpreadsheetException
691
     */
692 1
    public function hasHyperlink(): bool
693
    {
694 1
        if (!isset($this->parent)) {
695 1
            throw new SpreadsheetException('Cannot check for hyperlink when cell is not bound to a worksheet');
696
        }
697
698
        return $this->getWorksheet()->hyperlinkExists($this->getCoordinate());
699
    }
700
701
    /**
702
     * Get Hyperlink.
703
     *
704
     * @throws SpreadsheetException
705
     */
706 94
    public function getHyperlink(): Hyperlink
707
    {
708 94
        if (!isset($this->parent)) {
709 1
            throw new SpreadsheetException('Cannot get hyperlink for cell that is not bound to a worksheet');
710
        }
711
712 93
        return $this->getWorksheet()->getHyperlink($this->getCoordinate());
713
    }
714
715
    /**
716
     * Set Hyperlink.
717
     *
718
     * @throws SpreadsheetException
719
     */
720 2
    public function setHyperlink(?Hyperlink $hyperlink = null): self
721
    {
722 2
        if (!isset($this->parent)) {
723 1
            throw new SpreadsheetException('Cannot set hyperlink for cell that is not bound to a worksheet');
724
        }
725
726 1
        $this->getWorksheet()->setHyperlink($this->getCoordinate(), $hyperlink);
727
728 1
        return $this->updateInCollection();
729
    }
730
731
    /**
732
     * Get cell collection.
733
     */
734 10093
    public function getParent(): ?Cells
735
    {
736 10093
        return $this->parent;
737
    }
738
739
    /**
740
     * Get parent worksheet.
741
     *
742
     * @throws SpreadsheetException
743
     */
744 10103
    public function getWorksheet(): Worksheet
745
    {
746 10103
        $parent = $this->parent;
747 10103
        if ($parent !== null) {
748 10103
            $worksheet = $parent->getParent();
749
        } else {
750 1
            $worksheet = null;
751
        }
752
753 10103
        if ($worksheet === null) {
754 1
            throw new SpreadsheetException('Worksheet no longer exists');
755
        }
756
757 10103
        return $worksheet;
758
    }
759
760 9
    public function getWorksheetOrNull(): ?Worksheet
761
    {
762 9
        $parent = $this->parent;
763 9
        if ($parent !== null) {
764 9
            $worksheet = $parent->getParent();
765
        } else {
766
            $worksheet = null;
767
        }
768
769 9
        return $worksheet;
770
    }
771
772
    /**
773
     * Is this cell in a merge range.
774
     */
775 7
    public function isInMergeRange(): bool
776
    {
777 7
        return (bool) $this->getMergeRange();
778
    }
779
780
    /**
781
     * Is this cell the master (top left cell) in a merge range (that holds the actual data value).
782
     */
783 59
    public function isMergeRangeValueCell(): bool
784
    {
785 59
        if ($mergeRange = $this->getMergeRange()) {
786 22
            $mergeRange = Coordinate::splitRange($mergeRange);
787 22
            [$startCell] = $mergeRange[0];
788
789 22
            return $this->getCoordinate() === $startCell;
790
        }
791
792 39
        return false;
793
    }
794
795
    /**
796
     * If this cell is in a merge range, then return the range.
797
     *
798
     * @return false|string
799
     */
800 62
    public function getMergeRange()
801
    {
802 62
        foreach ($this->getWorksheet()->getMergeCells() as $mergeRange) {
803 22
            if ($this->isInRange($mergeRange)) {
804 22
                return $mergeRange;
805
            }
806
        }
807
808 42
        return false;
809
    }
810
811
    /**
812
     * Get cell style.
813
     */
814 10095
    public function getStyle(): Style
815
    {
816 10095
        return $this->getWorksheet()->getStyle($this->getCoordinate());
817
    }
818
819
    /**
820
     * Get cell style.
821
     */
822 6
    public function getAppliedStyle(): Style
823
    {
824 6
        if ($this->getWorksheet()->conditionalStylesExists($this->getCoordinate()) === false) {
825 2
            return $this->getStyle();
826
        }
827 4
        $range = $this->getWorksheet()->getConditionalRange($this->getCoordinate());
828 4
        if ($range === null) {
829
            return $this->getStyle();
830
        }
831
832 4
        $matcher = new CellStyleAssessor($this, $range);
833
834 4
        return $matcher->matchConditions($this->getWorksheet()->getConditionalStyles($this->getCoordinate()));
835
    }
836
837
    /**
838
     * Re-bind parent.
839
     */
840
    public function rebindParent(Worksheet $parent): self
841
    {
842
        $this->parent = $parent->getCellCollection();
843
844
        return $this->updateInCollection();
845
    }
846
847
    /**
848
     *    Is cell in a specific range?
849
     *
850
     * @param string $range Cell range (e.g. A1:A1)
851
     */
852 230
    public function isInRange(string $range): bool
853
    {
854 230
        [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($range);
855
856
        // Translate properties
857 230
        $myColumn = Coordinate::columnIndexFromString($this->getColumn());
858 230
        $myRow = $this->getRow();
859
860
        // Verify if cell is in range
861 230
        return ($rangeStart[0] <= $myColumn) && ($rangeEnd[0] >= $myColumn)
862 230
            && ($rangeStart[1] <= $myRow) && ($rangeEnd[1] >= $myRow);
863
    }
864
865
    /**
866
     * Compare 2 cells.
867
     *
868
     * @param Cell $a Cell a
869
     * @param Cell $b Cell b
870
     *
871
     * @return int Result of comparison (always -1 or 1, never zero!)
872
     */
873
    public static function compareCells(self $a, self $b): int
874
    {
875
        if ($a->getRow() < $b->getRow()) {
876
            return -1;
877
        } elseif ($a->getRow() > $b->getRow()) {
878
            return 1;
879
        } elseif (Coordinate::columnIndexFromString($a->getColumn()) < Coordinate::columnIndexFromString($b->getColumn())) {
880
            return -1;
881
        }
882
883
        return 1;
884
    }
885
886
    /**
887
     * Get value binder to use.
888
     */
889 9667
    public static function getValueBinder(): IValueBinder
890
    {
891 9667
        if (self::$valueBinder === null) {
892 254
            self::$valueBinder = new DefaultValueBinder();
893
        }
894
895 9667
        return self::$valueBinder;
896
    }
897
898
    /**
899
     * Set value binder to use.
900
     */
901 160
    public static function setValueBinder(IValueBinder $binder): void
902
    {
903 160
        self::$valueBinder = $binder;
904
    }
905
906
    /**
907
     * Implement PHP __clone to create a deep clone, not just a shallow copy.
908
     */
909 17
    public function __clone()
910
    {
911 17
        $vars = get_object_vars($this);
912 17
        foreach ($vars as $propertyName => $propertyValue) {
913 17
            if ((is_object($propertyValue)) && ($propertyName !== 'parent')) {
914 17
                $this->$propertyName = clone $propertyValue;
915
            } else {
916 17
                $this->$propertyName = $propertyValue;
917
            }
918
        }
919
    }
920
921
    /**
922
     * Get index to cellXf.
923
     */
924 10140
    public function getXfIndex(): int
925
    {
926 10140
        return $this->xfIndex;
927
    }
928
929
    /**
930
     * Set index to cellXf.
931
     */
932 1815
    public function setXfIndex(int $indexValue): self
933
    {
934 1815
        $this->xfIndex = $indexValue;
935
936 1815
        return $this->updateInCollection();
937
    }
938
939
    /**
940
     * Set the formula attributes.
941
     *
942
     * @param null|array<string, string> $attributes
943
     */
944 285
    public function setFormulaAttributes(?array $attributes): self
945
    {
946 285
        $this->formulaAttributes = $attributes;
947
948 285
        return $this;
949
    }
950
951
    /**
952
     * Get the formula attributes.
953
     *
954
     * @return null|array<string, string>
955
     */
956 173
    public function getFormulaAttributes(): mixed
957
    {
958 173
        return $this->formulaAttributes;
959
    }
960
961
    /**
962
     * Convert to string.
963
     */
964 2
    public function __toString(): string
965
    {
966 2
        $retVal = $this->value;
967
968 2
        return StringHelper::convertToString($retVal, false);
969
    }
970
971 358
    public function getIgnoredErrors(): IgnoredErrors
972
    {
973 358
        return $this->ignoredErrors;
974
    }
975
976 3
    public function isLocked(): bool
977
    {
978 3
        $protected = $this->parent?->getParent()?->getProtection()?->getSheet();
979 3
        if ($protected !== true) {
980 1
            return false;
981
        }
982 3
        $locked = $this->getStyle()->getProtection()->getLocked();
983
984 3
        return $locked !== Protection::PROTECTION_UNPROTECTED;
985
    }
986
987 2
    public function isHiddenOnFormulaBar(): bool
988
    {
989 2
        if ($this->getDataType() !== DataType::TYPE_FORMULA) {
990 2
            return false;
991
        }
992 2
        $protected = $this->parent?->getParent()?->getProtection()?->getSheet();
993 2
        if ($protected !== true) {
994 2
            return false;
995
        }
996 2
        $hidden = $this->getStyle()->getProtection()->getHidden();
997
998 2
        return $hidden !== Protection::PROTECTION_UNPROTECTED;
999
    }
1000
}
1001