Failed Conditions
Pull Request — master (#3962)
by Owen
28:46 queued 17:47
created

Cell::getCalculatedValue()   F

Complexity

Conditions 52
Paths > 20000

Size

Total Lines 167
Code Lines 120

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 112
CRAP Score 52.5497

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 120
dl 0
loc 167
ccs 112
cts 119
cp 0.9412
rs 0
c 1
b 0
f 0
cc 52
nc 237100
nop 1
crap 52.5497

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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