Skip to content

Commit d0fae3f

Browse files
authored
Eliminate Some Phpstan Annotations (#3746)
* Eliminate Some Phpstan Annotations Some changes are possible due to Php8+ features like null-safe operators and Stringable. * Possible Uninitialized Variable Scrutinizer might be technically correct. * CellAddress Static -> Self I don't understand the use case for extending it, which would be the reason for using static rather than self. * Update Worksheet.php
1 parent e53e44d commit d0fae3f

20 files changed

+129
-57
lines changed

src/PhpSpreadsheet/Cell/AdvancedValueBinder.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ public function bindValue(Cell $cell, $value = null)
6767
$currencyCode = $matches['PrefixedCurrency'] ?? $matches['PostfixedCurrency'];
6868
$value = (float) ($sign . trim(str_replace([$decimalSeparatorNoPreg, $currencyCode, ' ', '-'], ['.', '', '', ''], preg_replace('/(\d)' . $thousandsSeparator . '(\d)/u', '$1$2', $value)))); // @phpstan-ignore-line
6969

70-
return $this->setCurrency($value, $cell, $currencyCode); // @phpstan-ignore-line
70+
return $this->setCurrency($value, $cell, $currencyCode ?? '');
7171
}
7272

7373
// Check for time without seconds e.g. '9:45', '09:45'

src/PhpSpreadsheet/Cell/Cell.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -296,9 +296,9 @@ public function setValueExplicit(mixed $value, string $dataType = DataType::TYPE
296296

297297
$this->updateInCollection();
298298
$cellCoordinate = $this->getCoordinate();
299-
self::updateIfCellIsTableHeader($this->getParent()->getParent(), $this, $oldValue, $value); // @phpstan-ignore-line
299+
self::updateIfCellIsTableHeader($this->getParent()?->getParent(), $this, $oldValue, $value);
300300

301-
return $this->getParent()->get($cellCoordinate); // @phpstan-ignore-line
301+
return $this->getParent()?->get($cellCoordinate) ?? $this;
302302
}
303303

304304
public const CALCULATE_DATE_TIME_ASIS = 0;

src/PhpSpreadsheet/Cell/CellAddress.php

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ public function __construct(string $cellAddress, ?Worksheet $worksheet = null)
2727

2828
public function __destruct()
2929
{
30-
$this->worksheet = null;
30+
unset($this->worksheet);
3131
}
3232

3333
/**
@@ -45,21 +45,19 @@ public static function fromColumnAndRow(mixed $columnId, mixed $rowId, ?Workshee
4545
{
4646
self::validateColumnAndRow($columnId, $rowId);
4747

48-
/** @phpstan-ignore-next-line */
49-
return new static(Coordinate::stringFromColumnIndex($columnId) . ((string) $rowId), $worksheet);
48+
return new self(Coordinate::stringFromColumnIndex($columnId) . ((string) $rowId), $worksheet);
5049
}
5150

5251
public static function fromColumnRowArray(array $array, ?Worksheet $worksheet = null): self
5352
{
5453
[$columnId, $rowId] = $array;
5554

56-
return static::fromColumnAndRow($columnId, $rowId, $worksheet);
55+
return self::fromColumnAndRow($columnId, $rowId, $worksheet);
5756
}
5857

5958
public static function fromCellAddress(mixed $cellAddress, ?Worksheet $worksheet = null): self
6059
{
61-
/** @phpstan-ignore-next-line */
62-
return new static($cellAddress, $worksheet);
60+
return new self($cellAddress, $worksheet);
6361
}
6462

