repo
stringlengths
7
63
file_url
stringlengths
81
284
file_path
stringlengths
5
200
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:02:33
2026-01-05 05:24:06
truncated
bool
2 classes
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Style/ConditionalFormatting/Wizard.php
src/PhpSpreadsheet/Style/ConditionalFormatting/Wizard.php
<?php namespace PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting; use PhpOffice\PhpSpreadsheet\Exception; use PhpOffice\PhpSpreadsheet\Style\Conditional; use PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\Wizard\WizardInterface; class Wizard { public const CELL_VALUE = 'cellValue'; public const TEXT_VALUE = 'textValue'; public const BLANKS = Conditional::CONDITION_CONTAINSBLANKS; public const NOT_BLANKS = Conditional::CONDITION_NOTCONTAINSBLANKS; public const ERRORS = Conditional::CONDITION_CONTAINSERRORS; public const NOT_ERRORS = Conditional::CONDITION_NOTCONTAINSERRORS; public const EXPRESSION = Conditional::CONDITION_EXPRESSION; public const FORMULA = Conditional::CONDITION_EXPRESSION; public const DATES_OCCURRING = 'DateValue'; public const DUPLICATES = Conditional::CONDITION_DUPLICATES; public const UNIQUE = Conditional::CONDITION_UNIQUE; public const VALUE_TYPE_LITERAL = 'value'; public const VALUE_TYPE_CELL = 'cell'; public const VALUE_TYPE_FORMULA = 'formula'; protected string $cellRange; public function __construct(string $cellRange) { $this->cellRange = $cellRange; } public function newRule(string $ruleType): WizardInterface { return match ($ruleType) { self::CELL_VALUE => new Wizard\CellValue($this->cellRange), self::TEXT_VALUE => new Wizard\TextValue($this->cellRange), self::BLANKS => new Wizard\Blanks($this->cellRange, true), self::NOT_BLANKS => new Wizard\Blanks($this->cellRange, false), self::ERRORS => new Wizard\Errors($this->cellRange, true), self::NOT_ERRORS => new Wizard\Errors($this->cellRange, false), self::EXPRESSION, self::FORMULA => new Wizard\Expression($this->cellRange), self::DATES_OCCURRING => new Wizard\DateValue($this->cellRange), self::DUPLICATES => new Wizard\Duplicates($this->cellRange, false), self::UNIQUE => new Wizard\Duplicates($this->cellRange, true), default => throw new Exception('No wizard exists for this CF rule type'), }; } public static function fromConditional(Conditional $conditional, string $cellRange = 'A1'): WizardInterface { $conditionalType = $conditional->getConditionType(); return match ($conditionalType) { Conditional::CONDITION_CELLIS => Wizard\CellValue::fromConditional($conditional, $cellRange), Conditional::CONDITION_CONTAINSTEXT, Conditional::CONDITION_NOTCONTAINSTEXT, Conditional::CONDITION_BEGINSWITH, Conditional::CONDITION_ENDSWITH => Wizard\TextValue::fromConditional($conditional, $cellRange), Conditional::CONDITION_CONTAINSBLANKS, Conditional::CONDITION_NOTCONTAINSBLANKS => Wizard\Blanks::fromConditional($conditional, $cellRange), Conditional::CONDITION_CONTAINSERRORS, Conditional::CONDITION_NOTCONTAINSERRORS => Wizard\Errors::fromConditional($conditional, $cellRange), Conditional::CONDITION_TIMEPERIOD => Wizard\DateValue::fromConditional($conditional, $cellRange), Conditional::CONDITION_EXPRESSION => Wizard\Expression::fromConditional($conditional, $cellRange), Conditional::CONDITION_DUPLICATES, Conditional::CONDITION_UNIQUE => Wizard\Duplicates::fromConditional($conditional, $cellRange), default => throw new Exception('No wizard exists for this CF rule type'), }; } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalDataBar.php
src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalDataBar.php
<?php namespace PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting; class ConditionalDataBar { private ?bool $showValue = null; private ?ConditionalFormatValueObject $minimumConditionalFormatValueObject = null; private ?ConditionalFormatValueObject $maximumConditionalFormatValueObject = null; private string $color = ''; private ?ConditionalFormattingRuleExtension $conditionalFormattingRuleExt = null; public function getShowValue(): ?bool { return $this->showValue; } public function setShowValue(bool $showValue): self { $this->showValue = $showValue; return $this; } public function getMinimumConditionalFormatValueObject(): ?ConditionalFormatValueObject { return $this->minimumConditionalFormatValueObject; } public function setMinimumConditionalFormatValueObject(ConditionalFormatValueObject $minimumConditionalFormatValueObject): self { $this->minimumConditionalFormatValueObject = $minimumConditionalFormatValueObject; return $this; } public function getMaximumConditionalFormatValueObject(): ?ConditionalFormatValueObject { return $this->maximumConditionalFormatValueObject; } public function setMaximumConditionalFormatValueObject(ConditionalFormatValueObject $maximumConditionalFormatValueObject): self { $this->maximumConditionalFormatValueObject = $maximumConditionalFormatValueObject; return $this; } public function getColor(): string { return $this->color; } public function setColor(string $color): self { $this->color = $color; return $this; } public function getConditionalFormattingRuleExt(): ?ConditionalFormattingRuleExtension { return $this->conditionalFormattingRuleExt; } public function setConditionalFormattingRuleExt(ConditionalFormattingRuleExtension $conditionalFormattingRuleExt): self { $this->conditionalFormattingRuleExt = $conditionalFormattingRuleExt; return $this; } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalFormattingRuleExtension.php
src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalFormattingRuleExtension.php
<?php namespace PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting; use PhpOffice\PhpSpreadsheet\Style\Conditional; use SimpleXMLElement; class ConditionalFormattingRuleExtension { const CONDITION_EXTENSION_DATABAR = 'dataBar'; private string $id; /** @var string Conditional Formatting Rule */ private string $cfRule; private ConditionalDataBarExtension $dataBar; /** @var string Sequence of References */ private string $sqref = ''; /** * ConditionalFormattingRuleExtension constructor. */ public function __construct(?string $id = null, string $cfRule = self::CONDITION_EXTENSION_DATABAR) { if (null === $id) { $this->id = '{' . $this->generateUuid() . '}'; } else { $this->id = $id; } $this->cfRule = $cfRule; } private function generateUuid(): string { $chars = mb_str_split('xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx', 1, 'UTF-8'); foreach ($chars as $i => $char) { if ($char === 'x') { $chars[$i] = dechex(random_int(0, 15)); } elseif ($char === 'y') { $chars[$i] = dechex(random_int(8, 11)); } } return implode('', $chars); } /** @return mixed[] */ public static function parseExtLstXml(?SimpleXMLElement $extLstXml): array { $conditionalFormattingRuleExtensions = []; $conditionalFormattingRuleExtensionXml = null; if ($extLstXml instanceof SimpleXMLElement) { foreach ((count($extLstXml) > 0 ? $extLstXml : [$extLstXml]) as $extLst) { //this uri is conditionalFormattings //https://docs.microsoft.com/en-us/openspecs/office_standards/ms-xlsx/07d607af-5618-4ca2-b683-6a78dc0d9627 if (isset($extLst->ext['uri']) && (string) $extLst->ext['uri'] === '{78C0D931-6437-407d-A8EE-F0AAD7539E65}') { $conditionalFormattingRuleExtensionXml = $extLst->ext; } } if ($conditionalFormattingRuleExtensionXml) { $ns = $conditionalFormattingRuleExtensionXml->getNamespaces(true); $extFormattingsXml = $conditionalFormattingRuleExtensionXml->children($ns['x14']); foreach ($extFormattingsXml->children($ns['x14']) as $extFormattingXml) { $extCfRuleXml = $extFormattingXml->cfRule; $attributes = $extCfRuleXml->attributes(); if (!$attributes || ((string) $attributes->type) !== Conditional::CONDITION_DATABAR) { continue; } $extFormattingRuleObj = new self((string) $attributes->id); $extFormattingRuleObj->setSqref((string) $extFormattingXml->children($ns['xm'])->sqref); $conditionalFormattingRuleExtensions[$extFormattingRuleObj->getId()] = $extFormattingRuleObj; $extDataBarObj = new ConditionalDataBarExtension(); $extFormattingRuleObj->setDataBarExt($extDataBarObj); $dataBarXml = $extCfRuleXml->dataBar; self::parseExtDataBarAttributesFromXml($extDataBarObj, $dataBarXml); self::parseExtDataBarElementChildrenFromXml($extDataBarObj, $dataBarXml, $ns); } } } return $conditionalFormattingRuleExtensions; } private static function parseExtDataBarAttributesFromXml( ConditionalDataBarExtension $extDataBarObj, SimpleXMLElement $dataBarXml ): void { $dataBarAttribute = $dataBarXml->attributes(); if ($dataBarAttribute === null) { return; } if ($dataBarAttribute->minLength) { $extDataBarObj->setMinLength((int) $dataBarAttribute->minLength); } if ($dataBarAttribute->maxLength) { $extDataBarObj->setMaxLength((int) $dataBarAttribute->maxLength); } if ($dataBarAttribute->border) { $extDataBarObj->setBorder((bool) (string) $dataBarAttribute->border); } if ($dataBarAttribute->gradient) { $extDataBarObj->setGradient((bool) (string) $dataBarAttribute->gradient); } if ($dataBarAttribute->direction) { $extDataBarObj->setDirection((string) $dataBarAttribute->direction); } if ($dataBarAttribute->negativeBarBorderColorSameAsPositive) { $extDataBarObj->setNegativeBarBorderColorSameAsPositive((bool) (string) $dataBarAttribute->negativeBarBorderColorSameAsPositive); } if ($dataBarAttribute->axisPosition) { $extDataBarObj->setAxisPosition((string) $dataBarAttribute->axisPosition); } } /** @param string[] $ns */ private static function parseExtDataBarElementChildrenFromXml(ConditionalDataBarExtension $extDataBarObj, SimpleXMLElement $dataBarXml, array $ns): void { if ($dataBarXml->borderColor) { $attributes = $dataBarXml->borderColor->attributes(); if ($attributes !== null) { $extDataBarObj->setBorderColor((string) $attributes['rgb']); } } if ($dataBarXml->negativeFillColor) { $attributes = $dataBarXml->negativeFillColor->attributes(); if ($attributes !== null) { $extDataBarObj->setNegativeFillColor((string) $attributes['rgb']); } } if ($dataBarXml->negativeBorderColor) { $attributes = $dataBarXml->negativeBorderColor->attributes(); if ($attributes !== null) { $extDataBarObj->setNegativeBorderColor((string) $attributes['rgb']); } } if ($dataBarXml->axisColor) { $axisColorAttr = $dataBarXml->axisColor->attributes(); if ($axisColorAttr !== null) { $extDataBarObj->setAxisColor((string) $axisColorAttr['rgb'], (string) $axisColorAttr['theme'], (string) $axisColorAttr['tint']); } } $cfvoIndex = 0; foreach ($dataBarXml->cfvo as $cfvo) { $f = (string) $cfvo->children($ns['xm'])->f; $attributes = $cfvo->attributes(); if (!($attributes)) { continue; } if ($cfvoIndex === 0) { $extDataBarObj->setMinimumConditionalFormatValueObject(new ConditionalFormatValueObject((string) $attributes['type'], null, (empty($f) ? null : $f))); } if ($cfvoIndex === 1) { $extDataBarObj->setMaximumConditionalFormatValueObject(new ConditionalFormatValueObject((string) $attributes['type'], null, (empty($f) ? null : $f))); } ++$cfvoIndex; } } public function getId(): string { return $this->id; } public function setId(string $id): self { $this->id = $id; return $this; } public function getCfRule(): string { return $this->cfRule; } public function setCfRule(string $cfRule): self { $this->cfRule = $cfRule; return $this; } public function getDataBarExt(): ConditionalDataBarExtension { return $this->dataBar; } public function setDataBarExt(ConditionalDataBarExtension $dataBar): self { $this->dataBar = $dataBar; return $this; } public function getSqref(): string { return $this->sqref; } public function setSqref(string $sqref): self { $this->sqref = $sqref; return $this; } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Style/ConditionalFormatting/CellStyleAssessor.php
src/PhpSpreadsheet/Style/ConditionalFormatting/CellStyleAssessor.php
<?php namespace PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting; use PhpOffice\PhpSpreadsheet\Cell\Cell; use PhpOffice\PhpSpreadsheet\Style\Conditional; use PhpOffice\PhpSpreadsheet\Style\Style; class CellStyleAssessor { protected CellMatcher $cellMatcher; protected StyleMerger $styleMerger; protected Cell $cell; public function __construct(Cell $cell, string $conditionalRange) { $this->cell = $cell; $this->cellMatcher = new CellMatcher($cell, $conditionalRange); $this->styleMerger = new StyleMerger($cell->getStyle()); } /** * @param Conditional[] $conditionalStyles */ public function matchConditions(array $conditionalStyles = []): Style { foreach ($conditionalStyles as $conditional) { if ($this->cellMatcher->evaluateConditional($conditional) === true) { // Merging the conditional style into the base style goes in here $this->styleMerger->mergeStyle($conditional->getStyle($this->cell->getValue())); if ($conditional->getStopIfTrue() === true) { break; } } } return $this->styleMerger->getStyle(); } /** * @param Conditional[] $conditionalStyles */ public function matchConditionsReturnNullIfNoneMatched(array $conditionalStyles, string $cellData, bool $stopAtFirstMatch = false): ?Style { $matched = false; $value = (float) $cellData; foreach ($conditionalStyles as $conditional) { if ($this->cellMatcher->evaluateConditional($conditional) === true) { $matched = true; // Merging the conditional style into the base style goes in here $this->styleMerger->mergeStyle($conditional->getStyle($value)); if ($conditional->getStopIfTrue() === true || $stopAtFirstMatch) { break; } } } if ($matched) { return $this->styleMerger->getStyle(); } return null; } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Style/ConditionalFormatting/MergedCellStyle.php
src/PhpSpreadsheet/Style/ConditionalFormatting/MergedCellStyle.php
<?php namespace PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting; use PhpOffice\PhpSpreadsheet\Style\Fill; use PhpOffice\PhpSpreadsheet\Style\Style; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; class MergedCellStyle { private bool $matched = false; /** * Indicate whether the last call to getMergedStyle found * any conditional or table styles affecting the cell in question. */ public function getMatched(): bool { return $this->matched; } /** * Return a style that combines the base style for a cell * with any conditional or table styles applicable to the cell. * * @param bool $tableFormats True/false to indicate whether * custom table styles should be considered. * Note that builtin table styles are not supported. * @param bool $conditionals True/false to indicate whether * conditional styles should be considered. */ public function getMergedStyle(Worksheet $worksheet, string $coordinate, bool $tableFormats = true, bool $conditionals = true, ?bool $builtInTableStyles = null): Style { $builtInTableStyles ??= $tableFormats; $this->matched = false; $styleMerger = new StyleMerger($worksheet->getStyle($coordinate)); if ($tableFormats) { $this->assessTables($worksheet, $coordinate, $styleMerger); } if ($builtInTableStyles) { $this->assessBuiltinTables($worksheet, $coordinate, $styleMerger); } if ($conditionals) { $this->assessConditionals($worksheet, $coordinate, $styleMerger); } return $styleMerger->getStyle(); } private function assessTables(Worksheet $worksheet, string $coordinate, StyleMerger $styleMerger): void { $tables = $worksheet->getTablesWithStylesForCell($worksheet->getCell($coordinate)); foreach ($tables as $ts) { $dxfsTableStyle = $ts->getStyle()->getTableDxfsStyle(); if ($dxfsTableStyle !== null) { $tableRow = $ts->getRowNumber($coordinate); if ($tableRow === 0 && $dxfsTableStyle->getHeaderRowStyle() !== null) { $styleMerger->mergeStyle( $dxfsTableStyle->getHeaderRowStyle() ); $this->matched = true; } elseif ($tableRow % 2 === 1 && $dxfsTableStyle->getFirstRowStripeStyle() !== null) { $styleMerger->mergeStyle( $dxfsTableStyle->getFirstRowStripeStyle() ); $this->matched = true; } elseif ($tableRow % 2 === 0 && $dxfsTableStyle->getSecondRowStripeStyle() !== null) { $styleMerger->mergeStyle( $dxfsTableStyle->getSecondRowStripeStyle() ); $this->matched = true; } } } } private static ?Style $headerStyle = null; private static ?Style $firstRowStyle = null; private function assessBuiltinTables(Worksheet $worksheet, string $coordinate, StyleMerger $styleMerger): void { if (self::$headerStyle === null) { self::$headerStyle = new Style(); self::$headerStyle->getFill() ->setFillType(Fill::FILL_SOLID) ->getEndColor() ->setArgb('FF000000'); self::$headerStyle->getFill()->getStartColor() ->setArgb('FF000000'); self::$headerStyle->getFont() ->getColor()->setRgb('FFFFFF'); } if (self::$firstRowStyle === null) { self::$firstRowStyle = new Style(); self::$firstRowStyle->getFill() ->setFillType(Fill::FILL_SOLID) ->getEndColor() ->setArgb('FFD9D9D9'); self::$firstRowStyle->getFill()->getStartColor() ->setArgb('FFD9D9D9'); } $tables = $worksheet->getTablesWithoutStylesForCell($worksheet->getCell($coordinate)); foreach ($tables as $table) { $tableRow = $table->getRowNumber($coordinate); if ($tableRow === 0 && $table->getShowHeaderRow()) { $styleMerger->mergeStyle(self::$headerStyle); $this->matched = true; } elseif ($tableRow % 2 === 1) { $styleMerger->mergeStyle(self::$firstRowStyle); $this->matched = true; } } } private function assessConditionals(Worksheet $worksheet, string $coordinate, StyleMerger $styleMerger): void { if ($worksheet->getConditionalRange($coordinate) !== null) { $assessor = new CellStyleAssessor($worksheet->getCell($coordinate), $worksheet->getConditionalRange($coordinate)); } else { $assessor = new CellStyleAssessor($worksheet->getCell($coordinate), $coordinate); } $matchedStyle = $assessor ->matchConditionsReturnNullIfNoneMatched( $worksheet->getConditionalStyles($coordinate), $worksheet->getCell($coordinate) ->getCalculatedValueString(), true ); if ($matchedStyle !== null) { $this->matched = true; $styleMerger->mergeStyle($matchedStyle); } } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Style/ConditionalFormatting/StyleMerger.php
src/PhpSpreadsheet/Style/ConditionalFormatting/StyleMerger.php
<?php namespace PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting; use PhpOffice\PhpSpreadsheet\Style\Border; use PhpOffice\PhpSpreadsheet\Style\Borders; use PhpOffice\PhpSpreadsheet\Style\Fill; use PhpOffice\PhpSpreadsheet\Style\Font; use PhpOffice\PhpSpreadsheet\Style\Style; class StyleMerger { protected Style $baseStyle; public function __construct(Style $baseStyle) { // Setting to $baseStyle sometimes causes problems later on. $array = $baseStyle->exportArray(); $this->baseStyle = new Style(); $this->baseStyle->applyFromArray($array); } public function getStyle(): Style { return $this->baseStyle; } public function mergeStyle(Style $style): void { if ($style->getNumberFormat()->getFormatCode() !== null) { $this->baseStyle->getNumberFormat()->setFormatCode($style->getNumberFormat()->getFormatCode()); } $this->mergeFontStyle($this->baseStyle->getFont(), $style->getFont()); $this->mergeFillStyle($this->baseStyle->getFill(), $style->getFill()); $this->mergeBordersStyle($this->baseStyle->getBorders(), $style->getBorders()); } protected function mergeFontStyle(Font $baseFontStyle, Font $fontStyle): void { if ($fontStyle->getBold() !== null) { $baseFontStyle->setBold($fontStyle->getBold()); } if ($fontStyle->getItalic() !== null) { $baseFontStyle->setItalic($fontStyle->getItalic()); } if ($fontStyle->getStrikethrough() !== null) { $baseFontStyle->setStrikethrough($fontStyle->getStrikethrough()); } if ($fontStyle->getUnderline() !== null) { $baseFontStyle->setUnderline($fontStyle->getUnderline()); } if ($fontStyle->getColor()->getARGB() !== null) { $baseFontStyle->setColor($fontStyle->getColor()); } } protected function mergeFillStyle(Fill $baseFillStyle, Fill $fillStyle): void { if ($fillStyle->getFillType() !== null) { $baseFillStyle->setFillType($fillStyle->getFillType()); } $baseFillStyle->setRotation($fillStyle->getRotation()); if ($fillStyle->getStartColor()->getARGB() !== null) { $baseFillStyle->setStartColor($fillStyle->getStartColor()); } if ($fillStyle->getEndColor()->getARGB() !== null) { $baseFillStyle->setEndColor($fillStyle->getEndColor()); } } protected function mergeBordersStyle(Borders $baseBordersStyle, Borders $bordersStyle): void { $this->mergeBorderStyle($baseBordersStyle->getTop(), $bordersStyle->getTop()); $this->mergeBorderStyle($baseBordersStyle->getBottom(), $bordersStyle->getBottom()); $this->mergeBorderStyle($baseBordersStyle->getLeft(), $bordersStyle->getLeft()); $this->mergeBorderStyle($baseBordersStyle->getRight(), $bordersStyle->getRight()); } protected function mergeBorderStyle(Border $baseBorderStyle, Border $borderStyle): void { if ($borderStyle->getBorderStyle() !== Border::BORDER_OMIT) { $baseBorderStyle->setBorderStyle( $borderStyle->getBorderStyle() ); } if ($borderStyle->getColor()->getARGB() !== null) { $baseBorderStyle->setColor($borderStyle->getColor()); } } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalIconSet.php
src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalIconSet.php
<?php namespace PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting; class ConditionalIconSet { /** The icon set to display. */ private ?IconSetValues $iconSetType = null; /** If true, reverses the default order of the icons in this icon set. */ private ?bool $reverse = null; /** Indicates whether to show the values of the cells on which this icon set is applied. */ private ?bool $showValue = null; /** * If true, indicates that the icon set is a custom icon set. * If this value is "true", there MUST be the same number of cfIcon elements * as cfvo elements. * If this value is "false", there MUST be 0 cfIcon elements. */ private ?bool $custom = null; /** @var ConditionalFormatValueObject[] */ private array $cfvos = []; public function getIconSetType(): ?IconSetValues { return $this->iconSetType; } public function setIconSetType(IconSetValues $type): self { $this->iconSetType = $type; return $this; } public function getReverse(): ?bool { return $this->reverse; } public function setReverse(bool $reverse): self { $this->reverse = $reverse; return $this; } public function getShowValue(): ?bool { return $this->showValue; } public function setShowValue(bool $showValue): self { $this->showValue = $showValue; return $this; } public function getCustom(): ?bool { return $this->custom; } public function setCustom(bool $custom): self { $this->custom = $custom; return $this; } /** * Get the conditional format value objects. * * @return ConditionalFormatValueObject[] */ public function getCfvos(): array { return $this->cfvos; } /** * Set the conditional format value objects. * * @param ConditionalFormatValueObject[] $cfvos */ public function setCfvos(array $cfvos): self { $this->cfvos = $cfvos; return $this; } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalFormatValueObject.php
src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalFormatValueObject.php
<?php namespace PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting; class ConditionalFormatValueObject { private string $type; private null|float|int|string $value; private ?string $cellFormula; /** * For icon sets, determines whether this threshold value uses the greater * than or equal to operator. False indicates 'greater than' is used instead * of 'greater than or equal to'. */ private ?bool $greaterThanOrEqual = null; public function __construct(string $type, null|float|int|string $value = null, ?string $cellFormula = null) { $this->type = $type; $this->value = $value; $this->cellFormula = $cellFormula; } public function getType(): string { return $this->type; } public function setType(string $type): self { $this->type = $type; return $this; } public function getValue(): null|float|int|string { return $this->value; } public function setValue(null|float|int|string $value): self { $this->value = $value; return $this; } public function getCellFormula(): ?string { return $this->cellFormula; } public function setCellFormula(?string $cellFormula): self { $this->cellFormula = $cellFormula; return $this; } public function getGreaterThanOrEqual(): ?bool { return $this->greaterThanOrEqual; } public function setGreaterThanOrEqual(?bool $greaterThanOrEqual): self { $this->greaterThanOrEqual = $greaterThanOrEqual; return $this; } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Style/ConditionalFormatting/Wizard/WizardInterface.php
src/PhpSpreadsheet/Style/ConditionalFormatting/Wizard/WizardInterface.php
<?php namespace PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\Wizard; use PhpOffice\PhpSpreadsheet\Style\Conditional; use PhpOffice\PhpSpreadsheet\Style\Style; interface WizardInterface { public function getCellRange(): string; public function setCellRange(string $cellRange): void; public function getStyle(): Style; public function setStyle(Style $style): void; public function getStopIfTrue(): bool; public function setStopIfTrue(bool $stopIfTrue): void; public function getConditional(): Conditional; public static function fromConditional(Conditional $conditional, string $cellRange = 'A1'): self; }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Style/ConditionalFormatting/Wizard/Expression.php
src/PhpSpreadsheet/Style/ConditionalFormatting/Wizard/Expression.php
<?php namespace PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\Wizard; use PhpOffice\PhpSpreadsheet\Exception; use PhpOffice\PhpSpreadsheet\Style\Conditional; use PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\Wizard; /** * @method Expression formula(string $expression) */ class Expression extends WizardAbstract implements WizardInterface { protected string $expression; public function __construct(string $cellRange) { parent::__construct($cellRange); } public function expression(string $expression): self { $expression = $this->validateOperand($expression, Wizard::VALUE_TYPE_FORMULA); $this->expression = $expression; return $this; } public function getConditional(): Conditional { /** @var string[] */ $expression = $this->adjustConditionsForCellReferences([$this->expression]); $conditional = new Conditional(); $conditional->setConditionType(Conditional::CONDITION_EXPRESSION); $conditional->setConditions($expression); $conditional->setStyle($this->getStyle()); $conditional->setStopIfTrue($this->getStopIfTrue()); return $conditional; } public static function fromConditional(Conditional $conditional, string $cellRange = 'A1'): WizardInterface { if ($conditional->getConditionType() !== Conditional::CONDITION_EXPRESSION) { throw new Exception('Conditional is not an Expression CF Rule conditional'); } $wizard = new self($cellRange); $wizard->style = $conditional->getStyle(); $wizard->stopIfTrue = $conditional->getStopIfTrue(); $wizard->expression = self::reverseAdjustCellRef((string) ($conditional->getConditions()[0]), $cellRange); return $wizard; } /** * @param string[] $arguments */ public function __call(string $methodName, array $arguments): self { if ($methodName !== 'formula') { throw new Exception('Invalid Operation for Expression CF Rule Wizard'); } $this->expression(...$arguments); return $this; } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Style/ConditionalFormatting/Wizard/WizardAbstract.php
src/PhpSpreadsheet/Style/ConditionalFormatting/Wizard/WizardAbstract.php
<?php namespace PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\Wizard; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\Wizard; use PhpOffice\PhpSpreadsheet\Style\Style; abstract class WizardAbstract { protected ?Style $style = null; protected string $expression; protected string $cellRange; protected string $referenceCell; protected int $referenceRow; protected bool $stopIfTrue = false; protected int $referenceColumn; public function __construct(string $cellRange) { $this->setCellRange($cellRange); } public function getCellRange(): string { return $this->cellRange; } public function setCellRange(string $cellRange): void { $this->cellRange = $cellRange; $this->setReferenceCellForExpressions($cellRange); } protected function setReferenceCellForExpressions(string $conditionalRange): void { $conditionalRange = Coordinate::splitRange(str_replace('$', '', strtoupper($conditionalRange))); [$this->referenceCell] = $conditionalRange[0]; [$this->referenceColumn, $this->referenceRow] = Coordinate::indexesFromString($this->referenceCell); } public function getStopIfTrue(): bool { return $this->stopIfTrue; } public function setStopIfTrue(bool $stopIfTrue): void { $this->stopIfTrue = $stopIfTrue; } public function getStyle(): Style { return $this->style ?? new Style(false, true); } public function setStyle(Style $style): void { $this->style = $style; } protected function validateOperand(string $operand, string $operandValueType = Wizard::VALUE_TYPE_LITERAL): string { if ( $operandValueType === Wizard::VALUE_TYPE_LITERAL && str_starts_with($operand, '"') && str_ends_with($operand, '"') ) { $operand = str_replace('""', '"', substr($operand, 1, -1)); } elseif ($operandValueType === Wizard::VALUE_TYPE_FORMULA && str_starts_with($operand, '=')) { $operand = substr($operand, 1); } return $operand; } /** @param string[] $matches */ protected static function reverseCellAdjustment(array $matches, int $referenceColumn, int $referenceRow): string { $worksheet = $matches[1]; $column = $matches[6]; $row = $matches[7]; if (!str_contains($column, '$')) { $column = Coordinate::columnIndexFromString($column); $column -= $referenceColumn - 1; $column = Coordinate::stringFromColumnIndex($column); } if (!str_contains($row, '$')) { $row = (int) $row - ($referenceRow - 1); } return "{$worksheet}{$column}{$row}"; } public static function reverseAdjustCellRef(string $condition, string $cellRange): string { $conditionalRange = Coordinate::splitRange(str_replace('$', '', strtoupper($cellRange))); [$referenceCell] = $conditionalRange[0]; [$referenceColumnIndex, $referenceRow] = Coordinate::indexesFromString($referenceCell); $splitCondition = explode(Calculation::FORMULA_STRING_QUOTE, $condition); $i = false; foreach ($splitCondition as &$value) { // Only count/replace in alternating array entries (ie. not in quoted strings) $i = $i === false; if ($i) { $value = (string) preg_replace_callback( '/' . Calculation::CALCULATION_REGEXP_CELLREF_RELATIVE . '/i', fn ($matches): string => self::reverseCellAdjustment($matches, $referenceColumnIndex, $referenceRow), $value ); } } unset($value); // Then rebuild the condition string to return it return implode(Calculation::FORMULA_STRING_QUOTE, $splitCondition); } /** @param string[] $matches */ protected function conditionCellAdjustment(array $matches): string { $worksheet = $matches[1]; $column = $matches[6]; $row = $matches[7]; if (!str_contains($column, '$')) { $column = Coordinate::columnIndexFromString($column); $column += $this->referenceColumn - 1; $column = Coordinate::stringFromColumnIndex($column); } if (!str_contains($row, '$')) { $row = (int) $row + ($this->referenceRow - 1); } return "{$worksheet}{$column}{$row}"; } protected function cellConditionCheck(string $condition): string { $splitCondition = explode(Calculation::FORMULA_STRING_QUOTE, $condition); $i = false; foreach ($splitCondition as &$value) { // Only count/replace in alternating array entries (ie. not in quoted strings) $i = $i === false; if ($i) { $value = (string) preg_replace_callback( '/' . Calculation::CALCULATION_REGEXP_CELLREF_RELATIVE . '/i', [$this, 'conditionCellAdjustment'], $value ); } } unset($value); // Then rebuild the condition string to return it return implode(Calculation::FORMULA_STRING_QUOTE, $splitCondition); } /** * @param mixed[] $conditions * * @return mixed[] */ protected function adjustConditionsForCellReferences(array $conditions): array { return array_map( [$this, 'cellConditionCheck'], $conditions ); } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Style/ConditionalFormatting/Wizard/Errors.php
src/PhpSpreadsheet/Style/ConditionalFormatting/Wizard/Errors.php
<?php namespace PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\Wizard; use PhpOffice\PhpSpreadsheet\Exception; use PhpOffice\PhpSpreadsheet\Style\Conditional; use PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\Wizard; /** * @method Errors notError() * @method Errors isError() */ class Errors extends WizardAbstract implements WizardInterface { protected const OPERATORS = [ 'notError' => false, 'isError' => true, ]; protected const EXPRESSIONS = [ Wizard::NOT_ERRORS => 'NOT(ISERROR(%s))', Wizard::ERRORS => 'ISERROR(%s)', ]; protected bool $inverse; public function __construct(string $cellRange, bool $inverse = false) { parent::__construct($cellRange); $this->inverse = $inverse; } protected function inverse(bool $inverse): void { $this->inverse = $inverse; } protected function getExpression(): void { $this->expression = sprintf( self::EXPRESSIONS[$this->inverse ? Wizard::ERRORS : Wizard::NOT_ERRORS], $this->referenceCell ); } public function getConditional(): Conditional { $this->getExpression(); $conditional = new Conditional(); $conditional->setConditionType( $this->inverse ? Conditional::CONDITION_CONTAINSERRORS : Conditional::CONDITION_NOTCONTAINSERRORS ); $conditional->setConditions([$this->expression]); $conditional->setStyle($this->getStyle()); $conditional->setStopIfTrue($this->getStopIfTrue()); return $conditional; } public static function fromConditional(Conditional $conditional, string $cellRange = 'A1'): WizardInterface { if ( $conditional->getConditionType() !== Conditional::CONDITION_CONTAINSERRORS && $conditional->getConditionType() !== Conditional::CONDITION_NOTCONTAINSERRORS ) { throw new Exception('Conditional is not an Errors CF Rule conditional'); } $wizard = new self($cellRange); $wizard->style = $conditional->getStyle(); $wizard->stopIfTrue = $conditional->getStopIfTrue(); $wizard->inverse = $conditional->getConditionType() === Conditional::CONDITION_CONTAINSERRORS; return $wizard; } /** * @param mixed[] $arguments */ public function __call(string $methodName, array $arguments): self { if (!array_key_exists($methodName, self::OPERATORS)) { throw new Exception('Invalid Operation for Errors CF Rule Wizard'); } $this->inverse(self::OPERATORS[$methodName]); return $this; } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Style/ConditionalFormatting/Wizard/DateValue.php
src/PhpSpreadsheet/Style/ConditionalFormatting/Wizard/DateValue.php
<?php namespace PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\Wizard; use PhpOffice\PhpSpreadsheet\Exception; use PhpOffice\PhpSpreadsheet\Style\Conditional; /** * @method DateValue yesterday() * @method DateValue today() * @method DateValue tomorrow() * @method DateValue lastSevenDays() * @method DateValue lastWeek() * @method DateValue thisWeek() * @method DateValue nextWeek() * @method DateValue lastMonth() * @method DateValue thisMonth() * @method DateValue nextMonth() */ class DateValue extends WizardAbstract implements WizardInterface { protected const MAGIC_OPERATIONS = [ 'yesterday' => Conditional::TIMEPERIOD_YESTERDAY, 'today' => Conditional::TIMEPERIOD_TODAY, 'tomorrow' => Conditional::TIMEPERIOD_TOMORROW, 'lastSevenDays' => Conditional::TIMEPERIOD_LAST_7_DAYS, 'last7Days' => Conditional::TIMEPERIOD_LAST_7_DAYS, 'lastWeek' => Conditional::TIMEPERIOD_LAST_WEEK, 'thisWeek' => Conditional::TIMEPERIOD_THIS_WEEK, 'nextWeek' => Conditional::TIMEPERIOD_NEXT_WEEK, 'lastMonth' => Conditional::TIMEPERIOD_LAST_MONTH, 'thisMonth' => Conditional::TIMEPERIOD_THIS_MONTH, 'nextMonth' => Conditional::TIMEPERIOD_NEXT_MONTH, ]; protected const EXPRESSIONS = [ Conditional::TIMEPERIOD_YESTERDAY => 'FLOOR(%s,1)=TODAY()-1', Conditional::TIMEPERIOD_TODAY => 'FLOOR(%s,1)=TODAY()', Conditional::TIMEPERIOD_TOMORROW => 'FLOOR(%s,1)=TODAY()+1', Conditional::TIMEPERIOD_LAST_7_DAYS => 'AND(TODAY()-FLOOR(%s,1)<=6,FLOOR(%s,1)<=TODAY())', Conditional::TIMEPERIOD_LAST_WEEK => 'AND(TODAY()-ROUNDDOWN(%s,0)>=(WEEKDAY(TODAY())),TODAY()-ROUNDDOWN(%s,0)<(WEEKDAY(TODAY())+7))', Conditional::TIMEPERIOD_THIS_WEEK => 'AND(TODAY()-ROUNDDOWN(%s,0)<=WEEKDAY(TODAY())-1,ROUNDDOWN(%s,0)-TODAY()<=7-WEEKDAY(TODAY()))', Conditional::TIMEPERIOD_NEXT_WEEK => 'AND(ROUNDDOWN(%s,0)-TODAY()>(7-WEEKDAY(TODAY())),ROUNDDOWN(%s,0)-TODAY()<(15-WEEKDAY(TODAY())))', Conditional::TIMEPERIOD_LAST_MONTH => 'AND(MONTH(%s)=MONTH(EDATE(TODAY(),0-1)),YEAR(%s)=YEAR(EDATE(TODAY(),0-1)))', Conditional::TIMEPERIOD_THIS_MONTH => 'AND(MONTH(%s)=MONTH(TODAY()),YEAR(%s)=YEAR(TODAY()))', Conditional::TIMEPERIOD_NEXT_MONTH => 'AND(MONTH(%s)=MONTH(EDATE(TODAY(),0+1)),YEAR(%s)=YEAR(EDATE(TODAY(),0+1)))', ]; protected string $operator; public function __construct(string $cellRange) { parent::__construct($cellRange); } protected function operator(string $operator): void { $this->operator = $operator; } protected function setExpression(): void { $referenceCount = substr_count(self::EXPRESSIONS[$this->operator], '%s'); $references = array_fill(0, $referenceCount, $this->referenceCell); $this->expression = sprintf(self::EXPRESSIONS[$this->operator], ...$references); } public function getConditional(): Conditional { $this->setExpression(); $conditional = new Conditional(); $conditional->setConditionType(Conditional::CONDITION_TIMEPERIOD); $conditional->setText($this->operator); $conditional->setConditions([$this->expression]); $conditional->setStyle($this->getStyle()); $conditional->setStopIfTrue($this->getStopIfTrue()); return $conditional; } public static function fromConditional(Conditional $conditional, string $cellRange = 'A1'): WizardInterface { if ($conditional->getConditionType() !== Conditional::CONDITION_TIMEPERIOD) { throw new Exception('Conditional is not a Date Value CF Rule conditional'); } $wizard = new self($cellRange); $wizard->style = $conditional->getStyle(); $wizard->stopIfTrue = $conditional->getStopIfTrue(); $wizard->operator = $conditional->getText(); return $wizard; } /** * @param mixed[] $arguments */ public function __call(string $methodName, array $arguments): self { if (!isset(self::MAGIC_OPERATIONS[$methodName])) { throw new Exception('Invalid Operation for Date Value CF Rule Wizard'); } $this->operator(self::MAGIC_OPERATIONS[$methodName]); return $this; } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Style/ConditionalFormatting/Wizard/Blanks.php
src/PhpSpreadsheet/Style/ConditionalFormatting/Wizard/Blanks.php
<?php namespace PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\Wizard; use PhpOffice\PhpSpreadsheet\Exception; use PhpOffice\PhpSpreadsheet\Style\Conditional; use PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\Wizard; /** * @method Blanks notBlank() * @method Blanks notEmpty() * @method Blanks isBlank() * @method Blanks isEmpty() */ class Blanks extends WizardAbstract implements WizardInterface { protected const OPERATORS = [ 'notBlank' => false, 'isBlank' => true, 'notEmpty' => false, 'empty' => true, ]; protected const EXPRESSIONS = [ Wizard::NOT_BLANKS => 'LEN(TRIM(%s))>0', Wizard::BLANKS => 'LEN(TRIM(%s))=0', ]; protected bool $inverse; public function __construct(string $cellRange, bool $inverse = false) { parent::__construct($cellRange); $this->inverse = $inverse; } protected function inverse(bool $inverse): void { $this->inverse = $inverse; } protected function getExpression(): void { $this->expression = sprintf( self::EXPRESSIONS[$this->inverse ? Wizard::BLANKS : Wizard::NOT_BLANKS], $this->referenceCell ); } public function getConditional(): Conditional { $this->getExpression(); $conditional = new Conditional(); $conditional->setConditionType( $this->inverse ? Conditional::CONDITION_CONTAINSBLANKS : Conditional::CONDITION_NOTCONTAINSBLANKS ); $conditional->setConditions([$this->expression]); $conditional->setStyle($this->getStyle()); $conditional->setStopIfTrue($this->getStopIfTrue()); return $conditional; } public static function fromConditional(Conditional $conditional, string $cellRange = 'A1'): WizardInterface { if ( $conditional->getConditionType() !== Conditional::CONDITION_CONTAINSBLANKS && $conditional->getConditionType() !== Conditional::CONDITION_NOTCONTAINSBLANKS ) { throw new Exception('Conditional is not a Blanks CF Rule conditional'); } $wizard = new self($cellRange); $wizard->style = $conditional->getStyle(); $wizard->stopIfTrue = $conditional->getStopIfTrue(); $wizard->inverse = $conditional->getConditionType() === Conditional::CONDITION_CONTAINSBLANKS; return $wizard; } /** * @param mixed[] $arguments */ public function __call(string $methodName, array $arguments): self { if (!array_key_exists($methodName, self::OPERATORS)) { throw new Exception('Invalid Operation for Blanks CF Rule Wizard'); } $this->inverse(self::OPERATORS[$methodName]); return $this; } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Style/ConditionalFormatting/Wizard/TextValue.php
src/PhpSpreadsheet/Style/ConditionalFormatting/Wizard/TextValue.php
<?php namespace PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\Wizard; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Exception; use PhpOffice\PhpSpreadsheet\Style\Conditional; use PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\Wizard; /** * @method TextValue contains(string $value, string $operandValueType = Wizard::VALUE_TYPE_LITERAL) * @method TextValue doesNotContain(string $value, string $operandValueType = Wizard::VALUE_TYPE_LITERAL) * @method TextValue doesntContain(string $value, string $operandValueType = Wizard::VALUE_TYPE_LITERAL) * @method TextValue beginsWith(string $value, string $operandValueType = Wizard::VALUE_TYPE_LITERAL) * @method TextValue startsWith(string $value, string $operandValueType = Wizard::VALUE_TYPE_LITERAL) * @method TextValue endsWith(string $value, string $operandValueType = Wizard::VALUE_TYPE_LITERAL) */ class TextValue extends WizardAbstract implements WizardInterface { protected const MAGIC_OPERATIONS = [ 'contains' => Conditional::OPERATOR_CONTAINSTEXT, 'doesntContain' => Conditional::OPERATOR_NOTCONTAINS, 'doesNotContain' => Conditional::OPERATOR_NOTCONTAINS, 'beginsWith' => Conditional::OPERATOR_BEGINSWITH, 'startsWith' => Conditional::OPERATOR_BEGINSWITH, 'endsWith' => Conditional::OPERATOR_ENDSWITH, ]; protected const OPERATORS = [ Conditional::OPERATOR_CONTAINSTEXT => Conditional::CONDITION_CONTAINSTEXT, Conditional::OPERATOR_NOTCONTAINS => Conditional::CONDITION_NOTCONTAINSTEXT, Conditional::OPERATOR_BEGINSWITH => Conditional::CONDITION_BEGINSWITH, Conditional::OPERATOR_ENDSWITH => Conditional::CONDITION_ENDSWITH, ]; protected const EXPRESSIONS = [ Conditional::OPERATOR_CONTAINSTEXT => 'NOT(ISERROR(SEARCH(%s,%s)))', Conditional::OPERATOR_NOTCONTAINS => 'ISERROR(SEARCH(%s,%s))', Conditional::OPERATOR_BEGINSWITH => 'LEFT(%s,LEN(%s))=%s', Conditional::OPERATOR_ENDSWITH => 'RIGHT(%s,LEN(%s))=%s', ]; protected string $operator; protected string $operand; protected string $operandValueType; public function __construct(string $cellRange) { parent::__construct($cellRange); } protected function operator(string $operator): void { if (!isset(self::OPERATORS[$operator])) { throw new Exception('Invalid Operator for Text Value CF Rule Wizard'); } $this->operator = $operator; } protected function operand(string $operand, string $operandValueType = Wizard::VALUE_TYPE_LITERAL): void { $operand = $this->validateOperand($operand, $operandValueType); $this->operand = $operand; $this->operandValueType = $operandValueType; } protected function wrapValue(string $value): string { return '"' . $value . '"'; } protected function setExpression(): void { $operand = $this->operandValueType === Wizard::VALUE_TYPE_LITERAL ? $this->wrapValue(str_replace('"', '""', $this->operand)) : $this->cellConditionCheck($this->operand); if ( $this->operator === Conditional::OPERATOR_CONTAINSTEXT || $this->operator === Conditional::OPERATOR_NOTCONTAINS ) { $this->expression = sprintf(self::EXPRESSIONS[$this->operator], $operand, $this->referenceCell); } else { $this->expression = sprintf(self::EXPRESSIONS[$this->operator], $this->referenceCell, $operand, $operand); } } public function getConditional(): Conditional { $this->setExpression(); $conditional = new Conditional(); $conditional->setConditionType(self::OPERATORS[$this->operator]); $conditional->setOperatorType($this->operator); $conditional->setText( $this->operandValueType !== Wizard::VALUE_TYPE_LITERAL ? $this->cellConditionCheck($this->operand) : $this->operand ); $conditional->setConditions([$this->expression]); $conditional->setStyle($this->getStyle()); $conditional->setStopIfTrue($this->getStopIfTrue()); return $conditional; } public static function fromConditional(Conditional $conditional, string $cellRange = 'A1'): WizardInterface { if (!in_array($conditional->getConditionType(), self::OPERATORS, true)) { throw new Exception('Conditional is not a Text Value CF Rule conditional'); } $wizard = new self($cellRange); $wizard->operator = (string) array_search($conditional->getConditionType(), self::OPERATORS, true); $wizard->style = $conditional->getStyle(); $wizard->stopIfTrue = $conditional->getStopIfTrue(); // Best-guess to try and identify if the text is a string literal, a cell reference or a formula? $wizard->operandValueType = Wizard::VALUE_TYPE_LITERAL; $condition = $conditional->getText(); if (preg_match('/^' . Calculation::CALCULATION_REGEXP_CELLREF_RELATIVE . '$/i', $condition)) { $wizard->operandValueType = Wizard::VALUE_TYPE_CELL; $condition = self::reverseAdjustCellRef($condition, $cellRange); } elseif ( preg_match('/\(\)/', $condition) || preg_match('/' . Calculation::CALCULATION_REGEXP_CELLREF_RELATIVE . '/i', $condition) ) { $wizard->operandValueType = Wizard::VALUE_TYPE_FORMULA; } $wizard->operand = $condition; return $wizard; } /** * @param mixed[] $arguments */ public function __call(string $methodName, array $arguments): self { if (!isset(self::MAGIC_OPERATIONS[$methodName])) { throw new Exception('Invalid Operation for Text Value CF Rule Wizard'); } $this->operator(self::MAGIC_OPERATIONS[$methodName]); //$this->operand(...$arguments); if (count($arguments) < 2) { /** @var string */ $arg0 = $arguments[0]; $this->operand($arg0); } else { /** @var string */ $arg0 = $arguments[0]; /** @var string */ $arg1 = $arguments[1]; $this->operand($arg0, $arg1); } return $this; } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Style/ConditionalFormatting/Wizard/Duplicates.php
src/PhpSpreadsheet/Style/ConditionalFormatting/Wizard/Duplicates.php
<?php namespace PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\Wizard; use PhpOffice\PhpSpreadsheet\Exception; use PhpOffice\PhpSpreadsheet\Style\Conditional; /** * @method Errors duplicates() * @method Errors unique() */ class Duplicates extends WizardAbstract implements WizardInterface { protected const OPERATORS = [ 'duplicates' => false, 'unique' => true, ]; protected bool $inverse; public function __construct(string $cellRange, bool $inverse = false) { parent::__construct($cellRange); $this->inverse = $inverse; } protected function inverse(bool $inverse): void { $this->inverse = $inverse; } public function getConditional(): Conditional { $conditional = new Conditional(); $conditional->setConditionType( $this->inverse ? Conditional::CONDITION_UNIQUE : Conditional::CONDITION_DUPLICATES ); $conditional->setStyle($this->getStyle()); $conditional->setStopIfTrue($this->getStopIfTrue()); return $conditional; } public static function fromConditional(Conditional $conditional, string $cellRange = 'A1'): WizardInterface { if ( $conditional->getConditionType() !== Conditional::CONDITION_DUPLICATES && $conditional->getConditionType() !== Conditional::CONDITION_UNIQUE ) { throw new Exception('Conditional is not a Duplicates CF Rule conditional'); } $wizard = new self($cellRange); $wizard->style = $conditional->getStyle(); $wizard->stopIfTrue = $conditional->getStopIfTrue(); $wizard->inverse = $conditional->getConditionType() === Conditional::CONDITION_UNIQUE; return $wizard; } /** * @param mixed[] $arguments */ public function __call(string $methodName, array $arguments): self { if (!array_key_exists($methodName, self::OPERATORS)) { throw new Exception('Invalid Operation for Errors CF Rule Wizard'); } $this->inverse(self::OPERATORS[$methodName]); return $this; } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Style/ConditionalFormatting/Wizard/CellValue.php
src/PhpSpreadsheet/Style/ConditionalFormatting/Wizard/CellValue.php
<?php namespace PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\Wizard; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Exception; use PhpOffice\PhpSpreadsheet\Style\Conditional; use PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\CellMatcher; use PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\Wizard; /** * @method CellValue equals($value, string $operandValueType = Wizard::VALUE_TYPE_LITERAL) * @method CellValue notEquals($value, string $operandValueType = Wizard::VALUE_TYPE_LITERAL) * @method CellValue greaterThan($value, string $operandValueType = Wizard::VALUE_TYPE_LITERAL) * @method CellValue greaterThanOrEqual($value, string $operandValueType = Wizard::VALUE_TYPE_LITERAL) * @method CellValue lessThan($value, string $operandValueType = Wizard::VALUE_TYPE_LITERAL) * @method CellValue lessThanOrEqual($value, string $operandValueType = Wizard::VALUE_TYPE_LITERAL) * @method CellValue between($value, string $operandValueType = Wizard::VALUE_TYPE_LITERAL) * @method CellValue notBetween($value, string $operandValueType = Wizard::VALUE_TYPE_LITERAL) * @method CellValue and($value, string $operandValueType = Wizard::VALUE_TYPE_LITERAL) */ class CellValue extends WizardAbstract implements WizardInterface { protected const MAGIC_OPERATIONS = [ 'equals' => Conditional::OPERATOR_EQUAL, 'notEquals' => Conditional::OPERATOR_NOTEQUAL, 'greaterThan' => Conditional::OPERATOR_GREATERTHAN, 'greaterThanOrEqual' => Conditional::OPERATOR_GREATERTHANOREQUAL, 'lessThan' => Conditional::OPERATOR_LESSTHAN, 'lessThanOrEqual' => Conditional::OPERATOR_LESSTHANOREQUAL, 'between' => Conditional::OPERATOR_BETWEEN, 'notBetween' => Conditional::OPERATOR_NOTBETWEEN, ]; protected const SINGLE_OPERATORS = CellMatcher::COMPARISON_OPERATORS; protected const RANGE_OPERATORS = CellMatcher::COMPARISON_RANGE_OPERATORS; protected string $operator = Conditional::OPERATOR_EQUAL; /** @var array<int|string> */ protected array $operand = [0]; /** * @var string[] */ protected array $operandValueType = []; public function __construct(string $cellRange) { parent::__construct($cellRange); } protected function operator(string $operator): void { if ((!isset(self::SINGLE_OPERATORS[$operator])) && (!isset(self::RANGE_OPERATORS[$operator]))) { throw new Exception('Invalid Operator for Cell Value CF Rule Wizard'); } $this->operator = $operator; } protected function operand(int $index, mixed $operand, string $operandValueType = Wizard::VALUE_TYPE_LITERAL): void { if (is_string($operand)) { $operand = $this->validateOperand($operand, $operandValueType); } $this->operand[$index] = $operand; //* @phpstan-ignore-line $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) { if ($operandValueType === Wizard::VALUE_TYPE_LITERAL) { return '"' . str_replace('"', '""', $value) . '"'; } return $this->cellConditionCheck($value); } if (null === $value) { $value = 'NULL'; } elseif (is_bool($value)) { $value = $value ? 'TRUE' : 'FALSE'; } return $value; } public function getConditional(): Conditional { if (!isset(self::RANGE_OPERATORS[$this->operator])) { unset($this->operand[1], $this->operandValueType[1]); } $values = array_map([$this, 'wrapValue'], $this->operand, $this->operandValueType); $conditional = new Conditional(); $conditional->setConditionType(Conditional::CONDITION_CELLIS); $conditional->setOperatorType($this->operator); $conditional->setConditions($values); $conditional->setStyle($this->getStyle()); $conditional->setStopIfTrue($this->getStopIfTrue()); return $conditional; } protected static function unwrapString(string $condition): string { if ((str_starts_with($condition, '"')) && (str_starts_with(strrev($condition), '"'))) { $condition = substr($condition, 1, -1); } return str_replace('""', '"', $condition); } public static function fromConditional(Conditional $conditional, string $cellRange = 'A1'): WizardInterface { if ($conditional->getConditionType() !== Conditional::CONDITION_CELLIS) { throw new Exception('Conditional is not a Cell Value CF Rule conditional'); } $wizard = new self($cellRange); $wizard->style = $conditional->getStyle(); $wizard->stopIfTrue = $conditional->getStopIfTrue(); $wizard->operator = $conditional->getOperatorType(); $conditions = $conditional->getConditions(); foreach ($conditions as $index => $condition) { // Best-guess to try and identify if the text is a string literal, a cell reference or a formula? $operandValueType = Wizard::VALUE_TYPE_LITERAL; if (is_string($condition)) { if (Calculation::keyInExcelConstants($condition)) { $condition = Calculation::getExcelConstants($condition); } elseif (preg_match('/^' . Calculation::CALCULATION_REGEXP_CELLREF_RELATIVE . '$/i', $condition)) { $operandValueType = Wizard::VALUE_TYPE_CELL; $condition = self::reverseAdjustCellRef($condition, $cellRange); } elseif ( preg_match('/\(\)/', $condition) || preg_match('/' . Calculation::CALCULATION_REGEXP_CELLREF_RELATIVE . '/i', $condition) ) { $operandValueType = Wizard::VALUE_TYPE_FORMULA; $condition = self::reverseAdjustCellRef($condition, $cellRange); } else { $condition = self::unwrapString($condition); } } $wizard->operand($index, $condition, $operandValueType); } return $wizard; } /** * @param mixed[] $arguments */ public function __call(string $methodName, array $arguments): self { if (!isset(self::MAGIC_OPERATIONS[$methodName]) && $methodName !== 'and') { throw new Exception('Invalid Operator for Cell Value CF Rule Wizard'); } if ($methodName === 'and') { if (!isset(self::RANGE_OPERATORS[$this->operator])) { throw new Exception('AND Value is only appropriate for range operators'); } $this->operand(1, ...$arguments); return $this; } $this->operator(self::MAGIC_OPERATIONS[$methodName]); //$this->operand(0, ...$arguments); if (count($arguments) < 2) { $this->operand(0, $arguments[0]); } else { /** @var string */ $arg1 = $arguments[1]; $this->operand(0, $arguments[0], $arg1); } return $this; } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Style/NumberFormat/FractionFormatter.php
src/PhpSpreadsheet/Style/NumberFormat/FractionFormatter.php
<?php namespace PhpOffice\PhpSpreadsheet\Style\NumberFormat; use PhpOffice\PhpSpreadsheet\Calculation\MathTrig; class FractionFormatter extends BaseFormatter { /** @param null|bool|float|int|string $value value to be formatted */ public static function format(mixed $value, string $format): string { $format = self::stripQuotes($format); $value = (float) $value; $absValue = abs($value); $sign = ($value < 0.0) ? '-' : ''; $integerPart = floor($absValue); $decimalPart = self::getDecimal((string) $absValue); if ($decimalPart === '0') { return "{$sign}{$integerPart}"; } $decimalLength = strlen($decimalPart); $decimalDivisor = 10 ** $decimalLength; preg_match('/(#?.*\?)\/(\?+|\d+)/', $format, $matches); $formatIntegerPart = $matches[1] ?? '0'; if (isset($matches[2]) && is_numeric($matches[2])) { $fractionDivisor = 100 / (int) $matches[2]; } else { /** @var float $fractionDivisor */ $fractionDivisor = MathTrig\Gcd::evaluate((int) $decimalPart, $decimalDivisor); } $adjustedDecimalPart = (int) round((int) $decimalPart / $fractionDivisor, 0); $adjustedDecimalDivisor = $decimalDivisor / $fractionDivisor; if ((str_contains($formatIntegerPart, '0'))) { return "{$sign}{$integerPart} {$adjustedDecimalPart}/{$adjustedDecimalDivisor}"; } elseif ((str_contains($formatIntegerPart, '#'))) { if ($integerPart == 0) { return "{$sign}{$adjustedDecimalPart}/{$adjustedDecimalDivisor}"; } return "{$sign}{$integerPart} {$adjustedDecimalPart}/{$adjustedDecimalDivisor}"; } elseif ((str_starts_with($formatIntegerPart, '? ?'))) { if ($integerPart == 0) { $integerPart = ''; } return "{$sign}{$integerPart} {$adjustedDecimalPart}/{$adjustedDecimalDivisor}"; } $adjustedDecimalPart += $integerPart * $adjustedDecimalDivisor; return "{$sign}{$adjustedDecimalPart}/{$adjustedDecimalDivisor}"; } private static function getDecimal(string $value): string { $decimalPart = '0'; if (preg_match('/^\d*[.](\d*[1-9])0*$/', $value, $matches) === 1) { $decimalPart = $matches[1]; } return $decimalPart; } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Style/NumberFormat/Formatter.php
src/PhpSpreadsheet/Style/NumberFormat/Formatter.php
<?php namespace PhpOffice\PhpSpreadsheet\Style\NumberFormat; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Reader\Xls\Color\BIFF8; use PhpOffice\PhpSpreadsheet\RichText\RichText; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; use PhpOffice\PhpSpreadsheet\Style\Color; use PhpOffice\PhpSpreadsheet\Style\NumberFormat; class Formatter extends BaseFormatter { /** * Matches any @ symbol that isn't enclosed in quotes. */ private const SYMBOL_AT = '/@(?=(?:[^"]*"[^"]*")*[^"]*\Z)/miu'; private const QUOTE_REPLACEMENT = "\u{fffe}"; // invalid Unicode character /** * Matches any ; symbol that isn't enclosed in quotes, for a "section" split. */ private const SECTION_SPLIT = '/;(?=(?:[^"]*"[^"]*")*[^"]*\Z)/miu'; private static function splitFormatComparison( mixed $value, ?string $condition, mixed $comparisonValue, string $defaultCondition, mixed $defaultComparisonValue ): bool { if (!$condition) { $condition = $defaultCondition; $comparisonValue = $defaultComparisonValue; } return match ($condition) { '>' => $value > $comparisonValue, '<' => $value < $comparisonValue, '<=' => $value <= $comparisonValue, '<>' => $value != $comparisonValue, '=' => $value == $comparisonValue, default => $value >= $comparisonValue, }; } /** * @param float|int|numeric-string $value value to be formatted * @param string[] $sections * * @return mixed[] */ private static function splitFormatForSectionSelection(array $sections, mixed $value): array { // Extract the relevant section depending on whether number is positive, negative, or zero? // Text not supported yet. // Here is how the sections apply to various values in Excel: // 1 section: [POSITIVE/NEGATIVE/ZERO/TEXT] // 2 sections: [POSITIVE/ZERO/TEXT] [NEGATIVE] // 3 sections: [POSITIVE/TEXT] [NEGATIVE] [ZERO] // 4 sections: [POSITIVE] [NEGATIVE] [ZERO] [TEXT] $sectionCount = count($sections); // Colour could be a named colour, or a numeric index entry in the colour-palette $color_regex = '/\[(' . implode('|', Color::NAMED_COLORS) . '|color\s*(\d+))\]/mui'; $cond_regex = '/\[(>|>=|<|<=|=|<>)([+-]?\d+([.]\d+)?)\]/'; $colors = ['', '', '', '', '']; $conditionOperations = ['', '', '', '', '']; $conditionComparisonValues = [0, 0, 0, 0, 0]; for ($idx = 0; $idx < $sectionCount; ++$idx) { if (preg_match($color_regex, $sections[$idx], $matches)) { if (isset($matches[2])) { $colors[$idx] = '#' . BIFF8::lookup((int) $matches[2] + 7)['rgb']; } else { $colors[$idx] = $matches[0]; } $sections[$idx] = (string) preg_replace($color_regex, '', $sections[$idx]); } if (preg_match($cond_regex, $sections[$idx], $matches)) { $conditionOperations[$idx] = $matches[1]; $conditionComparisonValues[$idx] = $matches[2]; $sections[$idx] = (string) preg_replace($cond_regex, '', $sections[$idx]); } } $color = $colors[0]; $format = $sections[0]; $absval = $value; switch ($sectionCount) { case 2: $absval = abs($value + 0); if (!self::splitFormatComparison($value, $conditionOperations[0], $conditionComparisonValues[0], '>=', 0)) { $color = $colors[1]; $format = $sections[1]; } break; case 3: case 4: $absval = abs($value + 0); if (!self::splitFormatComparison($value, $conditionOperations[0], $conditionComparisonValues[0], '>', 0)) { if (self::splitFormatComparison($value, $conditionOperations[1], $conditionComparisonValues[1], '<', 0)) { $color = $colors[1]; $format = $sections[1]; } else { $color = $colors[2]; $format = $sections[2]; } } break; } return [$color, $format, $absval]; } /** * Convert a value in a pre-defined format to a PHP string. * * @param null|array<mixed>|bool|float|int|RichText|string $value Value to format * @param string $format Format code: see = self::FORMAT_* for predefined values; * or can be any valid MS Excel custom format string * @param null|array<mixed>|callable $callBack Callback function for additional formatting of string * @param bool $lessFloatPrecision If true, unstyled floats will be converted to a more human-friendly but less computationally accurate value * * @return string Formatted string */ public static function toFormattedString($value, string $format, null|array|callable $callBack = null, bool $lessFloatPrecision = false): string { while (is_array($value)) { $value = array_shift($value); } if (is_bool($value)) { return $value ? Calculation::getTRUE() : Calculation::getFALSE(); } // For now we do not treat strings in sections, although section 4 of a format code affects strings // Process a single block format code containing @ for text substitution $formatx = str_replace('\"', self::QUOTE_REPLACEMENT, $format); if (preg_match(self::SECTION_SPLIT, $format) === 0 && preg_match(self::SYMBOL_AT, $formatx) === 1) { if (!str_contains($format, '"')) { return str_replace('@', StringHelper::convertToString($value, lessFloatPrecision: $lessFloatPrecision), $format); } //escape any dollar signs on the string, so they are not replaced with an empty value $value = str_replace( ['$', '"'], ['\$', self::QUOTE_REPLACEMENT], StringHelper::convertToString($value, lessFloatPrecision: $lessFloatPrecision) ); return str_replace( ['"', self::QUOTE_REPLACEMENT], ['', '"'], preg_replace(self::SYMBOL_AT, $value, $formatx) ?? $value ); } // If we have a text value, return it "as is" if (!is_numeric($value)) { return StringHelper::convertToString($value, lessFloatPrecision: $lessFloatPrecision); } // For 'General' format code, we just pass the value although this is not entirely the way Excel does it, // it seems to round numbers to a total of 10 digits. if (($format === NumberFormat::FORMAT_GENERAL) || ($format === NumberFormat::FORMAT_TEXT)) { if (is_float($value) && $lessFloatPrecision) { return self::adjustSeparators((string) $value); } return self::adjustSeparators( StringHelper::convertToString($value, lessFloatPrecision: $lessFloatPrecision) ); } // Ignore square-$-brackets prefix in format string, like "[$-411]ge.m.d", "[$-010419]0%", etc $format = (string) preg_replace('/^\[\$-[^\]]*\]/', '', $format); $format = (string) preg_replace_callback( '/(["])(?:(?=(\\\?))\2.)*?\1/u', fn (array $matches): string => str_replace('.', chr(0x00), $matches[0]), $format ); // Convert any other escaped characters to quoted strings, e.g. (\T to "T") $format = (string) preg_replace('/(\\\(((.)(?!((AM\/PM)|(A\/P))))|([^ ])))(?=(?:[^"]|"[^"]*")*$)/ui', '"${2}"', $format); // Get the sections, there can be up to four sections, separated with a semicolon (but only if not a quoted literal) $sections = preg_split(self::SECTION_SPLIT, $format) ?: []; [$colors, $format, $value] = self::splitFormatForSectionSelection($sections, $value); // In Excel formats, "_" is used to add spacing, // The following character indicates the size of the spacing, which we can't do in HTML, so we just use a standard space /** @var string */ $temp = $format; $format = (string) preg_replace('/_.?/ui', ' ', $temp); // Let's begin inspecting the format and converting the value to a formatted string if ( // Check for date/time characters (not inside quotes) (preg_match('/(\[\$[A-Z]*-[0-9A-F]*\])*[hmsdy](?=(?:[^"]|"[^"]*")*$)/miu', $format)) // Look out for Currency formats Issue 4124 && !(preg_match('/\[\$[A-Z]{3}\]/miu', $format)) // A date/time with a decimal time shouldn't have a digit placeholder before the decimal point && (preg_match('/[0\?#]\.(?![^\[]*\])/miu', $format) === 0) ) { // datetime format /** @var float|int */ $temp = $value; $value = DateFormatter::format($temp, $format); } else { if (str_starts_with($format, '"') && str_ends_with($format, '"') && substr_count($format, '"') === 2) { $value = substr($format, 1, -1); } elseif (preg_match('/[0#, ]%/', $format)) { // % number format - avoid weird '-0' problem /** @var float */ $temp = $value; $value = PercentageFormatter::format(0 + (float) $temp, $format); } else { /** @var float|int|numeric-string */ $temp = $value; $value = NumberFormatter::format($temp, $format); } } // Additional formatting provided by callback function if (is_callable($callBack)) { $value = $callBack($value, $colors); } /** @var string $value */ return str_replace(chr(0x00), '.', $value); } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Style/NumberFormat/NumberFormatter.php
src/PhpSpreadsheet/Style/NumberFormat/NumberFormatter.php
<?php namespace PhpOffice\PhpSpreadsheet\Style\NumberFormat; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; use PhpOffice\PhpSpreadsheet\Style\NumberFormat; class NumberFormatter extends BaseFormatter { private const NUMBER_REGEX = '/(0+)(\.?)(0*)/'; /** * @param string[] $numbers * @param string[] $masks * * @return mixed[] */ private static function mergeComplexNumberFormatMasks(array $numbers, array $masks): array { $decimalCount = strlen($numbers[1]); $postDecimalMasks = []; do { $tempMask = array_pop($masks); if ($tempMask !== null) { $postDecimalMasks[] = $tempMask; $decimalCount -= strlen($tempMask); } } while ($tempMask !== null && $decimalCount > 0); return [ implode('.', $masks), implode('.', array_reverse($postDecimalMasks)), ]; } private static function processComplexNumberFormatMask(mixed $number, string $mask): string { /** @var string $result */ $result = $number; $maskingBlockCount = preg_match_all('/0+/', $mask, $maskingBlocks, PREG_OFFSET_CAPTURE); if ($maskingBlockCount > 1) { $maskingBlocks = array_reverse($maskingBlocks[0]); $offset = 0; foreach ($maskingBlocks as $block) { $size = strlen($block[0]); $divisor = 10 ** $size; $offset = $block[1]; /** @var float $numberFloat */ $numberFloat = $number; $blockValue = sprintf("%0{$size}d", fmod($numberFloat, $divisor)); $number = floor($numberFloat / $divisor); $mask = substr_replace($mask, $blockValue, $offset, $size); } /** @var string $numberString */ $numberString = $number; if ($number > 0) { $mask = substr_replace($mask, $numberString, $offset, 0); } $result = $mask; } return self::makeString($result); } private static function complexNumberFormatMask(mixed $number, string $mask, bool $splitOnPoint = true): string { /** @var float $numberFloat */ $numberFloat = $number; if ($splitOnPoint) { $masks = explode('.', $mask); if (count($masks) <= 2) { $decmask = $masks[1] ?? ''; $decpos = substr_count($decmask, '0'); $numberFloat = round($numberFloat, $decpos); } } $sign = ($numberFloat < 0.0) ? '-' : ''; $number = self::f2s(abs($numberFloat)); if ($splitOnPoint && str_contains($mask, '.') && str_contains($number, '.')) { $numbers = explode('.', $number); $masks = explode('.', $mask); if (count($masks) > 2) { $masks = self::mergeComplexNumberFormatMasks($numbers, $masks); } /** @var string[] $masks */ $integerPart = self::complexNumberFormatMask($numbers[0], $masks[0], false); $numlen = strlen($numbers[1]); $msklen = strlen($masks[1]); if ($numlen < $msklen) { $numbers[1] .= str_repeat('0', $msklen - $numlen); } $decimalPart = strrev(self::complexNumberFormatMask(strrev($numbers[1]), strrev($masks[1]), false)); $decimalPart = substr($decimalPart, 0, $msklen); return "{$sign}{$integerPart}.{$decimalPart}"; } if (strlen($number) < strlen($mask)) { $number = str_repeat('0', strlen($mask) - strlen($number)) . $number; } $result = self::processComplexNumberFormatMask($number, $mask); return "{$sign}{$result}"; } public static function f2s(float $f): string { return self::floatStringConvertScientific((string) $f); } public static function floatStringConvertScientific(string $s): string { // convert only normalized form of scientific notation: // optional sign, single digit 1-9, // decimal point and digits (allowed to be omitted), // E (e permitted), optional sign, one or more digits if (preg_match('/^([+-])?([1-9])([.]([0-9]+))?[eE]([+-]?[0-9]+)$/', $s, $matches) === 1) { $exponent = (int) $matches[5]; $sign = ($matches[1] === '-') ? '-' : ''; if ($exponent >= 0) { $exponentPlus1 = $exponent + 1; $out = $matches[2] . $matches[4]; $len = strlen($out); if ($len < $exponentPlus1) { $out .= str_repeat('0', $exponentPlus1 - $len); } $out = substr($out, 0, $exponentPlus1) . ((strlen($out) === $exponentPlus1) ? '' : ('.' . substr($out, $exponentPlus1))); $s = "$sign$out"; } else { $s = $sign . '0.' . str_repeat('0', -$exponent - 1) . $matches[2] . $matches[4]; } } return $s; } /** @param string[] $matches */ private static function formatStraightNumericValue(mixed $value, string $format, array $matches, bool $useThousands): string { /** @var float $valueFloat */ $valueFloat = $value; $left = $matches[1]; $dec = $matches[2]; $right = $matches[3]; // minimum width of formatted number (including dot) $minWidth = strlen($left) + strlen($dec) + strlen($right); if ($useThousands) { $value = number_format( $valueFloat, strlen($right), StringHelper::getDecimalSeparator(), StringHelper::getThousandsSeparator() ); return self::pregReplace(self::NUMBER_REGEX, $value, $format); } if (preg_match('/[0#]E[+-]0/i', $format)) { // Scientific format $decimals = strlen($right); $size = $decimals + 3; return sprintf("%{$size}.{$decimals}E", $valueFloat); } if (preg_match('/0([^\d\.]+)0/', $format) || substr_count($format, '.') > 1) { if ($valueFloat == floor($valueFloat) && substr_count($format, '.') === 1) { $value *= 10 ** strlen(explode('.', $format)[1]); //* @phpstan-ignore-line } $result = self::complexNumberFormatMask($value, $format); if (str_contains($result, 'E')) { // This is a hack and doesn't match Excel. // It will, at least, be an accurate representation, // even if formatted incorrectly. // This is needed for absolute values >=1E18. $result = self::f2s($valueFloat); } return $result; } $sprintf_pattern = "%0$minWidth." . strlen($right) . 'F'; /** @var float $valueFloat */ $valueFloat = $value; $value = self::adjustSeparators(sprintf($sprintf_pattern, round($valueFloat, strlen($right)))); 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, // so this test is never true. Furthermore, testing // on Excel shows this format uses Euro symbol, not "EUR". // if ($format === NumberFormat::FORMAT_CURRENCY_EUR_SIMPLE) { // return 'EUR ' . sprintf('%1.2f', $value); // } $baseFormat = $format; $useThousands = self::areThousandsRequired($format); $scale = self::scaleThousandsMillions($format); if (preg_match('/[#\?0]?.*[#\?0]\/(\?+|\d+|#)/', $format)) { // It's a dirty hack; but replace # and 0 digit placeholders with ? $format = (string) preg_replace('/[#0]+\//', '?/', $format); $format = (string) preg_replace('/\/[#0]+/', '/?', $format); $value = FractionFormatter::format($value, $format); } else { // Handle the number itself // scale number $value = $value / $scale; $paddingPlaceholder = (str_contains($format, '?')); // Replace # or ? with 0 $format = self::pregReplace('/[\#\?](?=(?:[^"]*"[^"]*")*[^"]*\Z)/', '0', $format); // Remove locale code [$-###] for an LCID $format = self::pregReplace('/\[\$\-.*\]/', '', $format); $n = '/\[[^\]]+\]/'; $m = self::pregReplace($n, '', $format); // Some non-number strings are quoted, so we'll get rid of the quotes, likewise any positional * symbols $format = self::makeString(str_replace(['"', '*'], '', $format)); if (preg_match(self::NUMBER_REGEX, $m, $matches)) { // There are placeholders for digits, so inject digits from the value into the mask $value = self::formatStraightNumericValue($value, $format, $matches, $useThousands); if ($paddingPlaceholder === true) { $value = self::padValue($value, $baseFormat); } } elseif ($format !== NumberFormat::FORMAT_GENERAL) { // Yes, I know that this is basically just a hack; // if there's no placeholders for digits, just return the format mask "as is" $value = self::makeString(str_replace('?', '', $format)); } } if (preg_match('/\[\$(.*)\]/u', $format, $m)) { // Currency or Accounting $value = preg_replace('/-0+(( |\xc2\xa0))?\[/', '- [', (string) $value) ?? $value; $currencyCode = $m[1]; [$currencyCode] = explode('-', $currencyCode); if ($currencyCode == '') { $currencyCode = StringHelper::getCurrencyCode(); } $value = self::pregReplace('/\[\$([^\]]*)\]/u', $currencyCode, (string) $value); } if ( (str_contains((string) $value, '0.')) && ((str_contains($baseFormat, '#.')) || (str_contains($baseFormat, '?.'))) ) { $value = preg_replace('/(\b)0\.|([^\d])0\./', '${2}.', (string) $value); } return (string) $value; } /** @param mixed[]|string $value */ private static function makeString(array|string $value): string { return is_array($value) ? '' : "$value"; } private static function pregReplace(string $pattern, string $replacement, string $subject): string { return self::makeString(preg_replace($pattern, $replacement, $subject) ?? ''); } public static function padValue(string $value, string $baseFormat): string { $preDecimal = $postDecimal = ''; $pregArray = preg_split('/\.(?=(?:[^"]*"[^"]*")*[^"]*\Z)/miu', $baseFormat . '.?'); if (is_array($pregArray)) { $preDecimal = $pregArray[0]; $postDecimal = $pregArray[1] ?? ''; } $length = strlen($value); if (str_contains($postDecimal, '?')) { $value = str_pad(rtrim($value, '0. '), $length, ' ', STR_PAD_RIGHT); } if (str_contains($preDecimal, '?')) { $value = str_pad(ltrim($value, '0, '), $length, ' ', STR_PAD_LEFT); } return $value; } /** * Find out if we need thousands separator * This is indicated by a comma enclosed by a digit placeholders: #, 0 or ? */ public static function areThousandsRequired(string &$format): bool { $useThousands = (bool) preg_match('/([#\?0]),([#\?0])/', $format); if ($useThousands) { $format = self::pregReplace('/([#\?0]),([#\?0])/', '${1}${2}', $format); } return $useThousands; } /** * Scale thousands, millions,... * This is indicated by a number of commas after a digit placeholder: #, or 0.0,, or ?,. */ public static function scaleThousandsMillions(string &$format): int { $scale = 1; // same as no scale if (preg_match('/(#|0|\?)(,+)/', $format, $matches)) { $scale = 1000 ** strlen($matches[2]); // strip the commas $format = self::pregReplace('/([#\?0]),+/', '${1}', $format); } return $scale; } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Style/NumberFormat/PercentageFormatter.php
src/PhpSpreadsheet/Style/NumberFormat/PercentageFormatter.php
<?php namespace PhpOffice\PhpSpreadsheet\Style\NumberFormat; use PhpOffice\PhpSpreadsheet\Style\NumberFormat; class PercentageFormatter extends BaseFormatter { /** @param float|int $value */ public static function format($value, string $format): string { if ($format === NumberFormat::FORMAT_PERCENTAGE) { return round((100 * $value), 0) . '%'; } $value *= 100; $format = self::stripQuotes($format); [, $vDecimals] = explode('.', ((string) $value) . '.'); $vDecimalCount = strlen(rtrim($vDecimals, '0')); $format = str_replace('%', '%%', $format); $wholePartSize = strlen((string) floor(abs($value))); $decimalPartSize = 0; $placeHolders = ''; // Number of decimals if (preg_match('/\.([?0]+)/u', $format, $matches)) { $decimalPartSize = strlen($matches[1]); $vMinDecimalCount = strlen(rtrim($matches[1], '?')); $decimalPartSize = min(max($vMinDecimalCount, $vDecimalCount), $decimalPartSize); $placeHolders = str_repeat(' ', strlen($matches[1]) - $decimalPartSize); } // Number of digits to display before the decimal if (preg_match('/([#0,]+)\.?/u', $format, $matches)) { $firstZero = ltrim($matches[1], '#,'); $wholePartSize = max($wholePartSize, strlen($firstZero)); } $wholePartSize += $decimalPartSize + (int) ($decimalPartSize > 0); $replacement = "0{$wholePartSize}.{$decimalPartSize}"; $mask = (string) preg_replace('/[#0,]+\.?[?#0,]*/ui', "%{$replacement}F{$placeHolders}", $format); /** @var float $valueFloat */ $valueFloat = $value; return self::adjustSeparators(sprintf($mask, round($valueFloat, $decimalPartSize))); } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Style/NumberFormat/DateFormatter.php
src/PhpSpreadsheet/Style/NumberFormat/DateFormatter.php
<?php namespace PhpOffice\PhpSpreadsheet\Style\NumberFormat; use PhpOffice\PhpSpreadsheet\Shared\Date; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; use Throwable; class DateFormatter { /** * Search/replace values to convert Excel date/time format masks to PHP format masks. */ private const DATE_FORMAT_REPLACEMENTS = [ // first remove escapes related to non-format characters '\\' => '', // 12-hour suffix 'am/pm' => 'A', // 4-digit year 'e' => 'Y', 'yyyy' => 'Y', // 2-digit year 'yy' => 'y', // first letter of month - no php equivalent 'mmmmm' => 'M', // full month name 'mmmm' => 'F', // short month name 'mmm' => 'M', // mm is minutes if time, but can also be month w/leading zero // so we try to identify times be the inclusion of a : separator in the mask // It isn't perfect, but the best way I know how ':mm' => ':i', 'mm:' => 'i:', // full day of week name 'dddd' => 'l', // short day of week name 'ddd' => 'D', // days leading zero 'dd' => 'd', // days no leading zero 'd' => 'j', // fractional seconds - no php equivalent '.s' => '', ]; /** * Search/replace values to convert Excel date/time format masks hours to PHP format masks (24 hr clock). */ private const DATE_FORMAT_REPLACEMENTS24 = [ 'hh' => 'H', 'h' => 'G', // month leading zero 'mm' => 'm', // month no leading zero 'm' => 'n', // seconds 'ss' => 's', ]; /** * Search/replace values to convert Excel date/time format masks hours to PHP format masks (12 hr clock). */ private const DATE_FORMAT_REPLACEMENTS12 = [ 'hh' => 'h', 'h' => 'g', // month leading zero 'mm' => 'm', // month no leading zero 'm' => 'n', // seconds 'ss' => 's', ]; private const HOURS_IN_DAY = 24; private const MINUTES_IN_DAY = 60 * self::HOURS_IN_DAY; private const SECONDS_IN_DAY = 60 * self::MINUTES_IN_DAY; private const INTERVAL_PRECISION = 10; private const INTERVAL_LEADING_ZERO = [ '[hh]', '[mm]', '[ss]', ]; private const INTERVAL_ROUND_PRECISION = [ // hours and minutes truncate '[h]' => self::INTERVAL_PRECISION, '[hh]' => self::INTERVAL_PRECISION, '[m]' => self::INTERVAL_PRECISION, '[mm]' => self::INTERVAL_PRECISION, // seconds round '[s]' => 0, '[ss]' => 0, ]; private const INTERVAL_MULTIPLIER = [ '[h]' => self::HOURS_IN_DAY, '[hh]' => self::HOURS_IN_DAY, '[m]' => self::MINUTES_IN_DAY, '[mm]' => self::MINUTES_IN_DAY, '[s]' => self::SECONDS_IN_DAY, '[ss]' => self::SECONDS_IN_DAY, ]; /** @param float|int|numeric-string $value */ private static function tryInterval(bool &$seekingBracket, string &$block, mixed $value, string $format): void { if ($seekingBracket) { if (str_contains($block, $format)) { $hours = (string) (int) round( self::INTERVAL_MULTIPLIER[$format] * $value, self::INTERVAL_ROUND_PRECISION[$format] ); if (strlen($hours) === 1 && in_array($format, self::INTERVAL_LEADING_ZERO, true)) { $hours = "0$hours"; } $block = str_replace($format, $hours, $block); $seekingBracket = false; } } } /** @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] // general syntax: [$<Currency string>-<language info>] // language info is in hexadecimal // strip off chinese part like [DBNum1][$-804] $format = (string) preg_replace('/^(\[DBNum\d\])*(\[\$[^\]]*\])/i', '', $format); // OpenOffice.org uses upper-case number formats, e.g. 'YYYY', convert to lower-case; // but we don't want to change any quoted strings /** @var callable $callable */ $callable = [self::class, 'setLowercaseCallback']; $format = (string) preg_replace_callback('/(?:^|")([^"]*)(?:$|")/', $callable, $format); // Only process the non-quoted blocks for date format characters $blocks = explode('"', $format); foreach ($blocks as $key => &$block) { if ($key % 2 == 0) { $block = strtr($block, self::DATE_FORMAT_REPLACEMENTS); if (!strpos($block, 'A')) { // 24-hour time format // when [h]:mm format, the [h] should replace to the hours of the value * 24 $seekingBracket = true; self::tryInterval($seekingBracket, $block, $value, '[h]'); self::tryInterval($seekingBracket, $block, $value, '[hh]'); self::tryInterval($seekingBracket, $block, $value, '[mm]'); self::tryInterval($seekingBracket, $block, $value, '[m]'); self::tryInterval($seekingBracket, $block, $value, '[s]'); self::tryInterval($seekingBracket, $block, $value, '[ss]'); $block = strtr($block, self::DATE_FORMAT_REPLACEMENTS24); } else { // 12-hour time format $block = strtr($block, self::DATE_FORMAT_REPLACEMENTS12); } } } $format = implode('"', $blocks); // escape any quoted characters so that DateTime format() will render them correctly /** @var callable $callback */ $callback = [self::class, 'escapeQuotesCallback']; $format = (string) preg_replace_callback('/"(.*)"/U', $callback, $format); try { $dateObj = Date::excelToDateTimeObject($value); } catch (Throwable) { return StringHelper::convertToString($value); } // If the colon preceding minute had been quoted, as happens in // Excel 2003 XML formats, m will not have been changed to i above. // Change it now. $format = (string) \preg_replace('/\\\:m/', ':i', $format); $microseconds = (int) $dateObj->format('u'); if (str_contains($format, ':s.000')) { $milliseconds = (int) round($microseconds / 1000.0); if ($milliseconds === 1000) { $milliseconds = 0; $dateObj->modify('+1 second'); } $dateObj->modify("-$microseconds microseconds"); $format = str_replace(':s.000', ':s.' . sprintf('%03d', $milliseconds), $format); } elseif (str_contains($format, ':s.00')) { $centiseconds = (int) round($microseconds / 10000.0); if ($centiseconds === 100) { $centiseconds = 0; $dateObj->modify('+1 second'); } $dateObj->modify("-$microseconds microseconds"); $format = str_replace(':s.00', ':s.' . sprintf('%02d', $centiseconds), $format); } elseif (str_contains($format, ':s.0')) { $deciseconds = (int) round($microseconds / 100000.0); if ($deciseconds === 10) { $deciseconds = 0; $dateObj->modify('+1 second'); } $dateObj->modify("-$microseconds microseconds"); $format = str_replace(':s.0', ':s.' . sprintf('%1d', $deciseconds), $format); } else { // no fractional second if ($microseconds >= 500000) { $dateObj->modify('+1 second'); } $dateObj->modify("-$microseconds microseconds"); } return $dateObj->format($format); } /** @param string[] $matches */ private static function setLowercaseCallback(array $matches): string { return mb_strtolower($matches[0]); } /** @param string[] $matches */ private static function escapeQuotesCallback(array $matches): string { return '\\' . implode('\\', mb_str_split($matches[1], 1, 'UTF-8')); } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Style/NumberFormat/BaseFormatter.php
src/PhpSpreadsheet/Style/NumberFormat/BaseFormatter.php
<?php namespace PhpOffice\PhpSpreadsheet\Style\NumberFormat; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; abstract class BaseFormatter { protected static function stripQuotes(string $format): string { // Some non-number strings are quoted, so we'll get rid of the quotes, likewise any positional * symbols return str_replace(['"', '*'], '', $format); } protected static function adjustSeparators(string $value): string { $thousandsSeparator = StringHelper::getThousandsSeparator(); $decimalSeparator = StringHelper::getDecimalSeparator(); if ($thousandsSeparator !== ',' || $decimalSeparator !== '.') { $value = str_replace(['.', ',', "\u{fffd}"], ["\u{fffd}", $thousandsSeparator, $decimalSeparator], $value); } return $value; } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Style/NumberFormat/Wizard/Number.php
src/PhpSpreadsheet/Style/NumberFormat/Wizard/Number.php
<?php namespace PhpOffice\PhpSpreadsheet\Style\NumberFormat\Wizard; use PhpOffice\PhpSpreadsheet\Exception; class Number extends NumberBase implements Wizard { public const WITH_THOUSANDS_SEPARATOR = true; public const WITHOUT_THOUSANDS_SEPARATOR = false; protected bool $thousandsSeparator = true; /** * @param int $decimals number of decimal places to display, in the range 0-30 * @param bool $thousandsSeparator indicator whether the thousands separator should be used, or not * @param ?string $locale Set the locale for the number format; or leave as the default null. * Locale has no effect for Number Format values, and is retained here only for compatibility * with the other Wizards. * If provided, Locale values must be a valid formatted locale string (e.g. 'en-GB', 'fr', uz-Arab-AF). * * @throws Exception If a provided locale code is not a valid format */ public function __construct( int $decimals = 2, bool $thousandsSeparator = self::WITH_THOUSANDS_SEPARATOR, ?string $locale = null ) { $this->setDecimals($decimals); $this->setThousandsSeparator($thousandsSeparator); $this->setLocale($locale); } public function setThousandsSeparator(bool $thousandsSeparator = self::WITH_THOUSANDS_SEPARATOR): void { $this->thousandsSeparator = $thousandsSeparator; } /** * As MS Excel cannot easily handle Lakh, which is the only locale-specific Number format variant, * we don't use locale with Numbers. */ protected function getLocaleFormat(): string { return $this->format(); } public function format(): string { return sprintf( '%s0%s', $this->thousandsSeparator ? '#,##' : null, $this->decimals > 0 ? '.' . str_repeat('0', $this->decimals) : null ); } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Style/NumberFormat/Wizard/Date.php
src/PhpSpreadsheet/Style/NumberFormat/Wizard/Date.php
<?php namespace PhpOffice\PhpSpreadsheet\Style\NumberFormat\Wizard; class Date extends DateTimeWizard { /** * Year (4 digits), e.g. 2023. */ public const YEAR_FULL = 'yyyy'; /** * Year (last 2 digits), e.g. 23. */ public const YEAR_SHORT = 'yy'; public const MONTH_FIRST_LETTER = 'mmmmm'; /** * Month name, long form, e.g. January. */ public const MONTH_NAME_FULL = 'mmmm'; /** * Month name, short form, e.g. Jan. */ public const MONTH_NAME_SHORT = 'mmm'; /** * Month number with a leading zero if required, e.g. 01. */ public const MONTH_NUMBER_LONG = 'mm'; /** * Month number without a leading zero, e.g. 1. */ public const MONTH_NUMBER_SHORT = 'm'; /** * Day of the week, full form, e.g. Tuesday. */ public const WEEKDAY_NAME_LONG = 'dddd'; /** * Day of the week, short form, e.g. Tue. */ public const WEEKDAY_NAME_SHORT = 'ddd'; /** * Day number with a leading zero, e.g. 03. */ public const DAY_NUMBER_LONG = 'dd'; /** * Day number without a leading zero, e.g. 3. */ public const DAY_NUMBER_SHORT = 'd'; protected const DATE_BLOCKS = [ self::YEAR_FULL, self::YEAR_SHORT, self::MONTH_FIRST_LETTER, self::MONTH_NAME_FULL, self::MONTH_NAME_SHORT, self::MONTH_NUMBER_LONG, self::MONTH_NUMBER_SHORT, self::WEEKDAY_NAME_LONG, self::WEEKDAY_NAME_SHORT, self::DAY_NUMBER_LONG, self::DAY_NUMBER_SHORT, ]; public const SEPARATOR_DASH = '-'; public const SEPARATOR_DOT = '.'; public const SEPARATOR_SLASH = '/'; public const SEPARATOR_SPACE_NONBREAKING = "\u{a0}"; public const SEPARATOR_SPACE = ' '; protected const DATE_DEFAULT = [ self::YEAR_FULL, self::MONTH_NUMBER_LONG, self::DAY_NUMBER_LONG, ]; /** * @var array<?string> */ protected array $separators; /** * @var string[] */ protected array $formatBlocks; /** * @param null|array<?string>|string $separators * If you want to use the same separator for all format blocks, then it can be passed as a string literal; * if you wish to use different separators, then they should be passed as an array. * If you want to use only a single format block, then pass a null as the separator argument */ public function __construct($separators = self::SEPARATOR_DASH, string|null ...$formatBlocks) { $separators ??= self::SEPARATOR_DASH; $formatBlocks = (count($formatBlocks) === 0) ? self::DATE_DEFAULT : $formatBlocks; $this->separators = $this->padSeparatorArray( is_array($separators) ? $separators : [$separators], count($formatBlocks) - 1 ); $this->formatBlocks = array_map([$this, 'mapFormatBlocks'], $formatBlocks); } private function mapFormatBlocks(string $value): string { // Any date masking codes are returned as lower case values if (in_array(mb_strtolower($value), self::DATE_BLOCKS, true)) { return mb_strtolower($value); } // Wrap any string literals in quotes, so that they're clearly defined as string literals return $this->wrapLiteral($value); } public function format(): string { return implode('', array_map([$this, 'intersperse'], $this->formatBlocks, $this->separators)); } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Style/NumberFormat/Wizard/Time.php
src/PhpSpreadsheet/Style/NumberFormat/Wizard/Time.php
<?php namespace PhpOffice\PhpSpreadsheet\Style\NumberFormat\Wizard; class Time extends DateTimeWizard { /** * Hours without a leading zero, e.g. 9. */ public const HOURS_SHORT = 'h'; /** * Hours with a leading zero, e.g. 09. */ public const HOURS_LONG = 'hh'; /** * Minutes without a leading zero, e.g. 5. */ public const MINUTES_SHORT = 'm'; /** * Minutes with a leading zero, e.g. 05. */ public const MINUTES_LONG = 'mm'; /** * Seconds without a leading zero, e.g. 2. */ public const SECONDS_SHORT = 's'; /** * Seconds with a leading zero, e.g. 02. */ public const SECONDS_LONG = 'ss'; public const MORNING_AFTERNOON = 'AM/PM'; protected const TIME_BLOCKS = [ self::HOURS_LONG, self::HOURS_SHORT, self::MINUTES_LONG, self::MINUTES_SHORT, self::SECONDS_LONG, self::SECONDS_SHORT, self::MORNING_AFTERNOON, ]; public const SEPARATOR_COLON = ':'; public const SEPARATOR_SPACE_NONBREAKING = "\u{a0}"; public const SEPARATOR_SPACE = ' '; protected const TIME_DEFAULT = [ self::HOURS_LONG, self::MINUTES_LONG, self::SECONDS_LONG, ]; /** * @var array<?string> */ protected array $separators; /** * @var string[] */ protected array $formatBlocks; /** * @param null|string|string[] $separators * If you want to use the same separator for all format blocks, then it can be passed as a string literal; * if you wish to use different separators, then they should be passed as an array. * If you want to use only a single format block, then pass a null as the separator argument */ public function __construct($separators = self::SEPARATOR_COLON, string ...$formatBlocks) { $separators ??= self::SEPARATOR_COLON; $formatBlocks = (count($formatBlocks) === 0) ? self::TIME_DEFAULT : $formatBlocks; $this->separators = $this->padSeparatorArray( is_array($separators) ? $separators : [$separators], count($formatBlocks) - 1 ); $this->formatBlocks = array_map([$this, 'mapFormatBlocks'], $formatBlocks); } private function mapFormatBlocks(string $value): string { // Any date masking codes are returned as lower case values // except for AM/PM, which is set to uppercase if (in_array(mb_strtolower($value), self::TIME_BLOCKS, true)) { return mb_strtolower($value); } elseif (mb_strtoupper($value) === self::MORNING_AFTERNOON) { return mb_strtoupper($value); } // Wrap any string literals in quotes, so that they're clearly defined as string literals return $this->wrapLiteral($value); } public function format(): string { return implode('', array_map([$this, 'intersperse'], $this->formatBlocks, $this->separators)); } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Style/NumberFormat/Wizard/Currency.php
src/PhpSpreadsheet/Style/NumberFormat/Wizard/Currency.php
<?php namespace PhpOffice\PhpSpreadsheet\Style\NumberFormat\Wizard; class Currency extends CurrencyBase { protected ?bool $overrideSpacing = false; protected ?CurrencyNegative $overrideNegative = null; }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Style/NumberFormat/Wizard/CurrencyBase.php
src/PhpSpreadsheet/Style/NumberFormat/Wizard/CurrencyBase.php
<?php namespace PhpOffice\PhpSpreadsheet\Style\NumberFormat\Wizard; use NumberFormatter; use PhpOffice\PhpSpreadsheet\Exception; class CurrencyBase extends Number { public const LEADING_SYMBOL = true; public const TRAILING_SYMBOL = false; public const SYMBOL_WITH_SPACING = true; public const SYMBOL_WITHOUT_SPACING = false; protected string $currencyCode = '$'; protected bool $currencySymbolPosition = self::LEADING_SYMBOL; protected bool $currencySymbolSpacing = self::SYMBOL_WITHOUT_SPACING; protected const DEFAULT_STRIP_LEADING_RLM = false; protected bool $stripLeadingRLM = self::DEFAULT_STRIP_LEADING_RLM; public const DEFAULT_NEGATIVE = CurrencyNegative::minus; protected CurrencyNegative $negative = CurrencyNegative::minus; protected ?bool $overrideSpacing = null; protected ?CurrencyNegative $overrideNegative = null; // Not sure why original code uses nbsp private string $spaceOrNbsp = ' '; // or "\u{a0}" /** * @param string $currencyCode the currency symbol or code to display for this mask * @param int $decimals number of decimal places to display, in the range 0-30 * @param bool $thousandsSeparator indicator whether the thousands separator should be used, or not * @param bool $currencySymbolPosition indicates whether the currency symbol comes before or after the value * Possible values are Currency::LEADING_SYMBOL and Currency::TRAILING_SYMBOL * @param bool $currencySymbolSpacing indicates whether there is spacing between the currency symbol and the value * Possible values are Currency::SYMBOL_WITH_SPACING and Currency::SYMBOL_WITHOUT_SPACING * However, Currency always uses WITHOUT and Accounting always uses WITH * @param ?string $locale Set the locale for the currency format; or leave as the default null. * If provided, Locale values must be a valid formatted locale string (e.g. 'en-GB', 'fr', uz-Arab-AF). * Note that setting a locale will override any other settings defined in this class * other than the currency code; or decimals (unless the decimals value is set to 0). * @param bool $stripLeadingRLM remove leading RLM added with * ICU 72.1+. * @param CurrencyNegative $negative How to display negative numbers. * Always use parentheses for Accounting. * 4 options for Currency. * * @throws Exception If a provided locale code is not a valid format */ public function __construct( string $currencyCode = '$', int $decimals = 2, bool $thousandsSeparator = true, bool $currencySymbolPosition = self::LEADING_SYMBOL, bool $currencySymbolSpacing = self::SYMBOL_WITHOUT_SPACING, ?string $locale = null, bool $stripLeadingRLM = self::DEFAULT_STRIP_LEADING_RLM, CurrencyNegative $negative = CurrencyNegative::minus ) { $this->setCurrencyCode($currencyCode); $this->setThousandsSeparator($thousandsSeparator); $this->setDecimals($decimals); $this->setCurrencySymbolPosition($currencySymbolPosition); $this->setCurrencySymbolSpacing($currencySymbolSpacing); $this->setLocale($locale); $this->stripLeadingRLM = $stripLeadingRLM; $this->negative = $negative; } public function setCurrencyCode(string $currencyCode): void { $this->currencyCode = $currencyCode; } public function setCurrencySymbolPosition(bool $currencySymbolPosition = self::LEADING_SYMBOL): void { $this->currencySymbolPosition = $currencySymbolPosition; } public function setCurrencySymbolSpacing(bool $currencySymbolSpacing = self::SYMBOL_WITHOUT_SPACING): void { $this->currencySymbolSpacing = $currencySymbolSpacing; } public function setStripLeadingRLM(bool $stripLeadingRLM): void { $this->stripLeadingRLM = $stripLeadingRLM; } public function setNegative(CurrencyNegative $negative): void { $this->negative = $negative; } protected function getLocaleFormat(): string { $formatter = new Locale($this->fullLocale, NumberFormatter::CURRENCY); $mask = $formatter->format($this->stripLeadingRLM); if ($this->decimals === 0) { $mask = (string) preg_replace('/\.0+/miu', '', $mask); } return str_replace('¤', $this->formatCurrencyCode(), $mask); } private function formatCurrencyCode(): string { if ($this->locale === null) { return $this->currencyCode; } return "[\${$this->currencyCode}-{$this->locale}]"; } public function format(): string { if ($this->localeFormat !== null) { return $this->localeFormat; } $symbolWithSpacing = $this->overrideSpacing ?? ($this->currencySymbolSpacing === self::SYMBOL_WITH_SPACING); $negative = $this->overrideNegative ?? $this->negative; // format if positive $format = '_('; if ($this->currencySymbolPosition === self::LEADING_SYMBOL) { $format .= '"' . $this->currencyCode . '"'; if (preg_match('/^[A-Z]{3}$/i', $this->currencyCode) === 1) { $format .= $this->spaceOrNbsp; } if (preg_match('/^[A-Z]{3}$/i', $this->currencyCode) === 1) { $format .= $this->spaceOrNbsp; } if ($symbolWithSpacing) { $format .= '*' . $this->spaceOrNbsp; } } $format .= $this->thousandsSeparator ? '#,##0' : '0'; if ($this->decimals > 0) { $format .= '.' . str_repeat('0', $this->decimals); } if ($this->currencySymbolPosition === self::TRAILING_SYMBOL) { if ($symbolWithSpacing) { $format .= $this->spaceOrNbsp; } elseif (preg_match('/^[A-Z]{3}$/i', $this->currencyCode) === 1) { $format .= $this->spaceOrNbsp; } $format .= '[$' . $this->currencyCode . ']'; } $format .= '_)'; // format if negative $format .= ';_('; $format .= $negative->color(); $negativeStart = $negative->start(); if ($this->currencySymbolPosition === self::LEADING_SYMBOL) { if ($negativeStart === '-' && !$symbolWithSpacing) { $format .= $negativeStart; } $format .= '"' . $this->currencyCode . '"'; if (preg_match('/^[A-Z]{3}$/i', $this->currencyCode) === 1) { $format .= $this->spaceOrNbsp; } if ($symbolWithSpacing) { $format .= '*' . $this->spaceOrNbsp; } if ($negativeStart === '\(' || ($symbolWithSpacing && $negativeStart === '-')) { $format .= $negativeStart; } } else { $format .= $negative->start(); } $format .= $this->thousandsSeparator ? '#,##0' : '0'; if ($this->decimals > 0) { $format .= '.' . str_repeat('0', $this->decimals); } $format .= $negative->end(); if ($this->currencySymbolPosition === self::TRAILING_SYMBOL) { if ($symbolWithSpacing) { // Do nothing - I can't figure out how to get // everything to align if I put any kind of space here. //$format .= "\u{2009}"; } elseif (preg_match('/^[A-Z]{3}$/i', $this->currencyCode) === 1) { $format .= $this->spaceOrNbsp; } $format .= '[$' . $this->currencyCode . ']'; } if ($this->currencySymbolPosition === self::TRAILING_SYMBOL) { $format .= '_)'; } elseif ($symbolWithSpacing && $negativeStart === '-') { $format .= ' '; } // format if zero $format .= ';_('; if ($this->currencySymbolPosition === self::LEADING_SYMBOL) { $format .= '"' . $this->currencyCode . '"'; } if ($symbolWithSpacing) { if ($this->currencySymbolPosition === self::LEADING_SYMBOL) { $format .= '*' . $this->spaceOrNbsp; } $format .= '"-"'; if ($this->decimals > 0) { $format .= str_repeat('?', $this->decimals); } } else { if (preg_match('/^[A-Z]{3}$/i', $this->currencyCode) === 1) { $format .= $this->spaceOrNbsp; } $format .= '0'; if ($this->decimals > 0) { $format .= '.' . str_repeat('0', $this->decimals); } } if ($this->currencySymbolPosition === self::TRAILING_SYMBOL) { if ($symbolWithSpacing) { $format .= $this->spaceOrNbsp; } $format .= '[$' . $this->currencyCode . ']'; } $format .= '_)'; // format if text $format .= ';_(@_)'; return $format; } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Style/NumberFormat/Wizard/CurrencyNegative.php
src/PhpSpreadsheet/Style/NumberFormat/Wizard/CurrencyNegative.php
<?php namespace PhpOffice\PhpSpreadsheet\Style\NumberFormat\Wizard; enum CurrencyNegative { case minus; case redMinus; case parentheses; case redParentheses; public function start(): string { return match ($this) { self::minus, self::redMinus => '-', self::parentheses, self::redParentheses => '\(', }; } public function end(): string { return match ($this) { self::minus, self::redMinus => '', self::parentheses, self::redParentheses => '\)', }; } public function color(): string { return match ($this) { self::redParentheses, self::redMinus => '[Red]', self::parentheses, self::minus => '', }; } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Style/NumberFormat/Wizard/Wizard.php
src/PhpSpreadsheet/Style/NumberFormat/Wizard/Wizard.php
<?php namespace PhpOffice\PhpSpreadsheet\Style\NumberFormat\Wizard; interface Wizard { public function format(): string; }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Style/NumberFormat/Wizard/DateTime.php
src/PhpSpreadsheet/Style/NumberFormat/Wizard/DateTime.php
<?php namespace PhpOffice\PhpSpreadsheet\Style\NumberFormat\Wizard; class DateTime extends DateTimeWizard { /** * @var array<?string> */ protected array $separators; /** * @var array<DateTimeWizard|string> */ protected array $formatBlocks; /** * @param null|string|string[] $separators * If you want to use only a single format block, then pass a null as the separator argument * @param DateTimeWizard|string ...$formatBlocks */ public function __construct($separators, ...$formatBlocks) { $this->separators = $this->padSeparatorArray( is_array($separators) ? $separators : [$separators], count($formatBlocks) - 1 ); $this->formatBlocks = array_map([$this, 'mapFormatBlocks'], $formatBlocks); } private function mapFormatBlocks(DateTimeWizard|string $value): string { // Any date masking codes are returned as lower case values if ($value instanceof DateTimeWizard) { return $value->__toString(); } // Wrap any string literals in quotes, so that they're clearly defined as string literals return $this->wrapLiteral($value); } public function format(): string { return implode('', array_map([$this, 'intersperse'], $this->formatBlocks, $this->separators)); } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Style/NumberFormat/Wizard/DateTimeWizard.php
src/PhpSpreadsheet/Style/NumberFormat/Wizard/DateTimeWizard.php
<?php namespace PhpOffice\PhpSpreadsheet\Style\NumberFormat\Wizard; use Stringable; abstract class DateTimeWizard implements Stringable, Wizard { protected const NO_ESCAPING_NEEDED = "$+-/():!^&'~{}<>= "; /** * @param array<?string> $separators * * @return array<?string> */ protected function padSeparatorArray(array $separators, int $count): array { $lastSeparator = (string) array_pop($separators); return $separators + array_fill(0, $count, $lastSeparator); } protected function escapeSingleCharacter(string $value): string { if (str_contains(self::NO_ESCAPING_NEEDED, $value)) { return $value; } return "\\{$value}"; } protected function wrapLiteral(string $value): string { if (mb_strlen($value, 'UTF-8') === 1) { return $this->escapeSingleCharacter($value); } // Wrap any other string literals in quotes, so that they're clearly defined as string literals return '"' . str_replace('"', '""', $value) . '"'; } protected function intersperse(string $formatBlock, ?string $separator): string { return "{$formatBlock}{$separator}"; } public function __toString(): string { return $this->format(); } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Style/NumberFormat/Wizard/Duration.php
src/PhpSpreadsheet/Style/NumberFormat/Wizard/Duration.php
<?php namespace PhpOffice\PhpSpreadsheet\Style\NumberFormat\Wizard; class Duration extends DateTimeWizard { public const DAYS_DURATION = 'd'; /** * Hours as a duration (can exceed 24), e.g. 29. */ public const HOURS_DURATION = '[h]'; /** * Hours without a leading zero, e.g. 9. */ public const HOURS_SHORT = 'h'; /** * Hours with a leading zero, e.g. 09. */ public const HOURS_LONG = 'hh'; /** * Minutes as a duration (can exceed 60), e.g. 109. */ public const MINUTES_DURATION = '[m]'; /** * Minutes without a leading zero, e.g. 5. */ public const MINUTES_SHORT = 'm'; /** * Minutes with a leading zero, e.g. 05. */ public const MINUTES_LONG = 'mm'; /** * Seconds as a duration (can exceed 60), e.g. 129. */ public const SECONDS_DURATION = '[s]'; /** * Seconds without a leading zero, e.g. 2. */ public const SECONDS_SHORT = 's'; /** * Seconds with a leading zero, e.g. 02. */ public const SECONDS_LONG = 'ss'; protected const DURATION_BLOCKS = [ self::DAYS_DURATION, self::HOURS_DURATION, self::HOURS_LONG, self::HOURS_SHORT, self::MINUTES_DURATION, self::MINUTES_LONG, self::MINUTES_SHORT, self::SECONDS_DURATION, self::SECONDS_LONG, self::SECONDS_SHORT, ]; protected const DURATION_MASKS = [ self::DAYS_DURATION => self::DAYS_DURATION, self::HOURS_DURATION => self::HOURS_SHORT, self::MINUTES_DURATION => self::MINUTES_LONG, self::SECONDS_DURATION => self::SECONDS_LONG, ]; protected const DURATION_DEFAULTS = [ self::HOURS_LONG => self::HOURS_DURATION, self::HOURS_SHORT => self::HOURS_DURATION, self::MINUTES_LONG => self::MINUTES_DURATION, self::MINUTES_SHORT => self::MINUTES_DURATION, self::SECONDS_LONG => self::SECONDS_DURATION, self::SECONDS_SHORT => self::SECONDS_DURATION, ]; public const SEPARATOR_COLON = ':'; public const SEPARATOR_SPACE_NONBREAKING = "\u{a0}"; public const SEPARATOR_SPACE = ' '; public const DURATION_DEFAULT = [ self::HOURS_DURATION, self::MINUTES_LONG, self::SECONDS_LONG, ]; /** * @var array<?string> */ protected array $separators; /** * @var string[] */ protected array $formatBlocks; protected bool $durationIsSet = false; /** * @param null|string|string[] $separators * If you want to use the same separator for all format blocks, then it can be passed as a string literal; * if you wish to use different separators, then they should be passed as an array. * If you want to use only a single format block, then pass a null as the separator argument */ public function __construct($separators = self::SEPARATOR_COLON, string ...$formatBlocks) { $separators ??= self::SEPARATOR_COLON; $formatBlocks = (count($formatBlocks) === 0) ? self::DURATION_DEFAULT : $formatBlocks; $this->separators = $this->padSeparatorArray( is_array($separators) ? $separators : [$separators], count($formatBlocks) - 1 ); $this->formatBlocks = array_map([$this, 'mapFormatBlocks'], $formatBlocks); if ($this->durationIsSet === false) { // We need at least one duration mask, so if none has been set we change the first mask element // to a duration. $this->formatBlocks[0] = self::DURATION_DEFAULTS[mb_strtolower($this->formatBlocks[0])]; } } private function mapFormatBlocks(string $value): string { // Any duration masking codes are returned as lower case values if (in_array(mb_strtolower($value), self::DURATION_BLOCKS, true)) { if (array_key_exists(mb_strtolower($value), self::DURATION_MASKS)) { if ($this->durationIsSet) { // We should only have a single duration mask, the first defined in the mask set, // so convert any additional duration masks to standard time masks. $value = self::DURATION_MASKS[mb_strtolower($value)]; } $this->durationIsSet = true; } return mb_strtolower($value); } // Wrap any string literals in quotes, so that they're clearly defined as string literals return $this->wrapLiteral($value); } public function format(): string { return implode('', array_map([$this, 'intersperse'], $this->formatBlocks, $this->separators)); } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Style/NumberFormat/Wizard/Locale.php
src/PhpSpreadsheet/Style/NumberFormat/Wizard/Locale.php
<?php namespace PhpOffice\PhpSpreadsheet\Style\NumberFormat\Wizard; use NumberFormatter; use PhpOffice\PhpSpreadsheet\Exception; final class Locale { /** * Language code: ISO-639 2 character, alpha. * Optional script code: ISO-15924 4 alpha. * Optional country code: ISO-3166-1, 2 character alpha. * Separated by underscores or dashes. */ public const STRUCTURE = '/^(?P<language>[a-z]{2})([-_](?P<script>[a-z]{4}))?([-_](?P<country>[a-z]{2}))?$/i'; private NumberFormatter $formatter; public function __construct(?string $locale, int $style) { $formatterLocale = str_replace('-', '_', $locale ?? ''); $this->formatter = new NumberFormatter($formatterLocale, $style); if ($this->formatter->getLocale() !== $formatterLocale) { throw new Exception("Unable to read locale data for '{$locale}'"); } } public function format(bool $stripRlm = true): string { $str = $this->formatter->getPattern(); return ($stripRlm && str_starts_with($str, "\xe2\x80\x8f")) ? substr($str, 3) : $str; } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Style/NumberFormat/Wizard/NumberBase.php
src/PhpSpreadsheet/Style/NumberFormat/Wizard/NumberBase.php
<?php namespace PhpOffice\PhpSpreadsheet\Style\NumberFormat\Wizard; use NumberFormatter; use PhpOffice\PhpSpreadsheet\Exception; use PhpOffice\PhpSpreadsheet\Style\NumberFormat; use Stringable; abstract class NumberBase implements Stringable { protected const MAX_DECIMALS = 30; protected int $decimals = 2; protected ?string $locale = null; protected ?string $fullLocale = null; protected ?string $localeFormat = null; public function setDecimals(int $decimals = 2): void { $this->decimals = ($decimals > self::MAX_DECIMALS) ? self::MAX_DECIMALS : max($decimals, 0); } /** * Setting a locale will override any settings defined in this class. * * @throws Exception If the locale code is not a valid format */ public function setLocale(?string $locale = null): void { if ($locale === null) { $this->localeFormat = $this->locale = $this->fullLocale = null; return; } $this->locale = $this->validateLocale($locale); if (class_exists(NumberFormatter::class)) { $this->localeFormat = $this->getLocaleFormat(); } } /** * Stub: should be implemented as a concrete method in concrete wizards. */ abstract protected function getLocaleFormat(): string; /** * @throws Exception If the locale code is not a valid format */ private function validateLocale(string $locale): string { if (preg_match(Locale::STRUCTURE, $locale, $matches, PREG_UNMATCHED_AS_NULL) !== 1) { throw new Exception("Invalid locale code '{$locale}'"); } ['language' => $language, 'script' => $script, 'country' => $country] = $matches; // Set case and separator to match standardised locale case $language = strtolower($language); $script = ($script === null) ? null : ucfirst(strtolower($script)); $country = ($country === null) ? null : strtoupper($country); $this->fullLocale = implode('-', array_filter([$language, $script, $country])); return $country === null ? $language : "{$language}-{$country}"; } public function format(): string { return NumberFormat::FORMAT_GENERAL; } public function __toString(): string { return $this->format(); } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Style/NumberFormat/Wizard/Percentage.php
src/PhpSpreadsheet/Style/NumberFormat/Wizard/Percentage.php
<?php namespace PhpOffice\PhpSpreadsheet\Style\NumberFormat\Wizard; use NumberFormatter; use PhpOffice\PhpSpreadsheet\Exception; class Percentage extends NumberBase implements Wizard { /** * @param int $decimals number of decimal places to display, in the range 0-30 * @param ?string $locale Set the locale for the percentage format; or leave as the default null. * If provided, Locale values must be a valid formatted locale string (e.g. 'en-GB', 'fr', uz-Arab-AF). * * @throws Exception If a provided locale code is not a valid format */ public function __construct(int $decimals = 2, ?string $locale = null) { $this->setDecimals($decimals); $this->setLocale($locale); } protected function getLocaleFormat(): string { $formatter = new Locale($this->fullLocale, NumberFormatter::PERCENT); return $this->decimals > 0 ? str_replace('0', '0.' . str_repeat('0', $this->decimals), $formatter->format()) : $formatter->format(); } public function format(): string { if ($this->localeFormat !== null) { return $this->localeFormat; } return sprintf('0%s%%', $this->decimals > 0 ? '.' . str_repeat('0', $this->decimals) : null); } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Style/NumberFormat/Wizard/Accounting.php
src/PhpSpreadsheet/Style/NumberFormat/Wizard/Accounting.php
<?php namespace PhpOffice\PhpSpreadsheet\Style\NumberFormat\Wizard; use NumberFormatter; use PhpOffice\PhpSpreadsheet\Exception; class Accounting extends CurrencyBase { protected ?bool $overrideSpacing = true; protected ?CurrencyNegative $overrideNegative = CurrencyNegative::parentheses; /** * @throws Exception if the Intl extension and ICU version don't support Accounting formats */ protected function getLocaleFormat(): string { if (self::icuVersion() < 53.0) { // @codeCoverageIgnoreStart throw new Exception('The Intl extension does not support Accounting Formats without ICU 53'); // @codeCoverageIgnoreEnd } // Scrutinizer does not recognize CURRENCY_ACCOUNTING $formatter = new Locale($this->fullLocale, NumberFormatter::CURRENCY_ACCOUNTING); $mask = $formatter->format($this->stripLeadingRLM); if ($this->decimals === 0) { $mask = (string) preg_replace('/\.0+/miu', '', $mask); } return str_replace('¤', $this->formatCurrencyCode(), $mask); } public static function icuVersion(): float { [$major, $minor] = explode('.', INTL_ICU_VERSION); return (float) "{$major}.{$minor}"; } private function formatCurrencyCode(): string { if ($this->locale === null) { return $this->currencyCode . '*'; } return "[\${$this->currencyCode}-{$this->locale}]"; } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Style/NumberFormat/Wizard/Scientific.php
src/PhpSpreadsheet/Style/NumberFormat/Wizard/Scientific.php
<?php namespace PhpOffice\PhpSpreadsheet\Style\NumberFormat\Wizard; use PhpOffice\PhpSpreadsheet\Exception; class Scientific extends NumberBase implements Wizard { /** * @param int $decimals number of decimal places to display, in the range 0-30 * @param ?string $locale Set the locale for the scientific format; or leave as the default null. * Locale has no effect for Scientific Format values, and is retained here for compatibility * with the other Wizards. * If provided, Locale values must be a valid formatted locale string (e.g. 'en-GB', 'fr', uz-Arab-AF). * * @throws Exception If a provided locale code is not a valid format */ public function __construct(int $decimals = 2, ?string $locale = null) { $this->setDecimals($decimals); $this->setLocale($locale); } protected function getLocaleFormat(): string { return $this->format(); } public function format(): string { return sprintf('0%sE+00', $this->decimals > 0 ? '.' . str_repeat('0', $this->decimals) : null); } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Calculation/ArrayEnabled.php
src/PhpSpreadsheet/Calculation/ArrayEnabled.php
<?php namespace PhpOffice\PhpSpreadsheet\Calculation; use PhpOffice\PhpSpreadsheet\Calculation\Engine\ArrayArgumentHelper; use PhpOffice\PhpSpreadsheet\Calculation\Engine\ArrayArgumentProcessor; trait ArrayEnabled { private static bool $initializationNeeded = true; private static ArrayArgumentHelper $arrayArgumentHelper; /** * @param mixed[] $arguments */ private static function initialiseHelper(array $arguments): void { if (self::$initializationNeeded === true) { self::$arrayArgumentHelper = new ArrayArgumentHelper(); self::$initializationNeeded = false; } self::$arrayArgumentHelper->initialise($arguments); } /** * Handles array argument processing when the function accepts a single argument that can be an array argument. * Example use for: * DAYOFMONTH() or FACT(). * * @param mixed[] $values * * @return mixed[] */ protected static function evaluateSingleArgumentArray(callable $method, array $values): array { $result = []; foreach ($values as $value) { $result[] = $method($value); } return $result; } /** * Handles array argument processing when the function accepts multiple arguments, * and any of them can be an array argument. * Example use for: * ROUND() or DATE(). * * @return mixed[] */ protected static function evaluateArrayArguments(callable $method, mixed ...$arguments): array { self::initialiseHelper($arguments); $arguments = self::$arrayArgumentHelper->arguments(); return ArrayArgumentProcessor::processArguments(self::$arrayArgumentHelper, $method, ...$arguments); } /** * Handles array argument processing when the function accepts multiple arguments, * but only the first few (up to limit) can be an array arguments. * Example use for: * NETWORKDAYS() or CONCATENATE(), where the last argument is a matrix (or a series of values) that need * to be treated as a such rather than as an array arguments. * * @return mixed[] */ protected static function evaluateArrayArgumentsSubset(callable $method, int $limit, mixed ...$arguments): array { self::initialiseHelper(array_slice($arguments, 0, $limit)); $trailingArguments = array_slice($arguments, $limit); $arguments = self::$arrayArgumentHelper->arguments(); $arguments = array_merge($arguments, $trailingArguments); return ArrayArgumentProcessor::processArguments(self::$arrayArgumentHelper, $method, ...$arguments); } private static function testFalse(mixed $value): bool { return $value === false; } /** * Handles array argument processing when the function accepts multiple arguments, * but only the last few (from start) can be an array arguments. * Example use for: * Z.TEST() or INDEX(), where the first argument 1 is a matrix that needs to be treated as a dataset * rather than as an array argument. * * @return mixed[] */ protected static function evaluateArrayArgumentsSubsetFrom(callable $method, int $start, mixed ...$arguments): array { $arrayArgumentsSubset = array_combine( range($start, count($arguments) - $start), array_slice($arguments, $start) ); if (self::testFalse($arrayArgumentsSubset)) { return ['#VALUE!']; } self::initialiseHelper($arrayArgumentsSubset); $leadingArguments = array_slice($arguments, 0, $start); $arguments = self::$arrayArgumentHelper->arguments(); $arguments = array_merge($leadingArguments, $arguments); return ArrayArgumentProcessor::processArguments(self::$arrayArgumentHelper, $method, ...$arguments); } /** * Handles array argument processing when the function accepts multiple arguments, * and any of them can be an array argument except for the one specified by ignore. * Example use for: * HLOOKUP() and VLOOKUP(), where argument 1 is a matrix that needs to be treated as a database * rather than as an array argument. * * @return mixed[] */ protected static function evaluateArrayArgumentsIgnore(callable $method, int $ignore, mixed ...$arguments): array { $leadingArguments = array_slice($arguments, 0, $ignore); $ignoreArgument = array_slice($arguments, $ignore, 1); $trailingArguments = array_slice($arguments, $ignore + 1); self::initialiseHelper(array_merge($leadingArguments, [[null]], $trailingArguments)); $arguments = self::$arrayArgumentHelper->arguments(); array_splice($arguments, $ignore, 1, $ignoreArgument); return ArrayArgumentProcessor::processArguments(self::$arrayArgumentHelper, $method, ...$arguments); } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Calculation/Functions.php
src/PhpSpreadsheet/Calculation/Functions.php
<?php namespace PhpOffice\PhpSpreadsheet\Calculation; use PhpOffice\PhpSpreadsheet\Cell\Cell; use PhpOffice\PhpSpreadsheet\Shared\Date; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; class Functions { const PRECISION = 8.88E-016; /** * 2 / PI. */ const M_2DIVPI = 0.63661977236758134307553505349006; const COMPATIBILITY_EXCEL = 'Excel'; const COMPATIBILITY_GNUMERIC = 'Gnumeric'; const COMPATIBILITY_OPENOFFICE = 'OpenOfficeCalc'; /** Use of RETURNDATE_PHP_NUMERIC is discouraged - not 32-bit Y2038-safe, no timezone. */ const RETURNDATE_PHP_NUMERIC = 'P'; /** Use of RETURNDATE_UNIX_TIMESTAMP is discouraged - not 32-bit Y2038-safe, no timezone. */ const RETURNDATE_UNIX_TIMESTAMP = 'P'; const RETURNDATE_PHP_OBJECT = 'O'; const RETURNDATE_PHP_DATETIME_OBJECT = 'O'; const RETURNDATE_EXCEL = 'E'; public const NOT_YET_IMPLEMENTED = '#Not Yet Implemented'; /** * Compatibility mode to use for error checking and responses. */ protected static string $compatibilityMode = self::COMPATIBILITY_EXCEL; /** * Data Type to use when returning date values. */ protected static string $returnDateType = self::RETURNDATE_EXCEL; /** * Set the Compatibility Mode. * * @param string $compatibilityMode Compatibility Mode * Permitted values are: * Functions::COMPATIBILITY_EXCEL 'Excel' * Functions::COMPATIBILITY_GNUMERIC 'Gnumeric' * Functions::COMPATIBILITY_OPENOFFICE 'OpenOfficeCalc' * * @return bool (Success or Failure) */ public static function setCompatibilityMode(string $compatibilityMode): bool { if ( ($compatibilityMode == self::COMPATIBILITY_EXCEL) || ($compatibilityMode == self::COMPATIBILITY_GNUMERIC) || ($compatibilityMode == self::COMPATIBILITY_OPENOFFICE) ) { self::$compatibilityMode = $compatibilityMode; return true; } return false; } /** * Return the current Compatibility Mode. * * @return string Compatibility Mode * Possible Return values are: * Functions::COMPATIBILITY_EXCEL 'Excel' * Functions::COMPATIBILITY_GNUMERIC 'Gnumeric' * Functions::COMPATIBILITY_OPENOFFICE 'OpenOfficeCalc' */ public static function getCompatibilityMode(): string { return self::$compatibilityMode; } /** * Set the Return Date Format used by functions that return a date/time (Excel, PHP Serialized Numeric or PHP DateTime Object). * * @param string $returnDateType Return Date Format * Permitted values are: * Functions::RETURNDATE_UNIX_TIMESTAMP 'P' * Functions::RETURNDATE_PHP_DATETIME_OBJECT 'O' * Functions::RETURNDATE_EXCEL 'E' * * @return bool Success or failure */ public static function setReturnDateType(string $returnDateType): bool { if ( ($returnDateType == self::RETURNDATE_UNIX_TIMESTAMP) || ($returnDateType == self::RETURNDATE_PHP_DATETIME_OBJECT) || ($returnDateType == self::RETURNDATE_EXCEL) ) { self::$returnDateType = $returnDateType; return true; } return false; } /** * Return the current Return Date Format for functions that return a date/time (Excel, PHP Serialized Numeric or PHP Object). * * @return string Return Date Format * Possible Return values are: * Functions::RETURNDATE_UNIX_TIMESTAMP 'P' * Functions::RETURNDATE_PHP_DATETIME_OBJECT 'O' * Functions::RETURNDATE_EXCEL ' 'E' */ public static function getReturnDateType(): string { return self::$returnDateType; } /** * DUMMY. * * @return string #Not Yet Implemented */ public static function DUMMY(): string { return self::NOT_YET_IMPLEMENTED; } public static function isMatrixValue(mixed $idx): bool { $idx = StringHelper::convertToString($idx); return (substr_count($idx, '.') <= 1) || (preg_match('/\.[A-Z]/', $idx) > 0); } public static function isValue(mixed $idx): bool { $idx = StringHelper::convertToString($idx); return substr_count($idx, '.') === 0; } public static function isCellValue(mixed $idx): bool { $idx = StringHelper::convertToString($idx); return substr_count($idx, '.') > 1; } public static function ifCondition(mixed $condition): string { $condition = self::flattenSingleValue($condition); if ($condition === '' || $condition === null) { return '=""'; } if (!is_string($condition) || !in_array($condition[0], ['>', '<', '='], true)) { $condition = self::operandSpecialHandling($condition); if (is_bool($condition)) { return '=' . ($condition ? 'TRUE' : 'FALSE'); } if (!is_numeric($condition)) { if ($condition !== '""') { // Not an empty string // Escape any quotes in the string value $condition = (string) preg_replace('/"/ui', '""', $condition); } $condition = Calculation::wrapResult(strtoupper($condition)); } return str_replace('""""', '""', '=' . StringHelper::convertToString($condition)); } $operator = $operand = ''; if (1 === preg_match('/(=|<[>=]?|>=?)(.*)/', $condition, $matches)) { [, $operator, $operand] = $matches; } $operand = (string) self::operandSpecialHandling($operand); if (is_numeric(trim($operand, '"'))) { $operand = trim($operand, '"'); } elseif (!is_numeric($operand) && $operand !== 'FALSE' && $operand !== 'TRUE') { $operand = str_replace('"', '""', $operand); $operand = Calculation::wrapResult(strtoupper($operand)); $operand = StringHelper::convertToString($operand); } return str_replace('""""', '""', $operator . $operand); } private static function operandSpecialHandling(mixed $operand): bool|float|int|string { if (is_numeric($operand) || is_bool($operand)) { return $operand; } $operand = StringHelper::convertToString($operand); if (strtoupper($operand) === Calculation::getTRUE() || strtoupper($operand) === Calculation::getFALSE()) { return strtoupper($operand); } // Check for percentage if (preg_match('/^\-?\d*\.?\d*\s?\%$/', $operand)) { return ((float) rtrim($operand, '%')) / 100; } // Check for dates if (($dateValueOperand = Date::stringToExcel($operand)) !== false) { return $dateValueOperand; } return $operand; } /** * Convert a multi-dimensional array to a simple 1-dimensional array. * * @param mixed $array Array to be flattened * * @return array<mixed> Flattened array */ public static function flattenArray(mixed $array): array { if (!is_array($array)) { return (array) $array; } $flattened = []; $stack = array_values($array); while (!empty($stack)) { $value = array_shift($stack); if (is_array($value)) { array_unshift($stack, ...array_values($value)); } else { $flattened[] = $value; } } return $flattened; } /** * Convert a multi-dimensional array to a simple 1-dimensional array. * Same as above but argument is specified in ... format. * * @param mixed $array Array to be flattened * * @return array<mixed> Flattened array */ public static function flattenArray2(mixed ...$array): array { $flattened = []; $stack = array_values($array); while (!empty($stack)) { $value = array_shift($stack); if (is_array($value)) { array_unshift($stack, ...array_values($value)); } else { $flattened[] = $value; } } return $flattened; } public static function scalar(mixed $value): mixed { if (!is_array($value)) { return $value; } do { $value = array_pop($value); } while (is_array($value)); return $value; } /** * Convert a multi-dimensional array to a simple 1-dimensional array, but retain an element of indexing. * * @param array|mixed $array Array to be flattened * * @return array<mixed> Flattened array */ public static function flattenArrayIndexed($array): array { if (!is_array($array)) { return (array) $array; } $arrayValues = []; foreach ($array as $k1 => $value) { if (is_array($value)) { foreach ($value as $k2 => $val) { if (is_array($val)) { foreach ($val as $k3 => $v) { $arrayValues[$k1 . '.' . $k2 . '.' . $k3] = $v; } } else { $arrayValues[$k1 . '.' . $k2] = $val; } } } else { $arrayValues[$k1] = $value; } } return $arrayValues; } /** * Convert an array to a single scalar value by extracting the first element. * * @param mixed $value Array or scalar value */ public static function flattenSingleValue(mixed $value): mixed { while (is_array($value)) { $value = array_shift($value); } return $value; } public static function expandDefinedName(string $coordinate, Cell $cell): string { $worksheet = $cell->getWorksheet(); $spreadsheet = $worksheet->getParentOrThrow(); // Uppercase coordinate $pCoordinatex = strtoupper($coordinate); // Eliminate leading equal sign $pCoordinatex = (string) preg_replace('/^=/', '', $pCoordinatex); $defined = $spreadsheet->getDefinedName($pCoordinatex, $worksheet); if ($defined !== null) { $worksheet2 = $defined->getWorkSheet(); if (!$defined->isFormula() && $worksheet2 !== null) { $coordinate = "'" . $worksheet2->getTitle() . "'!" . (string) preg_replace('/^=/', '', str_replace('$', '', $defined->getValue())); } } return $coordinate; } public static function trimTrailingRange(string $coordinate): string { return (string) preg_replace('/:[\w\$]+$/', '', $coordinate); } public static function trimSheetFromCellReference(string $coordinate): string { if (str_contains($coordinate, '!')) { $coordinate = substr($coordinate, strrpos($coordinate, '!') + 1); } return $coordinate; } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Calculation/CalculationBase.php
src/PhpSpreadsheet/Calculation/CalculationBase.php
<?php namespace PhpOffice\PhpSpreadsheet\Calculation; class CalculationBase { /** * Get a list of all implemented functions as an array of function objects. * * @return array<string, array{category: string, functionCall: string|string[], argumentCount: string, passCellReference?: bool, passByReference?: bool[], custom?: bool}> */ public static function getFunctions(): array { return FunctionArray::$phpSpreadsheetFunctions; } /** * Get address of list of all implemented functions as an array of function objects. * * @return array<string, array<string, mixed>> */ protected static function &getFunctionsAddress(): array { return FunctionArray::$phpSpreadsheetFunctions; } /** * @param array{category: string, functionCall: string|string[], argumentCount: string, passCellReference?: bool, passByReference?: bool[], custom?: bool} $value */ public static function addFunction(string $key, array $value): bool { $key = strtoupper($key); if ( array_key_exists($key, FunctionArray::$phpSpreadsheetFunctions) && !self::isDummy($key) ) { return false; } $value['custom'] = true; FunctionArray::$phpSpreadsheetFunctions[$key] = $value; return true; } private static function isDummy(string $key): bool { // key is already known to exist $functionCall = FunctionArray::$phpSpreadsheetFunctions[$key]['functionCall'] ?? null; if (!is_array($functionCall)) { return false; } if (($functionCall[1] ?? '') !== 'DUMMY') { return false; } return true; } public static function removeFunction(string $key): bool { $key = strtoupper($key); if (array_key_exists($key, FunctionArray::$phpSpreadsheetFunctions)) { if (FunctionArray::$phpSpreadsheetFunctions[$key]['custom'] ?? false) { unset(FunctionArray::$phpSpreadsheetFunctions[$key]); return true; } } return false; } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Calculation/ExceptionHandler.php
src/PhpSpreadsheet/Calculation/ExceptionHandler.php
<?php namespace PhpOffice\PhpSpreadsheet\Calculation; class ExceptionHandler { /** * Register errorhandler. */ public function __construct() { /** @var callable $callable */ $callable = [Exception::class, 'errorHandlerCallback']; set_error_handler($callable, E_ALL); } /** * Unregister errorhandler. */ public function __destruct() { restore_error_handler(); } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Calculation/Calculation.php
src/PhpSpreadsheet/Calculation/Calculation.php
<?php namespace PhpOffice\PhpSpreadsheet\Calculation; use PhpOffice\PhpSpreadsheet\Calculation\Engine\BranchPruner; use PhpOffice\PhpSpreadsheet\Calculation\Engine\CyclicReferenceStack; use PhpOffice\PhpSpreadsheet\Calculation\Engine\Logger; use PhpOffice\PhpSpreadsheet\Calculation\Engine\Operands; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Calculation\Token\Stack; use PhpOffice\PhpSpreadsheet\Cell\AddressRange; use PhpOffice\PhpSpreadsheet\Cell\Cell; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Cell\DataType; use PhpOffice\PhpSpreadsheet\DefinedName; use PhpOffice\PhpSpreadsheet\NamedRange; use PhpOffice\PhpSpreadsheet\ReferenceHelper; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; use ReflectionClassConstant; use ReflectionMethod; use ReflectionParameter; use Throwable; use TypeError; class Calculation extends CalculationLocale { /** Constants */ /** Regular Expressions */ // Numeric operand const CALCULATION_REGEXP_NUMBER = '[-+]?\d*\.?\d+(e[-+]?\d+)?'; // String operand const CALCULATION_REGEXP_STRING = '"(?:[^"]|"")*"'; // Opening bracket const CALCULATION_REGEXP_OPENBRACE = '\('; // Function (allow for the old @ symbol that could be used to prefix a function, but we'll ignore it) const CALCULATION_REGEXP_FUNCTION = '@?(?:_xlfn\.)?(?:_xlws\.)?((?:__xludf\.)?[\p{L}][\p{L}\p{N}\.]*)[\s]*\('; // Cell reference (cell or range of cells, with or without a sheet reference) const CALCULATION_REGEXP_CELLREF = '((([^\s,!&%^\/\*\+<>=:`-]*)|(\'(?:[^\']|\'[^!])+?\')|(\"(?:[^\"]|\"[^!])+?\"))!)?\$?\b([a-z]{1,3})\$?(\d{1,7})(?![\w.])'; // Used only to detect spill operator # const CALCULATION_REGEXP_CELLREF_SPILL = '/' . self::CALCULATION_REGEXP_CELLREF . '#/i'; // Cell reference (with or without a sheet reference) ensuring absolute/relative const CALCULATION_REGEXP_CELLREF_RELATIVE = '((([^\s\(,!&%^\/\*\+<>=:`-]*)|(\'(?:[^\']|\'[^!])+?\')|(\"(?:[^\"]|\"[^!])+?\"))!)?(\$?\b[a-z]{1,3})(\$?\d{1,7})(?![\w.])'; const CALCULATION_REGEXP_COLUMN_RANGE = '(((([^\s\(,!&%^\/\*\+<>=:`-]*)|(\'(?:[^\']|\'[^!])+?\')|(\".(?:[^\"]|\"[^!])?\"))!)?(\$?[a-z]{1,3})):(?![.*])'; const CALCULATION_REGEXP_ROW_RANGE = '(((([^\s\(,!&%^\/\*\+<>=:`-]*)|(\'(?:[^\']|\'[^!])+?\')|(\"(?:[^\"]|\"[^!])+?\"))!)?(\$?[1-9][0-9]{0,6})):(?![.*])'; // Cell reference (with or without a sheet reference) ensuring absolute/relative // Cell ranges ensuring absolute/relative const CALCULATION_REGEXP_COLUMNRANGE_RELATIVE = '(\$?[a-z]{1,3}):(\$?[a-z]{1,3})'; const CALCULATION_REGEXP_ROWRANGE_RELATIVE = '(\$?\d{1,7}):(\$?\d{1,7})'; // Defined Names: Named Range of cells, or Named Formulae const CALCULATION_REGEXP_DEFINEDNAME = '((([^\s,!&%^\/\*\+<>=-]*)|(\'(?:[^\']|\'[^!])+?\')|(\"(?:[^\"]|\"[^!])+?\"))!)?([_\p{L}][_\p{L}\p{N}\.]*)'; // Structured Reference (Fully Qualified and Unqualified) const CALCULATION_REGEXP_STRUCTURED_REFERENCE = '([\p{L}_\\\][\p{L}\p{N}\._]+)?(\[(?:[^\d\]+-])?)'; // Error const CALCULATION_REGEXP_ERROR = '\#[A-Z][A-Z0_\/]*[!\?]?'; /** constants */ const RETURN_ARRAY_AS_ERROR = 'error'; const RETURN_ARRAY_AS_VALUE = 'value'; const RETURN_ARRAY_AS_ARRAY = 'array'; /** Preferable to use instance variable instanceArrayReturnType rather than this static property. */ private static string $returnArrayAsType = self::RETURN_ARRAY_AS_VALUE; /** Preferable to use this instance variable rather than static returnArrayAsType */ private ?string $instanceArrayReturnType = null; /** * Instance of this class. */ private static ?Calculation $instance = null; /** * Instance of the spreadsheet this Calculation Engine is using. */ private ?Spreadsheet $spreadsheet; /** * Calculation cache. * * @var mixed[] */ private array $calculationCache = []; /** * Calculation cache enabled. */ private bool $calculationCacheEnabled = true; private BranchPruner $branchPruner; private bool $branchPruningEnabled = true; /** * List of operators that can be used within formulae * The true/false value indicates whether it is a binary operator or a unary operator. */ private const CALCULATION_OPERATORS = [ '+' => true, '-' => true, '*' => true, '/' => true, '^' => true, '&' => true, '%' => false, '~' => false, '>' => true, '<' => true, '=' => true, '>=' => true, '<=' => true, '<>' => true, '∩' => true, '∪' => true, ':' => true, ]; /** * List of binary operators (those that expect two operands). */ private const BINARY_OPERATORS = [ '+' => true, '-' => true, '*' => true, '/' => true, '^' => true, '&' => true, '>' => true, '<' => true, '=' => true, '>=' => true, '<=' => true, '<>' => true, '∩' => true, '∪' => true, ':' => true, ]; /** * The debug log generated by the calculation engine. */ private Logger $debugLog; private bool $suppressFormulaErrors = false; private bool $processingAnchorArray = false; /** * Error message for any error that was raised/thrown by the calculation engine. */ public ?string $formulaError = null; /** * An array of the nested cell references accessed by the calculation engine, used for the debug log. */ private CyclicReferenceStack $cyclicReferenceStack; /** @var mixed[] */ private array $cellStack = []; /** * Current iteration counter for cyclic formulae * If the value is 0 (or less) then cyclic formulae will throw an exception, * otherwise they will iterate to the limit defined here before returning a result. */ private int $cyclicFormulaCounter = 1; private string $cyclicFormulaCell = ''; /** * Number of iterations for cyclic formulae. */ public int $cyclicFormulaCount = 1; /** * Excel constant string translations to their PHP equivalents * Constant conversion from text name/value to actual (datatyped) value. */ private const EXCEL_CONSTANTS = [ 'TRUE' => true, 'FALSE' => false, 'NULL' => null, ]; public static function keyInExcelConstants(string $key): bool { return array_key_exists($key, self::EXCEL_CONSTANTS); } public static function getExcelConstants(string $key): bool|null { return self::EXCEL_CONSTANTS[$key]; } /** * Internal functions used for special control purposes. * * @var array<string, array<string, array<string>|string>> */ private static array $controlFunctions = [ 'MKMATRIX' => [ 'argumentCount' => '*', 'functionCall' => [Internal\MakeMatrix::class, 'make'], ], 'NAME.ERROR' => [ 'argumentCount' => '*', 'functionCall' => [ExcelError::class, 'NAME'], ], 'WILDCARDMATCH' => [ 'argumentCount' => '2', 'functionCall' => [Internal\WildcardMatch::class, 'compare'], ], ]; public function __construct(?Spreadsheet $spreadsheet = null) { $this->spreadsheet = $spreadsheet; $this->cyclicReferenceStack = new CyclicReferenceStack(); $this->debugLog = new Logger($this->cyclicReferenceStack); $this->branchPruner = new BranchPruner($this->branchPruningEnabled); } /** * Get an instance of this class. * * @param ?Spreadsheet $spreadsheet Injected spreadsheet for working with a PhpSpreadsheet Spreadsheet object, * or NULL to create a standalone calculation engine */ public static function getInstance(?Spreadsheet $spreadsheet = null): self { if ($spreadsheet !== null) { return $spreadsheet->getCalculationEngine(); } if (!self::$instance) { self::$instance = new self(); } return self::$instance; } /** * Intended for use only via a destructor. * * @internal */ public static function getInstanceOrNull(?Spreadsheet $spreadsheet = null): ?self { if ($spreadsheet !== null) { return $spreadsheet->getCalculationEngineOrNull(); } return null; } /** * Flush the calculation cache for any existing instance of this class * but only if a Calculation instance exists. */ public function flushInstance(): void { $this->clearCalculationCache(); $this->branchPruner->clearBranchStore(); } /** * Get the Logger for this calculation engine instance. */ public function getDebugLog(): Logger { return $this->debugLog; } /** * __clone implementation. Cloning should not be allowed in a Singleton! */ final public function __clone() { throw new Exception('Cloning the calculation engine is not allowed!'); } /** * Set the Array Return Type (Array or Value of first element in the array). * * @param string $returnType Array return type * * @return bool Success or failure */ public static function setArrayReturnType(string $returnType): bool { if ( ($returnType == self::RETURN_ARRAY_AS_VALUE) || ($returnType == self::RETURN_ARRAY_AS_ERROR) || ($returnType == self::RETURN_ARRAY_AS_ARRAY) ) { self::$returnArrayAsType = $returnType; return true; } return false; } /** * Return the Array Return Type (Array or Value of first element in the array). * * @return string $returnType Array return type */ public static function getArrayReturnType(): string { return self::$returnArrayAsType; } /** * Set the Instance Array Return Type (Array or Value of first element in the array). * * @param string $returnType Array return type * * @return bool Success or failure */ public function setInstanceArrayReturnType(string $returnType): bool { if ( ($returnType == self::RETURN_ARRAY_AS_VALUE) || ($returnType == self::RETURN_ARRAY_AS_ERROR) || ($returnType == self::RETURN_ARRAY_AS_ARRAY) ) { $this->instanceArrayReturnType = $returnType; return true; } return false; } /** * Return the Array Return Type (Array or Value of first element in the array). * * @return string $returnType Array return type for instance if non-null, otherwise static property */ public function getInstanceArrayReturnType(): string { return $this->instanceArrayReturnType ?? self::$returnArrayAsType; } /** * Is calculation caching enabled? */ public function getCalculationCacheEnabled(): bool { return $this->calculationCacheEnabled; } /** * Enable/disable calculation cache. */ public function setCalculationCacheEnabled(bool $calculationCacheEnabled): self { $this->calculationCacheEnabled = $calculationCacheEnabled; $this->clearCalculationCache(); return $this; } /** * Enable calculation cache. */ public function enableCalculationCache(): void { $this->setCalculationCacheEnabled(true); } /** * Disable calculation cache. */ public function disableCalculationCache(): void { $this->setCalculationCacheEnabled(false); } /** * Clear calculation cache. */ public function clearCalculationCache(): void { $this->calculationCache = []; } /** * Clear calculation cache for a specified worksheet. */ public function clearCalculationCacheForWorksheet(string $worksheetName): void { if (isset($this->calculationCache[$worksheetName])) { unset($this->calculationCache[$worksheetName]); } } /** * Rename calculation cache for a specified worksheet. */ public function renameCalculationCacheForWorksheet(string $fromWorksheetName, string $toWorksheetName): void { if (isset($this->calculationCache[$fromWorksheetName])) { $this->calculationCache[$toWorksheetName] = &$this->calculationCache[$fromWorksheetName]; unset($this->calculationCache[$fromWorksheetName]); } } public function getBranchPruningEnabled(): bool { return $this->branchPruningEnabled; } public function setBranchPruningEnabled(mixed $enabled): self { $this->branchPruningEnabled = (bool) $enabled; $this->branchPruner = new BranchPruner($this->branchPruningEnabled); return $this; } public function enableBranchPruning(): void { $this->setBranchPruningEnabled(true); } public function disableBranchPruning(): void { $this->setBranchPruningEnabled(false); } /** * Wrap string values in quotes. */ public static function wrapResult(mixed $value): mixed { if (is_string($value)) { // Error values cannot be "wrapped" if (preg_match('/^' . self::CALCULATION_REGEXP_ERROR . '$/i', $value, $match)) { // Return Excel errors "as is" return $value; } // Return strings wrapped in quotes return self::FORMULA_STRING_QUOTE . $value . self::FORMULA_STRING_QUOTE; } elseif ((is_float($value)) && ((is_nan($value)) || (is_infinite($value)))) { // Convert numeric errors to NaN error return ExcelError::NAN(); } return $value; } /** * Remove quotes used as a wrapper to identify string values. */ public static function unwrapResult(mixed $value): mixed { if (is_string($value)) { if ((isset($value[0])) && ($value[0] == self::FORMULA_STRING_QUOTE) && (substr($value, -1) == self::FORMULA_STRING_QUOTE)) { return substr($value, 1, -1); } // Convert numeric errors to NAN error } elseif ((is_float($value)) && ((is_nan($value)) || (is_infinite($value)))) { return ExcelError::NAN(); } return $value; } /** * Calculate cell value (using formula from a cell ID) * Retained for backward compatibility. * * @param ?Cell $cell Cell to calculate */ public function calculate(?Cell $cell = null): mixed { try { return $this->calculateCellValue($cell); } catch (\Exception $e) { throw new Exception($e->getMessage()); } } /** * Calculate the value of a cell formula. * * @param ?Cell $cell Cell to calculate * @param bool $resetLog Flag indicating whether the debug log should be reset or not */ public function calculateCellValue(?Cell $cell = null, bool $resetLog = true): mixed { if ($cell === null) { return null; } if ($resetLog) { // Initialise the logging settings if requested $this->formulaError = null; $this->debugLog->clearLog(); $this->cyclicReferenceStack->clear(); $this->cyclicFormulaCounter = 1; } // Execute the calculation for the cell formula $this->cellStack[] = [ 'sheet' => $cell->getWorksheet()->getTitle(), 'cell' => $cell->getCoordinate(), ]; $cellAddressAttempted = false; $cellAddress = null; try { $value = $cell->getValue(); if (is_string($value) && $cell->getDataType() === DataType::TYPE_FORMULA) { $value = preg_replace_callback( self::CALCULATION_REGEXP_CELLREF_SPILL, fn (array $matches) => 'ANCHORARRAY(' . substr($matches[0], 0, -1) . ')', $value ); } $result = self::unwrapResult($this->_calculateFormulaValue($value, $cell->getCoordinate(), $cell)); //* @phpstan-ignore-line if ($this->spreadsheet === null) { throw new Exception('null spreadsheet in calculateCellValue'); } $cellAddressAttempted = true; $cellAddress = array_pop($this->cellStack); if ($cellAddress === null) { throw new Exception('null cellAddress in calculateCellValue'); } /** @var array{sheet: string, cell: string} $cellAddress */ $testSheet = $this->spreadsheet->getSheetByName($cellAddress['sheet']); if ($testSheet === null) { throw new Exception('worksheet not found in calculateCellValue'); } $testSheet->getCell($cellAddress['cell']); } catch (\Exception $e) { if (!$cellAddressAttempted) { $cellAddress = array_pop($this->cellStack); } if ($this->spreadsheet !== null && is_array($cellAddress) && array_key_exists('sheet', $cellAddress)) { $sheetName = $cellAddress['sheet'] ?? null; $testSheet = is_string($sheetName) ? $this->spreadsheet->getSheetByName($sheetName) : null; if ($testSheet !== null && array_key_exists('cell', $cellAddress)) { /** @var array{cell: string} $cellAddress */ $testSheet->getCell($cellAddress['cell']); } } throw new Exception($e->getMessage(), $e->getCode(), $e); } if (is_array($result) && $this->getInstanceArrayReturnType() !== self::RETURN_ARRAY_AS_ARRAY) { $testResult = Functions::flattenArray($result); if ($this->getInstanceArrayReturnType() == self::RETURN_ARRAY_AS_ERROR) { return ExcelError::VALUE(); } $result = array_shift($testResult); } if ($result === null && $cell->getWorksheet()->getSheetView()->getShowZeros()) { return 0; } elseif ((is_float($result)) && ((is_nan($result)) || (is_infinite($result)))) { return ExcelError::NAN(); } return $result; } /** * Validate and parse a formula string. * * @param string $formula Formula to parse * * @return array<mixed>|bool */ public function parseFormula(string $formula): array|bool { $formula = preg_replace_callback( self::CALCULATION_REGEXP_CELLREF_SPILL, fn (array $matches) => 'ANCHORARRAY(' . substr($matches[0], 0, -1) . ')', $formula ) ?? $formula; // Basic validation that this is indeed a formula // We return an empty array if not $formula = trim($formula); if ((!isset($formula[0])) || ($formula[0] != '=')) { return []; } $formula = ltrim(substr($formula, 1)); if (!isset($formula[0])) { return []; } // Parse the formula and return the token stack return $this->internalParseFormula($formula); } /** * Calculate the value of a formula. * * @param string $formula Formula to parse * @param ?string $cellID Address of the cell to calculate * @param ?Cell $cell Cell to calculate */ public function calculateFormula(string $formula, ?string $cellID = null, ?Cell $cell = null): mixed { // Initialise the logging settings $this->formulaError = null; $this->debugLog->clearLog(); $this->cyclicReferenceStack->clear(); $resetCache = $this->getCalculationCacheEnabled(); if ($this->spreadsheet !== null && $cellID === null && $cell === null) { $cellID = 'A1'; $cell = $this->spreadsheet->getActiveSheet()->getCell($cellID); } else { // Disable calculation cacheing because it only applies to cell calculations, not straight formulae // But don't actually flush any cache $this->calculationCacheEnabled = false; } // Execute the calculation try { $result = self::unwrapResult($this->_calculateFormulaValue($formula, $cellID, $cell)); } catch (\Exception $e) { throw new Exception($e->getMessage()); } if ($this->spreadsheet === null) { // Reset calculation cacheing to its previous state $this->calculationCacheEnabled = $resetCache; } return $result; } public function getValueFromCache(string $cellReference, mixed &$cellValue): bool { $this->debugLog->writeDebugLog('Testing cache value for cell %s', $cellReference); // Is calculation cacheing enabled? // If so, is the required value present in calculation cache? if (($this->calculationCacheEnabled) && (isset($this->calculationCache[$cellReference]))) { $this->debugLog->writeDebugLog('Retrieving value for cell %s from cache', $cellReference); // Return the cached result $cellValue = $this->calculationCache[$cellReference]; return true; } return false; } public function saveValueToCache(string $cellReference, mixed $cellValue): void { if ($this->calculationCacheEnabled) { $this->calculationCache[$cellReference] = $cellValue; } } /** * Parse a cell formula and calculate its value. * * @param string $formula The formula to parse and calculate * @param ?string $cellID The ID (e.g. A3) of the cell that we are calculating * @param ?Cell $cell Cell to calculate * @param bool $ignoreQuotePrefix If set to true, evaluate the formyla even if the referenced cell is quote prefixed */ public function _calculateFormulaValue(string $formula, ?string $cellID = null, ?Cell $cell = null, bool $ignoreQuotePrefix = false): mixed { $cellValue = null; // Quote-Prefixed cell values cannot be formulae, but are treated as strings if ($cell !== null && $ignoreQuotePrefix === false && $cell->getStyle()->getQuotePrefix() === true) { return self::wrapResult((string) $formula); } if (preg_match('/^=\s*cmd\s*\|/miu', $formula) !== 0) { return self::wrapResult($formula); } // Basic validation that this is indeed a formula // We simply return the cell value if not $formula = trim($formula); if ($formula === '' || $formula[0] !== '=') { return self::wrapResult($formula); } $formula = ltrim(substr($formula, 1)); if (!isset($formula[0])) { return self::wrapResult($formula); } $pCellParent = ($cell !== null) ? $cell->getWorksheet() : null; $wsTitle = ($pCellParent !== null) ? $pCellParent->getTitle() : "\x00Wrk"; $wsCellReference = $wsTitle . '!' . $cellID; if (($cellID !== null) && ($this->getValueFromCache($wsCellReference, $cellValue))) { return $cellValue; } $this->debugLog->writeDebugLog('Evaluating formula for cell %s', $wsCellReference); if (($wsTitle[0] !== "\x00") && ($this->cyclicReferenceStack->onStack($wsCellReference))) { if ($this->cyclicFormulaCount <= 0) { $this->cyclicFormulaCell = ''; return $this->raiseFormulaError('Cyclic Reference in Formula'); } elseif ($this->cyclicFormulaCell === $wsCellReference) { ++$this->cyclicFormulaCounter; if ($this->cyclicFormulaCounter >= $this->cyclicFormulaCount) { $this->cyclicFormulaCell = ''; return $cellValue; } } elseif ($this->cyclicFormulaCell == '') { if ($this->cyclicFormulaCounter >= $this->cyclicFormulaCount) { return $cellValue; } $this->cyclicFormulaCell = $wsCellReference; } } $this->debugLog->writeDebugLog('Formula for cell %s is %s', $wsCellReference, $formula); // Parse the formula onto the token stack and calculate the value $this->cyclicReferenceStack->push($wsCellReference); $cellValue = $this->processTokenStack($this->internalParseFormula($formula, $cell), $cellID, $cell); $this->cyclicReferenceStack->pop(); // Save to calculation cache if ($cellID !== null) { $this->saveValueToCache($wsCellReference, $cellValue); } // Return the calculated value return $cellValue; } /** * Ensure that paired matrix operands are both matrices and of the same size. * * @param mixed $operand1 First matrix operand * * @param-out mixed[] $operand1 * * @param mixed $operand2 Second matrix operand * * @param-out mixed[] $operand2 * * @param int $resize Flag indicating whether the matrices should be resized to match * and (if so), whether the smaller dimension should grow or the * larger should shrink. * 0 = no resize * 1 = shrink to fit * 2 = extend to fit * * @return mixed[] */ public static function checkMatrixOperands(mixed &$operand1, mixed &$operand2, int $resize = 1): array { // Examine each of the two operands, and turn them into an array if they aren't one already // Note that this function should only be called if one or both of the operand is already an array if (!is_array($operand1)) { if (is_array($operand2)) { [$matrixRows, $matrixColumns] = self::getMatrixDimensions($operand2); $operand1 = array_fill(0, $matrixRows, array_fill(0, $matrixColumns, $operand1)); $resize = 0; } else { $operand1 = [$operand1]; $operand2 = [$operand2]; } } elseif (!is_array($operand2)) { [$matrixRows, $matrixColumns] = self::getMatrixDimensions($operand1); $operand2 = array_fill(0, $matrixRows, array_fill(0, $matrixColumns, $operand2)); $resize = 0; } [$matrix1Rows, $matrix1Columns] = self::getMatrixDimensions($operand1); [$matrix2Rows, $matrix2Columns] = self::getMatrixDimensions($operand2); if ($resize === 3) { $resize = 2; } elseif (($matrix1Rows == $matrix2Columns) && ($matrix2Rows == $matrix1Columns)) { $resize = 1; } if ($resize == 2) { // Given two matrices of (potentially) unequal size, convert the smaller in each dimension to match the larger self::resizeMatricesExtend($operand1, $operand2, $matrix1Rows, $matrix1Columns, $matrix2Rows, $matrix2Columns); } elseif ($resize == 1) { // Given two matrices of (potentially) unequal size, convert the larger in each dimension to match the smaller /** @var mixed[][] $operand1 */ /** @var mixed[][] $operand2 */ self::resizeMatricesShrink($operand1, $operand2, $matrix1Rows, $matrix1Columns, $matrix2Rows, $matrix2Columns); } [$matrix1Rows, $matrix1Columns] = self::getMatrixDimensions($operand1); [$matrix2Rows, $matrix2Columns] = self::getMatrixDimensions($operand2); return [$matrix1Rows, $matrix1Columns, $matrix2Rows, $matrix2Columns]; } /** * Read the dimensions of a matrix, and re-index it with straight numeric keys starting from row 0, column 0. * * @param mixed[] $matrix matrix operand * * @return int[] An array comprising the number of rows, and number of columns */ public static function getMatrixDimensions(array &$matrix): array { $matrixRows = count($matrix); $matrixColumns = 0; foreach ($matrix as $rowKey => $rowValue) { if (!is_array($rowValue)) { $matrix[$rowKey] = [$rowValue]; $matrixColumns = max(1, $matrixColumns); } else { $matrix[$rowKey] = array_values($rowValue); $matrixColumns = max(count($rowValue), $matrixColumns); } } $matrix = array_values($matrix); return [$matrixRows, $matrixColumns]; } /** * Ensure that paired matrix operands are both matrices of the same size. * * @param mixed[][] $matrix1 First matrix operand * @param mixed[][] $matrix2 Second matrix operand * @param int $matrix1Rows Row size of first matrix operand * @param int $matrix1Columns Column size of first matrix operand * @param int $matrix2Rows Row size of second matrix operand * @param int $matrix2Columns Column size of second matrix operand */ private static function resizeMatricesShrink(array &$matrix1, array &$matrix2, int $matrix1Rows, int $matrix1Columns, int $matrix2Rows, int $matrix2Columns): void { if (($matrix2Columns < $matrix1Columns) || ($matrix2Rows < $matrix1Rows)) { if ($matrix2Rows < $matrix1Rows) { for ($i = $matrix2Rows; $i < $matrix1Rows; ++$i) { unset($matrix1[$i]); } } if ($matrix2Columns < $matrix1Columns) { for ($i = 0; $i < $matrix1Rows; ++$i) { for ($j = $matrix2Columns; $j < $matrix1Columns; ++$j) { unset($matrix1[$i][$j]); } } } } if (($matrix1Columns < $matrix2Columns) || ($matrix1Rows < $matrix2Rows)) { if ($matrix1Rows < $matrix2Rows) { for ($i = $matrix1Rows; $i < $matrix2Rows; ++$i) { unset($matrix2[$i]); } } if ($matrix1Columns < $matrix2Columns) { for ($i = 0; $i < $matrix2Rows; ++$i) { for ($j = $matrix1Columns; $j < $matrix2Columns; ++$j) { unset($matrix2[$i][$j]); } } } } } /** * Ensure that paired matrix operands are both matrices of the same size. * * @param mixed[] $matrix1 First matrix operand * @param mixed[] $matrix2 Second matrix operand * @param int $matrix1Rows Row size of first matrix operand * @param int $matrix1Columns Column size of first matrix operand * @param int $matrix2Rows Row size of second matrix operand * @param int $matrix2Columns Column size of second matrix operand */ private static function resizeMatricesExtend(array &$matrix1, array &$matrix2, int $matrix1Rows, int $matrix1Columns, int $matrix2Rows, int $matrix2Columns): void { if (($matrix2Columns < $matrix1Columns) || ($matrix2Rows < $matrix1Rows)) { if ($matrix2Columns < $matrix1Columns) { for ($i = 0; $i < $matrix2Rows; ++$i) { /** @var mixed[][] $matrix2 */ $x = ($matrix2Columns === 1) ? $matrix2[$i][0] : null; for ($j = $matrix2Columns; $j < $matrix1Columns; ++$j) { $matrix2[$i][$j] = $x; } } } if ($matrix2Rows < $matrix1Rows) { $x = ($matrix2Rows === 1) ? $matrix2[0] : array_fill(0, $matrix2Columns, null); for ($i = $matrix2Rows; $i < $matrix1Rows; ++$i) { $matrix2[$i] = $x; } } } if (($matrix1Columns < $matrix2Columns) || ($matrix1Rows < $matrix2Rows)) { if ($matrix1Columns < $matrix2Columns) { for ($i = 0; $i < $matrix1Rows; ++$i) { /** @var mixed[][] $matrix1 */ $x = ($matrix1Columns === 1) ? $matrix1[$i][0] : null; for ($j = $matrix1Columns; $j < $matrix2Columns; ++$j) {
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
true
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Calculation/FormulaToken.php
src/PhpSpreadsheet/Calculation/FormulaToken.php
<?php namespace PhpOffice\PhpSpreadsheet\Calculation; /** * PARTLY BASED ON: * Copyright (c) 2007 E. W. Bachtal, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software * and associated documentation files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial * portions of the Software. * * The software is provided "as is", without warranty of any kind, express or implied, including but not * limited to the warranties of merchantability, fitness for a particular purpose and noninfringement. In * no event shall the authors or copyright holders be liable for any claim, damages or other liability, * whether in an action of contract, tort or otherwise, arising from, out of or in connection with the * software or the use or other dealings in the software. * * https://ewbi.blogs.com/develops/2007/03/excel_formula_p.html * https://ewbi.blogs.com/develops/2004/12/excel_formula_p.html */ class FormulaToken { // Token types const TOKEN_TYPE_NOOP = 'Noop'; const TOKEN_TYPE_OPERAND = 'Operand'; const TOKEN_TYPE_FUNCTION = 'Function'; const TOKEN_TYPE_SUBEXPRESSION = 'Subexpression'; const TOKEN_TYPE_ARGUMENT = 'Argument'; const TOKEN_TYPE_OPERATORPREFIX = 'OperatorPrefix'; const TOKEN_TYPE_OPERATORINFIX = 'OperatorInfix'; const TOKEN_TYPE_OPERATORPOSTFIX = 'OperatorPostfix'; const TOKEN_TYPE_WHITESPACE = 'Whitespace'; const TOKEN_TYPE_UNKNOWN = 'Unknown'; // Token subtypes const TOKEN_SUBTYPE_NOTHING = 'Nothing'; const TOKEN_SUBTYPE_START = 'Start'; const TOKEN_SUBTYPE_STOP = 'Stop'; const TOKEN_SUBTYPE_TEXT = 'Text'; const TOKEN_SUBTYPE_NUMBER = 'Number'; const TOKEN_SUBTYPE_LOGICAL = 'Logical'; const TOKEN_SUBTYPE_ERROR = 'Error'; const TOKEN_SUBTYPE_RANGE = 'Range'; const TOKEN_SUBTYPE_MATH = 'Math'; const TOKEN_SUBTYPE_CONCATENATION = 'Concatenation'; const TOKEN_SUBTYPE_INTERSECTION = 'Intersection'; const TOKEN_SUBTYPE_UNION = 'Union'; /** * Value. */ private string $value; /** * Token Type (represented by TOKEN_TYPE_*). */ private string $tokenType; /** * Token SubType (represented by TOKEN_SUBTYPE_*). */ private string $tokenSubType; /** * Create a new FormulaToken. * * @param string $tokenType Token type (represented by TOKEN_TYPE_*) * @param string $tokenSubType Token Subtype (represented by TOKEN_SUBTYPE_*) */ public function __construct(string $value, string $tokenType = self::TOKEN_TYPE_UNKNOWN, string $tokenSubType = self::TOKEN_SUBTYPE_NOTHING) { // Initialise values $this->value = $value; $this->tokenType = $tokenType; $this->tokenSubType = $tokenSubType; } /** * Get Value. */ public function getValue(): string { return $this->value; } /** * Set Value. */ public function setValue(string $value): void { $this->value = $value; } /** * Get Token Type (represented by TOKEN_TYPE_*). */ public function getTokenType(): string { return $this->tokenType; } /** * Set Token Type (represented by TOKEN_TYPE_*). */ public function setTokenType(string $value): void { $this->tokenType = $value; } /** * Get Token SubType (represented by TOKEN_SUBTYPE_*). */ public function getTokenSubType(): string { return $this->tokenSubType; } /** * Set Token SubType (represented by TOKEN_SUBTYPE_*). */ public function setTokenSubType(string $value): void { $this->tokenSubType = $value; } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Calculation/Category.php
src/PhpSpreadsheet/Calculation/Category.php
<?php namespace PhpOffice\PhpSpreadsheet\Calculation; abstract class Category { // Function categories const CATEGORY_CUBE = 'Cube'; const CATEGORY_DATABASE = 'Database'; const CATEGORY_DATE_AND_TIME = 'Date and Time'; const CATEGORY_ENGINEERING = 'Engineering'; const CATEGORY_FINANCIAL = 'Financial'; const CATEGORY_INFORMATION = 'Information'; const CATEGORY_LOGICAL = 'Logical'; const CATEGORY_LOOKUP_AND_REFERENCE = 'Lookup and Reference'; const CATEGORY_MATH_AND_TRIG = 'Math and Trig'; const CATEGORY_STATISTICAL = 'Statistical'; const CATEGORY_TEXT_AND_DATA = 'Text and Data'; const CATEGORY_WEB = 'Web'; const CATEGORY_UNCATEGORISED = 'Uncategorised'; const CATEGORY_MICROSOFT_INTERNAL = 'MS Internal'; }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Calculation/Exception.php
src/PhpSpreadsheet/Calculation/Exception.php
<?php namespace PhpOffice\PhpSpreadsheet\Calculation; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; class Exception extends PhpSpreadsheetException { public const CALCULATION_ENGINE_PUSH_TO_STACK = 1; /** * Error handler callback. */ public static function errorHandlerCallback(int $code, string $string, string $file, int $line): void { $e = new self($string, $code); $e->line = $line; $e->file = $file; throw $e; } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Calculation/CalculationLocale.php
src/PhpSpreadsheet/Calculation/CalculationLocale.php
<?php namespace PhpOffice\PhpSpreadsheet\Calculation; class CalculationLocale extends CalculationBase { public const FORMULA_OPEN_FUNCTION_BRACE = '('; public const FORMULA_CLOSE_FUNCTION_BRACE = ')'; public const FORMULA_OPEN_MATRIX_BRACE = '{'; public const FORMULA_CLOSE_MATRIX_BRACE = '}'; public const FORMULA_STRING_QUOTE = '"'; // Strip xlfn and xlws prefixes from function name public const CALCULATION_REGEXP_STRIP_XLFN_XLWS = '/(_xlfn[.])?(_xlws[.])?(?=[\p{L}][\p{L}\p{N}\.]*[\s]*[(])/'; /** * The current locale setting. */ protected static string $localeLanguage = 'en_us'; // US English (default locale) /** * List of available locale settings * Note that this is read for the locale subdirectory only when requested. * * @var string[] */ protected static array $validLocaleLanguages = [ 'en', // English (default language) ]; /** * Locale-specific argument separator for function arguments. */ protected static string $localeArgumentSeparator = ','; /** @var string[] */ protected static array $localeFunctions = []; /** * Locale-specific translations for Excel constants (True, False and Null). * * @var array<string, string> */ protected static array $localeBoolean = [ 'TRUE' => 'TRUE', 'FALSE' => 'FALSE', 'NULL' => 'NULL', ]; /** @var array<int, array<int, string>> */ protected static array $falseTrueArray = []; public static function getLocaleBoolean(string $index): string { return self::$localeBoolean[$index]; } protected static function loadLocales(): void { $localeFileDirectory = __DIR__ . '/locale/'; $localeFileNames = glob($localeFileDirectory . '*', GLOB_ONLYDIR) ?: []; foreach ($localeFileNames as $filename) { $filename = substr($filename, strlen($localeFileDirectory)); if ($filename != 'en') { self::$validLocaleLanguages[] = $filename; $subdirs = glob("$localeFileDirectory$filename/*", GLOB_ONLYDIR) ?: []; foreach ($subdirs as $subdir) { $subdirx = basename($subdir); self::$validLocaleLanguages[] = "{$filename}_{$subdirx}"; } } } } /** * Return the locale-specific translation of TRUE. * * @return string locale-specific translation of TRUE */ public static function getTRUE(): string { return self::$localeBoolean['TRUE']; } /** * Return the locale-specific translation of FALSE. * * @return string locale-specific translation of FALSE */ public static function getFALSE(): string { return self::$localeBoolean['FALSE']; } /** * Get the currently defined locale code. */ public function getLocale(): string { return self::$localeLanguage; } protected function getLocaleFile(string $localeDir, string $locale, string $language, string $file): string { $localeFileName = $localeDir . str_replace('_', DIRECTORY_SEPARATOR, $locale) . DIRECTORY_SEPARATOR . $file; if (!file_exists($localeFileName)) { // If there isn't a locale specific file, look for a language specific file $localeFileName = $localeDir . $language . DIRECTORY_SEPARATOR . $file; if (!file_exists($localeFileName)) { throw new Exception('Locale file not found'); } } return $localeFileName; } /** @return array<int, array<int, string>> */ public function getFalseTrueArray(): array { if (!empty(self::$falseTrueArray)) { return self::$falseTrueArray; } if (count(self::$validLocaleLanguages) == 1) { self::loadLocales(); } $falseTrueArray = [['FALSE'], ['TRUE']]; foreach (self::$validLocaleLanguages as $language) { if (str_starts_with($language, 'en')) { continue; } $locale = $language; if (str_contains($locale, '_')) { [$language] = explode('_', $locale); } $localeDir = implode(DIRECTORY_SEPARATOR, [__DIR__, 'locale', null]); try { $functionNamesFile = $this->getLocaleFile($localeDir, $locale, $language, 'functions'); } catch (Exception $e) { continue; } // Retrieve the list of locale or language specific function names $localeFunctions = file($functionNamesFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: []; foreach ($localeFunctions as $localeFunction) { [$localeFunction] = explode('##', $localeFunction); // Strip out comments if (str_contains($localeFunction, '=')) { [$fName, $lfName] = array_map('trim', explode('=', $localeFunction)); if ($fName === 'FALSE') { $falseTrueArray[0][] = $lfName; } elseif ($fName === 'TRUE') { $falseTrueArray[1][] = $lfName; } } } } self::$falseTrueArray = $falseTrueArray; return $falseTrueArray; } /** * Set the locale code. * * @param string $locale The locale to use for formula translation, eg: 'en_us' */ public function setLocale(string $locale): bool { // Identify our locale and language $language = $locale = strtolower($locale); if (str_contains($locale, '_')) { [$language] = explode('_', $locale); } if (count(self::$validLocaleLanguages) == 1) { self::loadLocales(); } // Test whether we have any language data for this language (any locale) if (in_array($language, self::$validLocaleLanguages, true)) { // initialise language/locale settings self::$localeFunctions = []; self::$localeArgumentSeparator = ','; self::$localeBoolean = ['TRUE' => 'TRUE', 'FALSE' => 'FALSE', 'NULL' => 'NULL']; // Default is US English, if user isn't requesting US english, then read the necessary data from the locale files if ($locale !== 'en_us') { $localeDir = implode(DIRECTORY_SEPARATOR, [__DIR__, 'locale', null]); // Search for a file with a list of function names for locale try { $functionNamesFile = $this->getLocaleFile($localeDir, $locale, $language, 'functions'); } catch (Exception $e) { return false; } // Retrieve the list of locale or language specific function names $localeFunctions = file($functionNamesFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: []; $phpSpreadsheetFunctions = &self::getFunctionsAddress(); foreach ($localeFunctions as $localeFunction) { [$localeFunction] = explode('##', $localeFunction); // Strip out comments if (str_contains($localeFunction, '=')) { [$fName, $lfName] = array_map('trim', explode('=', $localeFunction)); if ((str_starts_with($fName, '*') || isset($phpSpreadsheetFunctions[$fName])) && ($lfName != '') && ($fName != $lfName)) { self::$localeFunctions[$fName] = $lfName; } } } // Default the TRUE and FALSE constants to the locale names of the TRUE() and FALSE() functions if (isset(self::$localeFunctions['TRUE'])) { self::$localeBoolean['TRUE'] = self::$localeFunctions['TRUE']; } if (isset(self::$localeFunctions['FALSE'])) { self::$localeBoolean['FALSE'] = self::$localeFunctions['FALSE']; } try { $configFile = $this->getLocaleFile($localeDir, $locale, $language, 'config'); } catch (Exception) { return false; } $localeSettings = file($configFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: []; foreach ($localeSettings as $localeSetting) { [$localeSetting] = explode('##', $localeSetting); // Strip out comments if (str_contains($localeSetting, '=')) { [$settingName, $settingValue] = array_map('trim', explode('=', $localeSetting)); $settingName = strtoupper($settingName); if ($settingValue !== '') { switch ($settingName) { case 'ARGUMENTSEPARATOR': self::$localeArgumentSeparator = $settingValue; break; } } } } } self::$functionReplaceFromExcel = self::$functionReplaceToExcel = self::$functionReplaceFromLocale = self::$functionReplaceToLocale = null; self::$localeLanguage = $locale; return true; } return false; } public static function translateSeparator( string $fromSeparator, string $toSeparator, string $formula, int &$inBracesLevel, string $openBrace = self::FORMULA_OPEN_FUNCTION_BRACE, string $closeBrace = self::FORMULA_CLOSE_FUNCTION_BRACE ): string { $strlen = mb_strlen($formula); for ($i = 0; $i < $strlen; ++$i) { $chr = mb_substr($formula, $i, 1); switch ($chr) { case $openBrace: ++$inBracesLevel; break; case $closeBrace: --$inBracesLevel; break; case $fromSeparator: if ($inBracesLevel > 0) { $formula = mb_substr($formula, 0, $i) . $toSeparator . mb_substr($formula, $i + 1); } } } return $formula; } /** * @param string[] $from * @param string[] $to */ protected static function translateFormulaBlock( array $from, array $to, string $formula, int &$inFunctionBracesLevel, int &$inMatrixBracesLevel, string $fromSeparator, string $toSeparator ): string { // Function Names $formula = (string) preg_replace($from, $to, $formula); // Temporarily adjust matrix separators so that they won't be confused with function arguments $formula = self::translateSeparator(';', '|', $formula, $inMatrixBracesLevel, self::FORMULA_OPEN_MATRIX_BRACE, self::FORMULA_CLOSE_MATRIX_BRACE); $formula = self::translateSeparator(',', '!', $formula, $inMatrixBracesLevel, self::FORMULA_OPEN_MATRIX_BRACE, self::FORMULA_CLOSE_MATRIX_BRACE); // Function Argument Separators $formula = self::translateSeparator($fromSeparator, $toSeparator, $formula, $inFunctionBracesLevel); // Restore matrix separators $formula = self::translateSeparator('|', ';', $formula, $inMatrixBracesLevel, self::FORMULA_OPEN_MATRIX_BRACE, self::FORMULA_CLOSE_MATRIX_BRACE); $formula = self::translateSeparator('!', ',', $formula, $inMatrixBracesLevel, self::FORMULA_OPEN_MATRIX_BRACE, self::FORMULA_CLOSE_MATRIX_BRACE); return $formula; } /** * @param string[] $from * @param string[] $to */ protected static function translateFormula(array $from, array $to, string $formula, string $fromSeparator, string $toSeparator): string { // Convert any Excel function names and constant names to the required language; // and adjust function argument separators if (self::$localeLanguage !== 'en_us') { $inFunctionBracesLevel = 0; $inMatrixBracesLevel = 0; // If there is the possibility of separators within a quoted string, then we treat them as literals if (str_contains($formula, self::FORMULA_STRING_QUOTE)) { // So instead we skip replacing in any quoted strings by only replacing in every other array element // after we've exploded the formula $temp = explode(self::FORMULA_STRING_QUOTE, $formula); $notWithinQuotes = false; foreach ($temp as &$value) { // Only adjust in alternating array entries $notWithinQuotes = $notWithinQuotes === false; if ($notWithinQuotes === true) { $value = self::translateFormulaBlock($from, $to, $value, $inFunctionBracesLevel, $inMatrixBracesLevel, $fromSeparator, $toSeparator); } } unset($value); // Then rebuild the formula string $formula = implode(self::FORMULA_STRING_QUOTE, $temp); } else { // If there's no quoted strings, then we do a simple count/replace $formula = self::translateFormulaBlock($from, $to, $formula, $inFunctionBracesLevel, $inMatrixBracesLevel, $fromSeparator, $toSeparator); } } return $formula; } /** @var null|string[] */ private static ?array $functionReplaceFromExcel; /** @var null|string[] */ private static ?array $functionReplaceToLocale; public function translateFormulaToLocale(string $formula): string { $formula = preg_replace(self::CALCULATION_REGEXP_STRIP_XLFN_XLWS, '', $formula) ?? ''; // Build list of function names and constants for translation if (self::$functionReplaceFromExcel === null) { self::$functionReplaceFromExcel = []; foreach (array_keys(self::$localeFunctions) as $excelFunctionName) { self::$functionReplaceFromExcel[] = '/(@?[^\w\.])' . preg_quote($excelFunctionName, '/') . '([\s]*\()/ui'; } foreach (array_keys(self::$localeBoolean) as $excelBoolean) { self::$functionReplaceFromExcel[] = '/(@?[^\w\.])' . preg_quote($excelBoolean, '/') . '([^\w\.])/ui'; } } if (self::$functionReplaceToLocale === null) { self::$functionReplaceToLocale = []; foreach (self::$localeFunctions as $localeFunctionName) { self::$functionReplaceToLocale[] = '$1' . trim($localeFunctionName) . '$2'; } foreach (self::$localeBoolean as $localeBoolean) { self::$functionReplaceToLocale[] = '$1' . trim($localeBoolean) . '$2'; } } return self::translateFormula( self::$functionReplaceFromExcel, self::$functionReplaceToLocale, $formula, ',', self::$localeArgumentSeparator ); } /** @var null|string[] */ protected static ?array $functionReplaceFromLocale; /** @var null|string[] */ protected static ?array $functionReplaceToExcel; public function translateFormulaToEnglish(string $formula): string { if (self::$functionReplaceFromLocale === null) { self::$functionReplaceFromLocale = []; foreach (self::$localeFunctions as $localeFunctionName) { self::$functionReplaceFromLocale[] = '/(@?[^\w\.])' . preg_quote($localeFunctionName, '/') . '([\s]*\()/ui'; } foreach (self::$localeBoolean as $excelBoolean) { self::$functionReplaceFromLocale[] = '/(@?[^\w\.])' . preg_quote($excelBoolean, '/') . '([^\w\.])/ui'; } } if (self::$functionReplaceToExcel === null) { self::$functionReplaceToExcel = []; foreach (array_keys(self::$localeFunctions) as $excelFunctionName) { self::$functionReplaceToExcel[] = '$1' . trim($excelFunctionName) . '$2'; } foreach (array_keys(self::$localeBoolean) as $excelBoolean) { self::$functionReplaceToExcel[] = '$1' . trim($excelBoolean) . '$2'; } } return self::translateFormula(self::$functionReplaceFromLocale, self::$functionReplaceToExcel, $formula, self::$localeArgumentSeparator, ','); } public static function localeFunc(string $function): string { if (self::$localeLanguage !== 'en_us') { $functionName = trim($function, '('); if (isset(self::$localeFunctions[$functionName])) { $brace = ($functionName != $function); $function = self::$localeFunctions[$functionName]; if ($brace) { $function .= '('; } } } return $function; } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Calculation/FunctionArray.php
src/PhpSpreadsheet/Calculation/FunctionArray.php
<?php namespace PhpOffice\PhpSpreadsheet\Calculation; class FunctionArray extends CalculationBase { /** * Array of functions usable on Spreadsheet. * * @var array<string, array{category: string, functionCall: string|string[], argumentCount: string, passCellReference?: bool, passByReference?: bool[], custom?: bool}> */ protected static array $phpSpreadsheetFunctions = [ 'ABS' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Absolute::class, 'evaluate'], 'argumentCount' => '1', ], 'ACCRINT' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Securities\AccruedInterest::class, 'periodic'], 'argumentCount' => '4-8', ], 'ACCRINTM' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Securities\AccruedInterest::class, 'atMaturity'], 'argumentCount' => '3-5', ], 'ACOS' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Trig\Cosine::class, 'acos'], 'argumentCount' => '1', ], 'ACOSH' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Trig\Cosine::class, 'acosh'], 'argumentCount' => '1', ], 'ACOT' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Trig\Cotangent::class, 'acot'], 'argumentCount' => '1', ], 'ACOTH' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Trig\Cotangent::class, 'acoth'], 'argumentCount' => '1', ], 'ADDRESS' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [LookupRef\Address::class, 'cell'], 'argumentCount' => '2-5', ], 'AGGREGATE' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '3+', ], 'AMORDEGRC' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Amortization::class, 'AMORDEGRC'], 'argumentCount' => '6,7', ], 'AMORLINC' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Amortization::class, 'AMORLINC'], 'argumentCount' => '6,7', ], 'ANCHORARRAY' => [ 'category' => Category::CATEGORY_MICROSOFT_INTERNAL, 'functionCall' => [Internal\ExcelArrayPseudoFunctions::class, 'anchorArray'], 'argumentCount' => '1', 'passCellReference' => true, 'passByReference' => [true], ], 'AND' => [ 'category' => Category::CATEGORY_LOGICAL, 'functionCall' => [Logical\Operations::class, 'logicalAnd'], 'argumentCount' => '1+', ], 'ARABIC' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Arabic::class, 'evaluate'], 'argumentCount' => '1', ], 'AREAS' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '1', ], 'ARRAYTOTEXT' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Text::class, 'fromArray'], 'argumentCount' => '1,2', ], 'ASC' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '1', ], 'ASIN' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Trig\Sine::class, 'asin'], 'argumentCount' => '1', ], 'ASINH' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Trig\Sine::class, 'asinh'], 'argumentCount' => '1', ], 'ATAN' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Trig\Tangent::class, 'atan'], 'argumentCount' => '1', ], 'ATAN2' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Trig\Tangent::class, 'atan2'], 'argumentCount' => '2', ], 'ATANH' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Trig\Tangent::class, 'atanh'], 'argumentCount' => '1', ], 'AVEDEV' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Averages::class, 'averageDeviations'], 'argumentCount' => '1+', ], 'AVERAGE' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Averages::class, 'average'], 'argumentCount' => '1+', ], 'AVERAGEA' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Averages::class, 'averageA'], 'argumentCount' => '1+', ], 'AVERAGEIF' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Conditional::class, 'AVERAGEIF'], 'argumentCount' => '2,3', ], 'AVERAGEIFS' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Conditional::class, 'AVERAGEIFS'], 'argumentCount' => '3+', ], 'BAHTTEXT' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Thai::class, 'getBahtText'], 'argumentCount' => '1', ], 'BASE' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Base::class, 'evaluate'], 'argumentCount' => '2,3', ], 'BESSELI' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\BesselI::class, 'BESSELI'], 'argumentCount' => '2', ], 'BESSELJ' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\BesselJ::class, 'BESSELJ'], 'argumentCount' => '2', ], 'BESSELK' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\BesselK::class, 'BESSELK'], 'argumentCount' => '2', ], 'BESSELY' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\BesselY::class, 'BESSELY'], 'argumentCount' => '2', ], 'BETADIST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Beta::class, 'distribution'], 'argumentCount' => '3-5', ], 'BETA.DIST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '4-6', ], 'BETAINV' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Beta::class, 'inverse'], 'argumentCount' => '3-5', ], 'BETA.INV' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Beta::class, 'inverse'], 'argumentCount' => '3-5', ], 'BIN2DEC' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ConvertBinary::class, 'toDecimal'], 'argumentCount' => '1', ], 'BIN2HEX' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ConvertBinary::class, 'toHex'], 'argumentCount' => '1,2', ], 'BIN2OCT' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ConvertBinary::class, 'toOctal'], 'argumentCount' => '1,2', ], 'BINOMDIST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Binomial::class, 'distribution'], 'argumentCount' => '4', ], 'BINOM.DIST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Binomial::class, 'distribution'], 'argumentCount' => '4', ], 'BINOM.DIST.RANGE' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Binomial::class, 'range'], 'argumentCount' => '3,4', ], 'BINOM.INV' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Binomial::class, 'inverse'], 'argumentCount' => '3', ], 'BITAND' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\BitWise::class, 'BITAND'], 'argumentCount' => '2', ], 'BITOR' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\BitWise::class, 'BITOR'], 'argumentCount' => '2', ], 'BITXOR' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\BitWise::class, 'BITXOR'], 'argumentCount' => '2', ], 'BITLSHIFT' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\BitWise::class, 'BITLSHIFT'], 'argumentCount' => '2', ], 'BITRSHIFT' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\BitWise::class, 'BITRSHIFT'], 'argumentCount' => '2', ], 'BYCOL' => [ 'category' => Category::CATEGORY_LOGICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '*', ], 'BYROW' => [ 'category' => Category::CATEGORY_LOGICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '*', ], 'CEILING' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Ceiling::class, 'ceiling'], 'argumentCount' => '1-2', // 2 for Excel, 1-2 for Ods/Gnumeric ], 'CEILING.MATH' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Ceiling::class, 'math'], 'argumentCount' => '1-3', ], // pseudo-function to help with Ods 'CEILING.ODS' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Ceiling::class, 'mathOds'], 'argumentCount' => '1-3', ], 'CEILING.PRECISE' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Ceiling::class, 'precise'], 'argumentCount' => '1,2', ], // pseudo-function implemented in Ods 'CEILING.XCL' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Ceiling::class, 'ceiling'], 'argumentCount' => '2', ], 'CELL' => [ 'category' => Category::CATEGORY_INFORMATION, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '1,2', ], 'CHAR' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\CharacterConvert::class, 'character'], 'argumentCount' => '1', ], 'CHIDIST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\ChiSquared::class, 'distributionRightTail'], 'argumentCount' => '2', ], 'CHISQ.DIST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\ChiSquared::class, 'distributionLeftTail'], 'argumentCount' => '3', ], 'CHISQ.DIST.RT' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\ChiSquared::class, 'distributionRightTail'], 'argumentCount' => '2', ], 'CHIINV' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\ChiSquared::class, 'inverseRightTail'], 'argumentCount' => '2', ], 'CHISQ.INV' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\ChiSquared::class, 'inverseLeftTail'], 'argumentCount' => '2', ], 'CHISQ.INV.RT' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\ChiSquared::class, 'inverseRightTail'], 'argumentCount' => '2', ], 'CHITEST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\ChiSquared::class, 'test'], 'argumentCount' => '2', ], 'CHISQ.TEST' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\ChiSquared::class, 'test'], 'argumentCount' => '2', ], 'CHOOSE' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [LookupRef\Selection::class, 'CHOOSE'], 'argumentCount' => '2+', ], 'CHOOSECOLS' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [LookupRef\ChooseRowsEtc::class, 'chooseCols'], 'argumentCount' => '2+', ], 'CHOOSEROWS' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [LookupRef\ChooseRowsEtc::class, 'chooseRows'], 'argumentCount' => '2+', ], 'CLEAN' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Trim::class, 'nonPrintable'], 'argumentCount' => '1', ], 'CODE' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\CharacterConvert::class, 'code'], 'argumentCount' => '1', ], 'COLUMN' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [LookupRef\RowColumnInformation::class, 'COLUMN'], 'argumentCount' => '-1', 'passCellReference' => true, 'passByReference' => [true], ], 'COLUMNS' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [LookupRef\RowColumnInformation::class, 'COLUMNS'], 'argumentCount' => '1', ], 'COMBIN' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Combinations::class, 'withoutRepetition'], 'argumentCount' => '2', ], 'COMBINA' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Combinations::class, 'withRepetition'], 'argumentCount' => '2', ], 'COMPLEX' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\Complex::class, 'COMPLEX'], 'argumentCount' => '2,3', ], 'CONCAT' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Concatenate::class, 'CONCATENATE'], 'argumentCount' => '1+', ], 'CONCATENATE' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Concatenate::class, 'actualCONCATENATE'], 'argumentCount' => '1+', ], 'CONFIDENCE' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Confidence::class, 'CONFIDENCE'], 'argumentCount' => '3', ], 'CONFIDENCE.NORM' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Confidence::class, 'CONFIDENCE'], 'argumentCount' => '3', ], 'CONFIDENCE.T' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '3', ], 'CONVERT' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ConvertUOM::class, 'CONVERT'], 'argumentCount' => '3', ], 'CORREL' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Trends::class, 'CORREL'], 'argumentCount' => '2', ], 'COS' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Trig\Cosine::class, 'cos'], 'argumentCount' => '1', ], 'COSH' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Trig\Cosine::class, 'cosh'], 'argumentCount' => '1', ], 'COT' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Trig\Cotangent::class, 'cot'], 'argumentCount' => '1', ], 'COTH' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Trig\Cotangent::class, 'coth'], 'argumentCount' => '1', ], 'COUNT' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Counts::class, 'COUNT'], 'argumentCount' => '1+', ], 'COUNTA' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Counts::class, 'COUNTA'], 'argumentCount' => '1+', ], 'COUNTBLANK' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Counts::class, 'COUNTBLANK'], 'argumentCount' => '1', ], 'COUNTIF' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Conditional::class, 'COUNTIF'], 'argumentCount' => '2', ], 'COUNTIFS' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Conditional::class, 'COUNTIFS'], 'argumentCount' => '2+', ], 'COUPDAYBS' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Coupons::class, 'COUPDAYBS'], 'argumentCount' => '3,4', ], 'COUPDAYS' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Coupons::class, 'COUPDAYS'], 'argumentCount' => '3,4', ], 'COUPDAYSNC' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Coupons::class, 'COUPDAYSNC'], 'argumentCount' => '3,4', ], 'COUPNCD' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Coupons::class, 'COUPNCD'], 'argumentCount' => '3,4', ], 'COUPNUM' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Coupons::class, 'COUPNUM'], 'argumentCount' => '3,4', ], 'COUPPCD' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Coupons::class, 'COUPPCD'], 'argumentCount' => '3,4', ], 'COVAR' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Trends::class, 'COVAR'], 'argumentCount' => '2', ], 'COVARIANCE.P' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Trends::class, 'COVAR'], 'argumentCount' => '2', ], 'COVARIANCE.S' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '2', ], 'CRITBINOM' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Distributions\Binomial::class, 'inverse'], 'argumentCount' => '3', ], 'CSC' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Trig\Cosecant::class, 'csc'], 'argumentCount' => '1', ], 'CSCH' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Trig\Cosecant::class, 'csch'], 'argumentCount' => '1', ], 'CUBEKPIMEMBER' => [ 'category' => Category::CATEGORY_CUBE, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '?', ], 'CUBEMEMBER' => [ 'category' => Category::CATEGORY_CUBE, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '?', ], 'CUBEMEMBERPROPERTY' => [ 'category' => Category::CATEGORY_CUBE, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '?', ], 'CUBERANKEDMEMBER' => [ 'category' => Category::CATEGORY_CUBE, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '?', ], 'CUBESET' => [ 'category' => Category::CATEGORY_CUBE, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '?', ], 'CUBESETCOUNT' => [ 'category' => Category::CATEGORY_CUBE, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '?', ], 'CUBEVALUE' => [ 'category' => Category::CATEGORY_CUBE, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '?', ], 'CUMIPMT' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\CashFlow\Constant\Periodic\Cumulative::class, 'interest'], 'argumentCount' => '6', ], 'CUMPRINC' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\CashFlow\Constant\Periodic\Cumulative::class, 'principal'], 'argumentCount' => '6', ], 'DATE' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [DateTimeExcel\Date::class, 'fromYMD'], 'argumentCount' => '3', ], 'DATEDIF' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [DateTimeExcel\Difference::class, 'interval'], 'argumentCount' => '2,3', ], 'DATESTRING' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '?', ], 'DATEVALUE' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [DateTimeExcel\DateValue::class, 'fromString'], 'argumentCount' => '1', ], 'DAVERAGE' => [ 'category' => Category::CATEGORY_DATABASE, 'functionCall' => [Database\DAverage::class, 'evaluate'], 'argumentCount' => '3', ], 'DAY' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [DateTimeExcel\DateParts::class, 'day'], 'argumentCount' => '1', ], 'DAYS' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [DateTimeExcel\Days::class, 'between'], 'argumentCount' => '2', ], 'DAYS360' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [DateTimeExcel\Days360::class, 'between'], 'argumentCount' => '2,3', ], 'DB' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Depreciation::class, 'DB'], 'argumentCount' => '4,5', ], 'DBCS' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '1', ], 'DCOUNT' => [ 'category' => Category::CATEGORY_DATABASE, 'functionCall' => [Database\DCount::class, 'evaluate'], 'argumentCount' => '3', ], 'DCOUNTA' => [ 'category' => Category::CATEGORY_DATABASE, 'functionCall' => [Database\DCountA::class, 'evaluate'], 'argumentCount' => '3', ], 'DDB' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Depreciation::class, 'DDB'], 'argumentCount' => '4,5', ], 'DEC2BIN' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ConvertDecimal::class, 'toBinary'], 'argumentCount' => '1,2', ], 'DEC2HEX' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ConvertDecimal::class, 'toHex'], 'argumentCount' => '1,2', ], 'DEC2OCT' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ConvertDecimal::class, 'toOctal'], 'argumentCount' => '1,2', ], 'DECIMAL' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '2', ], 'DEGREES' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Angle::class, 'toDegrees'], 'argumentCount' => '1', ], 'DELTA' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\Compare::class, 'DELTA'], 'argumentCount' => '1,2', ], 'DEVSQ' => [ 'category' => Category::CATEGORY_STATISTICAL, 'functionCall' => [Statistical\Deviations::class, 'sumSquares'], 'argumentCount' => '1+', ], 'DGET' => [ 'category' => Category::CATEGORY_DATABASE, 'functionCall' => [Database\DGet::class, 'evaluate'], 'argumentCount' => '3', ], 'DISC' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Securities\Rates::class, 'discount'], 'argumentCount' => '4,5', ], 'DMAX' => [ 'category' => Category::CATEGORY_DATABASE, 'functionCall' => [Database\DMax::class, 'evaluate'], 'argumentCount' => '3', ], 'DMIN' => [ 'category' => Category::CATEGORY_DATABASE, 'functionCall' => [Database\DMin::class, 'evaluate'], 'argumentCount' => '3', ], 'DOLLAR' => [ 'category' => Category::CATEGORY_TEXT_AND_DATA, 'functionCall' => [TextData\Format::class, 'DOLLAR'], 'argumentCount' => '1,2', ], 'DOLLARDE' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Dollar::class, 'decimal'], 'argumentCount' => '2', ], 'DOLLARFR' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\Dollar::class, 'fractional'], 'argumentCount' => '2', ], 'DPRODUCT' => [ 'category' => Category::CATEGORY_DATABASE, 'functionCall' => [Database\DProduct::class, 'evaluate'], 'argumentCount' => '3', ], 'DROP' => [ 'category' => Category::CATEGORY_LOOKUP_AND_REFERENCE, 'functionCall' => [LookupRef\ChooseRowsEtc::class, 'drop'], 'argumentCount' => '2-3', ], 'DSTDEV' => [ 'category' => Category::CATEGORY_DATABASE, 'functionCall' => [Database\DStDev::class, 'evaluate'], 'argumentCount' => '3', ], 'DSTDEVP' => [ 'category' => Category::CATEGORY_DATABASE, 'functionCall' => [Database\DStDevP::class, 'evaluate'], 'argumentCount' => '3', ], 'DSUM' => [ 'category' => Category::CATEGORY_DATABASE, 'functionCall' => [Database\DSum::class, 'evaluate'], 'argumentCount' => '3', ], 'DURATION' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '5,6', ], 'DVAR' => [ 'category' => Category::CATEGORY_DATABASE, 'functionCall' => [Database\DVar::class, 'evaluate'], 'argumentCount' => '3', ], 'DVARP' => [ 'category' => Category::CATEGORY_DATABASE, 'functionCall' => [Database\DVarP::class, 'evaluate'], 'argumentCount' => '3', ], 'ECMA.CEILING' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '1,2', ], 'EDATE' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [DateTimeExcel\Month::class, 'adjust'], 'argumentCount' => '2', ], 'EFFECT' => [ 'category' => Category::CATEGORY_FINANCIAL, 'functionCall' => [Financial\InterestRate::class, 'effective'], 'argumentCount' => '2', ], 'ENCODEURL' => [ 'category' => Category::CATEGORY_WEB, 'functionCall' => [Web\Service::class, 'urlEncode'], 'argumentCount' => '1', ], 'EOMONTH' => [ 'category' => Category::CATEGORY_DATE_AND_TIME, 'functionCall' => [DateTimeExcel\Month::class, 'lastDay'], 'argumentCount' => '2', ], 'ERF' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\Erf::class, 'ERF'], 'argumentCount' => '1,2', ], 'ERF.PRECISE' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\Erf::class, 'ERFPRECISE'], 'argumentCount' => '1', ], 'ERFC' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ErfC::class, 'ERFC'], 'argumentCount' => '1', ], 'ERFC.PRECISE' => [ 'category' => Category::CATEGORY_ENGINEERING, 'functionCall' => [Engineering\ErfC::class, 'ERFC'], 'argumentCount' => '1', ], 'ERROR.TYPE' => [ 'category' => Category::CATEGORY_INFORMATION, 'functionCall' => [Information\ExcelError::class, 'type'], 'argumentCount' => '1', ], 'EVEN' => [ 'category' => Category::CATEGORY_MATH_AND_TRIG, 'functionCall' => [MathTrig\Round::class, 'even'], 'argumentCount' => '1', ], 'EXACT' => [
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
true
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Calculation/FormulaParser.php
src/PhpSpreadsheet/Calculation/FormulaParser.php
<?php namespace PhpOffice\PhpSpreadsheet\Calculation; /** * PARTLY BASED ON: * Copyright (c) 2007 E. W. Bachtal, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software * and associated documentation files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial * portions of the Software. * * The software is provided "as is", without warranty of any kind, express or implied, including but not * limited to the warranties of merchantability, fitness for a particular purpose and noninfringement. In * no event shall the authors or copyright holders be liable for any claim, damages or other liability, * whether in an action of contract, tort or otherwise, arising from, out of or in connection with the * software or the use or other dealings in the software. * * https://ewbi.blogs.com/develops/2007/03/excel_formula_p.html * https://ewbi.blogs.com/develops/2004/12/excel_formula_p.html */ class FormulaParser { // Character constants const QUOTE_DOUBLE = '"'; const QUOTE_SINGLE = '\''; const BRACKET_CLOSE = ']'; const BRACKET_OPEN = '['; const BRACE_OPEN = '{'; const BRACE_CLOSE = '}'; const PAREN_OPEN = '('; const PAREN_CLOSE = ')'; const SEMICOLON = ';'; const WHITESPACE = ' '; const COMMA = ','; const ERROR_START = '#'; const OPERATORS_SN = '+-'; const OPERATORS_INFIX = '+-*/^&=><'; const OPERATORS_POSTFIX = '%'; /** * Formula. */ private string $formula; /** * Tokens. * * @var FormulaToken[] */ private array $tokens = []; /** * Create a new FormulaParser. * * @param ?string $formula Formula to parse */ public function __construct(?string $formula = '') { // Check parameters if ($formula === null) { throw new Exception('Invalid parameter passed: formula'); } // Initialise values $this->formula = trim($formula); // Parse! $this->parseToTokens(); } /** * Get Formula. */ public function getFormula(): string { return $this->formula; } /** * Get Token. * * @param int $id Token id */ public function getToken(int $id = 0): FormulaToken { if (isset($this->tokens[$id])) { return $this->tokens[$id]; } throw new Exception("Token with id $id does not exist."); } /** * Get Token count. */ public function getTokenCount(): int { return count($this->tokens); } /** * Get Tokens. * * @return FormulaToken[] */ public function getTokens(): array { return $this->tokens; } /** * Parse to tokens. */ private function parseToTokens(): void { // No attempt is made to verify formulas; assumes formulas are derived from Excel, where // they can only exist if valid; stack overflows/underflows sunk as nulls without exceptions. // Check if the formula has a valid starting = $formulaLength = strlen($this->formula); if ($formulaLength < 2 || $this->formula[0] != '=') { return; } // Helper variables $tokens1 = $tokens2 = $stack = []; $inString = $inPath = $inRange = $inError = false; $nextToken = null; //$token = $previousToken = null; $index = 1; $value = ''; $ERRORS = ['#NULL!', '#DIV/0!', '#VALUE!', '#REF!', '#NAME?', '#NUM!', '#N/A']; $COMPARATORS_MULTI = ['>=', '<=', '<>']; while ($index < $formulaLength) { // state-dependent character evaluation (order is important) // double-quoted strings // embeds are doubled // end marks token if ($inString) { if ($this->formula[$index] == self::QUOTE_DOUBLE) { if ((($index + 2) <= $formulaLength) && ($this->formula[$index + 1] == self::QUOTE_DOUBLE)) { $value .= self::QUOTE_DOUBLE; ++$index; } else { $inString = false; $tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_OPERAND, FormulaToken::TOKEN_SUBTYPE_TEXT); $value = ''; } } else { $value .= $this->formula[$index]; } ++$index; continue; } // single-quoted strings (links) // embeds are double // end does not mark a token if ($inPath) { if ($this->formula[$index] == self::QUOTE_SINGLE) { if ((($index + 2) <= $formulaLength) && ($this->formula[$index + 1] == self::QUOTE_SINGLE)) { $value .= self::QUOTE_SINGLE; ++$index; } else { $inPath = false; } } else { $value .= $this->formula[$index]; } ++$index; continue; } // bracked strings (R1C1 range index or linked workbook name) // no embeds (changed to "()" by Excel) // end does not mark a token if ($inRange) { if ($this->formula[$index] == self::BRACKET_CLOSE) { $inRange = false; } $value .= $this->formula[$index]; ++$index; continue; } // error values // end marks a token, determined from absolute list of values if ($inError) { $value .= $this->formula[$index]; ++$index; if (in_array($value, $ERRORS)) { $inError = false; $tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_OPERAND, FormulaToken::TOKEN_SUBTYPE_ERROR); $value = ''; } continue; } // scientific notation check if (str_contains(self::OPERATORS_SN, $this->formula[$index])) { if (strlen($value) > 1) { if (preg_match('/^[1-9]{1}(\.\d+)?E{1}$/', $this->formula[$index]) != 0) { $value .= $this->formula[$index]; ++$index; continue; } } } // independent character evaluation (order not important) // establish state-dependent character evaluations if ($this->formula[$index] == self::QUOTE_DOUBLE) { if ($value !== '') { // unexpected $tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_UNKNOWN); $value = ''; } $inString = true; ++$index; continue; } if ($this->formula[$index] == self::QUOTE_SINGLE) { if ($value !== '') { // unexpected $tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_UNKNOWN); $value = ''; } $inPath = true; ++$index; continue; } if ($this->formula[$index] == self::BRACKET_OPEN) { $inRange = true; $value .= self::BRACKET_OPEN; ++$index; continue; } if ($this->formula[$index] == self::ERROR_START) { if ($value !== '') { // unexpected $tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_UNKNOWN); $value = ''; } $inError = true; $value .= self::ERROR_START; ++$index; continue; } // mark start and end of arrays and array rows if ($this->formula[$index] == self::BRACE_OPEN) { if ($value !== '') { // unexpected $tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_UNKNOWN); $value = ''; } $tmp = new FormulaToken('ARRAY', FormulaToken::TOKEN_TYPE_FUNCTION, FormulaToken::TOKEN_SUBTYPE_START); $tokens1[] = $tmp; $stack[] = clone $tmp; $tmp = new FormulaToken('ARRAYROW', FormulaToken::TOKEN_TYPE_FUNCTION, FormulaToken::TOKEN_SUBTYPE_START); $tokens1[] = $tmp; $stack[] = clone $tmp; ++$index; continue; } if ($this->formula[$index] == self::SEMICOLON) { if ($value !== '') { $tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_OPERAND); $value = ''; } /** @var FormulaToken $tmp */ $tmp = array_pop($stack); $tmp->setValue(''); $tmp->setTokenSubType(FormulaToken::TOKEN_SUBTYPE_STOP); $tokens1[] = $tmp; $tmp = new FormulaToken(',', FormulaToken::TOKEN_TYPE_ARGUMENT); $tokens1[] = $tmp; $tmp = new FormulaToken('ARRAYROW', FormulaToken::TOKEN_TYPE_FUNCTION, FormulaToken::TOKEN_SUBTYPE_START); $tokens1[] = $tmp; $stack[] = clone $tmp; ++$index; continue; } if ($this->formula[$index] == self::BRACE_CLOSE) { if ($value !== '') { $tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_OPERAND); $value = ''; } /** @var FormulaToken $tmp */ $tmp = array_pop($stack); $tmp->setValue(''); $tmp->setTokenSubType(FormulaToken::TOKEN_SUBTYPE_STOP); $tokens1[] = $tmp; /** @var FormulaToken $tmp */ $tmp = array_pop($stack); $tmp->setValue(''); $tmp->setTokenSubType(FormulaToken::TOKEN_SUBTYPE_STOP); $tokens1[] = $tmp; ++$index; continue; } // trim white-space if ($this->formula[$index] == self::WHITESPACE) { if ($value !== '') { $tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_OPERAND); $value = ''; } $tokens1[] = new FormulaToken('', FormulaToken::TOKEN_TYPE_WHITESPACE); ++$index; while (($this->formula[$index] == self::WHITESPACE) && ($index < $formulaLength)) { ++$index; } continue; } // multi-character comparators if (($index + 2) <= $formulaLength) { if (in_array(substr($this->formula, $index, 2), $COMPARATORS_MULTI)) { if ($value !== '') { $tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_OPERAND); $value = ''; } $tokens1[] = new FormulaToken(substr($this->formula, $index, 2), FormulaToken::TOKEN_TYPE_OPERATORINFIX, FormulaToken::TOKEN_SUBTYPE_LOGICAL); $index += 2; continue; } } // standard infix operators if (str_contains(self::OPERATORS_INFIX, $this->formula[$index])) { if ($value !== '') { $tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_OPERAND); $value = ''; } $tokens1[] = new FormulaToken($this->formula[$index], FormulaToken::TOKEN_TYPE_OPERATORINFIX); ++$index; continue; } // standard postfix operators (only one) if (str_contains(self::OPERATORS_POSTFIX, $this->formula[$index])) { if ($value !== '') { $tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_OPERAND); $value = ''; } $tokens1[] = new FormulaToken($this->formula[$index], FormulaToken::TOKEN_TYPE_OPERATORPOSTFIX); ++$index; continue; } // start subexpression or function if ($this->formula[$index] == self::PAREN_OPEN) { if ($value !== '') { $tmp = new FormulaToken($value, FormulaToken::TOKEN_TYPE_FUNCTION, FormulaToken::TOKEN_SUBTYPE_START); $tokens1[] = $tmp; $stack[] = clone $tmp; $value = ''; } else { $tmp = new FormulaToken('', FormulaToken::TOKEN_TYPE_SUBEXPRESSION, FormulaToken::TOKEN_SUBTYPE_START); $tokens1[] = $tmp; $stack[] = clone $tmp; } ++$index; continue; } // function, subexpression, or array parameters, or operand unions if ($this->formula[$index] == self::COMMA) { if ($value !== '') { $tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_OPERAND); $value = ''; } /** @var FormulaToken $tmp */ $tmp = array_pop($stack); $tmp->setValue(''); $tmp->setTokenSubType(FormulaToken::TOKEN_SUBTYPE_STOP); $stack[] = $tmp; if ($tmp->getTokenType() == FormulaToken::TOKEN_TYPE_FUNCTION) { $tokens1[] = new FormulaToken(',', FormulaToken::TOKEN_TYPE_OPERATORINFIX, FormulaToken::TOKEN_SUBTYPE_UNION); } else { $tokens1[] = new FormulaToken(',', FormulaToken::TOKEN_TYPE_ARGUMENT); } ++$index; continue; } // stop subexpression if ($this->formula[$index] == self::PAREN_CLOSE) { if ($value !== '') { $tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_OPERAND); $value = ''; } /** @var FormulaToken $tmp */ $tmp = array_pop($stack); $tmp->setValue(''); $tmp->setTokenSubType(FormulaToken::TOKEN_SUBTYPE_STOP); $tokens1[] = $tmp; ++$index; continue; } // token accumulation $value .= $this->formula[$index]; ++$index; } // dump remaining accumulation if ($value !== '') { $tokens1[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_OPERAND); } // move tokenList to new set, excluding unnecessary white-space tokens and converting necessary ones to intersections $tokenCount = count($tokens1); for ($i = 0; $i < $tokenCount; ++$i) { $token = $tokens1[$i]; $previousToken = $tokens1[$i - 1] ?? null; $nextToken = $tokens1[$i + 1] ?? null; if ($token->getTokenType() != FormulaToken::TOKEN_TYPE_WHITESPACE) { $tokens2[] = $token; continue; } if ($previousToken === null) { continue; } if ( !( (($previousToken->getTokenType() == FormulaToken::TOKEN_TYPE_FUNCTION) && ($previousToken->getTokenSubType() == FormulaToken::TOKEN_SUBTYPE_STOP)) || (($previousToken->getTokenType() == FormulaToken::TOKEN_TYPE_SUBEXPRESSION) && ($previousToken->getTokenSubType() == FormulaToken::TOKEN_SUBTYPE_STOP)) || ($previousToken->getTokenType() == FormulaToken::TOKEN_TYPE_OPERAND) ) ) { continue; } if ($nextToken === null) { continue; } if ( !( (($nextToken->getTokenType() == FormulaToken::TOKEN_TYPE_FUNCTION) && ($nextToken->getTokenSubType() == FormulaToken::TOKEN_SUBTYPE_START)) || (($nextToken->getTokenType() == FormulaToken::TOKEN_TYPE_SUBEXPRESSION) && ($nextToken->getTokenSubType() == FormulaToken::TOKEN_SUBTYPE_START)) || ($nextToken->getTokenType() == FormulaToken::TOKEN_TYPE_OPERAND) ) ) { continue; } $tokens2[] = new FormulaToken($value, FormulaToken::TOKEN_TYPE_OPERATORINFIX, FormulaToken::TOKEN_SUBTYPE_INTERSECTION); } // move tokens to final list, switching infix "-" operators to prefix when appropriate, switching infix "+" operators // to noop when appropriate, identifying operand and infix-operator subtypes, and pulling "@" from function names $this->tokens = []; $tokenCount = count($tokens2); for ($i = 0; $i < $tokenCount; ++$i) { $token = $tokens2[$i]; $previousToken = $tokens2[$i - 1] ?? null; if ($token->getTokenType() == FormulaToken::TOKEN_TYPE_OPERATORINFIX && $token->getValue() == '-') { if ($i == 0) { $token->setTokenType(FormulaToken::TOKEN_TYPE_OPERATORPREFIX); } elseif ( (($previousToken?->getTokenType() == FormulaToken::TOKEN_TYPE_FUNCTION) && ($previousToken?->getTokenSubType() == FormulaToken::TOKEN_SUBTYPE_STOP)) || (($previousToken?->getTokenType() == FormulaToken::TOKEN_TYPE_SUBEXPRESSION) && ($previousToken?->getTokenSubType() == FormulaToken::TOKEN_SUBTYPE_STOP)) || ($previousToken?->getTokenType() == FormulaToken::TOKEN_TYPE_OPERATORPOSTFIX) || ($previousToken?->getTokenType() == FormulaToken::TOKEN_TYPE_OPERAND) ) { $token->setTokenSubType(FormulaToken::TOKEN_SUBTYPE_MATH); } else { $token->setTokenType(FormulaToken::TOKEN_TYPE_OPERATORPREFIX); } $this->tokens[] = $token; continue; } if ($token->getTokenType() == FormulaToken::TOKEN_TYPE_OPERATORINFIX && $token->getValue() == '+') { if ($i == 0) { continue; } elseif ( (($previousToken?->getTokenType() == FormulaToken::TOKEN_TYPE_FUNCTION) && ($previousToken?->getTokenSubType() == FormulaToken::TOKEN_SUBTYPE_STOP)) || (($previousToken?->getTokenType() == FormulaToken::TOKEN_TYPE_SUBEXPRESSION) && ($previousToken?->getTokenSubType() == FormulaToken::TOKEN_SUBTYPE_STOP)) || ($previousToken?->getTokenType() == FormulaToken::TOKEN_TYPE_OPERATORPOSTFIX) || ($previousToken?->getTokenType() == FormulaToken::TOKEN_TYPE_OPERAND) ) { $token->setTokenSubType(FormulaToken::TOKEN_SUBTYPE_MATH); } else { continue; } $this->tokens[] = $token; continue; } if ( $token->getTokenType() == FormulaToken::TOKEN_TYPE_OPERATORINFIX && $token->getTokenSubType() == FormulaToken::TOKEN_SUBTYPE_NOTHING ) { if (str_contains('<>=', substr($token->getValue(), 0, 1))) { $token->setTokenSubType(FormulaToken::TOKEN_SUBTYPE_LOGICAL); } elseif ($token->getValue() == '&') { $token->setTokenSubType(FormulaToken::TOKEN_SUBTYPE_CONCATENATION); } else { $token->setTokenSubType(FormulaToken::TOKEN_SUBTYPE_MATH); } $this->tokens[] = $token; continue; } if ( $token->getTokenType() == FormulaToken::TOKEN_TYPE_OPERAND && $token->getTokenSubType() == FormulaToken::TOKEN_SUBTYPE_NOTHING ) { if (!is_numeric($token->getValue())) { if (strtoupper($token->getValue()) == 'TRUE' || strtoupper($token->getValue()) == 'FALSE') { $token->setTokenSubType(FormulaToken::TOKEN_SUBTYPE_LOGICAL); } else { $token->setTokenSubType(FormulaToken::TOKEN_SUBTYPE_RANGE); } } else { $token->setTokenSubType(FormulaToken::TOKEN_SUBTYPE_NUMBER); } $this->tokens[] = $token; continue; } if ($token->getTokenType() == FormulaToken::TOKEN_TYPE_FUNCTION) { if ($token->getValue() !== '') { if (str_starts_with($token->getValue(), '@')) { $token->setValue(substr($token->getValue(), 1)); } } } $this->tokens[] = $token; } } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Calculation/BinaryComparison.php
src/PhpSpreadsheet/Calculation/BinaryComparison.php
<?php namespace PhpOffice\PhpSpreadsheet\Calculation; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; class BinaryComparison { /** * Epsilon Precision used for comparisons in calculations. */ private const DELTA = 0.1e-12; /** * Compare two strings in the same way as strcmp() except that lowercase come before uppercase letters. * * @param mixed $str1 First string value for the comparison, expect ?string * @param mixed $str2 Second string value for the comparison, expect ?string */ private static function strcmpLowercaseFirst(mixed $str1, mixed $str2): int { $str1 = StringHelper::convertToString($str1); $str2 = StringHelper::convertToString($str2); $inversedStr1 = StringHelper::strCaseReverse($str1); $inversedStr2 = StringHelper::strCaseReverse($str2); return strcmp($inversedStr1, $inversedStr2); } /** * PHP8.1 deprecates passing null to strcmp. * * @param mixed $str1 First string value for the comparison, expect ?string * @param mixed $str2 Second string value for the comparison, expect ?string */ private static function strcmpAllowNull(mixed $str1, mixed $str2): int { $str1 = StringHelper::convertToString($str1); $str2 = StringHelper::convertToString($str2); return strcmp($str1, $str2); } public static function compare(mixed $operand1, mixed $operand2, string $operator): bool { // Simple validate the two operands if they are string values if (is_string($operand1) && $operand1 > '' && $operand1[0] == Calculation::FORMULA_STRING_QUOTE) { $operand1 = Calculation::unwrapResult($operand1); } if (is_string($operand2) && $operand2 > '' && $operand2[0] == Calculation::FORMULA_STRING_QUOTE) { $operand2 = Calculation::unwrapResult($operand2); } // Use case-insensitive comparison if not OpenOffice mode if (Functions::getCompatibilityMode() != Functions::COMPATIBILITY_OPENOFFICE) { if (is_string($operand1)) { $operand1 = StringHelper::strToUpper($operand1); } if (is_string($operand2)) { $operand2 = StringHelper::strToUpper($operand2); } } $useLowercaseFirstComparison = is_string($operand1) && is_string($operand2) && Functions::getCompatibilityMode() === Functions::COMPATIBILITY_OPENOFFICE; return self::evaluateComparison($operand1, $operand2, $operator, $useLowercaseFirstComparison); } private static function evaluateComparison(mixed $operand1, mixed $operand2, string $operator, bool $useLowercaseFirstComparison): bool { return match ($operator) { '=' => self::equal($operand1, $operand2), '>' => self::greaterThan($operand1, $operand2, $useLowercaseFirstComparison), '<' => self::lessThan($operand1, $operand2, $useLowercaseFirstComparison), '>=' => self::greaterThanOrEqual($operand1, $operand2, $useLowercaseFirstComparison), '<=' => self::lessThanOrEqual($operand1, $operand2, $useLowercaseFirstComparison), '<>' => self::notEqual($operand1, $operand2), default => throw new Exception('Unsupported binary comparison operator'), }; } private static function equal(mixed $operand1, mixed $operand2): bool { if (is_numeric($operand1) && is_numeric($operand2)) { $result = (abs($operand1 - $operand2) < self::DELTA); } elseif (($operand1 === null && is_numeric($operand2)) || ($operand2 === null && is_numeric($operand1))) { $result = $operand1 == $operand2; } else { $result = self::strcmpAllowNull($operand1, $operand2) == 0; } return $result; } private static function greaterThanOrEqual(mixed $operand1, mixed $operand2, bool $useLowercaseFirstComparison): bool { if (is_numeric($operand1) && is_numeric($operand2)) { $result = ((abs($operand1 - $operand2) < self::DELTA) || ($operand1 > $operand2)); } elseif (($operand1 === null && is_numeric($operand2)) || ($operand2 === null && is_numeric($operand1))) { $result = $operand1 >= $operand2; } elseif ($useLowercaseFirstComparison) { $result = self::strcmpLowercaseFirst($operand1, $operand2) >= 0; } else { $result = self::strcmpAllowNull($operand1, $operand2) >= 0; } return $result; } private static function lessThanOrEqual(mixed $operand1, mixed $operand2, bool $useLowercaseFirstComparison): bool { if (is_numeric($operand1) && is_numeric($operand2)) { $result = ((abs($operand1 - $operand2) < self::DELTA) || ($operand1 < $operand2)); } elseif (($operand1 === null && is_numeric($operand2)) || ($operand2 === null && is_numeric($operand1))) { $result = $operand1 <= $operand2; } elseif ($useLowercaseFirstComparison) { $result = self::strcmpLowercaseFirst($operand1, $operand2) <= 0; } else { $result = self::strcmpAllowNull($operand1, $operand2) <= 0; } return $result; } private static function greaterThan(mixed $operand1, mixed $operand2, bool $useLowercaseFirstComparison): bool { return self::lessThanOrEqual($operand1, $operand2, $useLowercaseFirstComparison) !== true; } private static function lessThan(mixed $operand1, mixed $operand2, bool $useLowercaseFirstComparison): bool { return self::greaterThanOrEqual($operand1, $operand2, $useLowercaseFirstComparison) !== true; } private static function notEqual(mixed $operand1, mixed $operand2): bool { return self::equal($operand1, $operand2) !== true; } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Calculation/LookupRef/Address.php
src/PhpSpreadsheet/Calculation/LookupRef/Address.php
<?php namespace PhpOffice\PhpSpreadsheet\Calculation\LookupRef; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Cell\AddressHelper; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; class Address { use ArrayEnabled; public const ADDRESS_ABSOLUTE = 1; public const ADDRESS_COLUMN_RELATIVE = 2; public const ADDRESS_ROW_RELATIVE = 3; public const ADDRESS_RELATIVE = 4; public const REFERENCE_STYLE_A1 = true; public const REFERENCE_STYLE_R1C1 = false; /** * ADDRESS. * * Creates a cell address as text, given specified row and column numbers. * * Excel Function: * =ADDRESS(row, column, [relativity], [referenceStyle], [sheetText]) * * @param mixed $row Row number (integer) to use in the cell reference * Or can be an array of values * @param mixed $column Column number (integer) to use in the cell reference * Or can be an array of values * @param mixed $relativity Integer flag indicating the type of reference to return * 1 or omitted Absolute * 2 Absolute row; relative column * 3 Relative row; absolute column * 4 Relative * Or can be an array of values * @param mixed $referenceStyle A logical (boolean) value that specifies the A1 or R1C1 reference style. * TRUE or omitted ADDRESS returns an A1-style reference * FALSE ADDRESS returns an R1C1-style reference * Or can be an array of values * @param mixed $sheetName Optional Name of worksheet to use * Or can be an array of values * * @return mixed[]|string If an array of values is passed as the $testValue argument, then the returned result will also be * an array with the same dimensions */ public static function cell(mixed $row, mixed $column, mixed $relativity = 1, mixed $referenceStyle = true, mixed $sheetName = ''): array|string { if ( is_array($row) || is_array($column) || is_array($relativity) || is_array($referenceStyle) || is_array($sheetName) ) { return self::evaluateArrayArguments( [self::class, __FUNCTION__], $row, $column, $relativity, $referenceStyle, $sheetName ); } $relativity = ($relativity === null) ? 1 : (int) StringHelper::convertToString($relativity); $referenceStyle = $referenceStyle ?? true; $row = (int) StringHelper::convertToString($row); $column = (int) StringHelper::convertToString($column); if (($row < 1) || ($column < 1)) { return ExcelError::VALUE(); } $sheetName = self::sheetName(StringHelper::convertToString($sheetName)); if (is_int($referenceStyle)) { $referenceStyle = (bool) $referenceStyle; } if ((!is_bool($referenceStyle)) || $referenceStyle === self::REFERENCE_STYLE_A1) { return self::formatAsA1($row, $column, $relativity, $sheetName); } return self::formatAsR1C1($row, $column, $relativity, $sheetName); } private static function sheetName(string $sheetName): string { if ($sheetName > '') { if (str_contains($sheetName, ' ') || str_contains($sheetName, '[')) { $sheetName = "'{$sheetName}'"; } $sheetName .= '!'; } return $sheetName; } private static function formatAsA1(int $row, int $column, int $relativity, string $sheetName): string { $rowRelative = $columnRelative = '$'; if (($relativity == self::ADDRESS_COLUMN_RELATIVE) || ($relativity == self::ADDRESS_RELATIVE)) { $columnRelative = ''; } if (($relativity == self::ADDRESS_ROW_RELATIVE) || ($relativity == self::ADDRESS_RELATIVE)) { $rowRelative = ''; } $column = Coordinate::stringFromColumnIndex($column); return "{$sheetName}{$columnRelative}{$column}{$rowRelative}{$row}"; } private static function formatAsR1C1(int $row, int $column, int $relativity, string $sheetName): string { if (($relativity == self::ADDRESS_COLUMN_RELATIVE) || ($relativity == self::ADDRESS_RELATIVE)) { $column = "[{$column}]"; } if (($relativity == self::ADDRESS_ROW_RELATIVE) || ($relativity == self::ADDRESS_RELATIVE)) { $row = "[{$row}]"; } [$rowChar, $colChar] = AddressHelper::getRowAndColumnChars(); return "{$sheetName}$rowChar{$row}$colChar{$column}"; } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Calculation/LookupRef/ExcelMatch.php
src/PhpSpreadsheet/Calculation/LookupRef/ExcelMatch.php
<?php namespace PhpOffice\PhpSpreadsheet\Calculation\LookupRef; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Calculation\Internal\WildcardMatch; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; class ExcelMatch { use ArrayEnabled; public const MATCHTYPE_SMALLEST_VALUE = -1; public const MATCHTYPE_FIRST_VALUE = 0; public const MATCHTYPE_LARGEST_VALUE = 1; /** * MATCH. * * The MATCH function searches for a specified item in a range of cells * * Excel Function: * =MATCH(lookup_value, lookup_array, [match_type]) * * @param mixed $lookupValue The value that you want to match in lookup_array * @param mixed $lookupArray The range of cells being searched * @param mixed $matchType The number -1, 0, or 1. -1 means above, 0 means exact match, 1 means below. * If match_type is 1 or -1, the list has to be ordered. * * @return array<mixed>|float|int|string The relative position of the found item */ public static function MATCH(mixed $lookupValue, mixed $lookupArray, mixed $matchType = self::MATCHTYPE_LARGEST_VALUE): array|string|int|float { if (is_array($lookupValue)) { return self::evaluateArrayArgumentsIgnore([self::class, __FUNCTION__], 1, $lookupValue, $lookupArray, $matchType); } $lookupArray = Functions::flattenArray($lookupArray); try { // Input validation self::validateLookupValue($lookupValue); $matchType = self::validateMatchType($matchType); self::validateLookupArray($lookupArray); $keySet = array_keys($lookupArray); if ($matchType == self::MATCHTYPE_LARGEST_VALUE) { // If match_type is 1 the list has to be processed from last to first $lookupArray = array_reverse($lookupArray); $keySet = array_reverse($keySet); } $lookupArray = self::prepareLookupArray($lookupArray, $matchType); } catch (Exception $e) { return $e->getMessage(); } // MATCH() is not case-sensitive, so we convert lookup value to be lower cased if it's a string type. if (is_string($lookupValue)) { $lookupValue = StringHelper::strToLower($lookupValue); } $valueKey = match ($matchType) { self::MATCHTYPE_LARGEST_VALUE => self::matchLargestValue($lookupArray, $lookupValue, $keySet), self::MATCHTYPE_FIRST_VALUE => self::matchFirstValue($lookupArray, $lookupValue), default => self::matchSmallestValue($lookupArray, $lookupValue), }; if ($valueKey !== null) { return ++$valueKey; //* @phpstan-ignore-line } // Unsuccessful in finding a match, return #N/A error value return ExcelError::NA(); } /** @param mixed[] $lookupArray */ private static function matchFirstValue(array $lookupArray, mixed $lookupValue): int|string|null { if (is_string($lookupValue)) { $valueIsString = true; $wildcard = WildcardMatch::wildcard($lookupValue); } else { $valueIsString = false; $wildcard = ''; } $valueIsNumeric = is_int($lookupValue) || is_float($lookupValue); foreach ($lookupArray as $i => $lookupArrayValue) { if ( $valueIsString && is_string($lookupArrayValue) ) { if (WildcardMatch::compare($lookupArrayValue, $wildcard)) { return $i; // wildcard match } } else { if ($lookupArrayValue === $lookupValue) { return $i; // exact match } if ( $valueIsNumeric && (is_float($lookupArrayValue) || is_int($lookupArrayValue)) && $lookupArrayValue == $lookupValue ) { return $i; // exact match } } } return null; } /** * @param mixed[] $lookupArray * @param mixed[] $keySet */ private static function matchLargestValue(array $lookupArray, mixed $lookupValue, array $keySet): mixed { if (is_string($lookupValue)) { if (Functions::getCompatibilityMode() === Functions::COMPATIBILITY_OPENOFFICE) { $wildcard = WildcardMatch::wildcard($lookupValue); foreach (array_reverse($lookupArray) as $i => $lookupArrayValue) { if (is_string($lookupArrayValue) && WildcardMatch::compare($lookupArrayValue, $wildcard)) { return $i; } } } else { foreach ($lookupArray as $i => $lookupArrayValue) { if ($lookupArrayValue === $lookupValue) { return $keySet[$i]; } } } } $valueIsNumeric = is_int($lookupValue) || is_float($lookupValue); foreach ($lookupArray as $i => $lookupArrayValue) { if ($valueIsNumeric && (is_int($lookupArrayValue) || is_float($lookupArrayValue))) { if ($lookupArrayValue <= $lookupValue) { return array_search($i, $keySet); } } $typeMatch = gettype($lookupValue) === gettype($lookupArrayValue); if ($typeMatch && ($lookupArrayValue <= $lookupValue)) { return array_search($i, $keySet); } } return null; } /** @param mixed[] $lookupArray */ private static function matchSmallestValue(array $lookupArray, mixed $lookupValue): int|string|null { $valueKey = null; if (is_string($lookupValue)) { if (Functions::getCompatibilityMode() === Functions::COMPATIBILITY_OPENOFFICE) { $wildcard = WildcardMatch::wildcard($lookupValue); foreach ($lookupArray as $i => $lookupArrayValue) { if (is_string($lookupArrayValue) && WildcardMatch::compare($lookupArrayValue, $wildcard)) { return $i; } } } } $valueIsNumeric = is_int($lookupValue) || is_float($lookupValue); // The basic algorithm is: // Iterate and keep the highest match until the next element is smaller than the searched value. // Return immediately if perfect match is found foreach ($lookupArray as $i => $lookupArrayValue) { $typeMatch = gettype($lookupValue) === gettype($lookupArrayValue); $bothNumeric = $valueIsNumeric && (is_int($lookupArrayValue) || is_float($lookupArrayValue)); if ($lookupArrayValue === $lookupValue) { // Another "special" case. If a perfect match is found, // the algorithm gives up immediately return $i; } if ($bothNumeric && $lookupValue == $lookupArrayValue) { return $i; // exact match, as above } if (($typeMatch || $bothNumeric) && $lookupArrayValue >= $lookupValue) { $valueKey = $i; } elseif ($typeMatch && $lookupArrayValue < $lookupValue) { //Excel algorithm gives up immediately if the first element is smaller than the searched value break; } } return $valueKey; } private static function validateLookupValue(mixed $lookupValue): void { // Lookup_value type has to be number, text, or logical values if ((!is_numeric($lookupValue)) && (!is_string($lookupValue)) && (!is_bool($lookupValue))) { throw new Exception(ExcelError::NA()); } } private static function validateMatchType(mixed $matchType): int { // Match_type is 0, 1 or -1 // However Excel accepts other numeric values, // including numeric strings and floats. // It seems to just be interested in the sign. if (!is_numeric($matchType)) { throw new Exception(ExcelError::Value()); } if ($matchType > 0) { return self::MATCHTYPE_LARGEST_VALUE; } if ($matchType < 0) { return self::MATCHTYPE_SMALLEST_VALUE; } return self::MATCHTYPE_FIRST_VALUE; } /** @param mixed[] $lookupArray */ private static function validateLookupArray(array $lookupArray): void { // Lookup_array should not be empty $lookupArraySize = count($lookupArray); if ($lookupArraySize <= 0) { throw new Exception(ExcelError::NA()); } } /** * @param mixed[] $lookupArray * * @return mixed[] */ private static function prepareLookupArray(array $lookupArray, mixed $matchType): array { // Lookup_array should contain only number, text, or logical values, or empty (null) cells foreach ($lookupArray as $i => $value) { // check the type of the value if ((!is_numeric($value)) && (!is_string($value)) && (!is_bool($value)) && ($value !== null)) { throw new Exception(ExcelError::NA()); } // Convert strings to lowercase for case-insensitive testing if (is_string($value)) { $lookupArray[$i] = StringHelper::strToLower($value); } if ( ($value === null) && (($matchType == self::MATCHTYPE_LARGEST_VALUE) || ($matchType == self::MATCHTYPE_SMALLEST_VALUE)) ) { unset($lookupArray[$i]); } } return $lookupArray; } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Calculation/LookupRef/LookupBase.php
src/PhpSpreadsheet/Calculation/LookupRef/LookupBase.php
<?php namespace PhpOffice\PhpSpreadsheet\Calculation\LookupRef; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; abstract class LookupBase { protected static function validateLookupArray(mixed $lookupArray): void { if (!is_array($lookupArray)) { throw new Exception(ExcelError::REF()); } } /** * @param mixed[] $lookupArray * @param float|int|string $index_number number >= 1 */ protected static function validateIndexLookup(array $lookupArray, $index_number): int { // index_number must be a number greater than or equal to 1. // Excel results are inconsistent when index is non-numeric. // VLOOKUP(whatever, whatever, SQRT(-1)) yields NUM error, but // VLOOKUP(whatever, whatever, cellref) yields REF error // when cellref is '=SQRT(-1)'. So just try our best here. // Similar results if string (literal yields VALUE, cellRef REF). if (!is_numeric($index_number)) { throw new Exception(ExcelError::throwError($index_number)); } if ($index_number < 1) { throw new Exception(ExcelError::VALUE()); } // index_number must be less than or equal to the number of columns in lookupArray if (empty($lookupArray)) { throw new Exception(ExcelError::REF()); } return (int) $index_number; } protected static function checkMatch( bool $bothNumeric, bool $bothNotNumeric, bool $notExactMatch, int $rowKey, string $cellDataLower, string $lookupLower, ?int $rowNumber ): ?int { // remember the last key, but only if datatypes match if ($bothNumeric || $bothNotNumeric) { // Spreadsheets software returns first exact match, // we have sorted and we might have broken key orders // we want the first one (by its initial index) if ($notExactMatch) { $rowNumber = $rowKey; } elseif (($cellDataLower == $lookupLower) && (($rowNumber === null) || ($rowKey < $rowNumber))) { $rowNumber = $rowKey; } } return $rowNumber; } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Calculation/LookupRef/ChooseRowsEtc.php
src/PhpSpreadsheet/Calculation/LookupRef/ChooseRowsEtc.php
<?php namespace PhpOffice\PhpSpreadsheet\Calculation\LookupRef; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class ChooseRowsEtc { /** * Transpose 2-dimensional array. * See https://stackoverflow.com/questions/797251/transposing-multidimensional-arrays-in-php * especially the comment from user17994717. * * @param mixed[] $array * * @return mixed[] */ public static function transpose(array $array): array { return empty($array) ? [] : (array_map((count($array) === 1) ? (fn ($x) => [$x]) : null, ...$array)); // @phpstan-ignore-line } /** @return mixed[] */ private static function arrayValues(mixed $array): array { return is_array($array) ? array_values($array) : [$array]; } /** * CHOOSECOLS. * * @param mixed $input expecting two-dimensional array * * @return mixed[]|string */ public static function chooseCols(mixed $input, mixed ...$args): array|string { if (!is_array($input)) { $input = [[$input]]; } $retval = self::chooseRows(self::transpose($input), ...$args); return is_array($retval) ? self::transpose($retval) : $retval; } /** * CHOOSEROWS. * * @param mixed $input expecting two-dimensional array * * @return mixed[]|string */ public static function chooseRows(mixed $input, mixed ...$args): array|string { if (!is_array($input)) { $input = [[$input]]; } $inputArray = [[]]; // no row 0 $numRows = 0; foreach ($input as $inputRow) { $inputArray[] = self::arrayValues($inputRow); ++$numRows; } $outputArray = []; foreach (Functions::flattenArray2(...$args) as $arg) { if (!is_numeric($arg)) { return ExcelError::VALUE(); } $index = (int) $arg; if ($index < 0) { $index += $numRows + 1; } if ($index <= 0 || $index > $numRows) { return ExcelError::VALUE(); } $outputArray[] = $inputArray[$index]; } return $outputArray; } /** * @param mixed[] $array * * @return mixed[]|string */ private static function dropRows(array $array, mixed $offset): array|string { if ($offset === null) { return $array; } if (!is_numeric($offset)) { return ExcelError::VALUE(); } $offset = (int) $offset; $count = count($array); if (abs($offset) >= $count) { // In theory, this should be #CALC!, but Excel treats // #CALC! as corrupt, and it's not worth figuring out why return ExcelError::VALUE(); } if ($offset === 0) { return $array; } if ($offset > 0) { return array_slice($array, $offset); } return array_slice($array, 0, $count + $offset); } /** * DROP. * * @param mixed $input expect two-dimensional array * * @return mixed[]|string */ public static function drop(mixed $input, mixed $rows = null, mixed $columns = null): array|string { if (!is_array($input)) { $input = [[$input]]; } $inputArray = []; // no row 0 foreach ($input as $inputRow) { $inputArray[] = self::arrayValues($inputRow); } $outputArray1 = self::dropRows($inputArray, $rows); if (is_string($outputArray1)) { return $outputArray1; } $outputArray2 = self::transpose($outputArray1); $outputArray3 = self::dropRows($outputArray2, $columns); if (is_string($outputArray3)) { return $outputArray3; } return self::transpose($outputArray3); } /** * @param mixed[] $array * * @return mixed[]|string */ private static function takeRows(array $array, mixed $offset): array|string { if ($offset === null) { return $array; } if (!is_numeric($offset)) { return ExcelError::VALUE(); } $offset = (int) $offset; if ($offset === 0) { // should be #CALC! - see above return ExcelError::VALUE(); } $count = count($array); if (abs($offset) >= $count) { return $array; } if ($offset > 0) { return array_slice($array, 0, $offset); } return array_slice($array, $count + $offset); } /** * TAKE. * * @param mixed $input expecting two-dimensional array * * @return mixed[]|string */ public static function take(mixed $input, mixed $rows, mixed $columns = null): array|string { if (!is_array($input)) { $input = [[$input]]; } if ($rows === null && $columns === null) { return $input; } $inputArray = []; foreach ($input as $inputRow) { $inputArray[] = self::arrayValues($inputRow); } $outputArray1 = self::takeRows($inputArray, $rows); if (is_string($outputArray1)) { return $outputArray1; } $outputArray2 = self::transpose($outputArray1); $outputArray3 = self::takeRows($outputArray2, $columns); if (is_string($outputArray3)) { return $outputArray3; } return self::transpose($outputArray3); } /** * EXPAND. * * @param mixed $input expecting two-dimensional array * * @return mixed[]|string */ public static function expand(mixed $input, mixed $rows, mixed $columns = null, mixed $pad = '#N/A'): array|string { if (!is_array($input)) { $input = [[$input]]; } if ($rows === null && $columns === null) { return $input; } $numRows = count($input); $rows ??= $numRows; if (!is_numeric($rows)) { return ExcelError::VALUE(); } $rows = (int) $rows; if ($rows < count($input)) { return ExcelError::VALUE(); } $numCols = 0; foreach ($input as $inputRow) { $numCols = max($numCols, is_array($inputRow) ? count($inputRow) : 1); } $columns ??= $numCols; if (!is_numeric($columns)) { return ExcelError::VALUE(); } $columns = (int) $columns; if ($columns < $numCols) { return ExcelError::VALUE(); } $inputArray = []; foreach ($input as $inputRow) { $inputArray[] = array_pad(self::arrayValues($inputRow), $columns, $pad); } $outputArray = []; $padRow = array_pad([], $columns, $pad); for ($count = 0; $count < $rows; ++$count) { $outputArray[] = ($count >= $numRows) ? $padRow : $inputArray[$count]; } return $outputArray; } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Calculation/LookupRef/Offset.php
src/PhpSpreadsheet/Calculation/LookupRef/Offset.php
<?php namespace PhpOffice\PhpSpreadsheet\Calculation\LookupRef; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Cell\Cell; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Worksheet\Validations; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; class Offset { /** * OFFSET. * * Returns a reference to a range that is a specified number of rows and columns from a cell or range of cells. * The reference that is returned can be a single cell or a range of cells. You can specify the number of rows and * the number of columns to be returned. * * Excel Function: * =OFFSET(cellAddress, rows, cols, [height], [width]) * * @param null|string $cellAddress The reference from which you want to base the offset. * Reference must refer to a cell or range of adjacent cells; * otherwise, OFFSET returns the #VALUE! error value. * @param int $rows The number of rows, up or down, that you want the upper-left cell to refer to. * Using 5 as the rows argument specifies that the upper-left cell in the * reference is five rows below reference. Rows can be positive (which means * below the starting reference) or negative (which means above the starting * reference). * @param int $columns The number of columns, to the left or right, that you want the upper-left cell * of the result to refer to. Using 5 as the cols argument specifies that the * upper-left cell in the reference is five columns to the right of reference. * Cols can be positive (which means to the right of the starting reference) * or negative (which means to the left of the starting reference). * @param ?int $height The height, in number of rows, that you want the returned reference to be. * Height must be a positive number. * @param ?int $width The width, in number of columns, that you want the returned reference to be. * Width must be a positive number. * * @return array<mixed>|string An array containing a cell or range of cells, or a string on error */ public static function OFFSET(?string $cellAddress = null, $rows = 0, $columns = 0, $height = null, $width = null, ?Cell $cell = null): string|array { /** @var int */ $rows = Functions::flattenSingleValue($rows); /** @var int */ $columns = Functions::flattenSingleValue($columns); /** @var int */ $height = Functions::flattenSingleValue($height); /** @var int */ $width = Functions::flattenSingleValue($width); if ($cellAddress === null || $cellAddress === '') { return ExcelError::VALUE(); } if (!is_object($cell)) { return ExcelError::REF(); } $sheet = $cell->getParent()?->getParent(); // worksheet if ($sheet !== null) { $cellAddress = Validations::definedNameToCoordinate($cellAddress, $sheet); } [$cellAddress, $worksheet] = self::extractWorksheet($cellAddress, $cell); $startCell = $endCell = $cellAddress; if (strpos($cellAddress, ':')) { [$startCell, $endCell] = explode(':', $cellAddress); } [$startCellColumn, $startCellRow] = Coordinate::indexesFromString($startCell); [, $endCellRow, $endCellColumn] = Coordinate::indexesFromString($endCell); $startCellRow += $rows; $startCellColumn += $columns - 1; if (($startCellRow <= 0) || ($startCellColumn < 0)) { return ExcelError::REF(); } $endCellColumn = self::adjustEndCellColumnForWidth($endCellColumn, $width, $startCellColumn, $columns); $startCellColumn = Coordinate::stringFromColumnIndex($startCellColumn + 1); $endCellRow = self::adjustEndCellRowForHeight($height, $startCellRow, $rows, $endCellRow); if (($endCellRow <= 0) || ($endCellColumn < 0)) { return ExcelError::REF(); } $endCellColumn = Coordinate::stringFromColumnIndex($endCellColumn + 1); $cellAddress = "{$startCellColumn}{$startCellRow}"; if (($startCellColumn != $endCellColumn) || ($startCellRow != $endCellRow)) { $cellAddress .= ":{$endCellColumn}{$endCellRow}"; } return self::extractRequiredCells($worksheet, $cellAddress); } /** @return mixed[] */ private static function extractRequiredCells(?Worksheet $worksheet, string $cellAddress): array { return Calculation::getInstance($worksheet?->getParent()) ->extractCellRange($cellAddress, $worksheet, false); } /** @return array{string, ?Worksheet} */ private static function extractWorksheet(?string $cellAddress, Cell $cell): array { $cellAddress = self::assessCellAddress($cellAddress ?? '', $cell); $sheetName = ''; if (str_contains($cellAddress, '!')) { [$sheetName, $cellAddress] = Worksheet::extractSheetTitle($cellAddress, true, true); } $worksheet = ($sheetName !== '') ? $cell->getWorksheet()->getParentOrThrow()->getSheetByName($sheetName) : $cell->getWorksheet(); return [$cellAddress, $worksheet]; } private static function assessCellAddress(string $cellAddress, Cell $cell): string { if (preg_match('/^' . Calculation::CALCULATION_REGEXP_DEFINEDNAME . '$/mui', $cellAddress) !== false) { $cellAddress = Functions::expandDefinedName($cellAddress, $cell); } return $cellAddress; } /** * @param null|object|scalar $width * @param scalar $columns */ private static function adjustEndCellColumnForWidth(string $endCellColumn, $width, int $startCellColumn, $columns): int { $endCellColumn = Coordinate::columnIndexFromString($endCellColumn) - 1; if (($width !== null) && (!is_object($width))) { $endCellColumn = $startCellColumn + (int) $width - 1; } else { $endCellColumn += (int) $columns; } return $endCellColumn; } /** * @param null|object|scalar $height * @param scalar $rows */ private static function adjustEndCellRowForHeight($height, int $startCellRow, $rows, int $endCellRow): int { if (($height !== null) && (!is_object($height))) { $endCellRow = $startCellRow + (int) $height - 1; } else { $endCellRow += (int) $rows; } return $endCellRow; } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Calculation/LookupRef/Formula.php
src/PhpSpreadsheet/Calculation/LookupRef/Formula.php
<?php namespace PhpOffice\PhpSpreadsheet\Calculation\LookupRef; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Cell\Cell; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; class Formula { /** * FORMULATEXT. * * @param mixed $cellReference The cell to check * @param ?Cell $cell The current cell (containing this formula) */ public static function text(mixed $cellReference = '', ?Cell $cell = null): string { if ($cell === null) { return ExcelError::REF(); } $worksheet = null; $cellReference = StringHelper::convertToString($cellReference); if (1 === preg_match('/^' . Calculation::CALCULATION_REGEXP_CELLREF . '$/i', $cellReference, $matches)) { $cellReference = $matches[6] . $matches[7]; $worksheetName = trim($matches[3], "'"); $worksheet = (!empty($worksheetName)) ? $cell->getWorksheet()->getParentOrThrow()->getSheetByName($worksheetName) : $cell->getWorksheet(); } if ( $worksheet === null || !$worksheet->cellExists($cellReference) || !$worksheet->getCell($cellReference)->isFormula() ) { return ExcelError::NA(); } return $worksheet->getCell($cellReference)->getValueString(); } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Calculation/LookupRef/Indirect.php
src/PhpSpreadsheet/Calculation/LookupRef/Indirect.php
<?php namespace PhpOffice\PhpSpreadsheet\Calculation\LookupRef; use Exception; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Cell\AddressRange; use PhpOffice\PhpSpreadsheet\Cell\Cell; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; class Indirect { /** * Determine whether cell address is in A1 (true) or R1C1 (false) format. * * @param mixed $a1fmt Expect bool Helpers::CELLADDRESS_USE_A1 or CELLADDRESS_USE_R1C1, * but can be provided as numeric which is cast to bool */ private static function a1Format(mixed $a1fmt): bool { $a1fmt = Functions::flattenSingleValue($a1fmt); if ($a1fmt === null) { return Helpers::CELLADDRESS_USE_A1; } if (is_string($a1fmt)) { throw new Exception(ExcelError::VALUE()); } return (bool) $a1fmt; } /** * Convert cellAddress to string, verify not null string. * * @param null|mixed[]|string $cellAddress */ private static function validateAddress(array|string|null $cellAddress): string { $cellAddress = Functions::flattenSingleValue($cellAddress); if (!is_string($cellAddress) || !$cellAddress) { throw new Exception(ExcelError::REF()); } return $cellAddress; } /** * INDIRECT. * * Returns the reference specified by a text string. * References are immediately evaluated to display their contents. * * Excel Function: * =INDIRECT(cellAddress, bool) where the bool argument is optional * * @param mixed[]|string $cellAddress $cellAddress The cell address of the current cell (containing this formula) * @param mixed $a1fmt Expect bool Helpers::CELLADDRESS_USE_A1 or CELLADDRESS_USE_R1C1, * but can be provided as numeric which is cast to bool * @param Cell $cell The current cell (containing this formula) * * @return mixed[]|string An array containing a cell or range of cells, or a string on error */ public static function INDIRECT($cellAddress, mixed $a1fmt, Cell $cell): string|array { [$baseCol, $baseRow] = Coordinate::indexesFromString($cell->getCoordinate()); try { $a1 = self::a1Format($a1fmt); $cellAddress = self::validateAddress($cellAddress); } catch (Exception $e) { return $e->getMessage(); } [$cellAddress, $worksheet, $sheetName] = Helpers::extractWorksheet($cellAddress, $cell); if (preg_match('/^' . Calculation::CALCULATION_REGEXP_COLUMNRANGE_RELATIVE . '$/miu', $cellAddress, $matches)) { $cellAddress = self::handleRowColumnRanges($worksheet, ...explode(':', $cellAddress)); } elseif (preg_match('/^' . Calculation::CALCULATION_REGEXP_ROWRANGE_RELATIVE . '$/miu', $cellAddress, $matches)) { $cellAddress = self::handleRowColumnRanges($worksheet, ...explode(':', $cellAddress)); } try { [$cellAddress1, $cellAddress2, $cellAddress] = Helpers::extractCellAddresses($cellAddress, $a1, $cell->getWorkSheet(), $sheetName, $baseRow, $baseCol); } catch (Exception) { return ExcelError::REF(); } if ( (!preg_match('/^' . Calculation::CALCULATION_REGEXP_CELLREF . '$/miu', $cellAddress1, $matches)) || (($cellAddress2 !== null) && (!preg_match('/^' . Calculation::CALCULATION_REGEXP_CELLREF . '$/miu', $cellAddress2, $matches))) ) { return ExcelError::REF(); } return self::extractRequiredCells($worksheet, $cellAddress); } /** * Extract range values. * * @return mixed[] Array of values in range if range contains more than one element. * Otherwise, a single value is returned. */ private static function extractRequiredCells(?Worksheet $worksheet, string $cellAddress): array { return Calculation::getInstance($worksheet?->getParent()) ->extractCellRange($cellAddress, $worksheet, false, createCell: true); } private static function handleRowColumnRanges(?Worksheet $worksheet, string $start, string $end): string { // Being lazy, we're only checking a single row/column to get the max if (ctype_digit($start) && $start <= 1048576) { // Max 16,384 columns for Excel2007 $endColRef = ($worksheet !== null) ? $worksheet->getHighestDataColumn((int) $start) : AddressRange::MAX_COLUMN; return "A{$start}:{$endColRef}{$end}"; } elseif (ctype_alpha($start) && strlen($start) <= 3) { // Max 1,048,576 rows for Excel2007 $endRowRef = ($worksheet !== null) ? $worksheet->getHighestDataRow($start) : AddressRange::MAX_ROW; return "{$start}1:{$end}{$endRowRef}"; } return "{$start}:{$end}"; } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Calculation/LookupRef/HLookup.php
src/PhpSpreadsheet/Calculation/LookupRef/HLookup.php
<?php namespace PhpOffice\PhpSpreadsheet\Calculation\LookupRef; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; class HLookup extends LookupBase { use ArrayEnabled; /** * HLOOKUP * The HLOOKUP function searches for value in the top-most row of lookup_array and returns the value * in the same column based on the index_number. * * @param mixed $lookupValue The value that you want to match in lookup_array * @param mixed[][] $lookupArray The range of cells being searched * @param array<mixed>|float|int|string $indexNumber The row number in table_array from which the matching value must be returned. * The first row is 1. * @param mixed $notExactMatch determines if you are looking for an exact match based on lookup_value * * @return mixed The value of the found cell */ public static function lookup(mixed $lookupValue, $lookupArray, $indexNumber, mixed $notExactMatch = true): mixed { if (is_array($lookupValue) || is_array($indexNumber)) { return self::evaluateArrayArgumentsIgnore([self::class, __FUNCTION__], 1, $lookupValue, $lookupArray, $indexNumber, $notExactMatch); } $notExactMatch = (bool) ($notExactMatch ?? true); try { self::validateLookupArray($lookupArray); $lookupArray = self::convertLiteralArray($lookupArray); $indexNumber = self::validateIndexLookup($lookupArray, $indexNumber); } catch (Exception $e) { return $e->getMessage(); } $f = array_keys($lookupArray); $firstRow = reset($f); if ((!is_array($lookupArray[$firstRow])) || ($indexNumber > count($lookupArray))) { return ExcelError::REF(); } $firstkey = $f[0] - 1; $returnColumn = $firstkey + $indexNumber; /** @var mixed[][] $lookupArray */ $firstColumn = array_shift($f) ?? 1; $rowNumber = self::hLookupSearch($lookupValue, $lookupArray, $firstColumn, $notExactMatch); if ($rowNumber !== null) { // otherwise return the appropriate value return $lookupArray[$returnColumn][Coordinate::stringFromColumnIndex($rowNumber)]; } return ExcelError::NA(); } /** * @param mixed $lookupValue The value that you want to match in lookup_array * @param mixed[][] $lookupArray * @param int|string $column */ private static function hLookupSearch(mixed $lookupValue, array $lookupArray, $column, bool $notExactMatch): ?int { $lookupLower = StringHelper::strToLower(StringHelper::convertToString($lookupValue)); $rowNumber = null; foreach ($lookupArray[$column] as $rowKey => $rowData) { // break if we have passed possible keys /** @var string $rowKey */ $bothNumeric = is_numeric($lookupValue) && is_numeric($rowData); $bothNotNumeric = !is_numeric($lookupValue) && !is_numeric($rowData); /** @var scalar $rowData */ $cellDataLower = StringHelper::strToLower((string) $rowData); if ( $notExactMatch && (($bothNumeric && $rowData > $lookupValue) || ($bothNotNumeric && $cellDataLower > $lookupLower)) ) { break; } $rowNumber = self::checkMatch( $bothNumeric, $bothNotNumeric, $notExactMatch, Coordinate::columnIndexFromString($rowKey), $cellDataLower, $lookupLower, $rowNumber ); } return $rowNumber; } /** * @param mixed[] $lookupArray * * @return mixed[] */ private static function convertLiteralArray(array $lookupArray): array { if (array_key_exists(0, $lookupArray)) { $lookupArray2 = []; $row = 0; foreach ($lookupArray as $arrayVal) { ++$row; if (!is_array($arrayVal)) { $arrayVal = [$arrayVal]; } $arrayVal2 = []; foreach ($arrayVal as $key2 => $val2) { $index = Coordinate::stringFromColumnIndex($key2 + 1); $arrayVal2[$index] = $val2; } $lookupArray2[$row] = $arrayVal2; } $lookupArray = $lookupArray2; } return $lookupArray; } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Calculation/LookupRef/Vstack.php
src/PhpSpreadsheet/Calculation/LookupRef/Vstack.php
<?php namespace PhpOffice\PhpSpreadsheet\Calculation\LookupRef; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Vstack { /** * Excel function VSTACK. * * @return mixed[] */ public static function vstack(mixed ...$inputData): array|string { $returnMatrix = []; $columns = 0; foreach ($inputData as $matrix) { if (!is_array($matrix)) { $count = 1; } else { $count = count(reset($matrix)); //* @phpstan-ignore-line } $columns = max($columns, $count); } foreach ($inputData as $matrix) { if (!is_array($matrix)) { $matrix = [$matrix]; } foreach ($matrix as $row) { if (!is_array($row)) { $row = [$row]; } $returnMatrix[] = array_values(array_pad($row, $columns, ExcelError::NA())); } } return $returnMatrix; } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Calculation/LookupRef/Lookup.php
src/PhpSpreadsheet/Calculation/LookupRef/Lookup.php
<?php namespace PhpOffice\PhpSpreadsheet\Calculation\LookupRef; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Lookup { use ArrayEnabled; /** * LOOKUP * The LOOKUP function searches for value either from a one-row or one-column range or from an array. * * @param mixed $lookupValue The value that you want to match in lookup_array * @param mixed $lookupVector The range of cells being searched * @param null|mixed $resultVector The column from which the matching value must be returned * * @return mixed The value of the found cell */ public static function lookup(mixed $lookupValue, mixed $lookupVector, $resultVector = null): mixed { if (is_array($lookupValue)) { return self::evaluateArrayArgumentsSubset([self::class, __FUNCTION__], 1, $lookupValue, $lookupVector, $resultVector); } if (!is_array($lookupVector)) { return ExcelError::NA(); } /** @var mixed[][] $lookupVector */ $hasResultVector = isset($resultVector); $lookupRows = self::rowCount($lookupVector); $lookupColumns = self::columnCount($lookupVector); // we correctly orient our results if (($lookupRows === 1 && $lookupColumns > 1) || (!$hasResultVector && $lookupRows === 2 && $lookupColumns !== 2)) { $lookupVector = Matrix::transpose($lookupVector); $lookupRows = self::rowCount($lookupVector); /** @var mixed[][] $lookupVector */ $lookupColumns = self::columnCount($lookupVector); } $resultVector = self::verifyResultVector($resultVector ?? $lookupVector); //* @phpstan-ignore-line if ($lookupRows === 2 && !$hasResultVector) { $resultVector = array_pop($lookupVector); $lookupVector = array_shift($lookupVector); } /** @var array<int, mixed> $lookupVector */ /** @var array<int, mixed> $resultVector */ if ($lookupColumns !== 2) { $lookupVector = self::verifyLookupValues($lookupVector, $resultVector); } return VLookup::lookup($lookupValue, $lookupVector, 2); } /** * @param array<int, mixed> $lookupVector * @param array<int, mixed> $resultVector * * @return mixed[] */ private static function verifyLookupValues(array $lookupVector, array $resultVector): array { foreach ($lookupVector as &$value) { if (is_array($value)) { $k = array_keys($value); $key1 = $key2 = array_shift($k); ++$key2; $dataValue1 = $value[$key1]; } else { $key1 = 0; $key2 = 1; $dataValue1 = $value; } $dataValue2 = array_shift($resultVector); if (is_array($dataValue2)) { $dataValue2 = array_shift($dataValue2); } /** @var int $key2 */ $value = [$key1 => $dataValue1, $key2 => $dataValue2]; } unset($value); return $lookupVector; } /** * @param mixed[][] $resultVector * * @return mixed[] */ private static function verifyResultVector(array $resultVector): array { $resultRows = self::rowCount($resultVector); $resultColumns = self::columnCount($resultVector); // we correctly orient our results if ($resultRows === 1 && $resultColumns > 1) { $resultVector = Matrix::transpose($resultVector); } return $resultVector; } /** @param mixed[] $dataArray */ private static function rowCount(array $dataArray): int { return count($dataArray); } /** @param mixed[][] $dataArray */ private static function columnCount(array $dataArray): int { $rowKeys = array_keys($dataArray); $row = array_shift($rowKeys); return count($dataArray[$row]); } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Calculation/LookupRef/Helpers.php
src/PhpSpreadsheet/Calculation/LookupRef/Helpers.php
<?php namespace PhpOffice\PhpSpreadsheet\Calculation\LookupRef; use PhpOffice\PhpSpreadsheet\Cell\AddressHelper; use PhpOffice\PhpSpreadsheet\Cell\Cell; use PhpOffice\PhpSpreadsheet\DefinedName; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; class Helpers { public const CELLADDRESS_USE_A1 = true; public const CELLADDRESS_USE_R1C1 = false; private static function convertR1C1(string &$cellAddress1, ?string &$cellAddress2, bool $a1, ?int $baseRow = null, ?int $baseCol = null): string { if ($a1 === self::CELLADDRESS_USE_R1C1) { $cellAddress1 = AddressHelper::convertToA1($cellAddress1, $baseRow ?? 1, $baseCol ?? 1); if ($cellAddress2) { $cellAddress2 = AddressHelper::convertToA1($cellAddress2, $baseRow ?? 1, $baseCol ?? 1); } } return $cellAddress1 . ($cellAddress2 ? ":$cellAddress2" : ''); } private static function adjustSheetTitle(string &$sheetTitle, ?string $value): void { if ($sheetTitle) { $sheetTitle .= '!'; if (stripos($value ?? '', $sheetTitle) === 0) { $sheetTitle = ''; } } } /** @return array{string, ?string, string} */ public static function extractCellAddresses(string $cellAddress, bool $a1, Worksheet $sheet, string $sheetName = '', ?int $baseRow = null, ?int $baseCol = null): array { $cellAddress1 = $cellAddress; $cellAddress2 = null; $namedRange = DefinedName::resolveName($cellAddress1, $sheet, $sheetName); if ($namedRange !== null) { $workSheet = $namedRange->getWorkSheet(); $sheetTitle = ($workSheet === null) ? '' : $workSheet->getTitle(); $value = (string) preg_replace('/^=/', '', $namedRange->getValue()); self::adjustSheetTitle($sheetTitle, $value); $cellAddress1 = $sheetTitle . $value; $cellAddress = $cellAddress1; $a1 = self::CELLADDRESS_USE_A1; } if (str_contains($cellAddress, ':')) { [$cellAddress1, $cellAddress2] = explode(':', $cellAddress); } $cellAddress = self::convertR1C1($cellAddress1, $cellAddress2, $a1, $baseRow, $baseCol); return [$cellAddress1, $cellAddress2, $cellAddress]; } /** @return array{string, ?Worksheet, string} */ public static function extractWorksheet(string $cellAddress, Cell $cell): array { $sheetName = ''; if (str_contains($cellAddress, '!')) { [$sheetName, $cellAddress] = Worksheet::extractSheetTitle($cellAddress, true, true); } $worksheet = ($sheetName !== '') ? $cell->getWorksheet()->getParentOrThrow()->getSheetByName($sheetName) : $cell->getWorksheet(); return [$cellAddress, $worksheet, $sheetName]; } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Calculation/LookupRef/Sort.php
src/PhpSpreadsheet/Calculation/LookupRef/Sort.php
<?php namespace PhpOffice\PhpSpreadsheet\Calculation\LookupRef; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; class Sort extends LookupRefValidations { public const ORDER_ASCENDING = 1; public const ORDER_DESCENDING = -1; /** * SORT * The SORT function returns a sorted array of the elements in an array. * The returned array is the same shape as the provided array argument. * Both $sortIndex and $sortOrder can be arrays, to provide multi-level sorting. * * NOTE: If $sortArray contains a mixture of data types * (string/int/bool), the results may be unexpected. * This is also true if the array consists of string * representations of numbers, especially if there are * both positive and negative numbers in the mix. * * @param mixed $sortArray The range of cells being sorted * @param mixed $sortIndex The column or row number within the sortArray to sort on * @param mixed $sortOrder Flag indicating whether to sort ascending or descending * Ascending = 1 (self::ORDER_ASCENDING) * Descending = -1 (self::ORDER_DESCENDING) * @param mixed $byColumn Whether the sort should be determined by row (the default) or by column * * @return mixed The sorted values from the sort range */ public static function sort(mixed $sortArray, mixed $sortIndex = 1, mixed $sortOrder = self::ORDER_ASCENDING, mixed $byColumn = false): mixed { if (!is_array($sortArray)) { $sortArray = [[$sortArray]]; } /** @var mixed[][] */ $sortArray = self::enumerateArrayKeys($sortArray); $byColumn = (bool) $byColumn; $lookupIndexSize = $byColumn ? count($sortArray) : count($sortArray[0]); try { // If $sortIndex and $sortOrder are scalars, then convert them into arrays if (!is_array($sortIndex)) { $sortIndex = [$sortIndex]; $sortOrder = is_scalar($sortOrder) ? [$sortOrder] : $sortOrder; } // but the values of those array arguments still need validation $sortOrder = (empty($sortOrder) ? [self::ORDER_ASCENDING] : $sortOrder); self::validateArrayArgumentsForSort($sortIndex, $sortOrder, $lookupIndexSize); } catch (Exception $e) { return $e->getMessage(); } // We want a simple, enumerated array of arrays where we can reference column by its index number. /** @var callable(mixed): mixed */ $temp = 'array_values'; /** @var array<int> $sortOrder */ $sortArray = array_values(array_map($temp, $sortArray)); /** @var int[] $sortIndex */ return ($byColumn === true) ? self::sortByColumn($sortArray, $sortIndex, $sortOrder) : self::sortByRow($sortArray, $sortIndex, $sortOrder); } /** * SORTBY * The SORTBY function sorts the contents of a range or array based on the values in a corresponding range or array. * The returned array is the same shape as the provided array argument. * Both $sortIndex and $sortOrder can be arrays, to provide multi-level sorting. * Microsoft doesn't even bother documenting that a column sort * is possible. However, it is. According to: * https://exceljet.net/functions/sortby-function * When by_array is a horizontal range, SORTBY sorts horizontally by columns. * My interpretation of this is that by_array must be an * array which contains exactly one row. * * NOTE: If the "byArray" contains a mixture of data types * (string/int/bool), the results may be unexpected. * This is also true if the array consists of string * representations of numbers, especially if there are * both positive and negative numbers in the mix. * * @param mixed $sortArray The range of cells being sorted * @param mixed $args * At least one additional argument must be provided, The vector or range to sort on * After that, arguments are passed as pairs: * sort order: ascending or descending * Ascending = 1 (self::ORDER_ASCENDING) * Descending = -1 (self::ORDER_DESCENDING) * additional arrays or ranges for multi-level sorting * * @return mixed The sorted values from the sort range */ public static function sortBy(mixed $sortArray, mixed ...$args): mixed { if (!is_array($sortArray)) { $sortArray = [[$sortArray]]; } $transpose = false; $args0 = $args[0] ?? null; if (is_array($args0) && count($args0) === 1) { $args0 = reset($args0); if (is_array($args0) && count($args0) > 1) { $transpose = true; $sortArray = Matrix::transpose($sortArray); } } $sortArray = self::enumerateArrayKeys($sortArray); $lookupArraySize = count($sortArray); $argumentCount = count($args); try { $sortBy = $sortOrder = []; for ($i = 0; $i < $argumentCount; $i += 2) { $argsI = $args[$i]; if (!is_array($argsI)) { $argsI = [[$argsI]]; } $sortBy[] = self::validateSortVector($argsI, $lookupArraySize); $sortOrder[] = self::validateSortOrder($args[$i + 1] ?? self::ORDER_ASCENDING); } } catch (Exception $e) { return $e->getMessage(); } $temp = self::processSortBy($sortArray, $sortBy, $sortOrder); if ($transpose) { $temp = Matrix::transpose($temp); } return $temp; } /** * @param mixed[] $sortArray * * @return mixed[] */ private static function enumerateArrayKeys(array $sortArray): array { array_walk( $sortArray, function (&$columns): void { if (is_array($columns)) { $columns = array_values($columns); } } ); return array_values($sortArray); } private static function validateScalarArgumentsForSort(mixed &$sortIndex, mixed &$sortOrder, int $sortArraySize): void { $sortIndex = self::validatePositiveInt($sortIndex, false); if ($sortIndex > $sortArraySize) { throw new Exception(ExcelError::VALUE()); } $sortOrder = self::validateSortOrder($sortOrder); } /** * @param mixed[] $sortVector * * @return mixed[] */ private static function validateSortVector(array $sortVector, int $sortArraySize): array { // It doesn't matter if it's a row or a column vectors, it works either way $sortVector = Functions::flattenArray($sortVector); if (count($sortVector) !== $sortArraySize) { throw new Exception(ExcelError::VALUE()); } return $sortVector; } private static function validateSortOrder(mixed $sortOrder): int { $sortOrder = self::validateInt($sortOrder); if (($sortOrder == self::ORDER_ASCENDING || $sortOrder === self::ORDER_DESCENDING) === false) { throw new Exception(ExcelError::VALUE()); } return $sortOrder; } /** @param mixed[] $sortIndex */ private static function validateArrayArgumentsForSort(array &$sortIndex, mixed &$sortOrder, int $sortArraySize): void { // It doesn't matter if they're row or column vectors, it works either way $sortIndex = Functions::flattenArray($sortIndex); $sortOrder = Functions::flattenArray($sortOrder); if ( count($sortOrder) === 0 || count($sortOrder) > $sortArraySize || (count($sortOrder) > count($sortIndex)) ) { throw new Exception(ExcelError::VALUE()); } if (count($sortIndex) > count($sortOrder)) { // If $sortOrder has fewer elements than $sortIndex, then the last order element is repeated. $sortOrder = array_merge( $sortOrder, array_fill(0, count($sortIndex) - count($sortOrder), array_pop($sortOrder)) ); } foreach ($sortIndex as $key => &$value) { self::validateScalarArgumentsForSort($value, $sortOrder[$key], $sortArraySize); } } /** * @param mixed[] $sortVector * * @return mixed[] */ private static function prepareSortVectorValues(array $sortVector): array { // Strings should be sorted case-insensitive. // Booleans are a complete mess. Excel always seems to sort // booleans in a mixed vector at either the top or the bottom, // so converting them to string or int doesn't really work. // Best advice is to use them in a boolean-only vector. // Code below chooses int conversion, which is sensible, // and, as a bonus, compatible with LibreOffice. return array_map( function ($value) { if (is_bool($value)) { return (int) $value; } if (is_string($value)) { return StringHelper::strToLower($value); } return $value; }, $sortVector ); } /** * @param mixed[] $sortArray * @param mixed[] $sortIndex * @param int[] $sortOrder * * @return mixed[] */ private static function processSortBy(array $sortArray, array $sortIndex, array $sortOrder): array { $sortArguments = []; /** @var mixed[] */ $sortData = []; foreach ($sortIndex as $index => $sortValues) { /** @var mixed[] $sortValues */ $sortData[] = $sortValues; $sortArguments[] = self::prepareSortVectorValues($sortValues); $sortArguments[] = $sortOrder[$index] === self::ORDER_ASCENDING ? SORT_ASC : SORT_DESC; } $sortVector = self::executeVectorSortQuery($sortData, $sortArguments); return self::sortLookupArrayFromVector($sortArray, $sortVector); } /** * @param mixed[] $sortArray * @param int[] $sortIndex * @param int[] $sortOrder * * @return mixed[] */ private static function sortByRow(array $sortArray, array $sortIndex, array $sortOrder): array { $sortVector = self::buildVectorForSort($sortArray, $sortIndex, $sortOrder); return self::sortLookupArrayFromVector($sortArray, $sortVector); } /** * @param mixed[] $sortArray * @param int[] $sortIndex * @param int[] $sortOrder * * @return mixed[] */ private static function sortByColumn(array $sortArray, array $sortIndex, array $sortOrder): array { $sortArray = Matrix::transpose($sortArray); $result = self::sortByRow($sortArray, $sortIndex, $sortOrder); return Matrix::transpose($result); } /** * @param mixed[] $sortArray * @param int[] $sortIndex * @param int[] $sortOrder * * @return mixed[] */ private static function buildVectorForSort(array $sortArray, array $sortIndex, array $sortOrder): array { $sortArguments = []; $sortData = []; foreach ($sortIndex as $index => $sortIndexValue) { $sortValues = array_column($sortArray, $sortIndexValue - 1); $sortData[] = $sortValues; $sortArguments[] = self::prepareSortVectorValues($sortValues); $sortArguments[] = $sortOrder[$index] === self::ORDER_ASCENDING ? SORT_ASC : SORT_DESC; } $sortData = self::executeVectorSortQuery($sortData, $sortArguments); return $sortData; } /** * @param mixed[] $sortData * @param mixed[] $sortArguments * * @return mixed[] */ private static function executeVectorSortQuery(array $sortData, array $sortArguments): array { $sortData = Matrix::transpose($sortData); // We need to set an index that can be retained, as array_multisort doesn't maintain numeric keys. $sortDataIndexed = []; foreach ($sortData as $key => $value) { $sortDataIndexed[Coordinate::stringFromColumnIndex($key + 1)] = $value; } unset($sortData); $sortArguments[] = &$sortDataIndexed; array_multisort(...$sortArguments); // After the sort, we restore the numeric keys that will now be in the correct, sorted order $sortedData = []; foreach (array_keys($sortDataIndexed) as $key) { $sortedData[] = Coordinate::columnIndexFromString($key) - 1; } return $sortedData; } /** * @param mixed[] $sortArray * @param mixed[] $sortVector * * @return mixed[] */ private static function sortLookupArrayFromVector(array $sortArray, array $sortVector): array { // Building a new array in the correct (sorted) order works; but may be memory heavy for larger arrays $sortedArray = []; foreach ($sortVector as $index) { /** @var int|string $index */ $sortedArray[] = $sortArray[$index]; } return $sortedArray; // uksort( // $lookupArray, // function (int $a, int $b) use (array $sortVector) { // return $sortVector[$a] <=> $sortVector[$b]; // } // ); // // return $lookupArray; } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Calculation/LookupRef/TorowTocol.php
src/PhpSpreadsheet/Calculation/LookupRef/TorowTocol.php
<?php namespace PhpOffice\PhpSpreadsheet\Calculation\LookupRef; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ErrorValue; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class TorowTocol { /** * Excel function TOCOL. * * @return mixed[]|string */ public static function tocol(mixed $array, mixed $ignore = 0, mixed $byColumn = false): array|string { $result = self::torow($array, $ignore, $byColumn); if (is_array($result)) { return array_map((fn ($x) => [$x]), $result); } return $result; } /** * Excel function TOROW. * * @return mixed[]|string */ public static function torow(mixed $array, mixed $ignore = 0, mixed $byColumn = false): array|string { if (!is_numeric($ignore)) { return ExcelError::VALUE(); } $ignore = (int) $ignore; if ($ignore < 0 || $ignore > 3) { return ExcelError::VALUE(); } if (is_int($byColumn) || is_float($byColumn)) { $byColumn = (bool) $byColumn; } if (!is_bool($byColumn)) { return ExcelError::VALUE(); } if (!is_array($array)) { $array = [$array]; } if ($byColumn) { $temp = []; foreach ($array as $row) { if (!is_array($row)) { $row = [$row]; } $temp[] = Functions::flattenArray($row); } $array = ChooseRowsEtc::transpose($temp); } else { $array = Functions::flattenArray($array); } return self::byRow($array, $ignore); } /** * @param mixed[] $array * * @return mixed[] */ private static function byRow(array $array, int $ignore): array { $returnMatrix = []; foreach ($array as $row) { if (!is_array($row)) { $row = [$row]; } foreach ($row as $cell) { if ($cell === null) { if ($ignore === 1 || $ignore === 3) { continue; } $cell = 0; } elseif (ErrorValue::isError($cell)) { if ($ignore === 2 || $ignore === 3) { continue; } } $returnMatrix[] = $cell; } } return $returnMatrix; } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Calculation/LookupRef/Matrix.php
src/PhpSpreadsheet/Calculation/LookupRef/Matrix.php
<?php namespace PhpOffice\PhpSpreadsheet\Calculation\LookupRef; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Matrix { use ArrayEnabled; /** * Helper function; NOT an implementation of any Excel Function. * * @param mixed[] $values */ public static function isColumnVector(array $values): bool { return count($values, COUNT_RECURSIVE) === (count($values, COUNT_NORMAL) * 2); } /** * Helper function; NOT an implementation of any Excel Function. * * @param mixed[] $values */ public static function isRowVector(array $values): bool { return count($values, COUNT_RECURSIVE) > 1 && (count($values, COUNT_NORMAL) === 1 || count($values, COUNT_RECURSIVE) === count($values, COUNT_NORMAL)); } /** * TRANSPOSE. * * @param mixed $matrixData A matrix of values * * @return mixed[] */ public static function transpose($matrixData): array { $returnMatrix = []; if (!is_array($matrixData)) { $matrixData = [[$matrixData]]; } if (!is_array(end($matrixData))) { $matrixData = [$matrixData]; } $column = 0; /** @var mixed[][] $matrixData */ foreach ($matrixData as $matrixRow) { $row = 0; foreach ($matrixRow as $matrixCell) { $returnMatrix[$row][$column] = $matrixCell; ++$row; } ++$column; } return $returnMatrix; } /** * INDEX. * * Uses an index to choose a value from a reference or array * * Excel Function: * =INDEX(range_array, row_num, [column_num], [area_num]) * * @param mixed $matrix A range of cells or an array constant * @param mixed $rowNum The row in the array or range from which to return a value. * If row_num is omitted, column_num is required. * Or can be an array of values * @param mixed $columnNum The column in the array or range from which to return a value. * If column_num is omitted, row_num is required. * Or can be an array of values * * TODO Provide support for area_num, currently not supported * * @return mixed the value of a specified cell or array of cells * If an array of values is passed as the $rowNum and/or $columnNum arguments, then the returned result * will also be an array with the same dimensions */ public static function index(mixed $matrix, mixed $rowNum = 0, mixed $columnNum = null): mixed { if (is_array($rowNum) || is_array($columnNum)) { return self::evaluateArrayArgumentsSubsetFrom([self::class, __FUNCTION__], 1, $matrix, $rowNum, $columnNum); } $rowNum = $rowNum ?? 0; $columnNum = $columnNum ?? 0; if (is_scalar($matrix)) { if ($rowNum === 0 || $rowNum === 1) { if ($columnNum === 0 || $columnNum === 1) { if ($columnNum === 1 || $rowNum === 1) { return $matrix; } } } } try { $rowNum = LookupRefValidations::validatePositiveInt($rowNum); $columnNum = LookupRefValidations::validatePositiveInt($columnNum); } catch (Exception $e) { return $e->getMessage(); } if (is_array($matrix) && count($matrix) === 1 && $rowNum > 1) { $matrixKey = array_keys($matrix)[0]; if (is_array($matrix[$matrixKey])) { $tempMatrix = []; foreach ($matrix[$matrixKey] as $key => $value) { $tempMatrix[$key] = [$value]; } $matrix = $tempMatrix; } } if (!is_array($matrix) || ($rowNum > count($matrix))) { return ExcelError::REF(); } $rowKeys = array_keys($matrix); $columnKeys = @array_keys($matrix[$rowKeys[0]]); //* @phpstan-ignore-line if ($columnNum > count($columnKeys)) { return ExcelError::REF(); } if ($columnNum === 0) { return self::extractRowValue($matrix, $rowKeys, $rowNum); } $columnNum = $columnKeys[--$columnNum]; //* @phpstan-ignore-line if ($rowNum === 0) { return array_map( fn ($value): array => [$value], array_column($matrix, $columnNum) ); } $rowNum = $rowKeys[--$rowNum]; //* @phpstan-ignore-line /** @var mixed[][] $matrix */ return $matrix[$rowNum][$columnNum]; } /** * @param mixed[] $matrix * @param array<int, int> $rowKeys */ private static function extractRowValue(array $matrix, array $rowKeys, int $rowNum): mixed { if ($rowNum === 0) { return $matrix; } $rowNum = $rowKeys[--$rowNum]; $row = $matrix[$rowNum]; if (is_array($row)) { return [$rowNum => $row]; } return $row; } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Calculation/LookupRef/Hstack.php
src/PhpSpreadsheet/Calculation/LookupRef/Hstack.php
<?php namespace PhpOffice\PhpSpreadsheet\Calculation\LookupRef; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Hstack { /** * Excel function HSTACK. * * @return mixed[]|string */ public static function hstack(mixed ...$inputData): array|string { $maxRow = 0; foreach ($inputData as $matrix) { if (!is_array($matrix)) { $count = 1; } else { $count = count($matrix); } $maxRow = max($maxRow, $count); } /** @var mixed[] $inputData */ foreach ($inputData as &$matrix) { if (!is_array($matrix)) { $matrix = [$matrix]; } $rows = count($matrix); $reset = reset($matrix); $columns = is_array($reset) ? count($reset) : 1; while ($maxRow > $rows) { $matrix[] = array_pad([], $columns, ExcelError::NA()); ++$rows; } } $transpose = array_map(null, ...$inputData); //* @phpstan-ignore-line $returnMatrix = []; foreach ($transpose as $array) { $returnMatrix[] = Functions::flattenArray($array); } return $returnMatrix; } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Calculation/LookupRef/VLookup.php
src/PhpSpreadsheet/Calculation/LookupRef/VLookup.php
<?php namespace PhpOffice\PhpSpreadsheet\Calculation\LookupRef; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; class VLookup extends LookupBase { use ArrayEnabled; /** * VLOOKUP * The VLOOKUP function searches for value in the left-most column of lookup_array and returns the value * in the same row based on the index_number. * * @param mixed $lookupValue The value that you want to match in lookup_array * @param mixed[] $lookupArray The range of cells being searched * @param array<mixed>|float|int|string $indexNumber The column number in table_array from which the matching value must be returned. * The first column is 1. * @param mixed $notExactMatch determines if you are looking for an exact match based on lookup_value * * @return mixed The value of the found cell */ public static function lookup(mixed $lookupValue, $lookupArray, mixed $indexNumber, mixed $notExactMatch = true): mixed { if (is_array($lookupValue) || is_array($indexNumber)) { return self::evaluateArrayArgumentsIgnore([self::class, __FUNCTION__], 1, $lookupValue, $lookupArray, $indexNumber, $notExactMatch); } $notExactMatch = (bool) ($notExactMatch ?? true); try { self::validateLookupArray($lookupArray); $indexNumber = self::validateIndexLookup($lookupArray, $indexNumber); } catch (Exception $e) { return $e->getMessage(); } $f = array_keys($lookupArray); $firstRow = array_pop($f); if ((!is_array($lookupArray[$firstRow])) || ($indexNumber > count($lookupArray[$firstRow]))) { return ExcelError::REF(); } $columnKeys = array_keys($lookupArray[$firstRow]); $returnColumn = $columnKeys[--$indexNumber]; $firstColumn = array_shift($columnKeys) ?? 1; if (!$notExactMatch) { /** @var callable $callable */ $callable = [self::class, 'vlookupSort']; uasort($lookupArray, $callable); } /** @var string[][] $lookupArray */ $rowNumber = self::vLookupSearch($lookupValue, $lookupArray, $firstColumn, $notExactMatch); if ($rowNumber !== null) { // return the appropriate value return $lookupArray[$rowNumber][$returnColumn]; } return ExcelError::NA(); } /** * @param scalar[] $a * @param scalar[] $b */ private static function vlookupSort(array $a, array $b): int { reset($a); $firstColumn = key($a); $aLower = StringHelper::strToLower((string) $a[$firstColumn]); $bLower = StringHelper::strToLower((string) $b[$firstColumn]); if ($aLower == $bLower) { return 0; } return ($aLower < $bLower) ? -1 : 1; } /** * @param mixed $lookupValue The value that you want to match in lookup_array * @param string[][] $lookupArray * @param int|string $column */ private static function vLookupSearch(mixed $lookupValue, array $lookupArray, $column, bool $notExactMatch): ?int { $lookupLower = StringHelper::strToLower(StringHelper::convertToString($lookupValue)); $rowNumber = null; foreach ($lookupArray as $rowKey => $rowData) { $bothNumeric = self::numeric($lookupValue) && self::numeric($rowData[$column]); $bothNotNumeric = !self::numeric($lookupValue) && !self::numeric($rowData[$column]); $cellDataLower = StringHelper::strToLower((string) $rowData[$column]); // break if we have passed possible keys if ( $notExactMatch && (($bothNumeric && ($rowData[$column] > $lookupValue)) || ($bothNotNumeric && ($cellDataLower > $lookupLower))) ) { break; } $rowNumber = self::checkMatch( $bothNumeric, $bothNotNumeric, $notExactMatch, $rowKey, $cellDataLower, $lookupLower, $rowNumber ); } return $rowNumber; } private static function numeric(mixed $value): bool { return is_int($value) || is_float($value); } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Calculation/LookupRef/RowColumnInformation.php
src/PhpSpreadsheet/Calculation/LookupRef/RowColumnInformation.php
<?php namespace PhpOffice\PhpSpreadsheet\Calculation\LookupRef; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Calculation\Information\ErrorValue; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Cell\Cell; use PhpOffice\PhpSpreadsheet\Cell\Coordinate; use PhpOffice\PhpSpreadsheet\Exception as SpreadsheetException; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; class RowColumnInformation { /** * Test if cellAddress is null or whitespace string. * * @param null|mixed[]|string $cellAddress A reference to a range of cells */ private static function cellAddressNullOrWhitespace($cellAddress): bool { return $cellAddress === null || (!is_array($cellAddress) && trim($cellAddress) === ''); } private static function cellColumn(?Cell $cell): int { return ($cell !== null) ? Coordinate::columnIndexFromString($cell->getColumn()) : 1; } /** * COLUMN. * * Returns the column number of the given cell reference * If the cell reference is a range of cells, COLUMN returns the column numbers of each column * in the reference as a horizontal array. * If cell reference is omitted, and the function is being called through the calculation engine, * then it is assumed to be the reference of the cell in which the COLUMN function appears; * otherwise this function returns 1. * * Excel Function: * =COLUMN([cellAddress]) * * @param null|mixed[]|string $cellAddress A reference to a range of cells for which you want the column numbers * * @return int|int[]|string */ public static function COLUMN($cellAddress = null, ?Cell $cell = null): int|string|array { if (self::cellAddressNullOrWhitespace($cellAddress)) { return self::cellColumn($cell); } if (is_array($cellAddress)) { foreach ($cellAddress as $columnKey => $value) { $columnKey = (string) preg_replace('/[^a-z]/i', '', $columnKey); return Coordinate::columnIndexFromString($columnKey); } return self::cellColumn($cell); } $cellAddress = $cellAddress ?? ''; if ($cell != null) { [,, $sheetName] = Helpers::extractWorksheet($cellAddress, $cell); [,, $cellAddress] = Helpers::extractCellAddresses($cellAddress, true, $cell->getWorksheet(), $sheetName); } [, $cellAddress] = Worksheet::extractSheetTitle($cellAddress, true); $cellAddress ??= ''; if (str_contains($cellAddress, ':')) { [$startAddress, $endAddress] = explode(':', $cellAddress); $startAddress = (string) preg_replace('/[^a-z]/i', '', $startAddress); $endAddress = (string) preg_replace('/[^a-z]/i', '', $endAddress); return range( Coordinate::columnIndexFromString($startAddress), Coordinate::columnIndexFromString($endAddress) ); } $cellAddress = (string) preg_replace('/[^a-z]/i', '', $cellAddress); try { return Coordinate::columnIndexFromString($cellAddress); } catch (SpreadsheetException) { return ExcelError::NAME(); } } /** * COLUMNS. * * Returns the number of columns in an array or reference. * * Excel Function: * =COLUMNS(cellAddress) * * @param null|mixed[]|string $cellAddress An array or array formula, or a reference to a range of cells * for which you want the number of columns * * @return int|string The number of columns in cellAddress, or a string if arguments are invalid */ public static function COLUMNS($cellAddress = null) { if (self::cellAddressNullOrWhitespace($cellAddress)) { return 1; } if (is_string($cellAddress) && ErrorValue::isError($cellAddress)) { return $cellAddress; } if (!is_array($cellAddress)) { return ExcelError::VALUE(); } reset($cellAddress); $isMatrix = (is_numeric(key($cellAddress))); [$columns, $rows] = Calculation::getMatrixDimensions($cellAddress); if ($isMatrix) { return $rows; } return $columns; } private static function cellRow(?Cell $cell): int|string { return ($cell !== null) ? self::convert0ToName($cell->getRow()) : 1; } private static function convert0ToName(int|string $result): int|string { if (is_int($result) && ($result <= 0 || $result > 1048576)) { return ExcelError::NAME(); } return $result; } /** * ROW. * * Returns the row number of the given cell reference * If the cell reference is a range of cells, ROW returns the row numbers of each row in the reference * as a vertical array. * If cell reference is omitted, and the function is being called through the calculation engine, * then it is assumed to be the reference of the cell in which the ROW function appears; * otherwise this function returns 1. * * Excel Function: * =ROW([cellAddress]) * * @param null|mixed[][]|string $cellAddress A reference to a range of cells for which you want the row numbers * * @return int|mixed[]|string */ public static function ROW($cellAddress = null, ?Cell $cell = null): int|string|array { if (self::cellAddressNullOrWhitespace($cellAddress)) { return self::cellRow($cell); } if (is_array($cellAddress)) { foreach ($cellAddress as $rowKey => $rowValue) { foreach ($rowValue as $columnKey => $cellValue) { return (int) preg_replace('/\D/', '', $rowKey); } } return self::cellRow($cell); } $cellAddress = $cellAddress ?? ''; if ($cell !== null) { [,, $sheetName] = Helpers::extractWorksheet($cellAddress, $cell); [,, $cellAddress] = Helpers::extractCellAddresses($cellAddress, true, $cell->getWorksheet(), $sheetName); } [, $cellAddress] = Worksheet::extractSheetTitle($cellAddress, true); $cellAddress ??= ''; if (str_contains($cellAddress, ':')) { [$startAddress, $endAddress] = explode(':', $cellAddress); $startAddress = (int) (string) preg_replace('/\D/', '', $startAddress); $endAddress = (int) (string) preg_replace('/\D/', '', $endAddress); return array_map( fn ($value): array => [$value], range($startAddress, $endAddress) ); } [$cellAddress] = explode(':', $cellAddress); return self::convert0ToName((int) preg_replace('/\D/', '', $cellAddress)); } /** * ROWS. * * Returns the number of rows in an array or reference. * * Excel Function: * =ROWS(cellAddress) * * @param null|mixed[]|string $cellAddress An array or array formula, or a reference to a range of cells * for which you want the number of rows * * @return int|string The number of rows in cellAddress, or a string if arguments are invalid */ public static function ROWS($cellAddress = null) { if (self::cellAddressNullOrWhitespace($cellAddress)) { return 1; } if (is_string($cellAddress) && ErrorValue::isError($cellAddress)) { return $cellAddress; } if (!is_array($cellAddress)) { return ExcelError::VALUE(); } reset($cellAddress); $isMatrix = (is_numeric(key($cellAddress))); [$columns, $rows] = Calculation::getMatrixDimensions($cellAddress); if ($isMatrix) { return $columns; } return $rows; } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Calculation/LookupRef/Hyperlink.php
src/PhpSpreadsheet/Calculation/LookupRef/Hyperlink.php
<?php namespace PhpOffice\PhpSpreadsheet\Calculation\LookupRef; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Cell\Cell; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; class Hyperlink { /** * HYPERLINK. * * Excel Function: * =HYPERLINK(linkURL, [displayName]) * * @param mixed $linkURL Expect string. Value to check, is also the value returned when no error * @param mixed $displayName Expect string. Value to return when testValue is an error condition * @param ?Cell $cell The cell to set the hyperlink in * * @return string The value of $displayName (or $linkURL if $displayName was blank) */ public static function set(mixed $linkURL = '', mixed $displayName = null, ?Cell $cell = null): string { $linkURL = ($linkURL === null) ? '' : StringHelper::convertToString(Functions::flattenSingleValue($linkURL)); $displayName = ($displayName === null) ? '' : Functions::flattenSingleValue($displayName); if ((!is_object($cell)) || (trim($linkURL) == '')) { return ExcelError::REF(); } if (is_object($displayName)) { $displayName = $linkURL; } $displayName = StringHelper::convertToString($displayName); if (trim($displayName) === '') { $displayName = $linkURL; } $cell->getHyperlink() ->setUrl($linkURL); $cell->getHyperlink()->setTooltip($displayName); return $displayName; } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Calculation/LookupRef/Filter.php
src/PhpSpreadsheet/Calculation/LookupRef/Filter.php
<?php namespace PhpOffice\PhpSpreadsheet\Calculation\LookupRef; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Filter { public static function filter(mixed $lookupArray, mixed $matchArray, mixed $ifEmpty = null): mixed { if (!is_array($lookupArray)) { return ExcelError::VALUE(); } /** @var mixed[] $lookupArray */ if (!is_array($matchArray)) { return ExcelError::VALUE(); } $matchArray = self::enumerateArrayKeys($matchArray); $result = (Matrix::isColumnVector($matchArray)) ? self::filterByRow($lookupArray, $matchArray) : self::filterByColumn($lookupArray, $matchArray); if (empty($result)) { return $ifEmpty ?? ExcelError::CALC(); } /** @var callable(mixed): mixed */ $func = 'array_values'; return array_values(array_map($func, $result)); } /** * @param mixed[] $sortArray * * @return mixed[] */ private static function enumerateArrayKeys(array $sortArray): array { array_walk( $sortArray, function (&$columns): void { if (is_array($columns)) { $columns = array_values($columns); } } ); return array_values($sortArray); } /** * @param mixed[] $lookupArray * @param mixed[] $matchArray * * @return mixed[] */ private static function filterByRow(array $lookupArray, array $matchArray): array { $matchArray = array_values(array_column($matchArray, 0)); // @phpstan-ignore-line return array_filter( array_values($lookupArray), fn ($index): bool => (bool) ($matchArray[$index] ?? null), ARRAY_FILTER_USE_KEY ); } /** * @param mixed[] $lookupArray * @param mixed[] $matchArray * * @return mixed[] */ private static function filterByColumn(array $lookupArray, array $matchArray): array { $lookupArray = Matrix::transpose($lookupArray); if (count($matchArray) === 1) { $matchArray = array_pop($matchArray); } /** @var mixed[] $matchArray */ array_walk( $matchArray, function (&$value): void { $value = [$value]; } ); $result = self::filterByRow($lookupArray, $matchArray); return Matrix::transpose($result); } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Calculation/LookupRef/Unique.php
src/PhpSpreadsheet/Calculation/LookupRef/Unique.php
<?php namespace PhpOffice\PhpSpreadsheet\Calculation\LookupRef; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Shared\StringHelper; class Unique { /** * UNIQUE * The UNIQUE function searches for value either from a one-row or one-column range or from an array. * * @param mixed $lookupVector The range of cells being searched * @param mixed $byColumn Whether the uniqueness should be determined by row (the default) or by column * @param mixed $exactlyOnce Whether the function should return only entries that occur just once in the list * * @return mixed The unique values from the search range */ public static function unique(mixed $lookupVector, mixed $byColumn = false, mixed $exactlyOnce = false): mixed { if (!is_array($lookupVector)) { // Scalars are always returned "as is" return $lookupVector; } $byColumn = (bool) $byColumn; $exactlyOnce = (bool) $exactlyOnce; return ($byColumn === true) ? self::uniqueByColumn($lookupVector, $exactlyOnce) : self::uniqueByRow($lookupVector, $exactlyOnce); } /** @param mixed[] $lookupVector */ private static function uniqueByRow(array $lookupVector, bool $exactlyOnce): mixed { // When not $byColumn, we count whole rows or values, not individual values // so implode each row into a single string value array_walk( $lookupVector, //* @phpstan-ignore-next-line function (array &$value): void { $valuex = ''; $separator = ''; $numericIndicator = "\x01"; foreach ($value as $cellValue) { /** @var scalar $cellValue */ $valuex .= $separator . $cellValue; $separator = "\x00"; if (is_int($cellValue) || is_float($cellValue)) { $valuex .= $numericIndicator; } } $value = $valuex; } ); /** @var string[] $lookupVector */ $result = self::countValuesCaseInsensitive($lookupVector); if ($exactlyOnce === true) { $result = self::exactlyOnceFilter($result); } if (count($result) === 0) { return ExcelError::CALC(); } $result = array_keys($result); // restore rows from their strings array_walk( $result, function (string &$value): void { $value = explode("\x00", $value); foreach ($value as &$stringValue) { if (str_ends_with($stringValue, "\x01")) { // x01 should only end a string which is otherwise a float or int, // so phpstan is technically correct but what it fears should not happen. $stringValue = 0 + substr($stringValue, 0, -1); //@phpstan-ignore-line } } } ); return (count($result) === 1) ? array_pop($result) : $result; } /** @param mixed[] $lookupVector */ private static function uniqueByColumn(array $lookupVector, bool $exactlyOnce): mixed { /** @var string[] */ $flattenedLookupVector = Functions::flattenArray($lookupVector); if (count($lookupVector, COUNT_RECURSIVE) > count($flattenedLookupVector, COUNT_RECURSIVE) + 1) { // We're looking at a full column check (multiple rows) $transpose = Matrix::transpose($lookupVector); $result = self::uniqueByRow($transpose, $exactlyOnce); return (is_array($result)) ? Matrix::transpose($result) : $result; } $result = self::countValuesCaseInsensitive($flattenedLookupVector); if ($exactlyOnce === true) { $result = self::exactlyOnceFilter($result); } if (count($result) === 0) { return ExcelError::CALC(); } $result = array_keys($result); return $result; } /** * @param string[] $caseSensitiveLookupValues * * @return mixed[] */ private static function countValuesCaseInsensitive(array $caseSensitiveLookupValues): array { $caseInsensitiveCounts = array_count_values( array_map( fn (string $value): string => StringHelper::strToUpper($value), $caseSensitiveLookupValues ) ); $caseSensitiveCounts = []; foreach ($caseInsensitiveCounts as $caseInsensitiveKey => $count) { if (is_numeric($caseInsensitiveKey)) { $caseSensitiveCounts[$caseInsensitiveKey] = $count; } else { foreach ($caseSensitiveLookupValues as $caseSensitiveValue) { if ($caseInsensitiveKey === StringHelper::strToUpper($caseSensitiveValue)) { $caseSensitiveCounts[$caseSensitiveValue] = $count; break; } } } } return $caseSensitiveCounts; } /** * @param mixed[] $values * * @return mixed[] */ private static function exactlyOnceFilter(array $values): array { return array_filter( $values, fn ($value): bool => $value === 1 ); } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Calculation/LookupRef/Selection.php
src/PhpSpreadsheet/Calculation/LookupRef/Selection.php
<?php namespace PhpOffice\PhpSpreadsheet\Calculation\LookupRef; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Selection { use ArrayEnabled; /** * CHOOSE. * * Uses lookup_value to return a value from the list of value arguments. * Use CHOOSE to select one of up to 254 values based on the lookup_value. * * Excel Function: * =CHOOSE(index_num, value1, [value2], ...) * * @param mixed $chosenEntry The entry to select from the list (indexed from 1) * @param mixed ...$chooseArgs Data values * * @return mixed The selected value */ public static function choose(mixed $chosenEntry, mixed ...$chooseArgs): mixed { if (is_array($chosenEntry)) { return self::evaluateArrayArgumentsSubset([self::class, __FUNCTION__], 1, $chosenEntry, ...$chooseArgs); } $entryCount = count($chooseArgs) - 1; if (is_numeric($chosenEntry)) { --$chosenEntry; } else { return ExcelError::VALUE(); } $chosenEntry = (int) floor($chosenEntry); if (($chosenEntry < 0) || ($chosenEntry > $entryCount)) { return ExcelError::VALUE(); } if (is_array($chooseArgs[$chosenEntry])) { return Functions::flattenArray($chooseArgs[$chosenEntry]); } return $chooseArgs[$chosenEntry]; } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Calculation/LookupRef/LookupRefValidations.php
src/PhpSpreadsheet/Calculation/LookupRef/LookupRefValidations.php
<?php namespace PhpOffice\PhpSpreadsheet\Calculation\LookupRef; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ErrorValue; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class LookupRefValidations { public static function validateInt(mixed $value): int { if (!is_numeric($value)) { if (is_string($value) && ErrorValue::isError($value)) { throw new Exception($value); } throw new Exception(ExcelError::VALUE()); } return (int) floor((float) $value); } public static function validatePositiveInt(mixed $value, bool $allowZero = true): int { $value = self::validateInt($value); if (($allowZero === false && $value <= 0) || $value < 0) { throw new Exception(ExcelError::VALUE()); } return $value; } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Calculation/Statistical/StatisticalValidations.php
src/PhpSpreadsheet/Calculation/Statistical/StatisticalValidations.php
<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class StatisticalValidations { public static function validateFloat(mixed $value): float { if (!is_numeric($value)) { throw new Exception(ExcelError::VALUE()); } return (float) $value; } public static function validateInt(mixed $value): int { if (!is_numeric($value)) { throw new Exception(ExcelError::VALUE()); } return (int) floor((float) $value); } public static function validateBool(mixed $value): bool { if (!is_bool($value) && !is_numeric($value)) { throw new Exception(ExcelError::VALUE()); } return (bool) $value; } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Calculation/Statistical/Confidence.php
src/PhpSpreadsheet/Calculation/Statistical/Confidence.php
<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Confidence { use ArrayEnabled; /** * CONFIDENCE. * * Returns the confidence interval for a population mean * * @param mixed $alpha As a float * Or can be an array of values * @param mixed $stdDev Standard Deviation as a float * Or can be an array of values * @param mixed $size As an integer * Or can be an array of values * * @return array<mixed>|float|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function CONFIDENCE(mixed $alpha, mixed $stdDev, mixed $size) { if (is_array($alpha) || is_array($stdDev) || is_array($size)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $alpha, $stdDev, $size); } try { $alpha = StatisticalValidations::validateFloat($alpha); $stdDev = StatisticalValidations::validateFloat($stdDev); $size = StatisticalValidations::validateInt($size); } catch (Exception $e) { return $e->getMessage(); } if (($alpha <= 0) || ($alpha >= 1) || ($stdDev <= 0) || ($size < 1)) { return ExcelError::NAN(); } /** @var float $temp */ $temp = Distributions\StandardNormal::inverse(1 - $alpha / 2); /** @var float */ $result = Functions::scalar($temp * $stdDev / sqrt($size)); return $result; } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Calculation/Statistical/StandardDeviations.php
src/PhpSpreadsheet/Calculation/Statistical/StandardDeviations.php
<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical; class StandardDeviations { /** * STDEV. * * Estimates standard deviation based on a sample. The standard deviation is a measure of how * widely values are dispersed from the average value (the mean). * * Excel Function: * STDEV(value1[,value2[, ...]]) * * @param mixed ...$args Data values * * @return float|string The result, or a string containing an error */ public static function STDEV(mixed ...$args) { $result = Variances::VAR(...$args); if (!is_numeric($result)) { return $result; } return sqrt((float) $result); } /** * STDEVA. * * Estimates standard deviation based on a sample, including numbers, text, and logical values * * Excel Function: * STDEVA(value1[,value2[, ...]]) * * @param mixed ...$args Data values */ public static function STDEVA(mixed ...$args): float|string { $result = Variances::VARA(...$args); if (!is_numeric($result)) { return $result; } return sqrt((float) $result); } /** * STDEVP. * * Calculates standard deviation based on the entire population * * Excel Function: * STDEVP(value1[,value2[, ...]]) * * @param mixed ...$args Data values */ public static function STDEVP(mixed ...$args): float|string { $result = Variances::VARP(...$args); if (!is_numeric($result)) { return $result; } return sqrt((float) $result); } /** * STDEVPA. * * Calculates standard deviation based on the entire population, including numbers, text, and logical values * * Excel Function: * STDEVPA(value1[,value2[, ...]]) * * @param mixed ...$args Data values */ public static function STDEVPA(mixed ...$args): float|string { $result = Variances::VARPA(...$args); if (!is_numeric($result)) { return $result; } return sqrt((float) $result); } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Calculation/Statistical/Standardize.php
src/PhpSpreadsheet/Calculation/Statistical/Standardize.php
<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Standardize extends StatisticalValidations { use ArrayEnabled; /** * STANDARDIZE. * * Returns a normalized value from a distribution characterized by mean and standard_dev. * * @param array<mixed>|float $value Value to normalize * Or can be an array of values * @param array<mixed>|float $mean Mean Value * Or can be an array of values * @param array<mixed>|float $stdDev Standard Deviation * Or can be an array of values * * @return array<mixed>|float|string Standardized value, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function execute($value, $mean, $stdDev): array|string|float { if (is_array($value) || is_array($mean) || is_array($stdDev)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $mean, $stdDev); } try { $value = self::validateFloat($value); $mean = self::validateFloat($mean); $stdDev = self::validateFloat($stdDev); } catch (Exception $e) { return $e->getMessage(); } if ($stdDev <= 0) { return ExcelError::NAN(); } return ($value - $mean) / $stdDev; } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Calculation/Statistical/Permutations.php
src/PhpSpreadsheet/Calculation/Statistical/Permutations.php
<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Calculation\MathTrig; use PhpOffice\PhpSpreadsheet\Shared\IntOrFloat; class Permutations { use ArrayEnabled; /** * PERMUT. * * Returns the number of permutations for a given number of objects that can be * selected from number objects. A permutation is any set or subset of objects or * events where internal order is significant. Permutations are different from * combinations, for which the internal order is not significant. Use this function * for lottery-style probability calculations. * * @param mixed $numObjs Integer number of different objects * Or can be an array of values * @param mixed $numInSet Integer number of objects in each permutation * Or can be an array of values * * @return array<mixed>|float|int|string Number of permutations, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function PERMUT(mixed $numObjs, mixed $numInSet) { if (is_array($numObjs) || is_array($numInSet)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $numObjs, $numInSet); } try { $numObjs = StatisticalValidations::validateInt($numObjs); $numInSet = StatisticalValidations::validateInt($numInSet); } catch (Exception $e) { return $e->getMessage(); } if ($numObjs < $numInSet) { return ExcelError::NAN(); } /** @var float|int|string */ $result1 = MathTrig\Factorial::fact($numObjs); if (is_string($result1)) { return $result1; } /** @var float|int|string */ $result2 = MathTrig\Factorial::fact($numObjs - $numInSet); if (is_string($result2)) { return $result2; } $result = round($result1 / $result2); return IntOrFloat::evaluate($result); } /** * PERMUTATIONA. * * Returns the number of permutations for a given number of objects (with repetitions) * that can be selected from the total objects. * * @param mixed $numObjs Integer number of different objects * Or can be an array of values * @param mixed $numInSet Integer number of objects in each permutation * Or can be an array of values * * @return array<mixed>|float|int|string Number of permutations, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function PERMUTATIONA(mixed $numObjs, mixed $numInSet) { if (is_array($numObjs) || is_array($numInSet)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $numObjs, $numInSet); } try { $numObjs = StatisticalValidations::validateInt($numObjs); $numInSet = StatisticalValidations::validateInt($numInSet); } catch (Exception $e) { return $e->getMessage(); } if ($numObjs < 0 || $numInSet < 0) { return ExcelError::NAN(); } $result = $numObjs ** $numInSet; return IntOrFloat::evaluate($result); } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Calculation/Statistical/Size.php
src/PhpSpreadsheet/Calculation/Statistical/Size.php
<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Size { /** * LARGE. * * Returns the nth largest value in a data set. You can use this function to * select a value based on its relative standing. * * Excel Function: * LARGE(value1[,value2[, ...]],entry) * * @param mixed $args Data values * * @return float|string The result, or a string containing an error */ public static function large(mixed ...$args) { $aArgs = Functions::flattenArray($args); $entry = array_pop($aArgs); if ((is_numeric($entry)) && (!is_string($entry))) { $entry = (int) floor($entry); $mArgs = self::filter($aArgs); $count = Counts::COUNT($mArgs); --$entry; if ($count === 0 || $entry < 0 || $entry >= $count) { return ExcelError::NAN(); } rsort($mArgs); /** @var float[] $mArgs */ return $mArgs[$entry]; } return ExcelError::VALUE(); } /** * SMALL. * * Returns the nth smallest value in a data set. You can use this function to * select a value based on its relative standing. * * Excel Function: * SMALL(value1[,value2[, ...]],entry) * * @param mixed $args Data values * * @return float|string The result, or a string containing an error */ public static function small(mixed ...$args) { $aArgs = Functions::flattenArray($args); $entry = array_pop($aArgs); if ((is_numeric($entry)) && (!is_string($entry))) { $entry = (int) floor($entry); $mArgs = self::filter($aArgs); $count = Counts::COUNT($mArgs); --$entry; if ($count === 0 || $entry < 0 || $entry >= $count) { return ExcelError::NAN(); } sort($mArgs); /** @var float[] $mArgs */ return $mArgs[$entry]; } return ExcelError::VALUE(); } /** * @param mixed[] $args Data values * * @return mixed[] */ protected static function filter(array $args): array { $mArgs = []; foreach ($args as $arg) { // Is it a numeric value? if ((is_numeric($arg)) && (!is_string($arg))) { $mArgs[] = $arg; } } return $mArgs; } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Calculation/Statistical/AggregateBase.php
src/PhpSpreadsheet/Calculation/Statistical/AggregateBase.php
<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical; use PhpOffice\PhpSpreadsheet\Calculation\Functions; abstract class AggregateBase { /** * MS Excel does not count Booleans if passed as cell values, but they are counted if passed as literals. * OpenOffice Calc always counts Booleans. * Gnumeric never counts Booleans. */ protected static function testAcceptedBoolean(mixed $arg, mixed $k): mixed { if (!is_bool($arg)) { return $arg; } if (Functions::getCompatibilityMode() === Functions::COMPATIBILITY_GNUMERIC) { return $arg; } if (Functions::getCompatibilityMode() === Functions::COMPATIBILITY_OPENOFFICE) { return (int) $arg; } if (!Functions::isCellValue($k)) { return (int) $arg; } /*if ( (is_bool($arg)) && ((!Functions::isCellValue($k) && (Functions::getCompatibilityMode() === Functions::COMPATIBILITY_EXCEL)) || (Functions::getCompatibilityMode() === Functions::COMPATIBILITY_OPENOFFICE)) ) { $arg = (int) $arg; }*/ return $arg; } protected static function isAcceptedCountable(mixed $arg, mixed $k, bool $countNull = false): bool { if ($countNull && $arg === null && !Functions::isCellValue($k) && Functions::getCompatibilityMode() !== Functions::COMPATIBILITY_GNUMERIC) { return true; } if (!is_numeric($arg)) { return false; } if (!is_string($arg)) { return true; } if (!Functions::isCellValue($k) && Functions::getCompatibilityMode() === Functions::COMPATIBILITY_OPENOFFICE) { return true; } if (!Functions::isCellValue($k) && Functions::getCompatibilityMode() !== Functions::COMPATIBILITY_GNUMERIC) { return true; } return false; } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Calculation/Statistical/Averages.php
src/PhpSpreadsheet/Calculation/Statistical/Averages.php
<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Averages extends AggregateBase { /** * AVEDEV. * * Returns the average of the absolute deviations of data points from their mean. * AVEDEV is a measure of the variability in a data set. * * Excel Function: * AVEDEV(value1[,value2[, ...]]) * * @param mixed ...$args Data values * * @return float|string (string if result is an error) */ public static function averageDeviations(mixed ...$args): string|float { $aArgs = Functions::flattenArrayIndexed($args); // Return value $returnValue = 0.0; $aMean = self::average(...$args); if ($aMean === ExcelError::DIV0()) { return ExcelError::NAN(); } elseif ($aMean === ExcelError::VALUE()) { return ExcelError::VALUE(); } $aCount = 0; foreach ($aArgs as $k => $arg) { $arg = self::testAcceptedBoolean($arg, $k); // Is it a numeric value? // Strings containing numeric values are only counted if they are string literals (not cell values) // and then only in MS Excel and in Open Office, not in Gnumeric if ((is_string($arg)) && (!is_numeric($arg)) && (!Functions::isCellValue($k))) { return ExcelError::VALUE(); } if (self::isAcceptedCountable($arg, $k)) { /** @var float|int|numeric-string $arg */ /** @var float|int|numeric-string $aMean */ $returnValue += abs($arg - $aMean); ++$aCount; } } // Return if ($aCount === 0) { return ExcelError::DIV0(); } return $returnValue / $aCount; } /** * AVERAGE. * * Returns the average (arithmetic mean) of the arguments * * Excel Function: * AVERAGE(value1[,value2[, ...]]) * * @param mixed ...$args Data values * * @return float|int|string (string if result is an error) */ public static function average(mixed ...$args): string|int|float { $returnValue = $aCount = 0; // Loop through arguments foreach (Functions::flattenArrayIndexed($args) as $k => $arg) { $arg = self::testAcceptedBoolean($arg, $k); // Is it a numeric value? // Strings containing numeric values are only counted if they are string literals (not cell values) // and then only in MS Excel and in Open Office, not in Gnumeric if ((is_string($arg)) && (!is_numeric($arg)) && (!Functions::isCellValue($k))) { return ExcelError::VALUE(); } if (self::isAcceptedCountable($arg, $k)) { /** @var float|int|numeric-string $arg */ $returnValue += $arg; ++$aCount; } } // Return if ($aCount > 0) { return $returnValue / $aCount; } return ExcelError::DIV0(); } /** * AVERAGEA. * * Returns the average of its arguments, including numbers, text, and logical values * * Excel Function: * AVERAGEA(value1[,value2[, ...]]) * * @param mixed ...$args Data values * * @return float|int|string (string if result is an error) */ public static function averageA(mixed ...$args): string|int|float { $returnValue = null; $aCount = 0; // Loop through arguments foreach (Functions::flattenArrayIndexed($args) as $k => $arg) { if (is_numeric($arg)) { // do nothing } elseif (is_bool($arg)) { $arg = (int) $arg; } elseif (!Functions::isMatrixValue($k)) { $arg = 0; } else { return ExcelError::VALUE(); } $returnValue += $arg; ++$aCount; } if ($aCount > 0) { return $returnValue / $aCount; } return ExcelError::DIV0(); } /** * MEDIAN. * * Returns the median of the given numbers. The median is the number in the middle of a set of numbers. * * Excel Function: * MEDIAN(value1[,value2[, ...]]) * * @param mixed ...$args Data values * * @return float|string The result, or a string containing an error */ public static function median(mixed ...$args): float|string { $aArgs = Functions::flattenArray($args); $returnValue = ExcelError::NAN(); /** @var array<float|int> */ $aArgs = self::filterArguments($aArgs); $valueCount = count($aArgs); if ($valueCount > 0) { sort($aArgs, SORT_NUMERIC); $valueCount = $valueCount / 2; if ($valueCount == floor($valueCount)) { $returnValue = ($aArgs[$valueCount--] + $aArgs[$valueCount]) / 2; //* @phpstan-ignore-line } else { $valueCount = (int) floor($valueCount); $returnValue = $aArgs[$valueCount]; } } return $returnValue; } /** * MODE. * * Returns the most frequently occurring, or repetitive, value in an array or range of data * * Excel Function: * MODE(value1[,value2[, ...]]) * * @param mixed ...$args Data values * * @return float|string The result, or a string containing an error */ public static function mode(mixed ...$args): float|string { $returnValue = ExcelError::NA(); // Loop through arguments $aArgs = Functions::flattenArray($args); $aArgs = self::filterArguments($aArgs); if (!empty($aArgs)) { return self::modeCalc($aArgs); } return $returnValue; } /** * @param mixed[] $args * * @return mixed[] */ protected static function filterArguments(array $args): array { return array_filter( $args, function ($value): bool { // Is it a numeric value? return is_numeric($value) && (!is_string($value)); } ); } /** * Special variant of array_count_values that isn't limited to strings and integers, * but can work with floating point numbers as values. * * @param mixed[] $data */ private static function modeCalc(array $data): float|string { $frequencyArray = []; $index = 0; $maxfreq = 0; $maxfreqkey = ''; $maxfreqdatum = ''; foreach ($data as $datum) { /** @var float|string $datum */ $found = false; ++$index; foreach ($frequencyArray as $key => $value) { /** @var string[] $value */ if ((string) $value['value'] == (string) $datum) { ++$frequencyArray[$key]['frequency']; $freq = $frequencyArray[$key]['frequency']; if ($freq > $maxfreq) { $maxfreq = $freq; $maxfreqkey = $key; $maxfreqdatum = $datum; } elseif ($freq == $maxfreq) { if ($frequencyArray[$key]['index'] < $frequencyArray[$maxfreqkey]['index']) { //* @phpstan-ignore-line $maxfreqkey = $key; $maxfreqdatum = $datum; } } $found = true; break; } } if ($found === false) { $frequencyArray[] = [ 'value' => $datum, 'frequency' => 1, 'index' => $index, ]; } } if ($maxfreq <= 1) { return ExcelError::NA(); } return $maxfreqdatum; } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Calculation/Statistical/VarianceBase.php
src/PhpSpreadsheet/Calculation/Statistical/VarianceBase.php
<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical; use PhpOffice\PhpSpreadsheet\Calculation\Functions; abstract class VarianceBase { protected static function datatypeAdjustmentAllowStrings(int|float|string|bool $value): int|float { if (is_bool($value)) { return (int) $value; } elseif (is_string($value)) { return 0; } return $value; } protected static function datatypeAdjustmentBooleans(mixed $value): mixed { if (is_bool($value) && (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_OPENOFFICE)) { return (int) $value; } return $value; } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Calculation/Statistical/Percentiles.php
src/PhpSpreadsheet/Calculation/Statistical/Percentiles.php
<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Percentiles { public const RANK_SORT_DESCENDING = 0; public const RANK_SORT_ASCENDING = 1; /** * PERCENTILE. * * Returns the nth percentile of values in a range.. * * Excel Function: * PERCENTILE(value1[,value2[, ...]],entry) * * @param mixed $args Data values * * @return float|string The result, or a string containing an error */ public static function PERCENTILE(mixed ...$args) { $aArgs = Functions::flattenArray($args); // Calculate $entry = array_pop($aArgs); try { $entry = StatisticalValidations::validateFloat($entry); } catch (Exception $e) { return $e->getMessage(); } if (($entry < 0) || ($entry > 1)) { return ExcelError::NAN(); } $mArgs = self::percentileFilterValues($aArgs); $mValueCount = count($mArgs); if ($mValueCount > 0) { sort($mArgs); /** @var float[] $mArgs */ $count = Counts::COUNT($mArgs); $index = $entry * ($count - 1); $indexFloor = floor($index); $iBase = (int) $indexFloor; if ($index == $indexFloor) { return $mArgs[$iBase]; } $iNext = $iBase + 1; $iProportion = $index - $iBase; return $mArgs[$iBase] + (($mArgs[$iNext] - $mArgs[$iBase]) * $iProportion); } return ExcelError::NAN(); } /** * PERCENTRANK. * * Returns the rank of a value in a data set as a percentage of the data set. * Note that the returned rank is simply rounded to the appropriate significant digits, * rather than floored (as MS Excel), so value 3 for a value set of 1, 2, 3, 4 will return * 0.667 rather than 0.666 * * @param mixed $valueSet An array of (float) values, or a reference to, a list of numbers * @param mixed $value The number whose rank you want to find * @param mixed $significance The (integer) number of significant digits for the returned percentage value * * @return float|string (string if result is an error) */ public static function PERCENTRANK(mixed $valueSet, mixed $value, mixed $significance = 3): string|float { $valueSet = Functions::flattenArray($valueSet); $value = Functions::flattenSingleValue($value); $significance = ($significance === null) ? 3 : Functions::flattenSingleValue($significance); try { $value = StatisticalValidations::validateFloat($value); $significance = StatisticalValidations::validateInt($significance); } catch (Exception $e) { return $e->getMessage(); } $valueSet = self::rankFilterValues($valueSet); $valueCount = count($valueSet); if ($valueCount == 0) { return ExcelError::NA(); } sort($valueSet, SORT_NUMERIC); $valueAdjustor = $valueCount - 1; if (($value < $valueSet[0]) || ($value > $valueSet[$valueAdjustor])) { return ExcelError::NA(); } $pos = array_search($value, $valueSet); if ($pos === false) { /** @var float[] $valueSet */ $pos = 0; $testValue = $valueSet[0]; while ($testValue < $value) { $testValue = $valueSet[++$pos]; } --$pos; $pos += (($value - $valueSet[$pos]) / ($testValue - $valueSet[$pos])); } return round(((float) $pos) / $valueAdjustor, $significance); } /** * QUARTILE. * * Returns the quartile of a data set. * * Excel Function: * QUARTILE(value1[,value2[, ...]],entry) * * @param mixed $args Data values * * @return float|string The result, or a string containing an error */ public static function QUARTILE(mixed ...$args) { $aArgs = Functions::flattenArray($args); $entry = array_pop($aArgs); try { $entry = StatisticalValidations::validateFloat($entry); } catch (Exception $e) { return $e->getMessage(); } $entry = floor($entry); $entry /= 4; if (($entry < 0) || ($entry > 1)) { return ExcelError::NAN(); } return self::PERCENTILE($aArgs, $entry); } /** * RANK. * * Returns the rank of a number in a list of numbers. * * @param mixed $value The number whose rank you want to find * @param mixed $valueSet An array of float values, or a reference to, a list of numbers * @param mixed $order Order to sort the values in the value set * * @return float|string The result, or a string containing an error (0 = Descending, 1 = Ascending) */ public static function RANK(mixed $value, mixed $valueSet, mixed $order = self::RANK_SORT_DESCENDING) { $value = Functions::flattenSingleValue($value); $valueSet = Functions::flattenArray($valueSet); $order = ($order === null) ? self::RANK_SORT_DESCENDING : Functions::flattenSingleValue($order); try { $value = StatisticalValidations::validateFloat($value); $order = StatisticalValidations::validateInt($order); } catch (Exception $e) { return $e->getMessage(); } $valueSet = self::rankFilterValues($valueSet); if ($order === self::RANK_SORT_DESCENDING) { rsort($valueSet, SORT_NUMERIC); } else { sort($valueSet, SORT_NUMERIC); } $pos = array_search($value, $valueSet); if ($pos === false) { return ExcelError::NA(); } return ++$pos; } /** * @param mixed[] $dataSet * * @return mixed[] */ protected static function percentileFilterValues(array $dataSet): array { return array_filter( $dataSet, fn ($value): bool => is_numeric($value) && !is_string($value) ); } /** * @param mixed[] $dataSet * * @return mixed[] */ protected static function rankFilterValues(array $dataSet): array { return array_filter( $dataSet, fn ($value): bool => is_numeric($value) ); } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Calculation/Statistical/Deviations.php
src/PhpSpreadsheet/Calculation/Statistical/Deviations.php
<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Deviations { /** * DEVSQ. * * Returns the sum of squares of deviations of data points from their sample mean. * * Excel Function: * DEVSQ(value1[,value2[, ...]]) * * @param mixed ...$args Data values */ public static function sumSquares(mixed ...$args): string|float { $aArgs = Functions::flattenArrayIndexed($args); $aMean = Averages::average($aArgs); if (!is_numeric($aMean)) { return ExcelError::NAN(); } // Return value $returnValue = 0.0; $aCount = -1; foreach ($aArgs as $k => $arg) { // Is it a numeric value? if ( (is_bool($arg)) && ((!Functions::isCellValue($k)) || (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_OPENOFFICE)) ) { $arg = (int) $arg; } if ((is_numeric($arg)) && (!is_string($arg))) { $returnValue += ($arg - $aMean) ** 2; ++$aCount; } } return $aCount === 0 ? ExcelError::VALUE() : $returnValue; } /** * KURT. * * Returns the kurtosis of a data set. Kurtosis characterizes the relative peakedness * or flatness of a distribution compared with the normal distribution. Positive * kurtosis indicates a relatively peaked distribution. Negative kurtosis indicates a * relatively flat distribution. * * @param mixed[] ...$args Data Series */ public static function kurtosis(...$args): string|int|float { $aArgs = Functions::flattenArrayIndexed($args); $mean = Averages::average($aArgs); if (!is_numeric($mean)) { return ExcelError::DIV0(); } $stdDev = (float) StandardDeviations::STDEV($aArgs); if ($stdDev > 0) { $count = $summer = 0; foreach ($aArgs as $k => $arg) { if ((is_bool($arg)) && (!Functions::isMatrixValue($k))) { } else { // Is it a numeric value? if ((is_numeric($arg)) && (!is_string($arg))) { $summer += (($arg - $mean) / $stdDev) ** 4; ++$count; } } } if ($count > 3) { return $summer * ($count * ($count + 1) / (($count - 1) * ($count - 2) * ($count - 3))) - (3 * ($count - 1) ** 2 / (($count - 2) * ($count - 3))); } } return ExcelError::DIV0(); } /** * SKEW. * * Returns the skewness of a distribution. Skewness characterizes the degree of asymmetry * of a distribution around its mean. Positive skewness indicates a distribution with an * asymmetric tail extending toward more positive values. Negative skewness indicates a * distribution with an asymmetric tail extending toward more negative values. * * @param mixed[] ...$args Data Series * * @return float|int|string The result, or a string containing an error */ public static function skew(...$args): string|int|float { $aArgs = Functions::flattenArrayIndexed($args); $mean = Averages::average($aArgs); if (!is_numeric($mean)) { return ExcelError::DIV0(); } $stdDev = StandardDeviations::STDEV($aArgs); if ($stdDev === 0.0 || is_string($stdDev)) { return ExcelError::DIV0(); } $count = $summer = 0; // Loop through arguments foreach ($aArgs as $k => $arg) { if ((is_bool($arg)) && (!Functions::isMatrixValue($k))) { } elseif (!is_numeric($arg)) { return ExcelError::VALUE(); } else { // Is it a numeric value? if (!is_string($arg)) { $summer += (($arg - $mean) / $stdDev) ** 3; ++$count; } } } if ($count > 2) { return $summer * ($count / (($count - 1) * ($count - 2))); } return ExcelError::DIV0(); } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Calculation/Statistical/Variances.php
src/PhpSpreadsheet/Calculation/Statistical/Variances.php
<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Variances extends VarianceBase { /** * VAR. * * Estimates variance based on a sample. * * Excel Function: * VAR(value1[,value2[, ...]]) * * @param mixed ...$args Data values * * @return float|string (string if result is an error) */ public static function VAR(mixed ...$args): float|string { $returnValue = ExcelError::DIV0(); $summerA = $summerB = 0.0; // Loop through arguments $aArgs = Functions::flattenArray($args); $aCount = 0; foreach ($aArgs as $arg) { $arg = self::datatypeAdjustmentBooleans($arg); // Is it a numeric value? if ((is_numeric($arg)) && (!is_string($arg))) { $summerA += ($arg * $arg); $summerB += $arg; ++$aCount; } } if ($aCount > 1) { $summerA *= $aCount; $summerB *= $summerB; return ($summerA - $summerB) / ($aCount * ($aCount - 1)); } return $returnValue; } /** * VARA. * * Estimates variance based on a sample, including numbers, text, and logical values * * Excel Function: * VARA(value1[,value2[, ...]]) * * @param mixed ...$args Data values * * @return float|string (string if result is an error) */ public static function VARA(mixed ...$args): string|float { $returnValue = ExcelError::DIV0(); $summerA = $summerB = 0.0; // Loop through arguments $aArgs = Functions::flattenArrayIndexed($args); $aCount = 0; foreach ($aArgs as $k => $arg) { if ((is_string($arg)) && (Functions::isValue($k))) { return ExcelError::VALUE(); } elseif ((is_string($arg)) && (!Functions::isMatrixValue($k))) { } else { // Is it a numeric value? if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) && ($arg != '')))) { $arg = self::datatypeAdjustmentAllowStrings($arg); $summerA += ($arg * $arg); $summerB += $arg; ++$aCount; } } } if ($aCount > 1) { $summerA *= $aCount; $summerB *= $summerB; return ($summerA - $summerB) / ($aCount * ($aCount - 1)); } return $returnValue; } /** * VARP. * * Calculates variance based on the entire population * * Excel Function: * VARP(value1[,value2[, ...]]) * * @param mixed ...$args Data values * * @return float|string (string if result is an error) */ public static function VARP(mixed ...$args): float|string { // Return value $returnValue = ExcelError::DIV0(); $summerA = $summerB = 0.0; // Loop through arguments $aArgs = Functions::flattenArray($args); $aCount = 0; foreach ($aArgs as $arg) { $arg = self::datatypeAdjustmentBooleans($arg); // Is it a numeric value? if ((is_numeric($arg)) && (!is_string($arg))) { $summerA += ($arg * $arg); $summerB += $arg; ++$aCount; } } if ($aCount > 0) { $summerA *= $aCount; $summerB *= $summerB; return ($summerA - $summerB) / ($aCount * $aCount); } return $returnValue; } /** * VARPA. * * Calculates variance based on the entire population, including numbers, text, and logical values * * Excel Function: * VARPA(value1[,value2[, ...]]) * * @param mixed ...$args Data values * * @return float|string (string if result is an error) */ public static function VARPA(mixed ...$args): string|float { $returnValue = ExcelError::DIV0(); $summerA = $summerB = 0.0; // Loop through arguments $aArgs = Functions::flattenArrayIndexed($args); $aCount = 0; foreach ($aArgs as $k => $arg) { if ((is_string($arg)) && (Functions::isValue($k))) { return ExcelError::VALUE(); } elseif ((is_string($arg)) && (!Functions::isMatrixValue($k))) { } else { // Is it a numeric value? if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) && ($arg != '')))) { $arg = self::datatypeAdjustmentAllowStrings($arg); $summerA += ($arg * $arg); $summerB += $arg; ++$aCount; } } } if ($aCount > 0) { $summerA *= $aCount; $summerB *= $summerB; return ($summerA - $summerB) / ($aCount * $aCount); } return $returnValue; } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Calculation/Statistical/Trends.php
src/PhpSpreadsheet/Calculation/Statistical/Trends.php
<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Shared\Trend\Trend; class Trends { use ArrayEnabled; /** * @param array<mixed> $array1 * @param array<mixed> $array2 */ private static function filterTrendValues(array &$array1, array &$array2): void { foreach ($array1 as $key => $value) { if ((is_bool($value)) || (is_string($value)) || ($value === null)) { unset($array1[$key], $array2[$key]); } } } /** * @param mixed $array1 should be array, but scalar is made into one * @param mixed $array2 should be array, but scalar is made into one * * @param-out array<mixed> $array1 * @param-out array<mixed> $array2 */ private static function checkTrendArrays(mixed &$array1, mixed &$array2): void { if (!is_array($array1)) { $array1 = [$array1]; } if (!is_array($array2)) { $array2 = [$array2]; } $array1 = Functions::flattenArray($array1); $array2 = Functions::flattenArray($array2); self::filterTrendValues($array1, $array2); self::filterTrendValues($array2, $array1); // Reset the array indexes $array1 = array_merge($array1); $array2 = array_merge($array2); } /** * @param mixed[] $yValues * @param mixed[] $xValues */ protected static function validateTrendArrays(array $yValues, array $xValues): void { $yValueCount = count($yValues); $xValueCount = count($xValues); if (($yValueCount === 0) || ($yValueCount !== $xValueCount)) { throw new Exception(ExcelError::NA()); } elseif ($yValueCount === 1) { throw new Exception(ExcelError::DIV0()); } } /** * CORREL. * * Returns covariance, the average of the products of deviations for each data point pair. * * @param mixed $yValues array of mixed Data Series Y * @param null|mixed $xValues array of mixed Data Series X */ public static function CORREL(mixed $yValues, $xValues = null): float|string { if (($xValues === null) || (!is_array($yValues)) || (!is_array($xValues))) { return ExcelError::VALUE(); } try { self::checkTrendArrays($yValues, $xValues); self::validateTrendArrays($yValues, $xValues); } catch (Exception $e) { return $e->getMessage(); } $bestFitLinear = Trend::calculate(Trend::TREND_LINEAR, $yValues, $xValues); return $bestFitLinear->getCorrelation(); } /** * COVAR. * * Returns covariance, the average of the products of deviations for each data point pair. * * @param mixed[] $yValues array of mixed Data Series Y * @param mixed[] $xValues array of mixed Data Series X */ public static function COVAR(array $yValues, array $xValues): float|string { try { self::checkTrendArrays($yValues, $xValues); self::validateTrendArrays($yValues, $xValues); } catch (Exception $e) { return $e->getMessage(); } $bestFitLinear = Trend::calculate(Trend::TREND_LINEAR, $yValues, $xValues); return $bestFitLinear->getCovariance(); } /** * FORECAST. * * Calculates, or predicts, a future value by using existing values. * The predicted value is a y-value for a given x-value. * * @param mixed $xValue Float value of X for which we want to find Y * Or can be an array of values * @param mixed[] $yValues array of mixed Data Series Y * @param mixed[] $xValues array of mixed Data Series X * * @return array<mixed>|bool|float|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function FORECAST(mixed $xValue, array $yValues, array $xValues) { if (is_array($xValue)) { return self::evaluateArrayArgumentsSubset([self::class, __FUNCTION__], 1, $xValue, $yValues, $xValues); } try { $xValue = StatisticalValidations::validateFloat($xValue); self::checkTrendArrays($yValues, $xValues); self::validateTrendArrays($yValues, $xValues); } catch (Exception $e) { return $e->getMessage(); } $bestFitLinear = Trend::calculate(Trend::TREND_LINEAR, $yValues, $xValues); return $bestFitLinear->getValueOfYForX($xValue); } /** * GROWTH. * * Returns values along a predicted exponential Trend * * @param mixed[] $yValues Data Series Y * @param mixed[] $xValues Data Series X * @param mixed[] $newValues Values of X for which we want to find Y * @param mixed $const A logical (boolean) value specifying whether to force the intersect to equal 0 or not * * @return array<int, array<int, array<int, float>>> */ public static function GROWTH(array $yValues, array $xValues = [], array $newValues = [], mixed $const = true): array { $yValues = Functions::flattenArray($yValues); $xValues = Functions::flattenArray($xValues); $newValues = Functions::flattenArray($newValues); $const = ($const === null) ? true : (bool) Functions::flattenSingleValue($const); $bestFitExponential = Trend::calculate(Trend::TREND_EXPONENTIAL, $yValues, $xValues, $const); if (empty($newValues)) { $newValues = $bestFitExponential->getXValues(); } $returnArray = []; foreach ($newValues as $xValue) { /** @var float $xValue */ $returnArray[0][] = [$bestFitExponential->getValueOfYForX($xValue)]; } return $returnArray; } /** * INTERCEPT. * * Calculates the point at which a line will intersect the y-axis by using existing x-values and y-values. * * @param mixed[] $yValues Data Series Y * @param mixed[] $xValues Data Series X */ public static function INTERCEPT(array $yValues, array $xValues): float|string { try { self::checkTrendArrays($yValues, $xValues); self::validateTrendArrays($yValues, $xValues); } catch (Exception $e) { return $e->getMessage(); } $bestFitLinear = Trend::calculate(Trend::TREND_LINEAR, $yValues, $xValues); return $bestFitLinear->getIntersect(); } /** * LINEST. * * Calculates the statistics for a line by using the "least squares" method to calculate a straight line * that best fits your data, and then returns an array that describes the line. * * @param mixed[] $yValues Data Series Y * @param null|mixed[] $xValues Data Series X * @param mixed $const A logical (boolean) value specifying whether to force the intersect to equal 0 or not * @param mixed $stats A logical (boolean) value specifying whether to return additional regression statistics * * @return array<mixed>|string The result, or a string containing an error */ public static function LINEST(array $yValues, ?array $xValues = null, mixed $const = true, mixed $stats = false): string|array { $const = ($const === null) ? true : (bool) Functions::flattenSingleValue($const); $stats = ($stats === null) ? false : (bool) Functions::flattenSingleValue($stats); if ($xValues === null) { $xValues = $yValues; } try { self::checkTrendArrays($yValues, $xValues); self::validateTrendArrays($yValues, $xValues); } catch (Exception $e) { return $e->getMessage(); } $bestFitLinear = Trend::calculate(Trend::TREND_LINEAR, $yValues, $xValues, $const); if ($stats === true) { return [ [ $bestFitLinear->getSlope(), $bestFitLinear->getIntersect(), ], [ $bestFitLinear->getSlopeSE(), ($const === false) ? ExcelError::NA() : $bestFitLinear->getIntersectSE(), ], [ $bestFitLinear->getGoodnessOfFit(), $bestFitLinear->getStdevOfResiduals(), ], [ $bestFitLinear->getF(), $bestFitLinear->getDFResiduals(), ], [ $bestFitLinear->getSSRegression(), $bestFitLinear->getSSResiduals(), ], ]; } return [ $bestFitLinear->getSlope(), $bestFitLinear->getIntersect(), ]; } /** * LOGEST. * * Calculates an exponential curve that best fits the X and Y data series, * and then returns an array that describes the line. * * @param mixed[] $yValues Data Series Y * @param null|mixed[] $xValues Data Series X * @param mixed $const A logical (boolean) value specifying whether to force the intersect to equal 0 or not * @param mixed $stats A logical (boolean) value specifying whether to return additional regression statistics * * @return array<mixed>|string The result, or a string containing an error */ public static function LOGEST(array $yValues, ?array $xValues = null, mixed $const = true, mixed $stats = false): string|array { $const = ($const === null) ? true : (bool) Functions::flattenSingleValue($const); $stats = ($stats === null) ? false : (bool) Functions::flattenSingleValue($stats); if ($xValues === null) { $xValues = $yValues; } try { self::checkTrendArrays($yValues, $xValues); self::validateTrendArrays($yValues, $xValues); } catch (Exception $e) { return $e->getMessage(); } foreach ($yValues as $value) { if ($value < 0.0) { return ExcelError::NAN(); } } $bestFitExponential = Trend::calculate(Trend::TREND_EXPONENTIAL, $yValues, $xValues, $const); if ($stats === true) { return [ [ $bestFitExponential->getSlope(), $bestFitExponential->getIntersect(), ], [ $bestFitExponential->getSlopeSE(), ($const === false) ? ExcelError::NA() : $bestFitExponential->getIntersectSE(), ], [ $bestFitExponential->getGoodnessOfFit(), $bestFitExponential->getStdevOfResiduals(), ], [ $bestFitExponential->getF(), $bestFitExponential->getDFResiduals(), ], [ $bestFitExponential->getSSRegression(), $bestFitExponential->getSSResiduals(), ], ]; } return [ $bestFitExponential->getSlope(), $bestFitExponential->getIntersect(), ]; } /** * RSQ. * * Returns the square of the Pearson product moment correlation coefficient through data points * in known_y's and known_x's. * * @param mixed[] $yValues Data Series Y * @param mixed[] $xValues Data Series X * * @return float|string The result, or a string containing an error */ public static function RSQ(array $yValues, array $xValues) { try { self::checkTrendArrays($yValues, $xValues); self::validateTrendArrays($yValues, $xValues); } catch (Exception $e) { return $e->getMessage(); } $bestFitLinear = Trend::calculate(Trend::TREND_LINEAR, $yValues, $xValues); return $bestFitLinear->getGoodnessOfFit(); } /** * SLOPE. * * Returns the slope of the linear regression line through data points in known_y's and known_x's. * * @param mixed[] $yValues Data Series Y * @param mixed[] $xValues Data Series X * * @return float|string The result, or a string containing an error */ public static function SLOPE(array $yValues, array $xValues) { try { self::checkTrendArrays($yValues, $xValues); self::validateTrendArrays($yValues, $xValues); } catch (Exception $e) { return $e->getMessage(); } $bestFitLinear = Trend::calculate(Trend::TREND_LINEAR, $yValues, $xValues); return $bestFitLinear->getSlope(); } /** * STEYX. * * Returns the standard error of the predicted y-value for each x in the regression. * * @param mixed[] $yValues Data Series Y * @param mixed[] $xValues Data Series X */ public static function STEYX(array $yValues, array $xValues): float|string { try { self::checkTrendArrays($yValues, $xValues); self::validateTrendArrays($yValues, $xValues); } catch (Exception $e) { return $e->getMessage(); } $bestFitLinear = Trend::calculate(Trend::TREND_LINEAR, $yValues, $xValues); return $bestFitLinear->getStdevOfResiduals(); } /** * TREND. * * Returns values along a linear Trend * * @param mixed[] $yValues Data Series Y * @param mixed[] $xValues Data Series X * @param mixed[] $newValues Values of X for which we want to find Y * @param mixed $const A logical (boolean) value specifying whether to force the intersect to equal 0 or not * * @return array<int, array<int, array<int, float>>> */ public static function TREND(array $yValues, array $xValues = [], array $newValues = [], mixed $const = true): array { $yValues = Functions::flattenArray($yValues); $xValues = Functions::flattenArray($xValues); $newValues = Functions::flattenArray($newValues); $const = ($const === null) ? true : (bool) Functions::flattenSingleValue($const); $bestFitLinear = Trend::calculate(Trend::TREND_LINEAR, $yValues, $xValues, $const); if (empty($newValues)) { $newValues = $bestFitLinear->getXValues(); } $returnArray = []; foreach ($newValues as $xValue) { /** @var float $xValue */ $returnArray[0][] = [$bestFitLinear->getValueOfYForX($xValue)]; } return $returnArray; } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Calculation/Statistical/Counts.php
src/PhpSpreadsheet/Calculation/Statistical/Counts.php
<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical; use PhpOffice\PhpSpreadsheet\Calculation\Exception as CalcException; use PhpOffice\PhpSpreadsheet\Calculation\Functions; class Counts extends AggregateBase { /** * COUNT. * * Counts the number of cells that contain numbers within the list of arguments * * Excel Function: * COUNT(value1[,value2[, ...]]) * * @param mixed ...$args Data values */ public static function COUNT(mixed ...$args): int { $returnValue = 0; // Loop through arguments $aArgs = Functions::flattenArrayIndexed($args); foreach ($aArgs as $k => $arg) { $arg = self::testAcceptedBoolean($arg, $k); // Is it a numeric value? // Strings containing numeric values are only counted if they are string literals (not cell values) // and then only in MS Excel and in Open Office, not in Gnumeric if (self::isAcceptedCountable($arg, $k, true)) { ++$returnValue; } } return $returnValue; } /** * COUNTA. * * Counts the number of cells that are not empty within the list of arguments * * Excel Function: * COUNTA(value1[,value2[, ...]]) * * @param mixed ...$args Data values */ public static function COUNTA(mixed ...$args): int { $returnValue = 0; // Loop through arguments $aArgs = Functions::flattenArrayIndexed($args); foreach ($aArgs as $k => $arg) { // Nulls are counted if literals, but not if cell values if ($arg !== null || (!Functions::isCellValue($k))) { ++$returnValue; } } return $returnValue; } /** * COUNTBLANK. * * Counts the number of empty cells within the list of arguments * * Excel Function: * COUNTBLANK(value1[,value2[, ...]]) * * @param mixed $range Data values */ public static function COUNTBLANK(mixed $range): int { if ($range === null) { return 1; } if (!is_array($range) || array_key_exists(0, $range)) { throw new CalcException('Must specify range of cells, not any kind of literal'); } $returnValue = 0; // Loop through arguments $aArgs = Functions::flattenArray($range); foreach ($aArgs as $arg) { // Is it a blank cell? if (($arg === null) || ((is_string($arg)) && ($arg == ''))) { ++$returnValue; } } return $returnValue; } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Calculation/Statistical/Minimum.php
src/PhpSpreadsheet/Calculation/Statistical/Minimum.php
<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ErrorValue; class Minimum extends MaxMinBase { /** * MIN. * * MIN returns the value of the element of the values passed that has the smallest value, * with negative numbers considered smaller than positive numbers. * * Excel Function: * MIN(value1[,value2[, ...]]) * * @param mixed ...$args Data values */ public static function min(mixed ...$args): float|int|string { $returnValue = null; // Loop through arguments $aArgs = Functions::flattenArray($args); foreach ($aArgs as $arg) { if (ErrorValue::isError($arg)) { $returnValue = $arg; break; } // Is it a numeric value? if ((is_numeric($arg)) && (!is_string($arg))) { if (($returnValue === null) || ($arg < $returnValue)) { $returnValue = $arg; } } } if ($returnValue === null) { return 0; } /** @var float|int|string $returnValue */ return $returnValue; } /** * MINA. * * Returns the smallest value in a list of arguments, including numbers, text, and logical values * * Excel Function: * MINA(value1[,value2[, ...]]) * * @param mixed ...$args Data values */ public static function minA(mixed ...$args): float|int|string { $returnValue = null; // Loop through arguments $aArgs = Functions::flattenArray($args); foreach ($aArgs as $arg) { if (ErrorValue::isError($arg)) { $returnValue = $arg; break; } // Is it a numeric value? if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) && ($arg != '')))) { $arg = self::datatypeAdjustmentAllowStrings($arg); if (($returnValue === null) || ($arg < $returnValue)) { $returnValue = $arg; } } } if ($returnValue === null) { return 0; } /** @var float|int|string $returnValue */ return $returnValue; } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Calculation/Statistical/MaxMinBase.php
src/PhpSpreadsheet/Calculation/Statistical/MaxMinBase.php
<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical; abstract class MaxMinBase { protected static function datatypeAdjustmentAllowStrings(int|float|string|bool $value): int|float { if (is_bool($value)) { return (int) $value; } elseif (is_string($value)) { return 0; } return $value; } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Calculation/Statistical/Conditional.php
src/PhpSpreadsheet/Calculation/Statistical/Conditional.php
<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical; use PhpOffice\PhpSpreadsheet\Calculation\Database\DAverage; use PhpOffice\PhpSpreadsheet\Calculation\Database\DCount; use PhpOffice\PhpSpreadsheet\Calculation\Database\DMax; use PhpOffice\PhpSpreadsheet\Calculation\Database\DMin; use PhpOffice\PhpSpreadsheet\Calculation\Database\DSum; use PhpOffice\PhpSpreadsheet\Calculation\Exception as CalcException; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Conditional { private const CONDITION_COLUMN_NAME = 'CONDITION'; private const VALUE_COLUMN_NAME = 'VALUE'; private const CONDITIONAL_COLUMN_NAME = 'CONDITIONAL %d'; /** * AVERAGEIF. * * Returns the average value from a range of cells that contain numbers within the list of arguments * * Excel Function: * AVERAGEIF(range,condition[, average_range]) * * @param mixed $range Data values, expect array * @param null|mixed[]|string $condition the criteria that defines which cells will be checked * @param mixed $averageRange Data values */ public static function AVERAGEIF(mixed $range, null|array|string $condition, mixed $averageRange = []): null|int|float|string { if (!is_array($range) || !is_array($averageRange) || array_key_exists(0, $range) || array_key_exists(0, $averageRange)) { $refError = ExcelError::REF(); if (in_array($refError, [$range, $averageRange], true)) { return $refError; } throw new CalcException('Must specify range of cells, not any kind of literal'); } $database = self::databaseFromRangeAndValue($range, $averageRange); $condition = Functions::flattenSingleValue($condition); $condition = [[self::CONDITION_COLUMN_NAME, self::VALUE_COLUMN_NAME], [$condition, null]]; return DAverage::evaluate($database, self::VALUE_COLUMN_NAME, $condition); } /** * AVERAGEIFS. * * Counts the number of cells that contain numbers within the list of arguments * * Excel Function: * AVERAGEIFS(average_range, criteria_range1, criteria1, [criteria_range2, criteria2]…) * * @param mixed $args Pairs of Ranges and Criteria */ public static function AVERAGEIFS(mixed ...$args): null|int|float|string { if (empty($args)) { return 0.0; } if (count($args) === 3) { return self::AVERAGEIF($args[1], $args[2], $args[0]); //* @phpstan-ignore-line } foreach ($args as $arg) { if (is_array($arg) && array_key_exists(0, $arg)) { throw new CalcException('Must specify range of cells, not any kind of literal'); } } $conditions = self::buildConditionSetForValueRange(...$args); $database = self::buildDatabaseWithValueRange(...$args); return DAverage::evaluate($database, self::VALUE_COLUMN_NAME, $conditions); } /** * COUNTIF. * * Counts the number of cells that contain numbers within the list of arguments * * Excel Function: * COUNTIF(range,condition) * * @param mixed $range Data values, expect array * @param null|mixed[]|string $condition the criteria that defines which cells will be counted */ public static function COUNTIF(mixed $range, null|array|string $condition): string|int { if ( !is_array($range) || array_key_exists(0, $range) ) { if ($range === ExcelError::REF()) { return $range; } throw new CalcException('Must specify range of cells, not any kind of literal'); } // Filter out any empty values that shouldn't be included in a COUNT $range = array_filter( Functions::flattenArray($range), fn ($value): bool => $value !== null && $value !== '' ); $range = array_merge([[self::CONDITION_COLUMN_NAME]], array_chunk($range, 1)); $condition = Functions::flattenSingleValue($condition); $condition = array_merge([[self::CONDITION_COLUMN_NAME]], [[$condition]]); return DCount::evaluate($range, null, $condition, false); } /** * COUNTIFS. * * Counts the number of cells that contain numbers within the list of arguments * * Excel Function: * COUNTIFS(criteria_range1, criteria1, [criteria_range2, criteria2]…) * * @param mixed $args Pairs of Ranges and Criteria */ public static function COUNTIFS(mixed ...$args): int|string { if (empty($args)) { return 0; } elseif (count($args) === 2) { return self::COUNTIF(...$args); } $database = self::buildDatabase(...$args); $conditions = self::buildConditionSet(...$args); return DCount::evaluate($database, null, $conditions, false); } /** * MAXIFS. * * Returns the maximum value within a range of cells that contain numbers within the list of arguments * * Excel Function: * MAXIFS(max_range, criteria_range1, criteria1, [criteria_range2, criteria2]…) * * @param mixed $args Pairs of Ranges and Criteria */ public static function MAXIFS(mixed ...$args): null|float|string { if (empty($args)) { return 0.0; } $conditions = self::buildConditionSetForValueRange(...$args); $database = self::buildDatabaseWithValueRange(...$args); return DMax::evaluate($database, self::VALUE_COLUMN_NAME, $conditions, false); } /** * MINIFS. * * Returns the minimum value within a range of cells that contain numbers within the list of arguments * * Excel Function: * MINIFS(min_range, criteria_range1, criteria1, [criteria_range2, criteria2]…) * * @param mixed $args Pairs of Ranges and Criteria */ public static function MINIFS(mixed ...$args): null|float|string { if (empty($args)) { return 0.0; } $conditions = self::buildConditionSetForValueRange(...$args); $database = self::buildDatabaseWithValueRange(...$args); return DMin::evaluate($database, self::VALUE_COLUMN_NAME, $conditions, false); } /** * SUMIF. * * Totals the values of cells that contain numbers within the list of arguments * * Excel Function: * SUMIF(range, criteria, [sum_range]) * * @param mixed $range Data values, expecting array * @param mixed $sumRange Data values, expecting array */ public static function SUMIF(mixed $range, mixed $condition, mixed $sumRange = []): null|float|string { if ( !is_array($range) || array_key_exists(0, $range) || !is_array($sumRange) || array_key_exists(0, $sumRange) ) { $refError = ExcelError::REF(); if (in_array($refError, [$range, $sumRange], true)) { return $refError; } throw new CalcException('Must specify range of cells, not any kind of literal'); } $database = self::databaseFromRangeAndValue($range, $sumRange); $condition = Functions::flattenSingleValue($condition); $condition = [[self::CONDITION_COLUMN_NAME, self::VALUE_COLUMN_NAME], [$condition, null]]; return DSum::evaluate($database, self::VALUE_COLUMN_NAME, $condition); } /** * SUMIFS. * * Counts the number of cells that contain numbers within the list of arguments * * Excel Function: * SUMIFS(average_range, criteria_range1, criteria1, [criteria_range2, criteria2]…) * * @param mixed $args Pairs of Ranges and Criteria */ public static function SUMIFS(mixed ...$args): null|float|string { if (empty($args)) { return 0.0; } elseif (count($args) === 3) { return self::SUMIF($args[1], $args[2], $args[0]); } $conditions = self::buildConditionSetForValueRange(...$args); $database = self::buildDatabaseWithValueRange(...$args); return DSum::evaluate($database, self::VALUE_COLUMN_NAME, $conditions); } /** * @param mixed[] $args * * @return mixed[][] */ private static function buildConditionSet(...$args): array { $conditions = self::buildConditions(1, ...$args); return array_map(null, ...$conditions); } /** * @param mixed[] $args * * @return mixed[][] */ private static function buildConditionSetForValueRange(...$args): array { $conditions = self::buildConditions(2, ...$args); if (count($conditions) === 1) { return array_map( fn ($value): array => [$value], $conditions[0] ); } return array_map(null, ...$conditions); } /** * @param mixed[] $args * * @return mixed[][] */ private static function buildConditions(int $startOffset, ...$args): array { $conditions = []; $pairCount = 1; $argumentCount = count($args); for ($argument = $startOffset; $argument < $argumentCount; $argument += 2) { $conditions[] = array_merge([sprintf(self::CONDITIONAL_COLUMN_NAME, $pairCount)], [$args[$argument]]); ++$pairCount; } return $conditions; } /** * @param mixed[] $args * * @return mixed[] */ private static function buildDatabase(...$args): array { $database = []; return self::buildDataSet(0, $database, ...$args); } /** * @param mixed[] $args * * @return mixed[] */ private static function buildDatabaseWithValueRange(...$args): array { $database = []; $database[] = array_merge( [self::VALUE_COLUMN_NAME], Functions::flattenArray($args[0]) ); return self::buildDataSet(1, $database, ...$args); } /** * @param mixed[][] $database * @param mixed[] $args * * @return mixed[] */ private static function buildDataSet(int $startOffset, array $database, ...$args): array { $pairCount = 1; $argumentCount = count($args); for ($argument = $startOffset; $argument < $argumentCount; $argument += 2) { $database[] = array_merge( [sprintf(self::CONDITIONAL_COLUMN_NAME, $pairCount)], Functions::flattenArray($args[$argument]) ); ++$pairCount; } return array_map(null, ...$database); } /** * @param mixed[] $range * @param mixed[] $valueRange * * @return mixed[] */ private static function databaseFromRangeAndValue(array $range, array $valueRange = []): array { $range = Functions::flattenArray($range); $valueRange = Functions::flattenArray($valueRange); if (empty($valueRange)) { $valueRange = $range; } $database = array_map(null, array_merge([self::CONDITION_COLUMN_NAME], $range), array_merge([self::VALUE_COLUMN_NAME], $valueRange)); return $database; } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Calculation/Statistical/Maximum.php
src/PhpSpreadsheet/Calculation/Statistical/Maximum.php
<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ErrorValue; class Maximum extends MaxMinBase { /** * MAX. * * MAX returns the value of the element of the values passed that has the highest value, * with negative numbers considered smaller than positive numbers. * * Excel Function: * MAX(value1[,value2[, ...]]) * * @param mixed ...$args Data values */ public static function max(mixed ...$args): float|int|string { $returnValue = null; // Loop through arguments $aArgs = Functions::flattenArray($args); foreach ($aArgs as $arg) { if (ErrorValue::isError($arg)) { $returnValue = $arg; break; } // Is it a numeric value? if ((is_numeric($arg)) && (!is_string($arg))) { if (($returnValue === null) || ($arg > $returnValue)) { $returnValue = $arg; } } } if ($returnValue === null) { return 0; } /** @var float|int|string $returnValue */ return $returnValue; } /** * MAXA. * * Returns the greatest value in a list of arguments, including numbers, text, and logical values * * Excel Function: * MAXA(value1[,value2[, ...]]) * * @param mixed ...$args Data values */ public static function maxA(mixed ...$args): float|int|string { $returnValue = null; // Loop through arguments $aArgs = Functions::flattenArray($args); foreach ($aArgs as $arg) { if (ErrorValue::isError($arg)) { $returnValue = $arg; break; } // Is it a numeric value? if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) && ($arg != '')))) { $arg = self::datatypeAdjustmentAllowStrings($arg); if (($returnValue === null) || ($arg > $returnValue)) { $returnValue = $arg; } } } if ($returnValue === null) { return 0; } /** @var float|int|string $returnValue */ return $returnValue; } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Fisher.php
src/PhpSpreadsheet/Calculation/Statistical/Distributions/Fisher.php
<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Fisher { use ArrayEnabled; /** * FISHER. * * Returns the Fisher transformation at x. This transformation produces a function that * is normally distributed rather than skewed. Use this function to perform hypothesis * testing on the correlation coefficient. * * @param mixed $value Float value for which we want the probability * Or can be an array of values * * @return array<mixed>|float|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function distribution(mixed $value): array|string|float { if (is_array($value)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $value); } try { $value = DistributionValidations::validateFloat($value); } catch (Exception $e) { return $e->getMessage(); } if (($value <= -1) || ($value >= 1)) { return ExcelError::NAN(); } return 0.5 * log((1 + $value) / (1 - $value)); } /** * FISHERINV. * * Returns the inverse of the Fisher transformation. Use this transformation when * analyzing correlations between ranges or arrays of data. If y = FISHER(x), then * FISHERINV(y) = x. * * @param mixed $probability Float probability at which you want to evaluate the distribution * Or can be an array of values * * @return array<mixed>|float|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function inverse(mixed $probability): array|string|float { if (is_array($probability)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $probability); } try { $probability = DistributionValidations::validateFloat($probability); } catch (Exception $e) { return $e->getMessage(); } return (exp(2 * $probability) - 1) / (exp(2 * $probability) + 1); } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Calculation/Statistical/Distributions/ChiSquared.php
src/PhpSpreadsheet/Calculation/Statistical/Distributions/ChiSquared.php
<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class ChiSquared { use ArrayEnabled; private const EPS = 2.22e-16; /** * CHIDIST. * * Returns the one-tailed probability of the chi-squared distribution. * * @param mixed $value Float value for which we want the probability * Or can be an array of values * @param mixed $degrees Integer degrees of freedom * Or can be an array of values * * @return array<mixed>|float|int|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function distributionRightTail(mixed $value, mixed $degrees): array|string|int|float { if (is_array($value) || is_array($degrees)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $degrees); } try { $value = DistributionValidations::validateFloat($value); $degrees = DistributionValidations::validateInt($degrees); } catch (Exception $e) { return $e->getMessage(); } if ($degrees < 1) { return ExcelError::NAN(); } if ($value < 0) { if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC) { return 1; } return ExcelError::NAN(); } return 1 - (Gamma::incompleteGamma($degrees / 2, $value / 2) / Gamma::gammaValue($degrees / 2)); } /** * CHIDIST. * * Returns the one-tailed probability of the chi-squared distribution. * * @param mixed $value Float value for which we want the probability * Or can be an array of values * @param mixed $degrees Integer degrees of freedom * Or can be an array of values * @param mixed $cumulative Boolean value indicating if we want the cdf (true) or the pdf (false) * Or can be an array of values * * @return array<mixed>|float|int|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function distributionLeftTail(mixed $value, mixed $degrees, mixed $cumulative): array|string|int|float { if (is_array($value) || is_array($degrees) || is_array($cumulative)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $degrees, $cumulative); } try { $value = DistributionValidations::validateFloat($value); $degrees = DistributionValidations::validateInt($degrees); $cumulative = DistributionValidations::validateBool($cumulative); } catch (Exception $e) { return $e->getMessage(); } if ($degrees < 1) { return ExcelError::NAN(); } if ($value < 0) { if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC) { return 1; } return ExcelError::NAN(); } if ($cumulative === true) { $temp = self::distributionRightTail($value, $degrees); return 1 - (is_numeric($temp) ? $temp : 0); } return ($value ** (($degrees / 2) - 1) * exp(-$value / 2)) / ((2 ** ($degrees / 2)) * Gamma::gammaValue($degrees / 2)); } /** * CHIINV. * * Returns the inverse of the right-tailed probability of the chi-squared distribution. * * @param mixed $probability Float probability at which you want to evaluate the distribution * Or can be an array of values * @param mixed $degrees Integer degrees of freedom * Or can be an array of values * * @return array<mixed>|float|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function inverseRightTail(mixed $probability, mixed $degrees) { if (is_array($probability) || is_array($degrees)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $probability, $degrees); } try { $probability = DistributionValidations::validateProbability($probability); $degrees = DistributionValidations::validateInt($degrees); } catch (Exception $e) { return $e->getMessage(); } if ($degrees < 1) { return ExcelError::NAN(); } $callback = fn (float $value): float => 1 - (Gamma::incompleteGamma($degrees / 2, $value / 2) / Gamma::gammaValue($degrees / 2)); $newtonRaphson = new NewtonRaphson($callback); return $newtonRaphson->execute($probability); } /** * CHIINV. * * Returns the inverse of the left-tailed probability of the chi-squared distribution. * * @param mixed $probability Float probability at which you want to evaluate the distribution * Or can be an array of values * @param mixed $degrees Integer degrees of freedom * Or can be an array of values * * @return array<mixed>|float|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function inverseLeftTail(mixed $probability, mixed $degrees): array|string|float { if (is_array($probability) || is_array($degrees)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $probability, $degrees); } try { $probability = DistributionValidations::validateProbability($probability); $degrees = DistributionValidations::validateInt($degrees); } catch (Exception $e) { return $e->getMessage(); } if ($degrees < 1) { return ExcelError::NAN(); } return self::inverseLeftTailCalculation($probability, $degrees); } /** * CHITEST. * * Uses the chi-square test to calculate the probability that the differences between two supplied data sets * (of observed and expected frequencies), are likely to be simply due to sampling error, * or if they are likely to be real. * * @param float[] $actual an array of observed frequencies * @param float[] $expected an array of expected frequencies */ public static function test($actual, $expected): float|string { $rows = count($actual); /** @var float[] */ $actual = Functions::flattenArray($actual); /** @var float[] */ $expected = Functions::flattenArray($expected); $columns = intdiv(count($actual), $rows); $countActuals = count($actual); $countExpected = count($expected); if ($countActuals !== $countExpected || $countActuals === 1) { return ExcelError::NAN(); } $result = 0.0; for ($i = 0; $i < $countActuals; ++$i) { if ($expected[$i] == 0.0) { return ExcelError::DIV0(); } elseif ($expected[$i] < 0.0) { return ExcelError::NAN(); } $result += (($actual[$i] - $expected[$i]) ** 2) / $expected[$i]; } $degrees = self::degrees($rows, $columns); /** @var float|string */ $result = Functions::scalar(self::distributionRightTail($result, $degrees)); return $result; } protected static function degrees(int $rows, int $columns): int { if ($rows === 1) { return $columns - 1; } elseif ($columns === 1) { return $rows - 1; } return ($columns - 1) * ($rows - 1); } private static function inverseLeftTailCalculation(float $probability, int $degrees): float { // bracket the root $min = 0; $sd = sqrt(2.0 * $degrees); $max = 2 * $sd; $s = -1; while ($s * self::pchisq($max, $degrees) > $probability * $s) { $min = $max; $max += 2 * $sd; } // Find root using bisection $chi2 = 0.5 * ($min + $max); while (($max - $min) > self::EPS * $chi2) { if ($s * self::pchisq($chi2, $degrees) > $probability * $s) { $min = $chi2; } else { $max = $chi2; } $chi2 = 0.5 * ($min + $max); } return $chi2; } private static function pchisq(float $chi2, int $degrees): float { return self::gammp($degrees, 0.5 * $chi2); } private static function gammp(int $n, float $x): float { if ($x < 0.5 * $n + 1) { return self::gser($n, $x); } return 1 - self::gcf($n, $x); } // Return the incomplete gamma function P(n/2,x) evaluated by // series representation. Algorithm from numerical recipe. // Assume that n is a positive integer and x>0, won't check arguments. // Relative error controlled by the eps parameter private static function gser(int $n, float $x): float { /** @var float $gln */ $gln = Gamma::ln($n / 2); $a = 0.5 * $n; $ap = $a; $sum = 1.0 / $a; $del = $sum; for ($i = 1; $i < 101; ++$i) { ++$ap; $del = $del * $x / $ap; $sum += $del; if ($del < $sum * self::EPS) { break; } } return $sum * exp(-$x + $a * log($x) - $gln); } // Return the incomplete gamma function Q(n/2,x) evaluated by // its continued fraction representation. Algorithm from numerical recipe. // Assume that n is a postive integer and x>0, won't check arguments. // Relative error controlled by the eps parameter private static function gcf(int $n, float $x): float { /** @var float $gln */ $gln = Gamma::ln($n / 2); $a = 0.5 * $n; $b = $x + 1 - $a; $fpmin = 1.e-300; $c = 1 / $fpmin; $d = 1 / $b; $h = $d; for ($i = 1; $i < 101; ++$i) { $an = -$i * ($i - $a); $b += 2; $d = $an * $d + $b; if (abs($d) < $fpmin) { $d = $fpmin; } $c = $b + $an / $c; if (abs($c) < $fpmin) { $c = $fpmin; } $d = 1 / $d; $del = $d * $c; $h = $h * $del; if (abs($del - 1) < self::EPS) { break; } } return $h * exp(-$x + $a * log($x) - $gln); } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Calculation/Statistical/Distributions/StandardNormal.php
src/PhpSpreadsheet/Calculation/Statistical/Distributions/StandardNormal.php
<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Calculation\Statistical\Averages; use PhpOffice\PhpSpreadsheet\Calculation\Statistical\StandardDeviations; class StandardNormal { use ArrayEnabled; /** * NORMSDIST. * * Returns the standard normal cumulative distribution function. The distribution has * a mean of 0 (zero) and a standard deviation of one. Use this function in place of a * table of standard normal curve areas. * * NOTE: We don't need to check for arrays to array-enable this function, because that is already * handled by the logic in Normal::distribution() * All we need to do is pass the value through as scalar or as array. * * @param mixed $value Float value for which we want the probability * Or can be an array of values * * @return array<mixed>|float|string The result, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function cumulative(mixed $value) { return Normal::distribution($value, 0, 1, true); } /** * NORM.S.DIST. * * Returns the standard normal cumulative distribution function. The distribution has * a mean of 0 (zero) and a standard deviation of one. Use this function in place of a * table of standard normal curve areas. * * NOTE: We don't need to check for arrays to array-enable this function, because that is already * handled by the logic in Normal::distribution() * All we need to do is pass the value and cumulative through as scalar or as array. * * @param mixed $value Float value for which we want the probability * Or can be an array of values * @param mixed $cumulative Boolean value indicating if we want the cdf (true) or the pdf (false) * Or can be an array of values * * @return array<mixed>|float|string The result, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function distribution(mixed $value, mixed $cumulative) { return Normal::distribution($value, 0, 1, $cumulative); } /** * NORMSINV. * * Returns the inverse of the standard normal cumulative distribution * * @param mixed $value float probability for which we want the value * Or can be an array of values * * NOTE: We don't need to check for arrays to array-enable this function, because that is already * handled by the logic in Normal::inverse() * All we need to do is pass the value through as scalar or as array * * @return array<mixed>|float|string The result, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function inverse(mixed $value) { return Normal::inverse($value, 0, 1); } /** * GAUSS. * * Calculates the probability that a member of a standard normal population will fall between * the mean and z standard deviations from the mean. * * @param mixed $value Or can be an array of values * * @return array<mixed>|float|string The result, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function gauss(mixed $value): array|string|float { if (is_array($value)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $value); } if (!is_numeric($value)) { return ExcelError::VALUE(); } /** @var float $dist */ $dist = self::distribution($value, true); return $dist - 0.5; } /** * ZTEST. * * Returns the one-tailed P-value of a z-test. * * For a given hypothesized population mean, x, Z.TEST returns the probability that the sample mean would be * greater than the average of observations in the data set (array) — that is, the observed sample mean. * * @param mixed $dataSet The dataset should be an array of float values for the observations * @param mixed $m0 Alpha Parameter * Or can be an array of values * @param mixed $sigma A null or float value for the Beta (Standard Deviation) Parameter; * if null, we use the standard deviation of the dataset * Or can be an array of values * * @return array<mixed>|float|string (string if result is an error) * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function zTest(mixed $dataSet, mixed $m0, mixed $sigma = null) { if (is_array($m0) || is_array($sigma)) { return self::evaluateArrayArgumentsSubsetFrom([self::class, __FUNCTION__], 1, $dataSet, $m0, $sigma); } $dataSet = Functions::flattenArrayIndexed($dataSet); if (!is_numeric($m0) || ($sigma !== null && !is_numeric($sigma))) { return ExcelError::VALUE(); } if ($sigma === null) { /** @var float $sigma */ $sigma = StandardDeviations::STDEV($dataSet); } $n = count($dataSet); $sub1 = Averages::average($dataSet); if (!is_numeric($sub1)) { return $sub1; } $temp = self::cumulative(($sub1 - $m0) / ($sigma / sqrt($n))); return 1 - (is_numeric($temp) ? $temp : 0); } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Calculation/Statistical/Distributions/HyperGeometric.php
src/PhpSpreadsheet/Calculation/Statistical/Distributions/HyperGeometric.php
<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Combinations; class HyperGeometric { use ArrayEnabled; /** * HYPGEOMDIST. * * Returns the hypergeometric distribution. HYPGEOMDIST returns the probability of a given number of * sample successes, given the sample size, population successes, and population size. * * @param mixed $sampleSuccesses Integer number of successes in the sample * Or can be an array of values * @param mixed $sampleNumber Integer size of the sample * Or can be an array of values * @param mixed $populationSuccesses Integer number of successes in the population * Or can be an array of values * @param mixed $populationNumber Integer population size * Or can be an array of values * * @return array<mixed>|float|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function distribution(mixed $sampleSuccesses, mixed $sampleNumber, mixed $populationSuccesses, mixed $populationNumber): array|string|float { if ( is_array($sampleSuccesses) || is_array($sampleNumber) || is_array($populationSuccesses) || is_array($populationNumber) ) { return self::evaluateArrayArguments( [self::class, __FUNCTION__], $sampleSuccesses, $sampleNumber, $populationSuccesses, $populationNumber ); } try { $sampleSuccesses = DistributionValidations::validateInt($sampleSuccesses); $sampleNumber = DistributionValidations::validateInt($sampleNumber); $populationSuccesses = DistributionValidations::validateInt($populationSuccesses); $populationNumber = DistributionValidations::validateInt($populationNumber); } catch (Exception $e) { return $e->getMessage(); } if (($sampleSuccesses < 0) || ($sampleSuccesses > $sampleNumber) || ($sampleSuccesses > $populationSuccesses)) { return ExcelError::NAN(); } if (($sampleNumber <= 0) || ($sampleNumber > $populationNumber)) { return ExcelError::NAN(); } if (($populationSuccesses <= 0) || ($populationSuccesses > $populationNumber)) { return ExcelError::NAN(); } $successesPopulationAndSample = (float) Combinations::withoutRepetition($populationSuccesses, $sampleSuccesses); $numbersPopulationAndSample = (float) Combinations::withoutRepetition($populationNumber, $sampleNumber); $adjustedPopulationAndSample = (float) Combinations::withoutRepetition( $populationNumber - $populationSuccesses, $sampleNumber - $sampleSuccesses ); return $successesPopulationAndSample * $adjustedPopulationAndSample / $numbersPopulationAndSample; } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Exponential.php
src/PhpSpreadsheet/Calculation/Statistical/Distributions/Exponential.php
<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Exponential { use ArrayEnabled; /** * EXPONDIST. * * Returns the exponential distribution. Use EXPONDIST to model the time between events, * such as how long an automated bank teller takes to deliver cash. For example, you can * use EXPONDIST to determine the probability that the process takes at most 1 minute. * * @param mixed $value Float value for which we want the probability * Or can be an array of values * @param mixed $lambda The parameter value as a float * Or can be an array of values * @param mixed $cumulative Boolean value indicating if we want the cdf (true) or the pdf (false) * Or can be an array of values * * @return array<mixed>|float|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function distribution(mixed $value, mixed $lambda, mixed $cumulative): array|string|float { if (is_array($value) || is_array($lambda) || is_array($cumulative)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $lambda, $cumulative); } try { $value = DistributionValidations::validateFloat($value); $lambda = DistributionValidations::validateFloat($lambda); $cumulative = DistributionValidations::validateBool($cumulative); } catch (Exception $e) { return $e->getMessage(); } if (($value < 0) || ($lambda < 0)) { return ExcelError::NAN(); } if ($cumulative === true) { return 1 - exp(0 - $value * $lambda); } return $lambda * exp(0 - $value * $lambda); } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Poisson.php
src/PhpSpreadsheet/Calculation/Statistical/Distributions/Poisson.php
<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Calculation\MathTrig; class Poisson { use ArrayEnabled; /** * POISSON. * * Returns the Poisson distribution. A common application of the Poisson distribution * is predicting the number of events over a specific time, such as the number of * cars arriving at a toll plaza in 1 minute. * * @param mixed $value Float value for which we want the probability * Or can be an array of values * @param mixed $mean Mean value as a float * Or can be an array of values * @param mixed $cumulative Boolean value indicating if we want the cdf (true) or the pdf (false) * Or can be an array of values * * @return array<mixed>|float|string The result, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function distribution(mixed $value, mixed $mean, mixed $cumulative): array|string|float { if (is_array($value) || is_array($mean) || is_array($cumulative)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $mean, $cumulative); } try { $value = DistributionValidations::validateFloat($value); $mean = DistributionValidations::validateFloat($mean); $cumulative = DistributionValidations::validateBool($cumulative); } catch (Exception $e) { return $e->getMessage(); } if (($value < 0) || ($mean < 0)) { return ExcelError::NAN(); } if ($cumulative) { $summer = 0; $floor = floor($value); for ($i = 0; $i <= $floor; ++$i) { /** @var float $fact */ $fact = MathTrig\Factorial::fact($i); $summer += $mean ** $i / $fact; } return exp(0 - $mean) * $summer; } /** @var float $fact */ $fact = MathTrig\Factorial::fact($value); return (exp(0 - $mean) * $mean ** $value) / $fact; } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Binomial.php
src/PhpSpreadsheet/Calculation/Statistical/Distributions/Binomial.php
<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; use PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Combinations; class Binomial { use ArrayEnabled; /** * BINOMDIST. * * Returns the individual term binomial distribution probability. Use BINOMDIST in problems with * a fixed number of tests or trials, when the outcomes of any trial are only success or failure, * when trials are independent, and when the probability of success is constant throughout the * experiment. For example, BINOMDIST can calculate the probability that two of the next three * babies born are male. * * @param mixed $value Integer number of successes in trials * Or can be an array of values * @param mixed $trials Integer umber of trials * Or can be an array of values * @param mixed $probability Probability of success on each trial as a float * Or can be an array of values * @param mixed $cumulative Boolean value indicating if we want the cdf (true) or the pdf (false) * Or can be an array of values * * @return array<mixed>|float|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function distribution(mixed $value, mixed $trials, mixed $probability, mixed $cumulative) { if (is_array($value) || is_array($trials) || is_array($probability) || is_array($cumulative)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $trials, $probability, $cumulative); } try { $value = DistributionValidations::validateInt($value); $trials = DistributionValidations::validateInt($trials); $probability = DistributionValidations::validateProbability($probability); $cumulative = DistributionValidations::validateBool($cumulative); } catch (Exception $e) { return $e->getMessage(); } if (($value < 0) || ($value > $trials)) { return ExcelError::NAN(); } if ($cumulative) { return self::calculateCumulativeBinomial($value, $trials, $probability); } /** @var float $comb */ $comb = Combinations::withoutRepetition($trials, $value); return $comb * $probability ** $value * (1 - $probability) ** ($trials - $value); } /** * BINOM.DIST.RANGE. * * Returns the Binomial Distribution probability for the number of successes from a specified number * of trials falling into a specified range. * * @param mixed $trials Integer number of trials * Or can be an array of values * @param mixed $probability Probability of success on each trial as a float * Or can be an array of values * @param mixed $successes The integer number of successes in trials * Or can be an array of values * @param mixed $limit Upper limit for successes in trials as null, or an integer * If null, then this will indicate the same as the number of Successes * Or can be an array of values * * @return array<mixed>|float|int|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function range(mixed $trials, mixed $probability, mixed $successes, mixed $limit = null): array|string|float|int { if (is_array($trials) || is_array($probability) || is_array($successes) || is_array($limit)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $trials, $probability, $successes, $limit); } $limit = $limit ?? $successes; try { $trials = DistributionValidations::validateInt($trials); $probability = DistributionValidations::validateProbability($probability); $successes = DistributionValidations::validateInt($successes); $limit = DistributionValidations::validateInt($limit); } catch (Exception $e) { return $e->getMessage(); } if (($successes < 0) || ($successes > $trials)) { return ExcelError::NAN(); } if (($limit < 0) || ($limit > $trials) || $limit < $successes) { return ExcelError::NAN(); } $summer = 0; for ($i = $successes; $i <= $limit; ++$i) { /** @var float $comb */ $comb = Combinations::withoutRepetition($trials, $i); $summer += $comb * $probability ** $i * (1 - $probability) ** ($trials - $i); } return $summer; } /** * NEGBINOMDIST. * * Returns the negative binomial distribution. NEGBINOMDIST returns the probability that * there will be number_f failures before the number_s-th success, when the constant * probability of a success is probability_s. This function is similar to the binomial * distribution, except that the number of successes is fixed, and the number of trials is * variable. Like the binomial, trials are assumed to be independent. * * @param mixed $failures Number of Failures as an integer * Or can be an array of values * @param mixed $successes Threshold number of Successes as an integer * Or can be an array of values * @param mixed $probability Probability of success on each trial as a float * Or can be an array of values * * @return array<mixed>|float|string The result, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions * * TODO Add support for the cumulative flag not present for NEGBINOMDIST, but introduced for NEGBINOM.DIST * The cumulative default should be false to reflect the behaviour of NEGBINOMDIST */ public static function negative(mixed $failures, mixed $successes, mixed $probability): array|string|float { if (is_array($failures) || is_array($successes) || is_array($probability)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $failures, $successes, $probability); } try { $failures = DistributionValidations::validateInt($failures); $successes = DistributionValidations::validateInt($successes); $probability = DistributionValidations::validateProbability($probability); } catch (Exception $e) { return $e->getMessage(); } if (($failures < 0) || ($successes < 1)) { return ExcelError::NAN(); } if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC) { if (($failures + $successes - 1) <= 0) { return ExcelError::NAN(); } } /** @var float $comb */ $comb = Combinations::withoutRepetition($failures + $successes - 1, $successes - 1); return $comb * ($probability ** $successes) * ((1 - $probability) ** $failures); } /** * BINOM.INV. * * Returns the smallest value for which the cumulative binomial distribution is greater * than or equal to a criterion value * * @param mixed $trials number of Bernoulli trials as an integer * Or can be an array of values * @param mixed $probability probability of a success on each trial as a float * Or can be an array of values * @param mixed $alpha criterion value as a float * Or can be an array of values * * @return array<mixed>|int|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function inverse(mixed $trials, mixed $probability, mixed $alpha): array|string|int { if (is_array($trials) || is_array($probability) || is_array($alpha)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $trials, $probability, $alpha); } try { $trials = DistributionValidations::validateInt($trials); $probability = DistributionValidations::validateProbability($probability); $alpha = DistributionValidations::validateFloat($alpha); } catch (Exception $e) { return $e->getMessage(); } if ($trials < 0) { return ExcelError::NAN(); } elseif (($alpha < 0.0) || ($alpha > 1.0)) { return ExcelError::NAN(); } $successes = 0; while ($successes <= $trials) { $result = self::calculateCumulativeBinomial($successes, $trials, $probability); if ($result >= $alpha) { break; } ++$successes; } return $successes; } private static function calculateCumulativeBinomial(int $value, int $trials, float $probability): float|int { $summer = 0; for ($i = 0; $i <= $value; ++$i) { /** @var float $comb */ $comb = Combinations::withoutRepetition($trials, $i); $summer += $comb * $probability ** $i * (1 - $probability) ** ($trials - $i); } return $summer; } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Calculation/Statistical/Distributions/GammaBase.php
src/PhpSpreadsheet/Calculation/Statistical/Distributions/GammaBase.php
<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions; use PhpOffice\PhpSpreadsheet\Calculation\Functions; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; abstract class GammaBase { private const LOG_GAMMA_X_MAX_VALUE = 2.55e305; private const EPS = 2.22e-16; private const MAX_VALUE = 1.2e308; private const SQRT2PI = 2.5066282746310005024157652848110452530069867406099; private const MAX_ITERATIONS = 256; protected static function calculateDistribution(float $value, float $a, float $b, bool $cumulative): float { if ($cumulative) { return self::incompleteGamma($a, $value / $b) / self::gammaValue($a); } return (1 / ($b ** $a * self::gammaValue($a))) * $value ** ($a - 1) * exp(0 - ($value / $b)); } /** @return float|string */ protected static function calculateInverse(float $probability, float $alpha, float $beta) { $xLo = 0; $xHi = $alpha * $beta * 5; $dx = 1024; $x = $xNew = 1; $i = 0; while ((abs($dx) > Functions::PRECISION) && (++$i <= self::MAX_ITERATIONS)) { // Apply Newton-Raphson step $result = self::calculateDistribution($x, $alpha, $beta, true); $error = $result - $probability; if ($error == 0.0) { $dx = 0; } elseif ($error < 0.0) { $xLo = $x; } else { $xHi = $x; } $pdf = self::calculateDistribution($x, $alpha, $beta, false); // Avoid division by zero if ($pdf !== 0.0) { $dx = $error / $pdf; $xNew = $x - $dx; } // If the NR fails to converge (which for example may be the // case if the initial guess is too rough) we apply a bisection // step to determine a more narrow interval around the root. if (($xNew < $xLo) || ($xNew > $xHi) || ($pdf == 0.0)) { $xNew = ($xLo + $xHi) / 2; $dx = $xNew - $x; } $x = $xNew; } if ($i === self::MAX_ITERATIONS) { return ExcelError::NA(); } return $x; } // // Implementation of the incomplete Gamma function // public static function incompleteGamma(float $a, float $x): float { static $max = 32; $summer = 0; for ($n = 0; $n <= $max; ++$n) { $divisor = $a; for ($i = 1; $i <= $n; ++$i) { $divisor *= ($a + $i); } $summer += ($x ** $n / $divisor); } return $x ** $a * exp(0 - $x) * $summer; } private const GAMMA_VALUE_P0 = 1.000000000190015; private const GAMMA_VALUE_P = [ 1 => 76.18009172947146, 2 => -86.50532032941677, 3 => 24.01409824083091, 4 => -1.231739572450155, 5 => 1.208650973866179e-3, 6 => -5.395239384953e-6, ]; // // Implementation of the Gamma function // public static function gammaValue(float $value): float { if ($value == 0.0) { return 0; } $y = $x = $value; $tmp = $x + 5.5; $tmp -= ($x + 0.5) * log($tmp); $summer = self::GAMMA_VALUE_P0; for ($j = 1; $j <= 6; ++$j) { $summer += (self::GAMMA_VALUE_P[$j] / ++$y); } return exp(0 - $tmp + log(self::SQRT2PI * $summer / $x)); } private const LG_D1 = -0.5772156649015328605195174; private const LG_D2 = 0.4227843350984671393993777; private const LG_D4 = 1.791759469228055000094023; private const LG_P1 = [ 4.945235359296727046734888, 201.8112620856775083915565, 2290.838373831346393026739, 11319.67205903380828685045, 28557.24635671635335736389, 38484.96228443793359990269, 26377.48787624195437963534, 7225.813979700288197698961, ]; private const LG_P2 = [ 4.974607845568932035012064, 542.4138599891070494101986, 15506.93864978364947665077, 184793.2904445632425417223, 1088204.76946882876749847, 3338152.967987029735917223, 5106661.678927352456275255, 3074109.054850539556250927, ]; private const LG_P4 = [ 14745.02166059939948905062, 2426813.369486704502836312, 121475557.4045093227939592, 2663432449.630976949898078, 29403789566.34553899906876, 170266573776.5398868392998, 492612579337.743088758812, 560625185622.3951465078242, ]; private const LG_Q1 = [ 67.48212550303777196073036, 1113.332393857199323513008, 7738.757056935398733233834, 27639.87074403340708898585, 54993.10206226157329794414, 61611.22180066002127833352, 36351.27591501940507276287, 8785.536302431013170870835, ]; private const LG_Q2 = [ 183.0328399370592604055942, 7765.049321445005871323047, 133190.3827966074194402448, 1136705.821321969608938755, 5267964.117437946917577538, 13467014.54311101692290052, 17827365.30353274213975932, 9533095.591844353613395747, ]; private const LG_Q4 = [ 2690.530175870899333379843, 639388.5654300092398984238, 41355999.30241388052042842, 1120872109.61614794137657, 14886137286.78813811542398, 101680358627.2438228077304, 341747634550.7377132798597, 446315818741.9713286462081, ]; private const LG_C = [ -0.001910444077728, 8.4171387781295e-4, -5.952379913043012e-4, 7.93650793500350248e-4, -0.002777777777777681622553, 0.08333333333333333331554247, 0.0057083835261, ]; // Rough estimate of the fourth root of logGamma_xBig private const LG_FRTBIG = 2.25e76; private const PNT68 = 0.6796875; // Function cache for logGamma private static float $logGammaCacheResult = 0.0; private static float $logGammaCacheX = 0.0; /** * logGamma function. * * Original author was Jaco van Kooten. Ported to PHP by Paul Meagher. * * The natural logarithm of the gamma function. <br /> * Based on public domain NETLIB (Fortran) code by W. J. Cody and L. Stoltz <br /> * Applied Mathematics Division <br /> * Argonne National Laboratory <br /> * Argonne, IL 60439 <br /> * <p> * References: * <ol> * <li>W. J. Cody and K. E. Hillstrom, 'Chebyshev Approximations for the Natural * Logarithm of the Gamma Function,' Math. Comp. 21, 1967, pp. 198-203.</li> * <li>K. E. Hillstrom, ANL/AMD Program ANLC366S, DGAMMA/DLGAMA, May, 1969.</li> * <li>Hart, Et. Al., Computer Approximations, Wiley and sons, New York, 1968.</li> * </ol> * </p> * <p> * From the original documentation: * </p> * <p> * This routine calculates the LOG(GAMMA) function for a positive real argument X. * Computation is based on an algorithm outlined in references 1 and 2. * The program uses rational functions that theoretically approximate LOG(GAMMA) * to at least 18 significant decimal digits. The approximation for X > 12 is from * reference 3, while approximations for X < 12.0 are similar to those in reference * 1, but are unpublished. The accuracy achieved depends on the arithmetic system, * the compiler, the intrinsic functions, and proper selection of the * machine-dependent constants. * </p> * <p> * Error returns: <br /> * The program returns the value XINF for X .LE. 0.0 or when overflow would occur. * The computation is believed to be free of underflow and overflow. * </p> * * @version 1.1 * * @author Jaco van Kooten * * @return float MAX_VALUE for x < 0.0 or when overflow would occur, i.e. x > 2.55E305 */ public static function logGamma(float $x): float { if ($x == self::$logGammaCacheX) { return self::$logGammaCacheResult; } $y = $x; if ($y > 0.0 && $y <= self::LOG_GAMMA_X_MAX_VALUE) { if ($y <= self::EPS) { $res = -log($y); } elseif ($y <= 1.5) { $res = self::logGamma1($y); } elseif ($y <= 4.0) { $res = self::logGamma2($y); } elseif ($y <= 12.0) { $res = self::logGamma3($y); } else { $res = self::logGamma4($y); } } else { // -------------------------- // Return for bad arguments // -------------------------- $res = self::MAX_VALUE; } // ------------------------------ // Final adjustments and return // ------------------------------ self::$logGammaCacheX = $x; self::$logGammaCacheResult = $res; return $res; } private static function logGamma1(float $y): float { // --------------------- // EPS .LT. X .LE. 1.5 // --------------------- if ($y < self::PNT68) { $corr = -log($y); $xm1 = $y; } else { $corr = 0.0; $xm1 = $y - 1.0; } $xden = 1.0; $xnum = 0.0; if ($y <= 0.5 || $y >= self::PNT68) { for ($i = 0; $i < 8; ++$i) { $xnum = $xnum * $xm1 + self::LG_P1[$i]; $xden = $xden * $xm1 + self::LG_Q1[$i]; } return $corr + $xm1 * (self::LG_D1 + $xm1 * ($xnum / $xden)); } $xm2 = $y - 1.0; for ($i = 0; $i < 8; ++$i) { $xnum = $xnum * $xm2 + self::LG_P2[$i]; $xden = $xden * $xm2 + self::LG_Q2[$i]; } return $corr + $xm2 * (self::LG_D2 + $xm2 * ($xnum / $xden)); } private static function logGamma2(float $y): float { // --------------------- // 1.5 .LT. X .LE. 4.0 // --------------------- $xm2 = $y - 2.0; $xden = 1.0; $xnum = 0.0; for ($i = 0; $i < 8; ++$i) { $xnum = $xnum * $xm2 + self::LG_P2[$i]; $xden = $xden * $xm2 + self::LG_Q2[$i]; } return $xm2 * (self::LG_D2 + $xm2 * ($xnum / $xden)); } protected static function logGamma3(float $y): float { // ---------------------- // 4.0 .LT. X .LE. 12.0 // ---------------------- $xm4 = $y - 4.0; $xden = -1.0; $xnum = 0.0; for ($i = 0; $i < 8; ++$i) { $xnum = $xnum * $xm4 + self::LG_P4[$i]; $xden = $xden * $xm4 + self::LG_Q4[$i]; } return self::LG_D4 + $xm4 * ($xnum / $xden); } protected static function logGamma4(float $y): float { // --------------------------------- // Evaluate for argument .GE. 12.0 // --------------------------------- $res = 0.0; if ($y <= self::LG_FRTBIG) { $res = self::LG_C[6]; $ysq = $y * $y; for ($i = 0; $i < 6; ++$i) { $res = $res / $ysq + self::LG_C[$i]; } $res /= $y; $corr = log($y); $res = $res + log(self::SQRT2PI) - 0.5 * $corr; $res += $y * ($corr - 1.0); } return $res; } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Gamma.php
src/PhpSpreadsheet/Calculation/Statistical/Distributions/Gamma.php
<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Gamma extends GammaBase { use ArrayEnabled; /** * GAMMA. * * Return the gamma function value. * * @param mixed $value Float value for which we want the probability * Or can be an array of values * * @return array<mixed>|float|string The result, or a string containing an error * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function gamma(mixed $value): array|string|float { if (is_array($value)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $value); } try { $value = DistributionValidations::validateFloat($value); } catch (Exception $e) { return $e->getMessage(); } if ((((int) $value) == ((float) $value)) && $value <= 0.0) { return ExcelError::NAN(); } return self::gammaValue($value); } /** * GAMMADIST. * * Returns the gamma distribution. * * @param mixed $value Float Value at which you want to evaluate the distribution * Or can be an array of values * @param mixed $a Parameter to the distribution as a float * Or can be an array of values * @param mixed $b Parameter to the distribution as a float * Or can be an array of values * @param mixed $cumulative Boolean value indicating if we want the cdf (true) or the pdf (false) * Or can be an array of values * * @return array<mixed>|float|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function distribution(mixed $value, mixed $a, mixed $b, mixed $cumulative) { if (is_array($value) || is_array($a) || is_array($b) || is_array($cumulative)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $a, $b, $cumulative); } try { $value = DistributionValidations::validateFloat($value); $a = DistributionValidations::validateFloat($a); $b = DistributionValidations::validateFloat($b); $cumulative = DistributionValidations::validateBool($cumulative); } catch (Exception $e) { return $e->getMessage(); } if (($value < 0) || ($a <= 0) || ($b <= 0)) { return ExcelError::NAN(); } return self::calculateDistribution($value, $a, $b, $cumulative); } /** * GAMMAINV. * * Returns the inverse of the Gamma distribution. * * @param mixed $probability Float probability at which you want to evaluate the distribution * Or can be an array of values * @param mixed $alpha Parameter to the distribution as a float * Or can be an array of values * @param mixed $beta Parameter to the distribution as a float * Or can be an array of values * * @return array<mixed>|float|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function inverse(mixed $probability, mixed $alpha, mixed $beta) { if (is_array($probability) || is_array($alpha) || is_array($beta)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $probability, $alpha, $beta); } try { $probability = DistributionValidations::validateProbability($probability); $alpha = DistributionValidations::validateFloat($alpha); $beta = DistributionValidations::validateFloat($beta); } catch (Exception $e) { return $e->getMessage(); } if (($alpha <= 0.0) || ($beta <= 0.0)) { return ExcelError::NAN(); } return self::calculateInverse($probability, $alpha, $beta); } /** * GAMMALN. * * Returns the natural logarithm of the gamma function. * * @param mixed $value Float Value at which you want to evaluate the distribution * Or can be an array of values * * @return array<mixed>|float|string If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function ln(mixed $value): array|string|float { if (is_array($value)) { return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $value); } try { $value = DistributionValidations::validateFloat($value); } catch (Exception $e) { return $e->getMessage(); } if ($value <= 0) { return ExcelError::NAN(); } return log(self::gammaValue($value)); } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false
PHPOffice/PhpSpreadsheet
https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Calculation/Statistical/Distributions/Weibull.php
src/PhpSpreadsheet/Calculation/Statistical/Distributions/Weibull.php
<?php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions; use PhpOffice\PhpSpreadsheet\Calculation\ArrayEnabled; use PhpOffice\PhpSpreadsheet\Calculation\Exception; use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError; class Weibull { use ArrayEnabled; /** * WEIBULL. * * Returns the Weibull distribution. Use this distribution in reliability * analysis, such as calculating a device's mean time to failure. * * @param mixed $value Float value for the distribution * Or can be an array of values * @param mixed $alpha Float alpha Parameter * Or can be an array of values * @param mixed $beta Float beta Parameter * Or can be an array of values * @param mixed $cumulative Boolean value indicating if we want the cdf (true) or the pdf (false) * Or can be an array of values * * @return array<mixed>|float|string (string if result is an error) * If an array of numbers is passed as an argument, then the returned result will also be an array * with the same dimensions */ public static function distribution(mixed $value, mixed $alpha, mixed $beta, mixed $cumulative): array|string|float { if (is_array($value) || is_array($alpha) || is_array($beta) || is_array($cumulative)) { return self::evaluateArrayArguments([self::class, __FUNCTION__], $value, $alpha, $beta, $cumulative); } try { $value = DistributionValidations::validateFloat($value); $alpha = DistributionValidations::validateFloat($alpha); $beta = DistributionValidations::validateFloat($beta); $cumulative = DistributionValidations::validateBool($cumulative); } catch (Exception $e) { return $e->getMessage(); } if (($value < 0) || ($alpha <= 0) || ($beta <= 0)) { return ExcelError::NAN(); } if ($cumulative) { return 1 - exp(0 - ($value / $beta) ** $alpha); } return ($alpha / $beta ** $alpha) * $value ** ($alpha - 1) * exp(0 - ($value / $beta) ** $alpha); } }
php
MIT
e33834b4ea2a02088becbb41fb8954d915b46b12
2026-01-04T15:02:44.305364Z
false