Skip to content

Better Definitions for Mixed Parameters and Values Part 2 of Many #4026

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 31, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 12 additions & 6 deletions src/PhpSpreadsheet/Collection/Cells.php
Original file line number Diff line number Diff line change
Expand Up @@ -288,7 +288,7 @@ public function cloneCellCollection(Worksheet $worksheet): static
$newCollection->index[$key] = $value;
$stored = $newCollection->cache->set(
$newCollection->cachePrefix . $key,
clone $this->cache->get($this->cachePrefix . $key)
clone $this->getCache($key)
);
if ($stored === false) {
$this->destructIfNeeded($newCollection, 'Failed to copy cells in cache');
Expand Down Expand Up @@ -410,11 +410,7 @@ public function get(string $cellCoordinate): ?Cell
return null;
}

// Check if the entry that has been requested actually exists in the cache
$cell = $this->cache->get($this->cachePrefix . $cellCoordinate);
if ($cell === null) {
throw new PhpSpreadsheetException("Cell entry {$cellCoordinate} no longer exists in cache. This probably means that the cache was cleared by someone else.");
}
$cell = $this->getcache($cellCoordinate);

// Set current entry to the requested entry
$this->currentCoordinate = $cellCoordinate;
Expand Down Expand Up @@ -466,4 +462,14 @@ private function getAllCacheKeys(): iterable
yield $this->cachePrefix . $coordinate;
}
}

private function getCache(string $cellCoordinate): Cell
{
$cell = $this->cache->get($this->cachePrefix . $cellCoordinate);
if (!($cell instanceof Cell)) {
throw new PhpSpreadsheetException("Cell entry {$cellCoordinate} no longer exists in cache. This probably means that the cache was cleared by someone else.");
}

return $cell;
}
}
2 changes: 2 additions & 0 deletions src/PhpSpreadsheet/Helper/Html.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace PhpOffice\PhpSpreadsheet\Helper;