6563
/**
@@ -115,7 +113,7 @@ public function nextRow(int $offset = 1): self
115113
$newRowId = 1;
116114
}
117115

118-
return static::fromColumnAndRow($this->columnId, $newRowId);
116+
return self::fromColumnAndRow($this->columnId, $newRowId);
119117
}
120118

121119
public function previousRow(int $offset = 1): self
@@ -130,7 +128,7 @@ public function nextColumn(int $offset = 1): self
130128
$newColumnId = 1;
131129
}
132130

133-
return static::fromColumnAndRow($newColumnId, $this->rowId);
131+
return self::fromColumnAndRow($newColumnId, $this->rowId);
134132
}
135133

136134
public function previousColumn(int $offset = 1): self

src/PhpSpreadsheet/Cell/Coordinate.php

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -124,7 +124,7 @@ public static function absoluteCoordinate(string $cellAddress)
124124
}
125125

126126
// Create absolute coordinate
127-
[$column, $row] = self::coordinateFromString($cellAddress); // @phpstan-ignore-line
127+
[$column, $row] = self::coordinateFromString($cellAddress ?? 'A1');
128128
$column = ltrim($column, '$');
129129
$row = ltrim($row, '$');
130130

@@ -148,13 +148,12 @@ public static function splitRange($range)
148148
}
149149

150150
$exploded = explode(',', $range);
151-
$counter = count($exploded);
152-
for ($i = 0; $i < $counter; ++$i) {
153-
// @phpstan-ignore-next-line
154-
$exploded[$i] = explode(':', $exploded[$i]);
151+
$outArray = [];
152+
foreach ($exploded as $value) {
153+
$outArray[] = explode(':', $value);
155154
}
156155

157-
return $exploded;
156+
return $outArray;
158157
}
159158

160159
/**
@@ -361,7 +360,7 @@ public static function extractAllCellReferencesInRange($cellRange): array
361360
}
362361
$worksheet = str_replace("'", "''", $worksheet);
363362
}
364-
[$ranges, $operators] = self::getCellBlocksFromRangeString($cellRange); // @phpstan-ignore-line
363+
[$ranges, $operators] = self::getCellBlocksFromRangeString($cellRange ?? 'A1');
365364

366365
$cells = [];
367366
foreach ($ranges as $range) {
@@ -571,8 +570,7 @@ private static function getCellBlocksFromRangeString($rangeString)
571570
$rangeString = str_replace('$', '', strtoupper($rangeString));
572571

573572
// split range sets on intersection (space) or union (,) operators
574-
$tokens = preg_split('/([ ,])/', $rangeString, -1, PREG_SPLIT_DELIM_CAPTURE);
575-
/** @phpstan-ignore-next-line */
573+
$tokens = preg_split('/([ ,])/', $rangeString, -1, PREG_SPLIT_DELIM_CAPTURE) ?: [];
576574
$split = array_chunk($tokens, 2);
577575
$ranges = array_column($split, 0);
578576
$operators = array_column($split, 1);

src/PhpSpreadsheet/Cell/DefaultValueBinder.php

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,10 @@
33
namespace PhpOffice\PhpSpreadsheet\Cell;
44

55
use DateTimeInterface;
6+
use PhpOffice\PhpSpreadsheet\Exception as SpreadsheetException;
67
use PhpOffice\PhpSpreadsheet\RichText\RichText;
78
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
9+
use Stringable;
810

911
class DefaultValueBinder implements IValueBinder
1012
{
@@ -21,14 +23,14 @@ public function bindValue(Cell $cell, $value)
2123
// sanitize UTF-8 strings
2224
if (is_string($value)) {
2325
$value = StringHelper::sanitizeUTF8($value);
24-
} elseif (is_object($value)) {
25-
// Handle any objects that might be injected
26-
if ($value instanceof DateTimeInterface) {
27-
$value = $value->format('Y-m-d H:i:s');
28-
} elseif (!($value instanceof RichText)) {
29-
// Attempt to cast any unexpected objects to string
30-
$value = (string) $value; // @phpstan-ignore-line
31-
}
26+
} elseif ($value === null || is_scalar($value) || $value instanceof RichText) {
27+
// No need to do anything
28+
} elseif ($value instanceof DateTimeInterface) {
29+
$value = $value->format('Y-m-d H:i:s');
30+
} elseif ($value instanceof Stringable) {
31+
$value = (string) $value;
32+
} else {
33+
throw new SpreadsheetException('Unable to bind unstringable ' . gettype($value));
3234
}
3335

3436
// Set value explicit

src/PhpSpreadsheet/Cell/StringValueBinder.php

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,10 @@
33
namespace PhpOffice\PhpSpreadsheet\Cell;
44

55
use DateTimeInterface;
6+
use PhpOffice\PhpSpreadsheet\Exception as SpreadsheetException;
67
use PhpOffice\PhpSpreadsheet\RichText\RichText;
78
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
9+
use Stringable;
810

911
class StringValueBinder implements IValueBinder
1012
{
@@ -82,6 +84,9 @@ public function bindValue(Cell $cell, $value): bool
8284
if (is_object($value)) {
8385
return $this->bindObjectValue($cell, $value);
8486
}
87+
if ($value !== null && !is_scalar($value)) {
88+
throw new SpreadsheetException('Unable to bind unstringable ' . gettype($value));
89+
}
8590

8691
// sanitize UTF-8 strings
8792
if (is_string($value)) {
@@ -111,14 +116,15 @@ protected function bindObjectValue(Cell $cell, object $value): bool
111116
// Handle any objects that might be injected
112117
if ($value instanceof DateTimeInterface) {
113118
$value = $value->format('Y-m-d H:i:s');
119+
$cell->setValueExplicit($value, DataType::TYPE_STRING);
114120
} elseif ($value instanceof RichText) {
115121
$cell->setValueExplicit($value, DataType::TYPE_INLINE);
116-
117-
return true;
122+
} elseif ($value instanceof Stringable) {
123+
$cell->setValueExplicit((string) $value, DataType::TYPE_STRING);
124+
} else {
125+
throw new SpreadsheetException('Unable to bind unstringable object of type ' . get_class($value));
118126
}
119127

120-
$cell->setValueExplicit((string) $value, DataType::TYPE_STRING); // @phpstan-ignore-line
121-
122128
return true;
123129
}
124130
}

src/PhpSpreadsheet/Chart/Chart.php

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -671,9 +671,10 @@ public function render($outputDestination = null)
671671
// Ensure that data series values are up-to-date before we render
672672
$this->refresh();
673673

674+
/** @var Renderer\IRenderer */
674675
$renderer = new $libraryName($this);
675676

676-
return $renderer->render($outputDestination); // @phpstan-ignore-line
677+
return $renderer->render($outputDestination);
677678
}
678679

