Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ and this project adheres to [Semantic Versioning](https://semver.org). Thia is a
- Php8.5 deprecates use of null as array index. [PR #4634](https://github.com/PHPOffice/PhpSpreadsheet/pull/4634)
- For Php8.5, replace one of our two uses of `__wakeup` with `__unserialize`, and eliminate the other. [PR #4639](https://github.com/PHPOffice/PhpSpreadsheet/pull/4639)
- Use prefix _xlfn for BASE function. [Issue #4638](https://github.com/PHPOffice/PhpSpreadsheet/issues/4638) [PR #4641](https://github.com/PHPOffice/PhpSpreadsheet/pull/4641)
- Additional support for union and intersection. [PR #4596](https://github.com/PHPOffice/PhpSpreadsheet/pull/4596)

## 2025-09-03 - 5.1.0

Expand Down
31 changes: 30 additions & 1 deletion src/PhpSpreadsheet/Calculation/Calculation.php
Original file line number Diff line number Diff line change
Expand Up @@ -1095,6 +1095,10 @@ private function internalParseFormula(string $formula, ?Cell $cell = null): bool
$this->branchPruner->initialiseForLoop();

$opCharacter = $formula[$index]; // Get the first character of the value at the current index position
if ($opCharacter === "\xe2") { // intersection or union
$opCharacter .= $formula[++$index];
$opCharacter .= $formula[++$index];
}

// Check for two-character operators (e.g. >=, <=, <>)
if ((isset(self::COMPARISON_OPERATORS[$opCharacter])) && (strlen($formula) > $index) && isset($formula[$index + 1], self::COMPARISON_OPERATORS[$formula[$index + 1]])) {
Expand All @@ -1115,7 +1119,7 @@ private function internalParseFormula(string $formula, ?Cell $cell = null): bool
++$index;
} elseif ($opCharacter === '+' && !$expectingOperator) { // Positive (unary plus rather than binary operator plus) can be discarded?
++$index; // Drop the redundant plus symbol
} elseif ((($opCharacter === '~') || ($opCharacter === '∩') || ($opCharacter === '∪')) && (!$isOperandOrFunction)) {
} elseif ((($opCharacter === '~') /*|| ($opCharacter === '∩') || ($opCharacter === '∪')*/) && (!$isOperandOrFunction)) {
// We have to explicitly deny a tilde, union or intersect because they are legal
return $this->raiseFormulaError("Formula Error: Illegal character '~'"); // on the stack but not in the input expression
} elseif ((isset(self::CALCULATION_OPERATORS[$opCharacter]) || $isOperandOrFunction) && $expectingOperator) { // Are we putting an operator on the stack?
Expand Down Expand Up @@ -1233,6 +1237,15 @@ private function internalParseFormula(string $formula, ?Cell $cell = null): bool
// MS Excel allows this if the content is cell references; but doesn't allow actual values,
// but at this point, we can't differentiate (so allow both)
return $this->raiseFormulaError('Formula Error: Unexpected ,');
/* The following code may be a better choice, but, with
the other changes for this PR, I can no longer come up
with a test case that gets here
$stack->push('Binary Operator', '∪');

++$index;
$expectingOperator = false;

continue;*/
}

/** @var array<string, int> $d */
Expand Down Expand Up @@ -1927,6 +1940,14 @@ private function processTokenStack(false|array $tokens, ?string $cellID = null,
$stack->push('Value', $cellIntersect, $cellRef);
}

break;
case '∪': // union
/** @var mixed[][] $operand1 */
/** @var mixed[][] $operand2 */
$cellUnion = array_merge($operand1, $operand2);
$this->debugLog->writeDebugLog('Evaluation Result is %s', $this->showTypeDetails($cellUnion));
$stack->push('Value', $cellUnion, 'A1');

break;
}
} elseif (($token === '~') || ($token === '%')) {
Expand Down Expand Up @@ -2792,6 +2813,14 @@ private function evaluateDefinedName(Cell $cell, DefinedName $namedRange, Worksh

$definedNameValue = $namedRange->getValue();
$definedNameType = $namedRange->isFormula() ? 'Formula' : 'Range';
if ($definedNameType === 'Range') {
if (preg_match('/^(.*!)?(.*)$/', $definedNameValue, $matches) === 1) {
$matches2 = trim($matches[2]);
$matches2 = preg_replace('/ +/', ' ∩ ', $matches2) ?? $matches2;
$matches2 = preg_replace('/,/', ' ∪ ', $matches2) ?? $matches2;
$definedNameValue = $matches[1] . $matches2;
}
}
$definedNameWorksheet = $namedRange->getWorksheet();

if ($definedNameValue[0] !== '=') {
Expand Down
31 changes: 31 additions & 0 deletions src/PhpSpreadsheet/Cell/Cell.php
Original file line number Diff line number Diff line change
Expand Up @@ -453,6 +453,7 @@ public function getCalculatedValue(bool $resetLog = true): mixed
}
$newColumn = $this->getColumn();
if (is_array($result)) {
$result = self::convertSpecialArray($result);
$this->formulaAttributes['t'] = 'array';
$this->formulaAttributes['ref'] = $maxCoordinate = $coordinate;
$newRow = $row = $this->getRow();
Expand Down Expand Up @@ -581,6 +582,36 @@ public function getCalculatedValue(bool $resetLog = true): mixed
return $this->convertDateTimeInt($this->value);
}

/**
* Convert array like the following (preserve values, lose indexes):
* [
* rowNumber1 => [colLetter1 => value, colLetter2 => value ...],
* rowNumber2 => [colLetter1 => value, colLetter2 => value ...],
* ...
* ].
*
* @param mixed[] $array
*
* @return mixed[]
*/
private static function convertSpecialArray(array $array): array
{
$newArray = [];
foreach ($array as $rowIndex => $row) {
if (!is_int($rowIndex) || $rowIndex <= 0 || !is_array($row)) {
return $array;
}
$keys = array_keys($row);
$key0 = $keys[0] ?? '';
if (!is_string($key0)) {
return $array;
}
$newArray[] = array_values($row);
}

return $newArray;
}

/**
* Set old calculated value (cached).
*
Expand Down
45 changes: 35 additions & 10 deletions tests/PhpSpreadsheetTests/Calculation/Engine/RangeTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,6 @@

class RangeTest extends TestCase
{
private string $incompleteMessage = 'Must be revisited';

private ?Spreadsheet $spreadSheet = null;

protected function getSpreadsheet(): Spreadsheet
Expand Down Expand Up @@ -162,9 +160,6 @@ public static function providerUTF8NamedRangeEvaluation(): array
#[DataProvider('providerCompositeNamedRangeEvaluation')]
public function testCompositeNamedRangeEvaluation(string $composite, int $expectedSum, int $expectedCount): void
{
if ($this->incompleteMessage !== '') {
self::markTestIncomplete($this->incompleteMessage);
}
$this->spreadSheet = $this->getSpreadsheet();

$workSheet = $this->spreadSheet->getActiveSheet();
Expand All @@ -182,17 +177,47 @@ public function testCompositeNamedRangeEvaluation(string $composite, int $expect
public static function providerCompositeNamedRangeEvaluation(): array
{
return [
// Calculation engine doesn't yet handle union ranges with overlap
'Union with overlap' => [
'A1:C1,A3:C3,B1:C3',
63,
'$A$1:$C$1,$A$3:$C$3,$B$1:$C$3',
99,
12,
],
'Union and Intersection' => [
'A1:C1,A3:C3 B1:C3',
23,
'$A$1:$C$1,$A$3:$C$3 $B$1:$C$3',
35,
5,
],
];
}

public function testIntersectCellFormula(): void
{
$this->spreadSheet = $this->getSpreadsheet();

$sheet = $this->spreadSheet->getActiveSheet();
$array = [
[null, 'Planets', 'Lives', 'Babies'],
['Batman', 5, 10, 4],
['Superman', 4, 56, 34],
['Spiderman', 23, 45, 67],
['Hulk', 12, 34, 58],
['Steve', 10, 34, 78],
];
$sheet->fromArray($array, null, 'A3', true);
$this->spreadSheet->addNamedRange(new NamedRange('Hulk', $sheet, '$B$7:$D$7'));
$this->spreadSheet->addNamedRange(new NamedRange('Planets', $sheet, '$B$4:$B$8'));
$this->spreadSheet->addNamedRange(new NamedRange('Intersect', $sheet, '$A$6:$D$6 $C$4:$C$8'));
$this->spreadSheet->addNamedRange(new NamedRange('SupHulk', $sheet, '$B$5:$D$5,$B$7:$D$7'));

$sheet->setCellValue('F1', '=Intersect');
$sheet->setCellValue('F2', '=SUM(SupHulk)');
$sheet->setCellValue('F3', '=Planets Hulk');
$sheet->setCellValue('F4', '=B4:D4 B4:C5');

$this->spreadSheet->returnArrayAsArray();
self::assertSame(45, $sheet->getCell('F1')->getCalculatedValue());
self::assertSame(198, $sheet->getCell('F2')->getCalculatedValue());
self::assertSame(12, $sheet->getCell('F3')->getCalculatedValue());
self::assertSame([[5, 10]], $sheet->getCell('F4')->getCalculatedValue());
}
}
61 changes: 61 additions & 0 deletions tests/PhpSpreadsheetTests/Cell/ConvertSpecialArrayTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
<?php

declare(strict_types=1);

namespace PhpOffice\PhpSpreadsheetTests\Cell;

use PhpOffice\PhpSpreadsheet\Cell\Cell;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
use ReflectionMethod;

class ConvertSpecialArrayTest extends TestCase
{
/**
* @param mixed[] $expected
* @param mixed[] $inArray
*/
#[DataProvider('providerSpecialArrays')]
public function testConvertSpecialArray(array $expected, array $inArray): void
{
$reflectionMethod = new ReflectionMethod(Cell::class, 'convertSpecialArray');
$result = $reflectionMethod->invokeArgs(null, [$inArray]);
self::assertSame($expected, $result);
}

public static function providerSpecialArrays(): array
{
return [
'expected form row index to array indexed by column' => [
[
[1, 2],
[3, 4],
],
[
1 => ['A' => 1, 'B' => 2],
2 => ['A' => 3, 'B' => 4],
],
],
'standard array unchanged' => [
[
1 => [1, 2],
2 => [3, 4],
],
[
1 => [1, 2],
2 => [3, 4],
],
],
'uses index 0 so unchanged' => [
[
['A' => 1, 'B' => 2],
['A' => 3, 'B' => 4],
],
[
['A' => 1, 'B' => 2],
['A' => 3, 'B' => 4],
],
],
];
}
}
13 changes: 6 additions & 7 deletions tests/PhpSpreadsheetTests/Worksheet/Table/Issue3659Test.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@

namespace PhpOffice\PhpSpreadsheetTests\Worksheet\Table;

use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PhpOffice\PhpSpreadsheet\Worksheet\Table;

class Issue3659Test extends SetupTeardown
Expand Down Expand Up @@ -49,7 +48,7 @@ public function testTableOnOtherSheet(): void
public function testTableAsArray(): void
{
$spreadsheet = $this->getSpreadsheet();
Calculation::getInstance($spreadsheet)->setInstanceArrayReturnType(Calculation::RETURN_ARRAY_AS_ARRAY);
$spreadsheet->returnArrayAsArray();
$sheet = $this->getSheet();
$sheet->setTitle('Feuil1');
$tableSheet = $spreadsheet->createSheet();
Expand All @@ -76,13 +75,13 @@ public function testTableAsArray(): void
$sheet->getCell('F9')->setValue('=Tableau1');
$sheet->getCell('J9')->setValue('=CONCAT(Tableau1)');
$sheet->getCell('J11')->setValue('=SUM(Tableau1[])');
$expectedResult = [2 => ['B' => 10], ['B' => 2], ['B' => 3], ['B' => 4]];
$expectedResult = [[10], [2], [3], [4]];
self::assertSame($expectedResult, $sheet->getCell('F1')->getCalculatedValue());
$expectedResult = [
2 => ['B' => 10, 'C' => 20, 'D' => null],
['B' => 2, 'C' => null, 'D' => null],
['B' => 3, 'C' => null, 'D' => null],
['B' => 4, 'C' => null, 'D' => null],
[10, 20, null],
[2, null, null],
[3, null, null],
[4, null, null],
];
self::assertSame($expectedResult, $sheet->getCell('H1')->getCalculatedValue());
self::assertSame($expectedResult, $sheet->getCell('F9')->getCalculatedValue());
Expand Down