use DOMAttr;
use DOMDocument;
use DOMElement;
use DOMNode;
Expand Down Expand Up @@ -708,6 +709,7 @@ protected function startFontTag(DOMElement $tag): void
{
$attrs = $tag->attributes;
if ($attrs !== null) {
/** @var DOMAttr $attribute */
foreach ($attrs as $attribute) {
$attributeName = strtolower($attribute->name);
$attributeName = preg_replace('/^html:/', '', $attributeName) ?? $attributeName; // in case from Xml spreadsheet
Expand Down
12 changes: 4 additions & 8 deletions src/PhpSpreadsheet/Helper/Sample.php
Original file line number Diff line number Diff line change
Expand Up @@ -81,13 +81,9 @@ public function getSamples(): array
$regex = new RegexIterator($iterator, '/^.+\.php$/', RecursiveRegexIterator::GET_MATCH);

$files = [];
/** @var string[] $file */
foreach ($regex as $file) {
$file = str_replace(str_replace('\\', '/', $baseDir) . '/', '', str_replace('\\', '/', $file[0]));
if (is_array($file)) {
// @codeCoverageIgnoreStart
throw new RuntimeException('str_replace returned array');
// @codeCoverageIgnoreEnd
}
$info = pathinfo($file);
$category = str_replace('_', ' ', $info['dirname'] ?? '');
$name = str_replace('_', ' ', (string) preg_replace('/(|\.php)/', '', $info['filename']));
Expand Down Expand Up @@ -254,10 +250,10 @@ public function logCalculationResult(
?string $descriptionCell = null
): void {
if ($descriptionCell !== null) {
$this->log($worksheet->getCell($descriptionCell)->getValue());
$this->log($worksheet->getCell($descriptionCell)->getValueString());
}
$this->log($worksheet->getCell($formulaCell)->getValue());
$this->log(sprintf('%s() Result is ', $functionName) . $worksheet->getCell($formulaCell)->getCalculatedValue());
$this->log($worksheet->getCell($formulaCell)->getValueString());
$this->log(sprintf('%s() Result is ', $functionName) . $worksheet->getCell($formulaCell)->getCalculatedValueString());
}

/**
Expand Down
2 changes: 2 additions & 0 deletions src/PhpSpreadsheet/Reader/Html.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace PhpOffice\PhpSpreadsheet\Reader;

use DOMAttr;
use DOMDocument;
use DOMElement;
use DOMNode;
Expand Down Expand Up @@ -291,6 +292,7 @@ protected function flushCell(Worksheet $sheet, string $column, int|string $row,
private function processDomElementBody(Worksheet $sheet, int &$row, string &$column, string &$cellContent, DOMElement $child): void
{
$attributeArray = [];
/** @var DOMAttr $attribute */
foreach ($child->attributes as $attribute) {
$attributeArray[$attribute->name] = $attribute->value;
}
Expand Down
2 changes: 2 additions & 0 deletions src/PhpSpreadsheet/Reader/Slk.php
Original file line number Diff line number Diff line change
Expand Up @@ -268,6 +268,7 @@ private function processCRecord(array $rowData, Spreadsheet &$spreadsheet, strin
if ($sharedFormula === true && $sharedRow >= 0 && $sharedColumn >= 0) {
$thisCoordinate = Coordinate::stringFromColumnIndex((int) $column) . $row;
$sharedCoordinate = Coordinate::stringFromColumnIndex($sharedColumn) . $sharedRow;
/** @var string */
$formula = $spreadsheet->getActiveSheet()->getCell($sharedCoordinate)->getValue();
$spreadsheet->getActiveSheet()->getCell($thisCoordinate)->setValue($formula);
$referenceHelper = ReferenceHelper::getInstance();
Expand All @@ -281,6 +282,7 @@ private function processCRecord(array $rowData, Spreadsheet &$spreadsheet, strin
return;
}
$columnLetter = Coordinate::stringFromColumnIndex((int) $column);
/** @var string */
$cellData = Calculation::unwrapResult($cellData);

// Set cell value
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ public function getParent(): ?self

/**
* Add a child. This will be either spgrContainer or spContainer.
*
* @param SpgrContainer|SpgrContainer\SpContainer $child child to be added
*/
public function addChild(mixed $child): void
{
Expand Down
2 changes: 1 addition & 1 deletion src/PhpSpreadsheet/Spreadsheet.php
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,7 @@ public function discardMacros(): void
*/
public function setRibbonXMLData(mixed $target, mixed $xmlData): void
{
if ($target !== null && $xmlData !== null) {
if (is_string($target) && is_string($xmlData)) {
$this->ribbonXMLData = ['target' => $target, 'data' => $xmlData];
} else {
$this->ribbonXMLData = null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -235,7 +235,7 @@ protected function processDuplicatesComparison(Conditional $conditional): bool
self::COMPARISON_DUPLICATES_OPERATORS[$conditional->getConditionType()],
$worksheetName,
$this->conditionalRange,
$this->cellConditionCheck($this->cell->getCalculatedValue())
$this->cellConditionCheck($this->cell->getCalculatedValueString())
);

return $this->evaluateExpression($expression);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ protected function operand(int $index, mixed $operand, string $operandValueType
$this->operandValueType[$index] = $operandValueType;
}

/** @param null|bool|float|int|string $value value to be wrapped */
protected function wrapValue(mixed $value, string $operandValueType): float|int|string
{
if (!is_numeric($value) && !is_bool($value) && null !== $value) {
Expand Down Expand Up @@ -175,7 +176,9 @@ public function __call(string $methodName, array $arguments): self
if (count($arguments) < 2) {
$this->operand(0, $arguments[0]);
} else {
$this->operand(0, $arguments[0], $arguments[1]);
/** @var string */
$arg1 = $arguments[1];
$this->operand(0, $arguments[0], $arg1);
}

return $this;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ public static function fromConditional(Conditional $conditional, string $cellRan
}

/**
* @param mixed[] $arguments
* @param string[] $arguments
*/
public function __call(string $methodName, array $arguments): self
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -148,9 +148,15 @@ public function __call(string $methodName, array $arguments): self
$this->operator(self::MAGIC_OPERATIONS[$methodName]);
//$this->operand(...$arguments);
if (count($arguments) < 2) {
$this->operand($arguments[0]);
/** @var string */
$arg0 = $arguments[0];
$this->operand($arg0);
} else {
$this->operand($arguments[0], $arguments[1]);
/** @var string */
$arg0 = $arguments[0];
/** @var string */
$arg1 = $arguments[1];
$this->operand($arg0, $arg1);
}

return $this;
Expand Down
1 change: 1 addition & 0 deletions src/PhpSpreadsheet/Style/NumberFormat/DateFormatter.php
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,7 @@ private static function tryInterval(bool &$seekingBracket, string &$block, mixed
}
}

/** @param float|int $value value to be formatted */
public static function format(mixed $value, string $format): string
{
// strip off first part containing e.g. [$-F800] or [$USD-409]
Expand Down
1 change: 1 addition & 0 deletions src/PhpSpreadsheet/Style/NumberFormat/NumberFormatter.php
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,7 @@ private static function formatStraightNumericValue(mixed $value, string $format,
return self::pregReplace(self::NUMBER_REGEX, $value, $format);
}

/** @param float|int|numeric-string $value value to be formatted */
public static function format(mixed $value, string $format): string
{
// The "_" in this string has already been stripped out,
Expand Down
18 changes: 12 additions & 6 deletions src/PhpSpreadsheet/Worksheet/AutoFilter.php
Original file line number Diff line number Diff line change
Expand Up @@ -309,7 +309,7 @@ public function shiftColumn(string $fromColumn, string $toColumn): static
/**
* Test if cell value is in the defined set of values.
*
* @param mixed[] $dataSet
* @param array{blanks: bool, filterValues: array<string,array<string,string>>} $dataSet
*/
protected static function filterTestInSimpleDataSet(mixed $cellValue, array $dataSet): bool
{
Expand All @@ -325,7 +325,7 @@ protected static function filterTestInSimpleDataSet(mixed $cellValue, array $dat
/**
* Test if cell value is in the defined set of Excel date values.
*
* @param mixed[] $dataSet
* @param array{blanks: bool, filterValues: array<string,array<string,string>>} $dataSet
*/
protected static function filterTestInDateGroupSet(mixed $cellValue, array $dataSet): bool
{
Expand Down Expand Up @@ -763,9 +763,13 @@ private function calculateTopTenValue(string $columnID, int $startRow, int $endR
sort($dataValues);
}

$slice = array_slice($dataValues, 0, $ruleValue);

$retVal = array_pop($slice);
if (is_numeric($ruleValue)) {
$ruleValue = (int) $ruleValue;
}
if ($ruleValue === null || is_int($ruleValue)) {
$slice = array_slice($dataValues, 0, $ruleValue);
$retVal = array_pop($slice);
}
}

return $retVal;
Expand Down Expand Up @@ -968,7 +972,7 @@ public function showHideRows(): static
$ruleOperator = $rule->getOperator();
}
if (is_numeric($ruleValue) && $ruleOperator === Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_PERCENT) {
$ruleValue = floor((float) $ruleValue * ($dataRowCount / 100));
$ruleValue = (int) floor((float) $ruleValue * ($dataRowCount / 100));
}
if (!is_array($ruleValue) && $ruleValue < 1) {
$ruleValue = 1;
Expand All @@ -977,6 +981,7 @@ public function showHideRows(): static
$ruleValue = 500;
}

/** @var float|int|string */
$maxVal = $this->calculateTopTenValue($columnID, $rangeStart[1] + 1, (int) $rangeEnd[1], $toptenRuleType, $ruleValue);

$operator = ($toptenRuleType == Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP)
Expand All @@ -1003,6 +1008,7 @@ public function showHideRows(): static
// Execute the filter test
/** @var callable */
$temp = [self::class, $columnFilterTest['method']];
/** @var bool */
$result // $result && // phpstan says $result is always true here
= call_user_func_array($temp, [$cellValue, $columnFilterTest['arguments']]);
// If filter test has resulted in FALSE, exit the loop straightaway rather than running any more tests
Expand Down
11 changes: 6 additions & 5 deletions src/PhpSpreadsheet/Worksheet/AutoFilter/Column.php
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ class Column
/**
* Autofilter Column Dynamic Attributes.
*
* @var mixed[]
* @var (float|int|string)[]
*/
private array $attributes = [];

Expand Down Expand Up @@ -209,7 +209,7 @@ public function setJoin(string $join): static
/**
* Set AutoFilter Attributes.
*
* @param mixed[] $attributes
* @param (float|int|string)[] $attributes
*
* @return $this
*/
Expand All @@ -225,7 +225,7 @@ public function setAttributes(array $attributes): static
* Set An AutoFilter Attribute.
*
* @param string $name Attribute Name
* @param int|string $value Attribute Value
* @param float|int|string $value Attribute Value
*
* @return $this
*/
Expand All @@ -240,7 +240,7 @@ public function setAttribute(string $name, $value): static
/**
* Get AutoFilter Column Attributes.
*
* @return int[]|string[]
* @return (float|int|string)[]
*/
public function getAttributes(): array
{
Expand All @@ -252,7 +252,7 @@ public function getAttributes(): array
*
* @param string $name Attribute Name
*/
public function getAttribute(string $name): null|int|string
public function getAttribute(string $name): null|float|int|string
{
if (isset($this->attributes[$name])) {
return $this->attributes[$name];
Expand Down Expand Up @@ -360,6 +360,7 @@ public function clearRules(): static
public function __clone()
{
$vars = get_object_vars($this);
/** @var AutoFilter\Column\Rule[] $value */
foreach ($vars as $key => $value) {
if ($key === 'parent') {
// Detach from autofilter parent
Expand Down
20 changes: 12 additions & 8 deletions src/PhpSpreadsheet/Worksheet/Worksheet.php
Original file line number Diff line number Diff line change
Expand Up @@ -745,7 +745,7 @@ public function calculateColumnWidths(): static
// Calculated value
// To formatted string
$cellValue = NumberFormat::toFormattedString(
$cell->getCalculatedValue(),
$cell->getCalculatedValueString(),
(string) $this->getParentOrThrow()->getCellXfByIndex($cell->getXfIndex())
->getNumberFormat()->getFormatCode(true)
);
Expand Down Expand Up @@ -2795,6 +2795,8 @@ public function fromArray(array $source, mixed $nullValue = null, string $startC
}

/**
* @param null|bool|float|int|RichText|string $nullValue value to use when null
*
* @throws Exception
* @throws \PhpOffice\PhpSpreadsheet\Calculation\Exception
*/
Expand All @@ -2811,8 +2813,10 @@ protected function cellToArray(Cell $cell, bool $calculateFormulas, bool $format

if ($formatData) {
$style = $this->getParentOrThrow()->getCellXfByIndex($cell->getXfIndex());
/** @var null|bool|float|int|RichText|string */
$returnValuex = $returnValue;
$returnValue = NumberFormat::toFormattedString(
$returnValue,
$returnValuex,
$style->getNumberFormat()->getFormatCode() ?? NumberFormat::FORMAT_GENERAL
);
}
Expand All @@ -2824,7 +2828,7 @@ protected function cellToArray(Cell $cell, bool $calculateFormulas, bool $format
/**
* Create array from a range of cells.
*
* @param mixed $nullValue Value returned in the array entry if a cell doesn't exist
* @param null|bool|float|int|RichText|string $nullValue Value returned in the array entry if a cell doesn't exist
* @param bool $calculateFormulas Should formulas be calculated?
* @param bool $formatData Should formatting be applied to cell values?
* @param bool $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero
Expand Down Expand Up @@ -2854,7 +2858,7 @@ public function rangeToArray(
/**
* Create array from a range of cells, yielding each row in turn.
*
* @param mixed $nullValue Value returned in the array entry if a cell doesn't exist
* @param null|bool|float|int|RichText|string $nullValue Value returned in the array entry if a cell doesn't exist
* @param bool $calculateFormulas Should formulas be calculated?
* @param bool $formatData Should formatting be applied to cell values?
* @param bool $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero
Expand Down Expand Up @@ -3002,7 +3006,7 @@ private function validateNamedRange(string $definedName, bool $returnNullIfInval
* Create array from a range of cells.
*
* @param string $definedName The Named Range that should be returned
* @param mixed $nullValue Value returned in the array entry if a cell doesn't exist
* @param null|bool|float|int|RichText|string $nullValue Value returned in the array entry if a cell doesn't exist
* @param bool $calculateFormulas Should formulas be calculated?
* @param bool $formatData Should formatting be applied to cell values?
* @param bool $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero
Expand Down Expand Up @@ -3035,7 +3039,7 @@ public function namedRangeToArray(
/**
* Create array from worksheet.
*
* @param mixed $nullValue Value returned in the array entry if a cell doesn't exist
* @param null|bool|float|int|RichText|string $nullValue Value returned in the array entry if a cell doesn't exist
* @param bool $calculateFormulas Should formulas be calculated?
* @param bool $formatData Should formatting be applied to cell values?
* @param bool $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero
Expand Down Expand Up @@ -3649,14 +3653,14 @@ public function setBackgroundImage(string $backgroundImage): self
public function copyCells(string $fromCell, string $toCells, bool $copyStyle = true): void
{
$toArray = Coordinate::extractAllCellReferencesInRange($toCells);
$value = $this->getCell($fromCell)->getValue();
$valueString = $this->getCell($fromCell)->getValueString();
$style = $this->getStyle($fromCell)->exportArray();
$fromIndexes = Coordinate::indexesFromString($fromCell);
$referenceHelper = ReferenceHelper::getInstance();
foreach ($toArray as $destination) {
if ($destination !== $fromCell) {
$toIndexes = Coordinate::indexesFromString($destination);
$this->getCell($destination)->setValue($referenceHelper->updateFormulaReferences($value, 'A1', $toIndexes[0] - $fromIndexes[0], $toIndexes[1] - $fromIndexes[1]));
$this->getCell($destination)->setValue($referenceHelper->updateFormulaReferences($valueString, 'A1', $toIndexes[0] - $fromIndexes[0], $toIndexes[1] - $fromIndexes[1]));
if ($copyStyle) {
$this->getCell($destination)->getStyle()->applyFromArray($style);
}
Expand Down
Loading
Loading