679680
public function getRotX(): ?int

src/PhpSpreadsheet/Chart/Renderer/IRenderer.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ public function __construct(Chart $chart);
1414
/**
1515
* Render the chart to given file (or stream).
1616
*
17-
* @param string $filename Name of the file render to
17+
* @param ?string $filename Name of the file render to
1818
*
1919
* @return bool true on success
2020
*/

src/PhpSpreadsheet/Reader/Xlsx.php

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -496,7 +496,7 @@ protected function loadSpreadsheetFromFile(string $filename): Spreadsheet
496496
$rels = $this->loadZip(self::INITIAL_FILE, Namespaces::RELATIONSHIPS);
497497

498498
$propertyReader = new PropertyReader($this->getSecurityScannerOrThrow(), $excel->getProperties());
499-
$chartDetails = [];
499+
$charts = $chartDetails = [];
500500
foreach ($rels->Relationship as $relx) {
501501
$rel = self::getAttributes($relx);
502502
$relTarget = (string) $rel['Target'];
@@ -1743,12 +1743,14 @@ protected function loadSpreadsheetFromFile(string $filename): Spreadsheet
17431743
// Modify range, and extract the first worksheet reference
17441744
// Need to split on a comma or a space if not in quotes, and extract the first part.
17451745
$definedNameValueParts = preg_split("/[ ,](?=([^']*'[^']*')*[^']*$)/miuU", $extractedRange);
1746-
// Extract sheet name
1747-
[$extractedSheetName] = Worksheet::extractSheetTitle((string) $definedNameValueParts[0], true); // @phpstan-ignore-line
1748-
$extractedSheetName = trim($extractedSheetName, "'"); // @phpstan-ignore-line
1746+
if (is_array($definedNameValueParts)) {
1747+
// Extract sheet name
1748+
[$extractedSheetName] = Worksheet::extractSheetTitle((string) $definedNameValueParts[0], true);
1749+
$extractedSheetName = trim((string) $extractedSheetName, "'");
17491750

1750-
// Locate sheet
1751-
$locatedSheet = $excel->getSheetByName($extractedSheetName);
1751+
// Locate sheet
1752+
$locatedSheet = $excel->getSheetByName($extractedSheetName);
1753+
}
17521754
}
17531755

17541756
if ($locatedSheet === null && !DefinedName::testIfFormula($extractedRange)) {
@@ -1790,8 +1792,8 @@ protected function loadSpreadsheetFromFile(string $filename): Spreadsheet
17901792
$objChart = $chartReader->readChart($chartElements, basename($chartEntryRef, '.xml'));
17911793
if (isset($charts[$chartEntryRef])) {
17921794
$chartPositionRef = $charts[$chartEntryRef]['sheet'] . '!' . $charts[$chartEntryRef]['id'];
1793-
if (isset($chartDetails[$chartPositionRef])) {
1794-
$excel->getSheetByName($charts[$chartEntryRef]['sheet'])->addChart($objChart); // @phpstan-ignore-line
1795+
if (isset($chartDetails[$chartPositionRef]) && $excel->getSheetByName($charts[$chartEntryRef]['sheet']) !== null) {
1796+
$excel->getSheetByName($charts[$chartEntryRef]['sheet'])->addChart($objChart);
17951797
$objChart->setWorksheet($excel->getSheetByName($charts[$chartEntryRef]['sheet']));
17961798
// For oneCellAnchor or absoluteAnchor positioned charts,
17971799
// toCoordinate is not in the data. Does it need to be calculated?

src/PhpSpreadsheet/Reader/Xlsx/BaseParserClass.php

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,14 @@
22

33
namespace PhpOffice\PhpSpreadsheet\Reader\Xlsx;
44

5+
use Stringable;
6+
57
class BaseParserClass
68
{
79
protected static function boolean(mixed $value): bool
810
{
911
if (is_object($value)) {
10-
$value = (string) $value; // @phpstan-ignore-line
12+
$value = ($value instanceof Stringable) ? ((string) $value) : 'true';
1113
}
1214

1315
if (is_numeric($value)) {

0 commit comments

Comments
 (0)