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
14 changes: 14 additions & 0 deletions src/PhpSpreadsheet/Calculation/Calculation.php
Original file line number Diff line number Diff line change
Expand Up @@ -3470,11 +3470,15 @@ public function calculateCellValue(?Cell $cell = null, $resetLog = true)
'cell' => $cell->getCoordinate(),
];

$cellAddressAttempted = false;
$cellAddress = null;

try {
$result = self::unwrapResult($this->_calculateFormulaValue($cell->getValue(), $cell->getCoordinate(), $cell));
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');
Expand All @@ -3485,6 +3489,16 @@ public function calculateCellValue(?Cell $cell = null, $resetLog = true)
}
$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)) {
$testSheet = $this->spreadsheet->getSheetByName($cellAddress['sheet']);
if ($testSheet !== null && array_key_exists('cell', $cellAddress)) {
$testSheet->getCell($cellAddress['cell']);
}
}

throw new Exception($e->getMessage());
}

Expand Down
49 changes: 49 additions & 0 deletions tests/PhpSpreadsheetTests/Calculation/CyclicTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
<?php

namespace PhpOffice\PhpSpreadsheetTests\Calculation;

use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PhpOffice\PhpSpreadsheet\Calculation\Exception as CalcException;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PHPUnit\Framework\TestCase;

class CyclicTest extends TestCase
{
public function testCyclicReference(): void
{
// Issue 3169
$spreadsheet = new Spreadsheet();

$table_data = [
['abc', 'def', 'ghi'],
['1', '4', '=B3+A3'],
['=SUM(A2:C2)', '2', '=A2+B2'],
];
// Don't allow cyclic references.
Calculation::getInstance($spreadsheet)->cyclicFormulaCount = 0;

$worksheet = $spreadsheet->getActiveSheet();
$worksheet->fromArray($table_data, '');

try {
$result = $worksheet->getCell('C2')->getCalculatedValue();
} catch (CalcException $e) {
$result = $e->getMessage();
}
self::assertSame(
'Worksheet!C2 -> Worksheet!A3 -> Worksheet!C2 -> Cyclic Reference in Formula',
$result
);

try {
$result = $worksheet->getCell('A3')->getCalculatedValue();
} catch (CalcException $e) {
$result = $e->getMessage();
}
self::assertSame(
'Worksheet!A3 -> Worksheet!C2 -> Worksheet!A3 -> Cyclic Reference in Formula',
$result
);
$spreadsheet->disconnectWorksheets();
}
}