Passed
Pull Request — master (#4286)
by Owen
15:27
created

Cell   F

Complexity

Total Complexity 192

Size/Duplication

Total Lines 975
Duplicated Lines 0 %

Test Coverage

Coverage 93.78%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 192
eloc 370
dl 0
loc 975
ccs 377
cts 402
cp 0.9378
rs 2
c 2
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 updateInCollection() 0 9 2
A getFormattedValue() 0 11 1
A getCalculatedValueString() 0 8 5
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 convertDateTimeInt() 0 15 6
A __toString() 0 5 4
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 setCalculateDateTimeType() 0 5 1
A getCalculateDateTimeType() 0 3 1
A getValueBinder() 0 7 2
A getHyperlink() 0 7 2
B updateIfCellIsTableHeader() 0 17 10
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 setValue() 0 9 2
A hasHyperlink() 0 7 2
A getFormulaAttributes() 0 3 1
A getValueString() 0 5 4
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
F setValueExplicit() 0 82 26
F getCalculatedValue() 0 168 52

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 mixed $formulaAttributes = null;
67
68
    private IgnoredErrors $ignoredErrors;
69
70
    /**
71
     * Update the cell into the cell collection.
72
     *
73
     * @throws SpreadsheetException
74
     */
75 9990
    public function updateInCollection(): self
76
    {
77 9990
        $parent = $this->parent;
78 9990
        if ($parent === null) {
79 2
            throw new SpreadsheetException('Cannot update when cell is not bound to a worksheet');
80
        }
81 9988
        $parent->update($this);
82
83 9988
        return $this;
84
    }
85
86 9509
    public function detach(): void
87
    {
88 9509
        $this->parent = null;
89
    }
90
91 8786
    public function attach(Cells $parent): void
92
    {
93 8786
        $this->parent = $parent;
94
    }
95
96
    /**
97
     * Create a new Cell.
98
     *
99
     * @throws SpreadsheetException
100
     */
101 10043
    public function __construct(mixed $value, ?string $dataType, Worksheet $worksheet)
102
    {
103
        // Initialise cell value
104 10043
        $this->value = $value;
105
106
        // Set worksheet cache
107 10043
        $this->parent = $worksheet->getCellCollection();
108
109
        // Set datatype?
110 10043
        if ($dataType !== null) {
111 10043
            if ($dataType == DataType::TYPE_STRING2) {
112
                $dataType = DataType::TYPE_STRING;
113
            }
114 10043
            $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 10043
        $this->ignoredErrors = new IgnoredErrors();
122
    }
123
124
    /**
125
     * Get cell coordinate column.
126
     *
127
     * @throws SpreadsheetException
128
     */
129 8119
    public function getColumn(): string
130
    {
131 8119
        $parent = $this->parent;
132 8119
        if ($parent === null) {
133 1
            throw new SpreadsheetException('Cannot get column when cell is not bound to a worksheet');
134
        }
135
136 8118
        return $parent->getCurrentColumn();
137
    }
138
139
    /**
140
     * Get cell coordinate row.
141
     *
142
     * @throws SpreadsheetException
143
     */
144 651
    public function getRow(): int
145
    {
146 651
        $parent = $this->parent;
147 651
        if ($parent === null) {
148 1
            throw new SpreadsheetException('Cannot get row when cell is not bound to a worksheet');
149
        }
150
151 650
        return $parent->getCurrentRow();
152
    }
153
154
    /**
155
     * Get cell coordinate.
156
     *
157
     * @throws SpreadsheetException
158
     */
159 10000
    public function getCoordinate(): string
160
    {
161 10000
        $parent = $this->parent;
162 10000
        if ($parent !== null) {
163 10000
            $coordinate = $parent->getCurrentCoordinate();
164
        } else {
165 2
            $coordinate = null;
166
        }
167 10000
        if ($coordinate === null) {
168 2
            throw new SpreadsheetException('Coordinate no longer exists');
169
        }
170
171 10000
        return $coordinate;
172
    }
173
174
    /**
175
     * Get cell value.
176
     */
177 9337
    public function getValue(): mixed
178
    {
179 9337
        return $this->value;
180
    }
181
182 515
    public function getValueString(): string
183
    {
184 515
        $value = $this->value;
185
186 515
        return ($value === '' || is_scalar($value) || $value instanceof Stringable) ? "$value" : '';
187
    }
188
189
    /**
190
     * Get cell value with formatting.
191
     */
192 94
    public function getFormattedValue(): string
193
    {
194 94
        $currentCalendar = SharedDate::getExcelCalendar();
195 94
        SharedDate::setExcelCalendar($this->getWorksheet()->getParent()?->getExcelCalendar());
196 94
        $formattedValue = (string) NumberFormat::toFormattedString(
197 94
            $this->getCalculatedValueString(),
198 94
            (string) $this->getStyle()->getNumberFormat()->getFormatCode(true)
199 94
        );
200 94
        SharedDate::setExcelCalendar($currentCalendar);
201
202 94
        return $formattedValue;
203
    }
204
205 9937
    protected static function updateIfCellIsTableHeader(?Worksheet $workSheet, self $cell, mixed $oldValue, mixed $newValue): void
206
    {
207 9937
        $oldValue = (is_scalar($oldValue) || $oldValue instanceof Stringable) ? ((string) $oldValue) : null;
208 9937
        $newValue = (is_scalar($newValue) || $newValue instanceof Stringable) ? ((string) $newValue) : null;
209 9937
        if (StringHelper::strToLower($oldValue ?? '') === StringHelper::strToLower($newValue ?? '') || $workSheet === null) {
210 915
            return;
211
        }
212
213 9914
        foreach ($workSheet->getTableCollection() as $table) {
214
            /** @var Table $table */
215 10
            if ($cell->isInRange($table->getRange())) {
216 7
                $rangeRowsColumns = Coordinate::getRangeBoundaries($table->getRange());
217 7
                if ($cell->getRow() === (int) $rangeRowsColumns[0][1]) {
218 4
                    Table\Column::updateStructuredReferences($workSheet, $oldValue, $newValue);
219
                }
220
221 7
                return;
222
            }
223
        }
224
    }
225
226
    /**
227
     * Set cell value.
228
     *
229
     *    Sets the value for a cell, automatically determining the datatype using the value binder
230
     *
231
     * @param mixed $value Value
232
     * @param null|IValueBinder $binder Value Binder to override the currently set Value Binder
233
     *
234
     * @throws SpreadsheetException
235
     */
236 9544
    public function setValue(mixed $value, ?IValueBinder $binder = null): self
237
    {
238
        // Cells?->Worksheet?->Spreadsheet
239 9544
        $binder ??= $this->parent?->getParent()?->getParent()?->getValueBinder() ?? self::getValueBinder();
240 9544
        if (!$binder->bindValue($this, $value)) {
241
            throw new SpreadsheetException('Value could not be bound to cell.');
242
        }
243
244 9543
        return $this;
245
    }
246
247
    /**
248
     * Set the value for a cell, with the explicit data type passed to the method (bypassing any use of the value binder).
249
     *
250
     * @param mixed $value Value
251
     * @param string $dataType Explicit data type, see DataType::TYPE_*
252
     *        Note that PhpSpreadsheet does not validate that the value and datatype are consistent, in using this
253
     *             method, then it is your responsibility as an end-user developer to validate that the value and
254
     *             the datatype match.
255
     *       If you do mismatch value and datatype, then the value you enter may be changed to match the datatype
256
     *          that you specify.
257
     *
258
     * @throws SpreadsheetException
259
     */
260 9943
    public function setValueExplicit(mixed $value, string $dataType = DataType::TYPE_STRING): self
261
    {
262 9943
        $oldValue = $this->value;
263 9943
        $quotePrefix = false;
264
265
        // set the value according to data type
266
        switch ($dataType) {
267 251
            case DataType::TYPE_NULL:
268 599
                $this->value = null;
269
270 599
                break;
271 251
            case DataType::TYPE_STRING2:
272 3
                $dataType = DataType::TYPE_STRING;
273
                // no break
274 251
            case DataType::TYPE_STRING:
275
                // Synonym for string
276 5097
                if (is_string($value) && strlen($value) > 1 && $value[0] === '=') {
277 39
                    $quotePrefix = true;
278
                }
279
                // no break
280 231
            case DataType::TYPE_INLINE:
281
                // Rich text
282 5113
                if ($value !== null && !is_scalar($value) && !($value instanceof Stringable)) {
283 2
                    throw new SpreadsheetException('Invalid unstringable value for datatype Inline/String/String2');
284
                }
285 5111
                $this->value = DataType::checkString(($value instanceof RichText) ? $value : ((string) $value));
286
287 5111
                break;
288 230
            case DataType::TYPE_NUMERIC:
289 7123
                if (is_string($value) && !is_numeric($value)) {
290 2
                    throw new SpreadsheetException('Invalid numeric value for datatype Numeric');
291
                }
292 7122
                $this->value = 0 + $value;
293
294 7122
                break;
295 187
            case DataType::TYPE_FORMULA:
296 8357
                if ($value !== null && !is_scalar($value) && !($value instanceof Stringable)) {
297 2
                    throw new SpreadsheetException('Invalid unstringable value for datatype Formula');
298
                }
299 8356
                $this->value = (string) $value;
300
301 8356
                break;
302 18
            case DataType::TYPE_BOOL:
303 610
                $this->value = (bool) $value;
304
305 610
                break;
306
            case DataType::TYPE_ISO_DATE:
307 6
                $this->value = SharedDate::convertIsoDate($value);
308 5
                $dataType = DataType::TYPE_NUMERIC;
309
310 5
                break;
311
            case DataType::TYPE_ERROR:
312 21
                $this->value = DataType::checkErrorCode($value);
313
314 21
                break;
315
            default:
316 1
                throw new SpreadsheetException('Invalid datatype: ' . $dataType);
317
        }
318
319
        // set the datatype
320 9938
        $this->dataType = $dataType;
321
322 9938
        $this->updateInCollection();
323 9937
        $cellCoordinate = $this->getCoordinate();
324 9937
        self::updateIfCellIsTableHeader($this->getParent()?->getParent(), $this, $oldValue, $value);
325 9937
        $worksheet = $this->getWorksheet();
326 9937
        $spreadsheet = $worksheet->getParent();
327 9937
        if (isset($spreadsheet) && $spreadsheet->getIndex($worksheet, true) >= 0) {
328 9934
            $originalSelected = $worksheet->getSelectedCells();
329 9934
            $activeSheetIndex = $spreadsheet->getActiveSheetIndex();
330 9934
            $style = $this->getStyle();
331 9934
            $oldQuotePrefix = $style->getQuotePrefix();
332 9934
            if ($oldQuotePrefix !== $quotePrefix) {
333 39
                $style->setQuotePrefix($quotePrefix);
334
            }
335 9934
            $worksheet->setSelectedCells($originalSelected);
336 9934
            if ($activeSheetIndex >= 0) {
337 9934
                $spreadsheet->setActiveSheetIndex($activeSheetIndex);
338
            }
339
        }
340
341 9937
        return $this->getParent()?->get($cellCoordinate) ?? $this;
342
    }
343
344
    public const CALCULATE_DATE_TIME_ASIS = 0;
345
    public const CALCULATE_DATE_TIME_FLOAT = 1;
346
    public const CALCULATE_TIME_FLOAT = 2;
347
348
    private static int $calculateDateTimeType = self::CALCULATE_DATE_TIME_ASIS;
349
350 45
    public static function getCalculateDateTimeType(): int
351
    {
352 45
        return self::$calculateDateTimeType;
353
    }
354
355
    /** @throws CalculationException */
356 45
    public static function setCalculateDateTimeType(int $calculateDateTimeType): void
357
    {
358 45
        self::$calculateDateTimeType = match ($calculateDateTimeType) {
359 45
            self::CALCULATE_DATE_TIME_ASIS, self::CALCULATE_DATE_TIME_FLOAT, self::CALCULATE_TIME_FLOAT => $calculateDateTimeType,
360 1
            default => throw new CalculationException("Invalid value $calculateDateTimeType for calculated date time type"),
361 45
        };
362
    }
363
364
    /**
365
     * Convert date, time, or datetime from int to float if desired.
366
     */
367 8740
    private function convertDateTimeInt(mixed $result): mixed
368
    {
369 8740
        if (is_int($result)) {
370 4994
            if (self::$calculateDateTimeType === self::CALCULATE_TIME_FLOAT) {
371 4
                if (SharedDate::isDateTime($this, $result, false)) {
372 2
                    $result = (float) $result;
373
                }
374 4990
            } elseif (self::$calculateDateTimeType === self::CALCULATE_DATE_TIME_FLOAT) {
375 4
                if (SharedDate::isDateTime($this, $result, true)) {
376 3
                    $result = (float) $result;
377
                }
378
            }
379
        }
380
381 8740
        return $result;
382
    }
383
384
    /**
385
     * Get calculated cell value converted to string.
386
     */
387 766
    public function getCalculatedValueString(): string
388
    {
389 766
        $value = $this->getCalculatedValue();
390 766
        while (is_array($value)) {
391 11
            $value = array_shift($value);
392
        }
393
394 766
        return ($value === '' || is_scalar($value) || $value instanceof Stringable) ? "$value" : '';
395
    }
396
397
    /**
398
     * Get calculated cell value.
399
     *
400
     * @param bool $resetLog Whether the calculation engine logger should be reset or not
401
     *
402
     * @throws CalculationException
403
     */
404 8985
    public function getCalculatedValue(bool $resetLog = true): mixed
405
    {
406 8985
        $title = 'unknown';
407 8985
        $oldAttributes = $this->formulaAttributes;
408 8985
        $oldAttributesT = $oldAttributes['t'] ?? '';
409 8985
        $coordinate = $this->getCoordinate();
410 8985
        $oldAttributesRef = $oldAttributes['ref'] ?? $coordinate;
411 8985
        if (!str_contains($oldAttributesRef, ':')) {
412 8985
            $oldAttributesRef .= ":$oldAttributesRef";
413
        }
414 8985
        $originalValue = $this->value;
415 8985
        $originalDataType = $this->dataType;
416 8985
        $this->formulaAttributes = [];
417 8985
        $spill = false;
418
419 8985
        if ($this->dataType === DataType::TYPE_FORMULA) {
420
            try {
421 8011
                $currentCalendar = SharedDate::getExcelCalendar();
422 8011
                SharedDate::setExcelCalendar($this->getWorksheet()->getParent()?->getExcelCalendar());
423 8011
                $thisworksheet = $this->getWorksheet();
424 8011
                $index = $thisworksheet->getParentOrThrow()->getActiveSheetIndex();
425 8011
                $selected = $thisworksheet->getSelectedCells();
426 8011
                $title = $thisworksheet->getTitle();
427 8011
                $calculation = Calculation::getInstance($thisworksheet->getParent());
428 8011
                $result = $calculation->calculateCellValue($this, $resetLog);
429 7764
                $result = $this->convertDateTimeInt($result);
430 7764
                $thisworksheet->setSelectedCells($selected);
431 7764
                $thisworksheet->getParentOrThrow()->setActiveSheetIndex($index);
432 7764
                if (is_array($result) && $calculation->getInstanceArrayReturnType() !== Calculation::RETURN_ARRAY_AS_ARRAY) {
433
                    while (is_array($result)) {
434
                        $result = array_shift($result);
435
                    }
436
                }
437
                // if return_as_array for formula like '=sheet!cell'
438 7764
                if (is_array($result) && count($result) === 1) {
439 28
                    $resultKey = array_keys($result)[0];
440 28
                    $resultValue = $result[$resultKey];
441 28
                    if (is_int($resultKey) && is_array($resultValue) && count($resultValue) === 1) {
442 4
                        $resultKey2 = array_keys($resultValue)[0];
443 4
                        $resultValue2 = $resultValue[$resultKey2];
444 4
                        if (is_string($resultKey2) && !is_array($resultValue2) && preg_match('/[a-zA-Z]{1,3}/', $resultKey2) === 1) {
445
                            $result = $resultValue2;
446
                        }
447
                    }
448
                }
449 7764
                $newColumn = $this->getColumn();
450 7764
                if (is_array($result)) {
451 106
                    $this->formulaAttributes['t'] = 'array';
452 106
                    $this->formulaAttributes['ref'] = $maxCoordinate = $coordinate;
453 106
                    $newRow = $row = $this->getRow();
454 106
                    $column = $this->getColumn();
455 106
                    foreach ($result as $resultRow) {
456 106
                        if (is_array($resultRow)) {
457 106
                            $newColumn = $column;
458 106
                            foreach ($resultRow as $resultValue) {
459 106
                                if ($row !== $newRow || $column !== $newColumn) {
460 102
                                    $maxCoordinate = $newColumn . $newRow;
461 102
                                    if ($thisworksheet->getCell($newColumn . $newRow)->getValue() !== null) {
462 40
                                        if (!Coordinate::coordinateIsInsideRange($oldAttributesRef, $newColumn . $newRow)) {
463 3
                                            $spill = true;
464
465 3
                                            break;
466
                                        }
467
                                    }
468
                                }
469 106
                                ++$newColumn;
470
                            }
471 106
                            ++$newRow;
472
                        } else {
473 3
                            if ($row !== $newRow || $column !== $newColumn) {
474 3
                                $maxCoordinate = $newColumn . $newRow;
475 3
                                if ($thisworksheet->getCell($newColumn . $newRow)->getValue() !== null) {
476 3
                                    if (!Coordinate::coordinateIsInsideRange($oldAttributesRef, $newColumn . $newRow)) {
477
                                        $spill = true;
478
                                    }
479
                                }
480
                            }
481 3
                            ++$newColumn;
482
                        }
483 106
                        if ($spill) {
484 3
                            break;
485
                        }
486
                    }
487 106
                    if (!$spill) {
488 104
                        $this->formulaAttributes['ref'] .= ":$maxCoordinate";
489
                    }
490 106
                    $thisworksheet->getCell($column . $row);
491
                }
492 7764
                if (is_array($result)) {
493 106
                    if ($oldAttributes !== null && $calculation->getInstanceArrayReturnType() === Calculation::RETURN_ARRAY_AS_ARRAY) {
494 41
                        if (($oldAttributesT) === 'array') {
495 40
                            $thisworksheet = $this->getWorksheet();
496 40
                            $coordinate = $this->getCoordinate();
497 40
                            $ref = $oldAttributesRef;
498 40
                            if (preg_match('/^([A-Z]{1,3})([0-9]{1,7})(:([A-Z]{1,3})([0-9]{1,7}))?$/', $ref, $matches) === 1) {
499 40
                                if (isset($matches[3])) {
500 40
                                    $minCol = $matches[1];
501 40
                                    $minRow = (int) $matches[2];
502
                                    // https://github.com/phpstan/phpstan/issues/11602
503 40
                                    $maxCol = $matches[4]; // @phpstan-ignore-line
504 40
                                    ++$maxCol;
505 40
                                    $maxRow = (int) $matches[5]; // @phpstan-ignore-line
506 40
                                    for ($row = $minRow; $row <= $maxRow; ++$row) {
507 40
                                        for ($col = $minCol; $col !== $maxCol; ++$col) {
508 40
                                            if ("$col$row" !== $coordinate) {
509 39
                                                $thisworksheet->getCell("$col$row")->setValue(null);
510
                                            }
511
                                        }
512
                                    }
513
                                }
514
                            }
515 40
                            $thisworksheet->getCell($coordinate);
516
                        }
517
                    }
518
                }
519 7764
                if ($spill) {
520 3
                    $result = ExcelError::SPILL();
521
                }
522 7764
                if (is_array($result)) {
523 104
                    $newRow = $row = $this->getRow();
524 104
                    $newColumn = $column = $this->getColumn();
525 104
                    foreach ($result as $resultRow) {
526 104
                        if (is_array($resultRow)) {
527 104
                            $newColumn = $column;
528 104
                            foreach ($resultRow as $resultValue) {
529 104
                                if ($row !== $newRow || $column !== $newColumn) {
530 100
                                    $thisworksheet->getCell($newColumn . $newRow)->setValue($resultValue);
531
                                }
532 104
                                ++$newColumn;
533
                            }
534 104
                            ++$newRow;
535
                        } else {
536 3
                            if ($row !== $newRow || $column !== $newColumn) {
537 3
                                $thisworksheet->getCell($newColumn . $newRow)->setValue($resultRow);
538
                            }
539 3
                            ++$newColumn;
540
                        }
541
                    }
542 104
                    $thisworksheet->getCell($column . $row);
543 104
                    $this->value = $originalValue;
544 7764
                    $this->dataType = $originalDataType;
545
                }
546 265
            } catch (SpreadsheetException $ex) {
547 265
                SharedDate::setExcelCalendar($currentCalendar);
548 265
                if (($ex->getMessage() === 'Unable to access External Workbook') && ($this->calculatedValue !== null)) {
549 1
                    return $this->calculatedValue; // Fallback for calculations referencing external files.
550 265
                } elseif (preg_match('/[Uu]ndefined (name|offset: 2|array key 2)/', $ex->getMessage()) === 1) {
551 29
                    return ExcelError::NAME();
552
                }
553
554 236
                throw new CalculationException(
555 236
                    $title . '!' . $this->getCoordinate() . ' -> ' . $ex->getMessage(),
556 236
                    $ex->getCode(),
557 236
                    $ex
558 236
                );
559
            }
560 7764
            SharedDate::setExcelCalendar($currentCalendar);
561
562 7764
            if ($result === Functions::NOT_YET_IMPLEMENTED) {
563 13
                return $this->calculatedValue; // Fallback if calculation engine does not support the formula.
564
            }
565
566 7756
            return $result;
567 7646
        } elseif ($this->value instanceof RichText) {
568 20
            return $this->value->getPlainText();
569
        }
570
571 7641
        return $this->convertDateTimeInt($this->value);
572
    }
573
574
    /**
575
     * Set old calculated value (cached).
576
     *
577
     * @param mixed $originalValue Value
578
     */
579 425
    public function setCalculatedValue(mixed $originalValue, bool $tryNumeric = true): self
580
    {
581 425
        if ($originalValue !== null) {
582 425
            $this->calculatedValue = ($tryNumeric && is_numeric($originalValue)) ? (0 + $originalValue) : $originalValue;
583
        }
584
585 425
        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 8974
    public function getDataType(): string
605
    {
606 8974
        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 17
    public function hasDataValidation(): bool
635
    {
636 17
        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 16
        return $this->getWorksheet()->dataValidationExists($this->getCoordinate());
641
    }
642
643
    /**
644
     * Get Data validation rules.
645
     *
646
     * @throws SpreadsheetException
647
     */
648 31
    public function getDataValidation(): DataValidation
649
    {
650 31
        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 30
        return $this->getWorksheet()->getDataValidation($this->getCoordinate());
655
    }
656
657
    /**
658
     * Set Data validation rules.
659
     *
660
     * @throws SpreadsheetException
661
     */
662 6
    public function setDataValidation(?DataValidation $dataValidation = null): self
663
    {
664 6
        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 5
        $this->getWorksheet()->setDataValidation($this->getCoordinate(), $dataValidation);
669
670 5
        return $this->updateInCollection();
671
    }
672
673
    /**
674
     * Does this cell contain valid value?
675
     */
676 7
    public function hasValidValue(): bool
677
    {
678 7
        $validator = new DataValidator();
679
680 7
        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 87
    public function getHyperlink(): Hyperlink
703
    {
704 87
        if (!isset($this->parent)) {
705 1
            throw new SpreadsheetException('Cannot get hyperlink for cell that is not bound to a worksheet');
706
        }
707
708 86
        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 9939
    public function getParent(): ?Cells
731
    {
732 9939
        return $this->parent;
733
    }
734
735
    /**
736
     * Get parent worksheet.
737
     *
738
     * @throws SpreadsheetException
739
     */
740 9949
    public function getWorksheet(): Worksheet
741
    {
742 9949
        $parent = $this->parent;
743 9949
        if ($parent !== null) {
744 9949
            $worksheet = $parent->getParent();
745
        } else {
746 1
            $worksheet = null;
747
        }
748
749 9949
        if ($worksheet === null) {
750 1
            throw new SpreadsheetException('Worksheet no longer exists');
751
        }
752
753 9949
        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 55
    public function isMergeRangeValueCell(): bool
780
    {
781 55
        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 35
        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 58
    public function getMergeRange()
797
    {
798 58
        foreach ($this->getWorksheet()->getMergeCells() as $mergeRange) {
799 22
            if ($this->isInRange($mergeRange)) {
800 22
                return $mergeRange;
801
            }
802
        }
803
804 38
        return false;
805
    }
806
807
    /**
808
     * Get cell style.
809
     */
810 9942
    public function getStyle(): Style
811
    {
812 9942
        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 261
    public function isInRange(string $range): bool
849
    {
850 261
        [$rangeStart, $rangeEnd] = Coordinate::rangeBoundaries($range);
851
852
        // Translate properties
853 261
        $myColumn = Coordinate::columnIndexFromString($this->getColumn());
854 261
        $myRow = $this->getRow();
855
856
        // Verify if cell is in range
857 261
        return ($rangeStart[0] <= $myColumn) && ($rangeEnd[0] >= $myColumn)
858 261
            && ($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 9545
    public static function getValueBinder(): IValueBinder
886
    {
887 9545
        if (self::$valueBinder === null) {
888 240
            self::$valueBinder = new DefaultValueBinder();
889
        }
890
891 9545
        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 13
    public function __clone()
906
    {
907 13
        $vars = get_object_vars($this);
908 13
        foreach ($vars as $propertyName => $propertyValue) {
909 13
            if ((is_object($propertyValue)) && ($propertyName !== 'parent')) {
910 13
                $this->$propertyName = clone $propertyValue;
911
            } else {
912 13
                $this->$propertyName = $propertyValue;
913
            }
914
        }
915
    }
916
917
    /**
918
     * Get index to cellXf.
919
     */
920 9985
    public function getXfIndex(): int
921
    {
922 9985
        return $this->xfIndex;
923
    }
924
925
    /**
926
     * Set index to cellXf.
927
     */
928 1732
    public function setXfIndex(int $indexValue): self
929
    {
930 1732
        $this->xfIndex = $indexValue;
931
932 1732
        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 276
    public function setFormulaAttributes(?array $attributes): self
943
    {
944 276
        $this->formulaAttributes = $attributes;
945
946 276
        return $this;
947
    }
948
949
    /**
950
     * Get the formula attributes.
951
     *
952
     * @return null|array<string, string>
953
     */
954 160
    public function getFormulaAttributes(): mixed
955
    {
956 160
        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 ($retVal === null || is_scalar($retVal) || $retVal instanceof Stringable) ? ((string) $retVal) : '';
967
    }
968
969 350
    public function getIgnoredErrors(): IgnoredErrors
970
    {
971 350
        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