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/tests/PhpSpreadsheetTests/NamedRange2Test.php | tests/PhpSpreadsheetTests/NamedRange2Test.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests;
use PhpOffice\PhpSpreadsheet\DefinedName;
use PhpOffice\PhpSpreadsheet\Exception as Except;
use PhpOffice\PhpSpreadsheet\NamedRange;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PHPUnit\Framework\TestCase;
class NamedRange2Test extends TestCase
{
private ?Spreadsheet $spreadsheet = null;
protected function setUp(): void
{
$spreadsheet = $this->spreadsheet = new Spreadsheet();
$worksheet1 = $spreadsheet->getActiveSheet();
$worksheet1->setTitle('SheetOne');
$spreadsheet->addNamedRange(
new NamedRange('FirstRel', $worksheet1, '=A1')
);
$spreadsheet->addNamedRange(
new NamedRange('FirstAbs', $worksheet1, '=$B$1')
);
$spreadsheet->addNamedRange(
new NamedRange('FirstRelMult', $worksheet1, '=C1:D2')
);
$spreadsheet->addNamedRange(
new NamedRange('FirstAbsMult', $worksheet1, '$E$3:$F$4')
);
$worksheet2 = $spreadsheet->createSheet();
$worksheet2->setTitle('SheetTwo');
$spreadsheet->addNamedRange(
new NamedRange('SecondRel', $worksheet2, '=A1')
);
$spreadsheet->addNamedRange(
new NamedRange('SecondAbs', $worksheet2, '=$B$1')
);
$spreadsheet->addNamedRange(
new NamedRange('SecondRelMult', $worksheet2, '=C1:D2')
);
$spreadsheet->addNamedRange(
new NamedRange('SecondAbsMult', $worksheet2, '$E$3:$F$4')
);
$spreadsheet->addDefinedName(DefinedName::createInstance('FirstFormula', $worksheet1, '=TODAY()-1'));
$spreadsheet->addDefinedName(DefinedName::createInstance('SecondFormula', $worksheet2, '=TODAY()-2'));
$this->spreadsheet->setActiveSheetIndex(0);
}
protected function tearDown(): void
{
if ($this->spreadsheet !== null) {
$this->spreadsheet->disconnectWorksheets();
$this->spreadsheet = null;
}
}
private function getSpreadsheet(): Spreadsheet
{
if ($this->spreadsheet !== null) {
return $this->spreadsheet;
}
$this->spreadsheet = new Spreadsheet();
return $this->spreadsheet;
}
public function testNamedRangeSetStyle(): void
{
$spreadsheet = $this->getSpreadsheet();
$sheet = $spreadsheet->getSheet(0);
$sheet->getStyle('FirstRel')->getNumberFormat()->setFormatCode('yyyy-mm-dd');
self::assertSame('yyyy-mm-dd', $sheet->getStyle('A1')->getNumberFormat()->getFormatCode());
$sheet->getStyle('FirstAbs')->getFont()->setName('Georgia');
self::assertSame('Georgia', $sheet->getStyle('B1')->getFont()->getName());
$sheet->getStyle('FirstRelMult')->getFont()->setItalic(true);
self::assertTrue($sheet->getStyle('D2')->getFont()->getItalic());
$sheet->getStyle('FirstAbsMult')->getFill()->setFillType('gray125');
self::assertSame('gray125', $sheet->getStyle('F4')->getFill()->getFillType());
self::assertSame('none', $sheet->getStyle('A1')->getFill()->getFillType());
$sheet = $spreadsheet->getSheet(1);
$sheet->getStyle('SecondAbsMult')->getFill()->setFillType('lightDown');
self::assertSame('lightDown', $sheet->getStyle('E3')->getFill()->getFillType());
}
#[\PHPUnit\Framework\Attributes\DataProvider('providerRangeOrFormula')]
public function testNamedRangeSetStyleBad(string $exceptionMessage, string $name): void
{
$this->expectException(Except::class);
$this->expectExceptionMessage($exceptionMessage);
$spreadsheet = $this->getSpreadsheet();
$sheet = $spreadsheet->getSheet(0);
$sheet->getStyle($name)->getNumberFormat()->setFormatCode('yyyy-mm-dd');
self::assertSame('yyyy-mm-dd', $sheet->getStyle('A1')->getNumberFormat()->getFormatCode());
}
public static function providerRangeOrFormula(): array
{
return [
'wrong sheet rel' => ['Invalid cell coordinate', 'SecondRel'],
'wrong sheet abs' => ['Invalid cell coordinate', 'SecondAbs'],
'wrong sheet relmult' => ['Invalid cell coordinate', 'SecondRelMult'],
'wrong sheet absmult' => ['Invalid cell coordinate', 'SecondAbsMult'],
'wrong sheet formula' => ['Invalid cell coordinate', 'SecondFormula'],
'right sheet formula' => ['Invalid cell coordinate', 'FirstFormula'],
'non-existent name' => ['Invalid cell coordinate', 'NonExistentName'],
'other sheet name' => ['Invalid Worksheet', 'SheetTwo!G7'],
'non-existent sheet name' => ['Invalid Worksheet', 'SheetAbc!G7'],
'unnamed formula' => ['Invalid cell coordinate', '=2+3'],
];
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/NamedRange3Test.php | tests/PhpSpreadsheetTests/NamedRange3Test.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests;
use PhpOffice\PhpSpreadsheet\NamedRange;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PHPUnit\Framework\TestCase;
class NamedRange3Test extends TestCase
{
public function testSheetNamePlusDefinedName(): void
{
$spreadsheet = new Spreadsheet();
$sheet1 = $spreadsheet->getActiveSheet();
$sheet1->setTitle('sheet1');
$sheet1->setCellValue('B1', 100);
$sheet1->setCellValue('B2', 200);
$sheet1->setCellValue('B3', 300);
$sheet1->setCellValue('B4', 400);
$sheet1->setCellValue('B5', 500);
$sheet2 = $spreadsheet->createsheet();
$sheet2->setTitle('sheet2');
$sheet2->setCellValue('A1', 10);
$sheet2->setCellValue('A2', 20);
$sheet2->setCellValue('A3', 30);
$sheet2->setCellValue('A4', 40);
$sheet2->setCellValue('A5', 50);
$spreadsheet->addNamedRange(
new NamedRange('somecells', $sheet2, '$A$1:$A$5', true)
);
$spreadsheet->addNamedRange(
new NamedRange('cellsonsheet1', $sheet1, '$B$1:$B$5')
);
$sheet1->getCell('G1')->setValue('=SUM(cellsonsheet1)');
self::assertSame(1500, $sheet1->getCell('G1')->getCalculatedValue());
$sheet1->getCell('G2')->setValue('=SUM(sheet2!somecells)');
self::assertSame(150, $sheet1->getCell('G2')->getCalculatedValue());
$sheet1->getCell('G3')->setValue('=SUM(somecells)');
self::assertSame('#NAME?', $sheet1->getCell('G3')->getCalculatedValue());
$sheet1->getCell('G4')->setValue('=SUM(sheet2!cellsonsheet1)');
self::assertSame(1500, $sheet1->getCell('G4')->getCalculatedValue());
$sheet1->getCell('G5')->setValue('=SUM(sheet2xxx!cellsonsheet1)');
self::assertSame('#NAME?', $sheet1->getCell('G5')->getCalculatedValue());
$spreadsheet->disconnectWorksheets();
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/ReferenceHelper5Test.php | tests/PhpSpreadsheetTests/ReferenceHelper5Test.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PHPUnit\Framework\TestCase;
class ReferenceHelper5Test extends TestCase
{
public function testIssue4246(): void
{
// code below would have thrown exception because
// row and column were swapped in code
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$row = 987654;
$rowMinus1 = $row - 1;
$rowPlus1 = $row + 1;
$sheet->getCell("A$rowMinus1")->setValue(1);
$sheet->getCell("B$rowMinus1")->setValue(2);
$sheet->getCell("C$rowMinus1")->setValue(3);
$sheet->getStyle("A$rowMinus1")->getFont()->setBold(true);
$sheet->getCell("A$row")->setValue(1);
$sheet->getCell("B$row")->setValue(2);
$sheet->getCell("C$row")->setValue(3);
$sheet->getStyle("B$row")->getFont()->setBold(true);
$sheet->insertNewRowBefore($row);
self::assertTrue(
$sheet->getStyle("A$row")->getFont()->getBold()
);
self::assertFalse(
$sheet->getStyle("B$row")->getFont()->getBold()
);
self::assertFalse(
$sheet->getStyle("A$rowPlus1")->getFont()->getBold()
);
self::assertTrue(
$sheet->getStyle("B$rowPlus1")->getFont()->getBold()
);
$spreadsheet->disconnectWorksheets();
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/SpreadsheetCopyCloneTest.php | tests/PhpSpreadsheetTests/SpreadsheetCopyCloneTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests;
use PhpOffice\PhpSpreadsheet\DefinedName;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
class SpreadsheetCopyCloneTest extends TestCase
{
private ?Spreadsheet $spreadsheet = null;
private ?Spreadsheet $spreadsheet2 = null;
protected function tearDown(): void
{
if ($this->spreadsheet !== null) {
$this->spreadsheet->disconnectWorksheets();
$this->spreadsheet = null;
}
if ($this->spreadsheet2 !== null) {
$this->spreadsheet2->disconnectWorksheets();
$this->spreadsheet2 = null;
}
}
#[DataProvider('providerCopyClone')]
public function testCopyClone(string $type): void
{
$spreadsheet = $this->spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setTitle('original');
$sheet->getStyle('A1')->getFont()->setName('font1');
$sheet->getStyle('A2')->getFont()->setName('font2');
$sheet->getStyle('A3')->getFont()->setName('font3');
$sheet->getStyle('B1')->getFont()->setName('font1');
$sheet->getStyle('B2')->getFont()->setName('font2');
$sheet->getCell('A1')->setValue('this is a1');
$sheet->getCell('A2')->setValue('this is a2');
$sheet->getCell('A3')->setValue('this is a3');
$sheet->getCell('B1')->setValue('this is b1');
$sheet->getCell('B2')->setValue('this is b2');
self::assertSame('font1', $sheet->getStyle('A1')->getFont()->getName());
$sheet->setSelectedCells('A3');
if ($type === 'copy') {
$spreadsheet2 = $this->spreadsheet2 = $spreadsheet->copy();
} else {
$spreadsheet2 = $this->spreadsheet2 = clone $spreadsheet;
}
self::assertSame($spreadsheet, $spreadsheet->getCalculationEngine()->getSpreadsheet());
self::assertSame($spreadsheet2, $spreadsheet2->getCalculationEngine()->getSpreadsheet());
self::assertSame('A3', $sheet->getSelectedCells());
$copysheet = $spreadsheet2->getActiveSheet();
self::assertSame('A3', $copysheet->getSelectedCells());
self::assertSame('original', $copysheet->getTitle());
$copysheet->setTitle('unoriginal');
self::assertSame('original', $sheet->getTitle());
self::assertSame('unoriginal', $copysheet->getTitle());
$copysheet->getStyle('A2')->getFont()->setName('font12');
$copysheet->getCell('A2')->setValue('this was a2');
self::assertSame('font1', $sheet->getStyle('A1')->getFont()->getName());
self::assertSame('font2', $sheet->getStyle('A2')->getFont()->getName());
self::assertSame('font3', $sheet->getStyle('A3')->getFont()->getName());
self::assertSame('font1', $sheet->getStyle('B1')->getFont()->getName());
self::assertSame('font2', $sheet->getStyle('B2')->getFont()->getName());
self::assertSame('this is a1', $sheet->getCell('A1')->getValue());
self::assertSame('this is a2', $sheet->getCell('A2')->getValue());
self::assertSame('this is a3', $sheet->getCell('A3')->getValue());
self::assertSame('this is b1', $sheet->getCell('B1')->getValue());
self::assertSame('this is b2', $sheet->getCell('B2')->getValue());
self::assertSame('font1', $copysheet->getStyle('A1')->getFont()->getName());
self::assertSame('font12', $copysheet->getStyle('A2')->getFont()->getName());
self::assertSame('font3', $copysheet->getStyle('A3')->getFont()->getName());
self::assertSame('font1', $copysheet->getStyle('B1')->getFont()->getName());
self::assertSame('font2', $copysheet->getStyle('B2')->getFont()->getName());
self::assertSame('this is a1', $copysheet->getCell('A1')->getValue());
self::assertSame('this was a2', $copysheet->getCell('A2')->getValue());
self::assertSame('this is a3', $copysheet->getCell('A3')->getValue());
self::assertSame('this is b1', $copysheet->getCell('B1')->getValue());
self::assertSame('this is b2', $copysheet->getCell('B2')->getValue());
}
#[DataProvider('providerCopyClone')]
public function testCopyCloneActiveSheet(string $type): void
{
$this->spreadsheet = new Spreadsheet();
$sheet0 = $this->spreadsheet->getActiveSheet();
$sheet1 = $this->spreadsheet->createSheet();
$sheet2 = $this->spreadsheet->createSheet();
$sheet3 = $this->spreadsheet->createSheet();
$sheet4 = $this->spreadsheet->createSheet();
$sheet0->getStyle('B1')->getFont()->setName('whatever');
$sheet1->getStyle('B1')->getFont()->setName('whatever');
$sheet2->getStyle('B1')->getFont()->setName('whatever');
$sheet3->getStyle('B1')->getFont()->setName('whatever');
$sheet4->getStyle('B1')->getFont()->setName('whatever');
$this->spreadsheet->setActiveSheetIndex(2);
if ($type === 'copy') {
$this->spreadsheet2 = $this->spreadsheet->copy();
} else {
$this->spreadsheet2 = clone $this->spreadsheet;
}
self::assertSame(2, $this->spreadsheet2->getActiveSheetIndex());
}
public static function providerCopyClone(): array
{
return [
['copy'],
['clone'],
];
}
#[DataProvider('providerCopyClone')]
public function testCopyCloneDefinedName(string $type): void
{
$spreadsheet = $this->spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet2 = $spreadsheet->createSheet();
$sheet->setTitle('original1');
$sheet2->setTitle('original2');
$spreadsheet->addDefinedName(
DefinedName::createInstance('defname1', $sheet, '$A$1:$A$3')
);
$spreadsheet->addDefinedName(
DefinedName::createInstance('defname2', $sheet2, '$B$1:$B$3', true, $sheet)
);
if ($type === 'copy') {
$spreadsheet2 = $this->spreadsheet2 = $spreadsheet->copy();
} else {
$spreadsheet2 = $this->spreadsheet2 = clone $spreadsheet;
}
$copySheet = $spreadsheet2->getSheetByNameOrThrow('original1');
$copySheet2 = $spreadsheet2->getSheetByNameOrThrow('original2');
$definedName = $spreadsheet2->getDefinedName('defname1');
self::assertNotNull($definedName);
self::assertSame('$A$1:$A$3', $definedName->getValue());
self::assertSame($copySheet, $definedName->getWorksheet());
self::assertNull($definedName->getScope());
$definedName = $spreadsheet2->getDefinedName('defname2', $copySheet);
self::assertNotNull($definedName);
self::assertSame('$B$1:$B$3', $definedName->getValue());
self::assertSame($copySheet2, $definedName->getWorksheet());
self::assertSame($copySheet, $definedName->getScope());
}
public static function providerCopyClone2(): array
{
return [
['copy', true, false, true, 'array'],
['clone', true, false, true, 'array'],
['copy', false, true, false, 'value'],
['clone', false, true, false, 'value'],
['copy', false, true, true, 'error'],
['clone', false, true, true, 'error'],
];
}
#[DataProvider('providerCopyClone2')]
public function testCopyClone2(string $type, bool $suppress, bool $cache, bool $pruning, string $return): void
{
$spreadsheet = $this->spreadsheet = new Spreadsheet();
$calc = $spreadsheet->getCalculationEngine();
$calc->setSuppressFormulaErrors($suppress);
$calc->setCalculationCacheEnabled($cache);
$calc->setBranchPruningEnabled($pruning);
$calc->setInstanceArrayReturnType($return);
if ($type === 'copy') {
$spreadsheet2 = $this->spreadsheet2 = $spreadsheet->copy();
} else {
$spreadsheet2 = $this->spreadsheet2 = clone $spreadsheet;
}
$calc2 = $spreadsheet2->getCalculationEngine();
self::assertSame($suppress, $calc2->getSuppressFormulaErrors());
self::assertSame($cache, $calc2->getCalculationCacheEnabled());
self::assertSame($pruning, $calc2->getBranchPruningEnabled());
self::assertSame($return, $calc2->getInstanceArrayReturnType());
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/SpreadsheetSerializeTest.php | tests/PhpSpreadsheetTests/SpreadsheetSerializeTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests;
use PhpOffice\PhpSpreadsheet\Exception as SpreadsheetException;
use PhpOffice\PhpSpreadsheet\Helper\Sample;
use PhpOffice\PhpSpreadsheet\NamedRange;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PHPUnit\Framework\TestCase;
class SpreadsheetSerializeTest extends TestCase
{
private ?Spreadsheet $spreadsheet = null;
protected function tearDown(): void
{
if ($this->spreadsheet !== null) {
$this->spreadsheet->disconnectWorksheets();
$this->spreadsheet = null;
}
}
public function testSerialize(): void
{
$this->spreadsheet = new Spreadsheet();
$sheet = $this->spreadsheet->getActiveSheet();
$sheet->getCell('A1')->setValue(10);
$serialized = serialize($this->spreadsheet);
$newSpreadsheet = unserialize($serialized);
self::assertInstanceOf(Spreadsheet::class, $newSpreadsheet);
self::assertNotSame($this->spreadsheet, $newSpreadsheet);
$newSheet = $newSpreadsheet->getActiveSheet();
self::assertSame(10, $newSheet->getCell('A1')->getValue());
$newSpreadsheet->disconnectWorksheets();
}
public function testNotJsonEncodable(): void
{
$this->spreadsheet = new Spreadsheet();
$this->expectException(SpreadsheetException::class);
$this->expectExceptionMessage('Spreadsheet objects cannot be json encoded');
json_encode($this->spreadsheet);
}
/**
* These tests are a bit weird.
* If prepareSerialize and readSerialize are run in the same
* process, the latter's assertions will always succeed.
* So to demonstrate that the
* problem is solved, they need to run in separate processes.
* But then they can't share the file name. So we need to send
* the file to a semi-hard-coded destination.
*/
private static function getTempFileName(): string
{
$helper = new Sample();
return $helper->getTemporaryFolder() . '/spreadsheet.serialize.test.txt';
}
public function testPrepareSerialize(): void
{
$this->spreadsheet = new Spreadsheet();
$sheet = $this->spreadsheet->getActiveSheet();
$this->spreadsheet->addNamedRange(new NamedRange('summedcells', $sheet, '$A$1:$A$5'));
$sheet->setCellValue('A1', 1);
$sheet->setCellValue('A2', 2);
$sheet->setCellValue('A3', 3);
$sheet->setCellValue('A4', 4);
$sheet->setCellValue('A5', 5);
$sheet->setCellValue('C1', '=SUM(summedcells)');
$ser = serialize($this->spreadsheet);
$this->spreadsheet->disconnectWorksheets();
$outputFileName = self::getTempFileName();
self::assertNotFalse(
file_put_contents($outputFileName, $ser)
);
$inputFileName = self::getTempFileName();
$ser = (string) file_get_contents($inputFileName);
unlink($inputFileName);
$spreadsheet = unserialize($ser);
self::assertInstanceOf(Spreadsheet::class, $spreadsheet);
$this->spreadsheet = $spreadsheet;
$sheet = $this->spreadsheet->getActiveSheet();
self::assertSame('=SUM(summedcells)', $sheet->getCell('C1')->getValue());
self::assertSame(15, $sheet->getCell('C1')->getCalculatedValue());
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/FloatImprecisionTest.php | tests/PhpSpreadsheetTests/FloatImprecisionTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
class FloatImprecisionTest extends TestCase
{
#[DataProvider('providerFloats')]
public function testCompareFloats(float $float1, float $float2): void
{
self::assertSame($float1, $float2);
}
public static function providerFloats(): array
{
return [
[12345.6789, 12345.67890000000079],
];
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/IOFactoryTest.php | tests/PhpSpreadsheetTests/IOFactoryTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Reader;
use PhpOffice\PhpSpreadsheet\Reader\Exception as ReaderException;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
class IOFactoryTest extends TestCase
{
#[DataProvider('providerCreateWriter')]
public function testCreateWriter(string $name, string $expected): void
{
$spreadsheet = new Spreadsheet();
$actual = IOFactory::createWriter($spreadsheet, $name);
self::assertSame($expected, $actual::class);
}
public static function providerCreateWriter(): array
{
return [
['Xls', Writer\Xls::class],
['Xlsx', Writer\Xlsx::class],
['Ods', Writer\Ods::class],
['Csv', Writer\Csv::class],
['Html', Writer\Html::class],
['Mpdf', Writer\Pdf\Mpdf::class],
['Tcpdf', Writer\Pdf\Tcpdf::class],
['Dompdf', Writer\Pdf\Dompdf::class],
];
}
public function testRegisterWriter(): void
{
IOFactory::registerWriter('Pdf', Writer\Pdf\Mpdf::class);
$spreadsheet = new Spreadsheet();
$actual = IOFactory::createWriter($spreadsheet, 'Pdf');
self::assertInstanceOf(Writer\Pdf\Mpdf::class, $actual);
}
#[DataProvider('providerCreateReader')]
public function testCreateReader(string $name, string $expected): void
{
$actual = IOFactory::createReader($name);
self::assertSame($expected, $actual::class);
}
public static function providerCreateReader(): array
{
return [
['Xls', Reader\Xls::class],
['Xlsx', Reader\Xlsx::class],
['Xml', Reader\Xml::class],
['Ods', Reader\Ods::class],
['Gnumeric', Reader\Gnumeric::class],
['Csv', Reader\Csv::class],
['Slk', Reader\Slk::class],
['Html', Reader\Html::class],
];
}
public function testRegisterReader(): void
{
IOFactory::registerReader('Custom', Reader\Html::class);
$actual = IOFactory::createReader('Custom');
self::assertInstanceOf(Reader\Html::class, $actual);
}
#[DataProvider('providerIdentify')]
public function testIdentifyCreateLoad(string $file, string $expectedName, string $expectedClass): void
{
$actual = IOFactory::identify($file);
self::assertSame($expectedName, $actual);
$actual = IOFactory::createReaderForFile($file);
self::assertSame($expectedClass, $actual::class);
IOFactory::load($file);
}
public static function providerIdentify(): array
{
return [
['samples/templates/26template.xlsx', 'Xlsx', Reader\Xlsx::class],
['samples/templates/GnumericTest.gnumeric', 'Gnumeric', Reader\Gnumeric::class],
['tests/data/Reader/Gnumeric/PageSetup.gnumeric.unzipped.xml', 'Gnumeric', Reader\Gnumeric::class],
['samples/templates/old.gnumeric', 'Gnumeric', Reader\Gnumeric::class],
['samples/templates/30template.xls', 'Xls', Reader\Xls::class],
['samples/templates/OOCalcTest.ods', 'Ods', Reader\Ods::class],
['samples/templates/SylkTest.slk', 'Slk', Reader\Slk::class],
['samples/templates/excel2003.xml', 'Xml', Reader\Xml::class],
// Following not readable by Excel.
//['samples/templates/Excel2003XMLTest.xml', 'Xml', Reader\Xml::class],
['samples/templates/46readHtml.html', 'Html', Reader\Html::class],
['tests/data/Reader/CSV/encoding.utf8bom.csv', 'Csv', Reader\Csv::class],
['tests/data/Reader/HTML/charset.UTF-16.lebom.html', 'Html', Reader\Html::class],
['tests/data/Reader/HTML/charset.UTF-8.bom.html', 'Html', Reader\Html::class],
];
}
public function testIdentifyInvalid(): void
{
$file = __DIR__ . '/../data/Reader/NotASpreadsheetFile.doc';
$this->expectException(ReaderException::class);
$this->expectExceptionMessage('Unable to identify a reader for this file');
IOFactory::identify($file);
}
public function testCreateInvalid(): void
{
$file = __DIR__ . '/../data/Reader/NotASpreadsheetFile.doc';
$this->expectException(ReaderException::class);
$this->expectExceptionMessage('Unable to identify a reader for this file');
IOFactory::createReaderForFile($file);
}
public function testLoadInvalid(): void
{
$file = __DIR__ . '/../data/Reader/NotASpreadsheetFile.doc';
$this->expectException(ReaderException::class);
$this->expectExceptionMessage('Unable to identify a reader for this file');
IOFactory::load($file);
}
public function testFormatAsExpected(): void
{
$fileName = 'samples/templates/30template.xls';
$actual = IOFactory::identify($fileName, [IOFactory::READER_XLS]);
self::assertSame('Xls', $actual);
}
public function testFormatNotAsExpectedThrowsException(): void
{
$fileName = 'samples/templates/30template.xls';
$this->expectException(ReaderException::class);
IOFactory::identify($fileName, [IOFactory::READER_ODS]);
}
public function testIdentifyNonExistingFileThrowException(): void
{
$this->expectException(ReaderException::class);
IOFactory::identify('/non/existing/file');
}
public function testIdentifyExistingDirectoryThrowExceptions(): void
{
$this->expectException(ReaderException::class);
IOFactory::identify('.');
}
public function testCreateInvalidWriter(): void
{
$this->expectException(Writer\Exception::class);
$spreadsheet = new Spreadsheet();
IOFactory::createWriter($spreadsheet, 'bad');
}
public function testCreateInvalidReader(): void
{
$this->expectException(ReaderException::class);
IOFactory::createReader('bad');
}
public function testCreateReaderUnknownExtension(): void
{
$filename = 'samples/Reader2/sampleData/example1.tsv';
$reader = IOFactory::createReaderForFile($filename);
self::assertEquals('PhpOffice\PhpSpreadsheet\Reader\Csv', $reader::class);
}
public function testCreateReaderCsvExtension(): void
{
$filename = 'samples/Reader2/sampleData/example1.csv';
$reader = IOFactory::createReaderForFile($filename);
self::assertEquals('PhpOffice\PhpSpreadsheet\Reader\Csv', $reader::class);
}
public function testCreateReaderNoExtension(): void
{
$filename = 'samples/Reader/sampleData/example1xls';
$reader = IOFactory::createReaderForFile($filename);
self::assertEquals('PhpOffice\PhpSpreadsheet\Reader\Xls', $reader::class);
}
public function testCreateReaderNotSpreadsheet(): void
{
$this->expectException(ReaderException::class);
$filename = __FILE__;
IOFactory::createReaderForFile($filename);
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/HashTableTest.php | tests/PhpSpreadsheetTests/HashTableTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests;
use PhpOffice\PhpSpreadsheet\Comment; // need Comparable object
use PhpOffice\PhpSpreadsheet\HashTable;
use PHPUnit\Framework\TestCase;
class HashTableTest extends TestCase
{
/** @return array{Comment, Comment} */
public static function createArray(): array
{
$comment1 = new Comment();
$comment1->setAuthor('Author1');
$comment2 = new Comment();
$comment2->setAuthor('Author2');
return [$comment1, $comment2];
}
public static function getAuthor(mixed $comment): string
{
return ($comment instanceof Comment) ? $comment->getAuthor() : '';
}
public function testAddRemoveClear(): void
{
$array1 = self::createArray();
$hash1 = new HashTable($array1);
self::assertSame(2, $hash1->count());
$comment3 = new Comment();
$comment3->setAuthor('Author3');
$hash1->add($comment3);
$comment4 = new Comment();
$comment4->setAuthor('Author4');
$hash1->add($comment4);
$comment5 = new Comment();
$comment5->setAuthor('Author5');
// don't add comment5
self::assertSame(4, $hash1->count());
self::assertNull($hash1->getByIndex(10));
$comment = $hash1->getByIndex(2);
self::assertSame('Author3', self::getAuthor($comment));
$hash1->remove($comment3);
self::assertSame(3, $hash1->count());
$comment = $hash1->getByIndex(2);
self::assertSame('Author4', self::getAuthor($comment));
$hash1->remove($comment5);
self::assertSame(3, $hash1->count(), 'Remove non-hash member');
$comment = $hash1->getByIndex(2);
self::assertSame('Author4', self::getAuthor($comment));
self::assertNull($hash1->getByHashCode('xyz'));
$hash1->clear();
self::AssertSame(0, $hash1->count());
}
public function testToArray(): void
{
$array1 = self::createArray();
$count1 = count($array1);
$hash1 = new HashTable($array1);
$array2 = $hash1->toArray();
self::assertCount($count1, $array2);
$idx = 0;
foreach ($array2 as $key => $value) {
self::assertEquals($array1[$idx], $value, "Item $idx");
self::assertSame($idx, $hash1->getIndexForHashCode($key));
++$idx;
}
}
public function testClone(): void
{
$array1 = self::createArray();
$hash1 = new HashTable($array1);
$hash2 = new HashTable();
self::assertSame(0, $hash2->count());
$hash2->addFromSource();
self::assertSame(0, $hash2->count());
$hash2->addFromSource($array1);
self::assertSame(2, $hash2->count());
self::assertEquals($hash1, $hash2, 'Add in constructor same as addFromSource');
$hash3 = clone $hash1;
self::assertEquals($hash1, $hash3, 'Clone equal to original');
self::assertSame($hash1->getByIndex(0), $hash2->getByIndex(0));
self::assertEquals($hash1->getByIndex(0), $hash3->getByIndex(0));
self::assertNotSame($hash1->getByIndex(0), $hash3->getByIndex(0));
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/IOFactoryRegisterTest.php | tests/PhpSpreadsheetTests/IOFactoryRegisterTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Reader;
use PhpOffice\PhpSpreadsheet\Reader\Exception as ReaderException;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer;
use PHPUnit\Framework\TestCase;
class IOFactoryRegisterTest extends TestCase
{
protected function tearDown(): void
{
IOFactory::restoreDefaultReadersAndWriters();
}
public function testRegisterWriter(): void
{
IOFactory::registerWriter('Pdf', Writer\Pdf\Mpdf::class);
$spreadsheet = new Spreadsheet();
$actual = IOFactory::createWriter($spreadsheet, 'Pdf');
self::assertInstanceOf(Writer\Pdf\Mpdf::class, $actual);
}
public function testRegisterReader(): void
{
IOFactory::registerReader('Custom', Reader\Html::class);
$actual = IOFactory::createReader('Custom');
self::assertInstanceOf(Reader\Html::class, $actual);
}
public function testRegisterInvalidWriter(): void
{
$this->expectException(Writer\Exception::class);
$this->expectExceptionMessage('writers must implement');
IOFactory::registerWriter('foo', 'bar'); // @phpstan-ignore-line
}
public function testRegisterInvalidReader(): void
{
$this->expectException(ReaderException::class);
$this->expectExceptionMessage('readers must implement');
IOFactory::registerReader('foo', 'bar'); // @phpstan-ignore-line
}
public static function testRegisterCustomReader(): void
{
IOFactory::registerReader(IOFactory::READER_XLSX, CustomReader::class);
$inputFileName = 'tests/data/Reader/XLSX/1900_Calendar.xlsx';
$loadSpreadsheet = IOFactory::load($inputFileName);
$sheet = $loadSpreadsheet->getActiveSheet();
self::assertSame('2022-01-01', $sheet->getCell('A1')->getFormattedValue());
$loadSpreadsheet->disconnectWorksheets();
$reader = new CustomReader();
$newSpreadsheet = $reader->load($inputFileName);
$newSheet = $newSpreadsheet->getActiveSheet();
self::assertSame('2022-01-01', $newSheet->getCell('A1')->getFormattedValue());
$newSpreadsheet->disconnectWorksheets();
$inputFileType = IOFactory::identify($inputFileName, null, true);
$objReader = IOFactory::createReader($inputFileType);
self::assertInstanceOf(CustomReader::class, $objReader);
$objSpreadsheet = $objReader->load($inputFileName);
$objSheet = $objSpreadsheet->getActiveSheet();
self::assertSame('2022-01-01', $objSheet->getCell('A1')->getFormattedValue());
$objSpreadsheet->disconnectWorksheets();
}
public static function testRegisterCustomWriter(): void
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1', 1);
$writer = new CustomWriter($spreadsheet);
$html = $writer->generateHtmlAll();
self::assertStringContainsString('<td class="column0 style0 n">1</td>', $html);
IOFactory::registerWriter(IOFactory::WRITER_HTML, CustomWriter::class);
$objWriter = IOFactory::createWriter($spreadsheet, CustomWriter::class);
self::assertInstanceOf(CustomWriter::class, $objWriter);
$html2 = $objWriter->generateHtmlAll();
self::assertStringContainsString('<td class="column0 style0 n">1</td>', $html2);
$spreadsheet->disconnectWorksheets();
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Issue1449Test.php | tests/PhpSpreadsheetTests/Issue1449Test.php | <?php
namespace PhpOffice\PhpSpreadsheetTests;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PHPUnit\Framework\TestCase;
class Issue1449Test extends TestCase
{
protected bool $skipTests = true;
public function testDeleteColumns(): void
{
$spreadsheet = new Spreadsheet();
$sheet1 = $spreadsheet->getActiveSheet();
$sheet2 = $spreadsheet->createSheet();
$sheet1->setTitle('Sheet1');
$sheet2->setTitle('Sheet2');
$sheet1->fromArray(
[
[3, 1, 2, 33, 1, 10, 20, 30, 40],
[4, 2, 3, 23, 2, 10, 20, 30, 40],
[5, 3, 4, 1, 3, 10, 20, 30, 40],
[6, 4, 6, 4, 3, 10, 20, 30, 40],
[7, 6, 6, 2, 2, 10, 20, 30, 40],
],
null,
'C1',
true
);
$sheet1->getCell('A1')->setValue('=SUM(C4:F7)');
$sheet2->getCell('A1')->setValue('=SUM(Sheet1!C3:G5)');
$sheet1->removeColumn('F', 4);
self::assertSame('=SUM(C4:E7)', $sheet1->getCell('A1')->getValue());
if (!$this->skipTests) {
// References on another sheet not working yet.
self::assertSame('=Sheet1!SUM(C3:E5)', $sheet2->getCell('A1')->getValue());
}
$spreadsheet->disconnectWorksheets();
}
public function testDeleteRows(): void
{
$spreadsheet = new Spreadsheet();
$sheet1 = $spreadsheet->getActiveSheet();
$sheet2 = $spreadsheet->createSheet();
$sheet1->setTitle('Sheet1');
$sheet2->setTitle('Sheet2');
$sheet1->fromArray(
[
[3, 1, 2, 33, 1, 10, 20, 30, 40],
[4, 2, 3, 23, 2, 10, 20, 30, 40],
[5, 3, 4, 1, 3, 10, 20, 30, 40],
[6, 4, 6, 4, 3, 10, 20, 30, 40],
[7, 6, 6, 2, 2, 10, 20, 30, 40],
],
null,
'C1',
true
);
$sheet1->getCell('A1')->setValue('=SUM(C4:F7)');
$sheet2->getCell('A1')->setValue('=SUM(Sheet1!C3:G5)');
$sheet1->removeRow(4, 2);
self::assertSame('=SUM(C4:F5)', $sheet1->getCell('A1')->getValue());
if (!$this->skipTests) {
// References on another sheet not working yet.
self::assertSame('=Sheet1!SUM(C3:G3)', $sheet2->getCell('A1')->getValue());
}
$spreadsheet->disconnectWorksheets();
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/NamedFormulaTest.php | tests/PhpSpreadsheetTests/NamedFormulaTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests;
use PhpOffice\PhpSpreadsheet\NamedFormula;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use PHPUnit\Framework\TestCase;
class NamedFormulaTest extends TestCase
{
private Spreadsheet $spreadsheet;
protected function setUp(): void
{
parent::setUp();
$this->spreadsheet = new Spreadsheet();
$this->spreadsheet->getActiveSheet()
->setTitle('Sheet #1');
$worksheet2 = new Worksheet();
$worksheet2->setTitle('Sheet #2');
$this->spreadsheet->addSheet($worksheet2);
$this->spreadsheet->setActiveSheetIndex(0);
}
public function testAddNamedRange(): void
{
$this->spreadsheet->addNamedFormula(
new NamedFormula('Foo', $this->spreadsheet->getActiveSheet(), '=19%')
);
self::assertCount(1, $this->spreadsheet->getDefinedNames());
self::assertCount(1, $this->spreadsheet->getNamedFormulae());
self::assertCount(0, $this->spreadsheet->getNamedRanges());
}
public function testAddDuplicateNamedRange(): void
{
$this->spreadsheet->addNamedFormula(
new NamedFormula('Foo', $this->spreadsheet->getActiveSheet(), '=19%')
);
$this->spreadsheet->addNamedFormula(
new NamedFormula('FOO', $this->spreadsheet->getActiveSheet(), '=16%')
);
self::assertCount(1, $this->spreadsheet->getNamedFormulae());
$formula = $this->spreadsheet->getNamedFormula('foo', $this->spreadsheet->getActiveSheet());
self::assertNotNull($formula);
self::assertSame(
'=16%',
$formula->getValue()
);
}
public function testAddScopedNamedFormulaWithSameName(): void
{
$this->spreadsheet->addNamedFormula(
new NamedFormula('Foo', $this->spreadsheet->getActiveSheet(), '=19%')
);
$this->spreadsheet->addNamedFormula(
new NamedFormula('FOO', $this->spreadsheet->getSheetByNameOrThrow('Sheet #2'), '=16%', true)
);
self::assertCount(2, $this->spreadsheet->getNamedFormulae());
$formula = $this->spreadsheet->getNamedFormula('foo', $this->spreadsheet->getActiveSheet());
self::assertNotNull($formula);
self::assertSame(
'=19%',
$formula->getValue()
);
$formula = $this->spreadsheet->getNamedFormula('foo', $this->spreadsheet->getSheetByNameOrThrow('Sheet #2'));
self::assertNotNull($formula);
self::assertSame(
'=16%',
$formula->getValue()
);
}
public function testRemoveNamedFormula(): void
{
$this->spreadsheet->addDefinedName(
new NamedFormula('Foo', $this->spreadsheet->getActiveSheet(), '=16%')
);
$this->spreadsheet->addDefinedName(
new NamedFormula('Bar', $this->spreadsheet->getActiveSheet(), '=19%')
);
$this->spreadsheet->removeNamedFormula('Foo', $this->spreadsheet->getActiveSheet());
self::assertCount(1, $this->spreadsheet->getNamedFormulae());
}
public function testRemoveGlobalNamedFormulaWhenDuplicateNames(): void
{
$this->spreadsheet->addNamedFormula(
new NamedFormula('Foo', $this->spreadsheet->getActiveSheet(), '=19%')
);
$this->spreadsheet->addNamedFormula(
new NamedFormula('FOO', $this->spreadsheet->getSheetByNameOrThrow('Sheet #2'), '=16%', true)
);
$this->spreadsheet->removeNamedFormula('Foo', $this->spreadsheet->getActiveSheet());
self::assertCount(1, $this->spreadsheet->getNamedFormulae());
$formula = $this->spreadsheet->getNamedFormula('foo', $this->spreadsheet->getSheetByNameOrThrow('Sheet #2'));
self::assertNotNull($formula);
self::assertSame(
'=16%',
$formula->getValue()
);
}
public function testRemoveScopedNamedFormulaWhenDuplicateNames(): void
{
$this->spreadsheet->addNamedFormula(
new NamedFormula('Foo', $this->spreadsheet->getActiveSheet(), '=19%')
);
$this->spreadsheet->addNamedFormula(
new NamedFormula('FOO', $this->spreadsheet->getSheetByNameOrThrow('Sheet #2'), '=16%', true)
);
$this->spreadsheet->removeNamedFormula('Foo', $this->spreadsheet->getSheetByNameOrThrow('Sheet #2'));
self::assertCount(1, $this->spreadsheet->getNamedFormulae());
$formula = $this->spreadsheet->getNamedFormula('foo');
self::assertNotNull($formula);
self::assertSame(
'=19%',
$formula->getValue()
);
}
public function testRemoveNonExistentNamedFormula(): void
{
self::assertCount(0, $this->spreadsheet->getNamedFormulae());
$this->spreadsheet->removeNamedFormula('Any');
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/SpreadsheetDuplicateSheetTest.php | tests/PhpSpreadsheetTests/SpreadsheetDuplicateSheetTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PHPUnit\Framework\TestCase;
class SpreadsheetDuplicateSheetTest extends TestCase
{
private ?Spreadsheet $spreadsheet = null;
protected function tearDown(): void
{
if ($this->spreadsheet !== null) {
$this->spreadsheet->disconnectWorksheets();
$this->spreadsheet = null;
}
}
public function testDuplicate(): void
{
$spreadsheet = $this->spreadsheet = new Spreadsheet();
$sheet = $this->spreadsheet->getActiveSheet();
$sheet->setTitle('original');
$sheet->getCell('A1')->setValue('text1');
$sheet->getCell('A2')->setValue('text2');
$sheet->getStyle('A1')
->getFont()
->setBold(true);
$sheet3 = $this->spreadsheet->createSheet();
$sheet3->setTitle('added');
$newSheet = $this->spreadsheet
->duplicateWorksheetByTitle('original');
$this->spreadsheet->duplicateWorksheetByTitle('added');
self::assertSame('original 1', $newSheet->getTitle());
self::assertSame(
'text1',
$newSheet->getCell('A1')->getValue()
);
self::assertSame(
'text2',
$newSheet->getCell('A2')->getValue()
);
self::assertTrue(
$newSheet->getStyle('A1')->getFont()->getBold()
);
self::assertFalse(
$newSheet->getStyle('A2')->getFont()->getBold()
);
$sheetNames = [];
foreach ($spreadsheet->getWorksheetIterator() as $worksheet) {
$sheetNames[] = $worksheet->getTitle();
}
$expected = ['original', 'original 1', 'added', 'added 1'];
self::assertSame($expected, $sheetNames);
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/SpreadsheetCoverageTest.php | tests/PhpSpreadsheetTests/SpreadsheetCoverageTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests;
use PhpOffice\PhpSpreadsheet\Exception as SSException;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PHPUnit\Framework\TestCase;
class SpreadsheetCoverageTest extends TestCase
{
private ?Spreadsheet $spreadsheet = null;
private ?Spreadsheet $spreadsheet2 = null;
protected function tearDown(): void
{
if ($this->spreadsheet !== null) {
$this->spreadsheet->disconnectWorksheets();
$this->spreadsheet = null;
}
if ($this->spreadsheet2 !== null) {
$this->spreadsheet2->disconnectWorksheets();
$this->spreadsheet2 = null;
}
}
public function testDocumentProperties(): void
{
$this->spreadsheet = new Spreadsheet();
$properties = $this->spreadsheet->getProperties();
$properties->setCreator('Anyone');
$properties->setTitle('Description');
$spreadsheet2 = $this->spreadsheet2 = new Spreadsheet();
self::assertNotEquals($properties, $this->spreadsheet2->getProperties());
$properties2 = clone $properties;
$spreadsheet2->setProperties($properties2);
self::assertEquals($properties, $spreadsheet2->getProperties());
}
public function testDocumentSecurity(): void
{
$spreadsheet = $this->spreadsheet = new Spreadsheet();
$security = $spreadsheet->getSecurity();
$security->setLockRevision(true);
$revisionsPassword = 'revpasswd';
$security->setRevisionsPassword($revisionsPassword);
$spreadsheet2 = $this->spreadsheet2 = new Spreadsheet();
self::assertNotEquals($security, $spreadsheet2->getSecurity());
$security2 = clone $security;
$spreadsheet2->setSecurity($security2);
self::assertEquals($security, $spreadsheet2->getSecurity());
}
public function testCellXfCollection(): void
{
$spreadsheet = $this->spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->getStyle('A1')->getFont()->setName('font1');
$sheet->getStyle('A2')->getFont()->setName('font2');
$sheet->getStyle('A3')->getFont()->setName('font3');
$sheet->getStyle('B1')->getFont()->setName('font1');
$sheet->getStyle('B2')->getFont()->setName('font2');
$collection = $spreadsheet->getCellXfCollection();
self::assertCount(4, $collection);
$font1Style = $collection[1];
self::assertTrue($spreadsheet->cellXfExists($font1Style));
self::assertSame('font1', $spreadsheet->getCellXfCollection()[1]->getFont()->getName());
self::assertSame('font1', $sheet->getStyle('A1')->getFont()->getName());
self::assertSame('font2', $sheet->getStyle('A2')->getFont()->getName());
self::assertSame('font3', $sheet->getStyle('A3')->getFont()->getName());
self::assertSame('font1', $sheet->getStyle('B1')->getFont()->getName());
self::assertSame('font2', $sheet->getStyle('B2')->getFont()->getName());
$spreadsheet->removeCellXfByIndex(1);
self::assertFalse($spreadsheet->cellXfExists($font1Style));
self::assertSame('font2', $spreadsheet->getCellXfCollection()[1]->getFont()->getName());
self::assertSame('Calibri', $sheet->getStyle('A1')->getFont()->getName());
self::assertSame('font2', $sheet->getStyle('A2')->getFont()->getName());
self::assertSame('font3', $sheet->getStyle('A3')->getFont()->getName());
self::assertSame('Calibri', $sheet->getStyle('B1')->getFont()->getName());
self::assertSame('font2', $sheet->getStyle('B2')->getFont()->getName());
}
public function testInvalidRemoveCellXfByIndex(): void
{
$this->expectException(SSException::class);
$this->expectExceptionMessage('CellXf index is out of bounds.');
$this->spreadsheet = new Spreadsheet();
$sheet = $this->spreadsheet->getActiveSheet();
$sheet->getStyle('A1')->getFont()->setName('font1');
$sheet->getStyle('A2')->getFont()->setName('font2');
$sheet->getStyle('A3')->getFont()->setName('font3');
$sheet->getStyle('B1')->getFont()->setName('font1');
$sheet->getStyle('B2')->getFont()->setName('font2');
$this->spreadsheet->removeCellXfByIndex(5);
}
public function testInvalidRemoveDefaultStyle(): void
{
$this->expectException(SSException::class);
$this->expectExceptionMessage('No default style found for this workbook');
// Removing default style probably should be disallowed.
$this->spreadsheet = new Spreadsheet();
$this->spreadsheet->removeCellXfByIndex(0);
$this->spreadsheet->getDefaultStyle();
}
public function testCellStyleXF(): void
{
$spreadsheet = $this->spreadsheet = new Spreadsheet();
$collection = $spreadsheet->getCellStyleXfCollection();
self::assertCount(1, $collection);
$styleXf = $collection[0];
self::assertSame($styleXf, $spreadsheet->getCellStyleXfByIndex(0));
$hash = $styleXf->getHashCode();
self::assertSame($styleXf, $spreadsheet->getCellStyleXfByHashCode($hash));
self::assertFalse($spreadsheet->getCellStyleXfByHashCode($hash . 'x'));
}
public function testInvalidRemoveCellStyleXfByIndex(): void
{
$this->expectException(SSException::class);
$this->expectExceptionMessage('CellStyleXf index is out of bounds.');
$this->spreadsheet = new Spreadsheet();
$this->spreadsheet->removeCellStyleXfByIndex(5);
}
public function testInvalidFirstSheetIndex(): void
{
$this->expectException(SSException::class);
$this->expectExceptionMessage('First sheet index must be a positive integer.');
$this->spreadsheet = new Spreadsheet();
$this->spreadsheet->setFirstSheetIndex(-1);
}
public function testInvalidVisibility(): void
{
$this->expectException(SSException::class);
$this->expectExceptionMessage('Invalid visibility value.');
$spreadsheet = $this->spreadsheet = new Spreadsheet();
$spreadsheet
->setVisibility(Spreadsheet::VISIBILITY_HIDDEN);
self::assertSame(Spreadsheet::VISIBILITY_HIDDEN, $spreadsheet->getVisibility());
$spreadsheet->setVisibility(null);
self::assertSame(Spreadsheet::VISIBILITY_VISIBLE, $spreadsheet->getVisibility());
$spreadsheet->setVisibility('badvalue');
}
public function testInvalidTabRatio(): void
{
$this->expectException(SSException::class);
$this->expectExceptionMessage('Tab ratio must be between 0 and 1000.');
$this->spreadsheet = new Spreadsheet();
$this->spreadsheet->setTabRatio(2000);
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/DocumentGeneratorTest.php | tests/PhpSpreadsheetTests/DocumentGeneratorTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PhpOffice\PhpSpreadsheet\Calculation\Category as Cat;
use PhpOffice\PhpSpreadsheet\Calculation\Functions;
use PhpOffice\PhpSpreadsheet\Calculation\Logical\Operations;
use PhpOffice\PhpSpreadsheetInfra\DocumentGenerator;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
use UnexpectedValueException;
class DocumentGeneratorTest extends TestCase
{
private static bool $succeededByName = false;
private static bool $succeededByCategory = false;
/** @param array<string, array{category: string, functionCall: array<string>|string, argumentCount: string, passCellReference?: bool, passByReference?: array<bool>, custom?: bool}> $phpSpreadsheetFunctions */
#[DataProvider('providerGenerateFunctionListByName')]
public function testGenerateFunctionListByName(array $phpSpreadsheetFunctions, string $expected): void
{
self::assertEquals($expected, DocumentGenerator::generateFunctionListByName($phpSpreadsheetFunctions));
self::$succeededByName = true;
}
/** @param array<string, array{category: string, functionCall: array<string>|string, argumentCount: string, passCellReference?: bool, passByReference?: array<bool>, custom?: bool}> $phpSpreadsheetFunctions */
#[DataProvider('providerGenerateFunctionListByCategory')]
public function testGenerateFunctionListByCategory(array $phpSpreadsheetFunctions, string $expected): void
{
self::assertEquals($expected, DocumentGenerator::generateFunctionListByCategory($phpSpreadsheetFunctions));
self::$succeededByCategory = true;
}
public static function providerGenerateFunctionListByName(): array
{
return [
[
[
'ABS' => ['category' => Cat::CATEGORY_MATH_AND_TRIG, 'functionCall' => 'abs', 'argumentCount' => '1'],
'AND' => ['category' => Cat::CATEGORY_LOGICAL, 'functionCall' => [Operations::class, 'logicalAnd'], 'argumentCount' => '2'],
'IFS' => ['category' => Cat::CATEGORY_LOGICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '3'],
],
<<<'EXPECTED'
# Function list by name
A more compact list can be found [here](./function-list-by-name-compact.md)
## A
Excel Function | Category | PhpSpreadsheet Function
-------------------------|--------------------------------|--------------------------------------
ABS | CATEGORY_MATH_AND_TRIG | abs
AND | CATEGORY_LOGICAL | \PhpOffice\PhpSpreadsheet\Calculation\Logical\Operations::logicalAnd
## I
Excel Function | Category | PhpSpreadsheet Function
-------------------------|--------------------------------|--------------------------------------
IFS | CATEGORY_LOGICAL | **Not yet Implemented**
EXPECTED
],
];
}
public static function providerGenerateFunctionListByCategory(): array
{
return [
[
[
'ABS' => ['category' => Cat::CATEGORY_MATH_AND_TRIG, 'functionCall' => 'abs', 'argumentCount' => '1'],
'AND' => ['category' => Cat::CATEGORY_LOGICAL, 'functionCall' => [Operations::class, 'logicalAnd'], 'argumentCount' => '2'],
'IFS' => ['category' => Cat::CATEGORY_LOGICAL, 'functionCall' => [Functions::class, 'DUMMY'], 'argumentCount' => '3'],
],
<<<'EXPECTED'
# Function list by category
## CATEGORY_CUBE
Excel Function | PhpSpreadsheet Function
-------------------------|--------------------------------------
## CATEGORY_DATABASE
Excel Function | PhpSpreadsheet Function
-------------------------|--------------------------------------
## CATEGORY_DATE_AND_TIME
Excel Function | PhpSpreadsheet Function
-------------------------|--------------------------------------
## CATEGORY_ENGINEERING
Excel Function | PhpSpreadsheet Function
-------------------------|--------------------------------------
## CATEGORY_FINANCIAL
Excel Function | PhpSpreadsheet Function
-------------------------|--------------------------------------
## CATEGORY_INFORMATION
Excel Function | PhpSpreadsheet Function
-------------------------|--------------------------------------
## CATEGORY_LOGICAL
Excel Function | PhpSpreadsheet Function
-------------------------|--------------------------------------
AND | \PhpOffice\PhpSpreadsheet\Calculation\Logical\Operations::logicalAnd
IFS | **Not yet Implemented**
## CATEGORY_LOOKUP_AND_REFERENCE
Excel Function | PhpSpreadsheet Function
-------------------------|--------------------------------------
## CATEGORY_MATH_AND_TRIG
Excel Function | PhpSpreadsheet Function
-------------------------|--------------------------------------
ABS | abs
## CATEGORY_STATISTICAL
Excel Function | PhpSpreadsheet Function
-------------------------|--------------------------------------
## CATEGORY_TEXT_AND_DATA
Excel Function | PhpSpreadsheet Function
-------------------------|--------------------------------------
## CATEGORY_WEB
Excel Function | PhpSpreadsheet Function
-------------------------|--------------------------------------
## CATEGORY_UNCATEGORISED
Excel Function | PhpSpreadsheet Function
-------------------------|--------------------------------------
## CATEGORY_MICROSOFT_INTERNAL
Excel Function | PhpSpreadsheet Function
-------------------------|--------------------------------------
EXPECTED
],
];
}
public function testGenerateFunctionBadArray(): void
{
$this->expectException(UnexpectedValueException::class);
$phpSpreadsheetFunctions = [
'ABS' => ['category' => Cat::CATEGORY_MATH_AND_TRIG, 'functionCall' => 1],
];
// Phpstan is right to complain about next line,
// but we still need to make sure it is handled correctly at run time.
DocumentGenerator::generateFunctionListByName(
$phpSpreadsheetFunctions //* @phpstan-ignore-line
);
}
public function testGenerateDocuments(): void
{
if (!self::$succeededByName || !self::$succeededByCategory) {
self::markTestSkipped('Not run because prior test failed');
}
$directory = 'docs/references/';
$phpSpreadsheetFunctions = Calculation::getFunctions();
ksort($phpSpreadsheetFunctions);
self::assertNotFalse(file_put_contents(
$directory . 'function-list-by-category.md',
DocumentGenerator::generateFunctionListByCategory(
$phpSpreadsheetFunctions
)
));
self::assertNotFalse(file_put_contents(
$directory . 'function-list-by-name.md',
DocumentGenerator::generateFunctionListByName(
$phpSpreadsheetFunctions
)
));
self::assertNotFalse(file_put_contents(
$directory . 'function-list-by-name-compact.md',
DocumentGenerator::generateFunctionListByName(
$phpSpreadsheetFunctions,
true
)
));
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/RichTextTest.php | tests/PhpSpreadsheetTests/RichTextTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests;
use PhpOffice\PhpSpreadsheet\Exception as SpreadsheetException;
use PhpOffice\PhpSpreadsheet\RichText\RichText;
use PhpOffice\PhpSpreadsheet\RichText\TextElement;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PHPUnit\Framework\TestCase;
class RichTextTest extends TestCase
{
public function testConstructorSpecifyingCell(): void
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$cell = $sheet->getCell('A1');
$cell->setValue(2);
self::assertSame(2, $cell->getCalculatedValue());
$cell->getStyle()->getFont()->setName('whatever');
$richText = new RichText($cell);
self::assertSame('whatever', $sheet->getCell('A1')->getStyle()->getFont()->getName());
self::assertEquals($richText, $cell->getValue());
self::assertSame('2', $cell->getCalculatedValue());
$spreadsheet->disconnectWorksheets();
}
public function testTextElements(): void
{
$element1 = new TextElement('A');
$element2 = new TextElement('B');
$element3 = new TextElement('C');
$richText = new RichText();
$richText->setRichTextElements([$element1, $element2, $element3]);
self::assertSame('ABC', $richText->getPlainText());
$cloneText = clone $richText;
self::assertEquals($richText, $cloneText);
self::assertNotSame($richText, $cloneText);
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->getCell('A1')->setValue($richText);
self::assertInstanceOf(RichText::class, $sheet->getCell('A1')->getValue());
self::assertSame('ABC', $sheet->getCell('A1')->getFormattedValue());
$sheet->getCell('B1')->setValue(-3.5);
self::assertSame([['ABC', '-3.5']], $sheet->toArray());
$spreadsheet->disconnectWorksheets();
}
public function testNullFont(): void
{
$richText = new RichText();
$textRun = $richText->createTextRun('hello');
$textRun->setFont(null);
try {
$textRun->getFontOrThrow();
$foundFont = true;
} catch (SpreadsheetException $e) {
$foundFont = false;
}
self::assertFalse($foundFont, 'expected exception not received');
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/CellReferenceHelperTest.php | tests/PhpSpreadsheetTests/CellReferenceHelperTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests;
use PhpOffice\PhpSpreadsheet\CellReferenceHelper;
use PhpOffice\PhpSpreadsheet\Exception as SpreadsheetException;
use PHPUnit\Framework\TestCase;
class CellReferenceHelperTest extends TestCase
{
#[\PHPUnit\Framework\Attributes\DataProvider('cellReferenceHelperInsertColumnsProvider')]
public function testCellReferenceHelperInsertColumns(string $expectedResult, string $cellAddress): void
{
$cellReferenceHelper = new CellReferenceHelper('E5', 2, 0);
$result = $cellReferenceHelper->updateCellReference($cellAddress);
self::assertSame($expectedResult, $result);
}
public static function cellReferenceHelperInsertColumnsProvider(): array
{
return [
['A1', 'A1'],
['D5', 'D5'],
['G5', 'E5'],
'issue3363 Y5' => ['Y5', 'W5'],
'issue3363 Z5' => ['Z5', 'X5'],
['AA5', 'Y5'],
['AB5', 'Z5'],
['XFC5', 'XFA5'],
['XFD5', 'XFB5'],
['XFD5', 'XFC5'],
['XFD5', 'XFD5'],
['$E5', '$E5'],
'issue3363 $Z5' => ['$Z5', '$Z5'],
['$XFA5', '$XFA5'],
['$XFB5', '$XFB5'],
['$XFC5', '$XFC5'],
['$XFD5', '$XFD5'],
['G$5', 'E$5'],
'issue3363 Y$5' => ['Y$5', 'W$5'],
['XFC$5', 'XFA$5'],
['XFD$5', 'XFB$5'],
['XFD$5', 'XFC$5'],
['XFD$5', 'XFD$5'],
['I5', 'G5'],
['$G$5', '$G$5'],
'issue3363 $Z$5' => ['$Z$5', '$Z$5'],
['$XFA$5', '$XFA$5'],
['$XFB$5', '$XFB$5'],
['$XFC$5', '$XFC$5'],
['$XFD$5', '$XFD$5'],
];
}
#[\PHPUnit\Framework\Attributes\DataProvider('cellReferenceHelperDeleteColumnsProvider')]
public function testCellReferenceHelperDeleteColumns(string $expectedResult, string $cellAddress): void
{
$cellReferenceHelper = new CellReferenceHelper('E5', -2, 0);
$result = $cellReferenceHelper->updateCellReference($cellAddress);
self::assertSame($expectedResult, $result);
}
public function testCantUseRange(): void
{
$this->expectException(SpreadsheetException::class);
$this->expectExceptionMessage('Only single cell references');
$cellReferenceHelper = new CellReferenceHelper('E5', 2, 0);
$cellReferenceHelper->updateCellReference('A1:A6');
}
public static function cellReferenceHelperDeleteColumnsProvider(): array
{
return [
['A1', 'A1'],
['D5', 'D5'],
['C5', 'E5'],
'issue3363 Y5' => ['Y5', 'AA5'],
'issue3363 Z5' => ['Z5', 'AB5'],
['$E5', '$E5'],
'issue3363 $Y5' => ['$Y5', '$Y5'],
['C$5', 'E$5'],
'issue3363 Z$5' => ['Z$5', 'AB$5'],
['E5', 'G5'],
['$G$5', '$G$5'],
'issue3363 $Z$5' => ['$Z$5', '$Z$5'],
];
}
#[\PHPUnit\Framework\Attributes\DataProvider('cellReferenceHelperInsertRowsProvider')]
public function testCellReferenceHelperInsertRows(string $expectedResult, string $cellAddress): void
{
$cellReferenceHelper = new CellReferenceHelper('E5', 0, 2);
$result = $cellReferenceHelper->updateCellReference($cellAddress);
self::assertSame($expectedResult, $result);
}
public static function cellReferenceHelperInsertRowsProvider(): array
{
return [
['A1', 'A1'],
['E4', 'E4'],
['E7', 'E5'],
['E1048575', 'E1048573'],
['E1048576', 'E1048574'],
['E1048576', 'E1048575'],
['E1048576', 'E1048576'],
'issue3363 Y5' => ['Y7', 'Y5'],
'issue3363 Z5' => ['Z7', 'Z5'],
['E$5', 'E$5'],
'issue3363 Y$5' => ['Y$5', 'Y$5'],
['$E7', '$E5'],
'issue3363 $Z5' => ['$Z7', '$Z5'],
['E11', 'E9'],
['$E$9', '$E$9'],
'issue3363 $Z$5' => ['$Z$5', '$Z$5'],
];
}
#[\PHPUnit\Framework\Attributes\DataProvider('cellReferenceHelperDeleteRowsProvider')]
public function testCellReferenceHelperDeleteRows(string $expectedResult, string $cellAddress): void
{
$cellReferenceHelper = new CellReferenceHelper('E5', 0, -2);
$result = $cellReferenceHelper->updateCellReference($cellAddress);
self::assertSame($expectedResult, $result);
}
public static function cellReferenceHelperDeleteRowsProvider(): array
{
return [
['A1', 'A1'],
['E4', 'E4'],
['E3', 'E5'],
'issue3363 Y5' => ['Y3', 'Y5'],
'issue3363 Z5' => ['Z3', 'Z5'],
['E$5', 'E$5'],
'issue3363 Y$5' => ['Y$5', 'Y$5'],
['$E3', '$E5'],
'issue3363 $Z5' => ['$Z3', '$Z5'],
['E7', 'E9'],
['$E$9', '$E$9'],
'issue3363 $Z$5' => ['$Z$5', '$Z$5'],
];
}
#[\PHPUnit\Framework\Attributes\DataProvider('cellReferenceHelperInsertColumnsAbsoluteProvider')]
public function testCellReferenceHelperInsertColumnsAbsolute(string $expectedResult, string $cellAddress): void
{
$cellReferenceHelper = new CellReferenceHelper('E5', 2, 0);
$result = $cellReferenceHelper->updateCellReference($cellAddress, true);
self::assertSame($expectedResult, $result);
}
public static function cellReferenceHelperInsertColumnsAbsoluteProvider(): array
{
return [
['A1', 'A1'],
['D5', 'D5'],
['G5', 'E5'],
'issue3363 Y5' => ['Y5', 'W5'],
'issue3363 Z5' => ['Z5', 'X5'],
['$G5', '$E5'],
'issue3363 $Y5' => ['$Y5', '$W5'],
['G$5', 'E$5'],
'issue3363 Y$5' => ['Y$5', 'W$5'],
['I5', 'G5'],
['$I$5', '$G$5'],
'issue3363 $Y$5' => ['$Y$5', '$W$5'],
];
}
#[\PHPUnit\Framework\Attributes\DataProvider('cellReferenceHelperDeleteColumnsAbsoluteProvider')]
public function testCellReferenceHelperDeleteColumnsAbsolute(string $expectedResult, string $cellAddress): void
{
$cellReferenceHelper = new CellReferenceHelper('E5', -2, 0);
$result = $cellReferenceHelper->updateCellReference($cellAddress, true);
self::assertSame($expectedResult, $result);
}
public static function cellReferenceHelperDeleteColumnsAbsoluteProvider(): array
{
return [
['A1', 'A1'],
['D5', 'D5'],
['C5', 'E5'],
'issue3363 Y5' => ['Y5', 'AA5'],
'issue3363 Z5' => ['Z5', 'AB5'],
['$C5', '$E5'],
'issue3363 $Y5' => ['$Y5', '$AA5'],
['C$5', 'E$5'],
'issue3363 Z$5' => ['Z$5', 'AB$5'],
['E5', 'G5'],
['$E$5', '$G$5'],
'issue3363 $Z$5' => ['$Z$5', '$AB$5'],
];
}
#[\PHPUnit\Framework\Attributes\DataProvider('cellReferenceHelperInsertRowsAbsoluteProvider')]
public function testCellReferenceHelperInsertRowsAbsolute(string $expectedResult, string $cellAddress): void
{
$cellReferenceHelper = new CellReferenceHelper('E5', 0, 2);
$result = $cellReferenceHelper->updateCellReference($cellAddress, true);
self::assertSame($expectedResult, $result);
}
public static function cellReferenceHelperInsertRowsAbsoluteProvider(): array
{
return [
['A1', 'A1'],
['E4', 'E4'],
['E7', 'E5'],
'issue3363 Y5' => ['Y7', 'Y5'],
'issue3363 Z5' => ['Z7', 'Z5'],
['E$7', 'E$5'],
'issue3363 Y$5' => ['Y$7', 'Y$5'],
['$E7', '$E5'],
'issue3363 $Y5' => ['$Y7', '$Y5'],
['E11', 'E9'],
['$E$11', '$E$9'],
'issue3363 $Z$5' => ['$Z$7', '$Z$5'],
];
}
#[\PHPUnit\Framework\Attributes\DataProvider('cellReferenceHelperDeleteRowsAbsoluteProvider')]
public function testCellReferenceHelperDeleteRowsAbsolute(string $expectedResult, string $cellAddress): void
{
$cellReferenceHelper = new CellReferenceHelper('E5', 0, -2);
$result = $cellReferenceHelper->updateCellReference($cellAddress, true);
self::assertSame($expectedResult, $result);
}
public static function cellReferenceHelperDeleteRowsAbsoluteProvider(): array
{
return [
['A1', 'A1'],
['E4', 'E4'],
['E3', 'E5'],
'issue3363 Y5' => ['Y3', 'Y5'],
'issue3363 Z5' => ['Z3', 'Z5'],
['E$3', 'E$5'],
'issue3363 Y$5' => ['Y$3', 'Y$5'],
['$E3', '$E5'],
'issue3363 $Z5' => ['$Z3', '$Z5'],
['E7', 'E9'],
['$E$7', '$E$9'],
'issue3363 $Z$5' => ['$Z$3', '$Z$5'],
];
}
public function testCellReferenceHelperDeleteColumnAltogether(): void
{
$cellReferenceHelper = new CellReferenceHelper('E5', -4, 0);
self::assertTrue($cellReferenceHelper->cellAddressInDeleteRange('A5'));
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/ReferenceHelper3Test.php | tests/PhpSpreadsheetTests/ReferenceHelper3Test.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PhpOffice\PhpSpreadsheet\NamedRange;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PHPUnit\Framework\TestCase;
class ReferenceHelper3Test extends TestCase
{
public function testIssue3661(): void
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setTitle('Data');
$spreadsheet->addNamedRange(new NamedRange('FIRST', $sheet, '=$A1'));
$spreadsheet->addNamedRange(new NamedRange('SECOND', $sheet, '=$B1'));
$spreadsheet->addNamedRange(new NamedRange('THIRD', $sheet, '=$C1'));
$sheet->fromArray([
[1, 2, 3, '=FIRST', '=SECOND', '=THIRD', '=10*$A1'],
[4, 5, 6, '=FIRST', '=SECOND', '=THIRD'],
[7, 8, 9, '=FIRST', '=SECOND', '=THIRD'],
]);
$sheet->insertNewRowBefore(1, 4);
$sheet->insertNewColumnBefore('A', 1);
self::assertSame(1, $sheet->getCell('E5')->getCalculatedValue());
self::assertSame(5, $sheet->getCell('F6')->getCalculatedValue());
self::assertSame(9, $sheet->getCell('G7')->getCalculatedValue());
self::assertSame('=10*$B5', $sheet->getCell('H5')->getValue());
self::assertSame(10, $sheet->getCell('H5')->getCalculatedValue());
$firstColumn = $spreadsheet->getNamedRange('FIRST');
/** @var NamedRange $firstColumn */
self::assertSame('=$B1', $firstColumn->getRange());
$spreadsheet->disconnectWorksheets();
}
public function testCompletelyRelative(): void
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setTitle('Data');
$spreadsheet->addNamedRange(new NamedRange('CellAbove', $sheet, '=A1048576'));
$spreadsheet->addNamedRange(new NamedRange('CellBelow', $sheet, '=A2'));
$spreadsheet->addNamedRange(new NamedRange('CellToLeft', $sheet, '=XFD1'));
$spreadsheet->addNamedRange(new NamedRange('CellToRight', $sheet, '=B1'));
$sheet->fromArray([
[null, 'Above', null, null, 'Above', null, null, 'Above', null, null, 'Above', null],
['Left', '=CellAbove', 'Right', 'Left', '=CellBelow', 'Right', 'Left', '=CellToLeft', 'Right', 'Left', '=CellToRight', 'Right'],
[null, 'Below', null, null, 'Below', null, null, 'Below', null, null, 'Below', null],
], null, 'A1', true);
self::assertSame('Above', $sheet->getCell('B2')->getCalculatedValue());
self::assertSame('Below', $sheet->getCell('E2')->getCalculatedValue());
self::assertSame('Left', $sheet->getCell('H2')->getCalculatedValue());
self::assertSame('Right', $sheet->getCell('K2')->getCalculatedValue());
Calculation::getInstance($spreadsheet)->flushInstance();
self::assertNull($sheet->getCell('L7')->getCalculatedValue(), 'value in L7 after flush is null');
// Reset it once more
Calculation::getInstance($spreadsheet)->flushInstance();
// shift 5 rows down and 1 column to the right
$sheet->insertNewRowBefore(1, 5);
$sheet->insertNewColumnBefore('A', 1);
self::assertSame('Above', $sheet->getCell('C7')->getCalculatedValue()); // Above
self::assertSame('Below', $sheet->getCell('F7')->getCalculatedValue());
self::assertSame('Left', $sheet->getCell('I7')->getCalculatedValue());
self::assertSame('Right', $sheet->getCell('L7')->getCalculatedValue());
$sheet2 = $spreadsheet->createSheet();
$sheet2->setCellValue('L6', 'NotThisCell');
$sheet2->setCellValue('L7', '=CellAbove');
self::assertSame('Above', $sheet2->getCell('L7')->getCalculatedValue(), 'relative value uses cell on worksheet where name is defined');
$spreadsheet->disconnectWorksheets();
}
private static bool $sumFormulaWorking = false;
public function testSumAboveCell(): void
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$spreadsheet->addNamedRange(new NamedRange('AboveCell', $sheet, 'A1048576'));
$sheet->setCellValue('C2', 123);
$sheet->setCellValue('C3', '=AboveCell');
$sheet->fromArray([
['Column 1', 'Column 2'],
[2, 1],
[4, 3],
[6, 5],
[8, 7],
[10, 9],
[12, 11],
[14, 13],
[16, 15],
['=SUM(A2:AboveCell)', '=SUM(B2:AboveCell)'],
], null, 'A1', true);
self::assertSame(123, $sheet->getCell('C3')->getCalculatedValue());
if (self::$sumFormulaWorking) {
self::assertSame(72, $sheet->getCell('A10')->getCalculatedValue());
} else {
$spreadsheet->disconnectWorksheets();
self::markTestIncomplete('PhpSpreadsheet does not handle this correctly');
}
$spreadsheet->disconnectWorksheets();
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/CommentTest.php | tests/PhpSpreadsheetTests/CommentTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests;
use PhpOffice\PhpSpreadsheet\Comment;
use PhpOffice\PhpSpreadsheet\RichText\RichText;
use PhpOffice\PhpSpreadsheet\RichText\TextElement;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Color;
use PHPUnit\Framework\TestCase;
class CommentTest extends TestCase
{
public function testCreateComment(): void
{
$comment = new Comment();
self::assertEquals('Author', $comment->getAuthor());
self::assertEquals('96pt', $comment->getWidth());
self::assertEquals('59.25pt', $comment->getMarginLeft());
self::assertEquals('1.5pt', $comment->getMarginTop());
self::assertEquals('55.5pt', $comment->getHeight());
self::assertEquals('FFFFFFE1', $comment->getFillColor()->getARGB());
self::assertEquals(Alignment::HORIZONTAL_GENERAL, $comment->getAlignment());
self::assertFalse($comment->getVisible());
}
public function testSetAuthor(): void
{
$comment = new Comment();
$comment->setAuthor('Mark Baker');
self::assertEquals('Mark Baker', $comment->getAuthor());
}
public function testSetMarginLeft(): void
{
$comment = new Comment();
$comment->setMarginLeft('20pt');
self::assertEquals('20pt', $comment->getMarginLeft());
}
public function testSetMarginTop(): void
{
$comment = new Comment();
$comment->setMarginTop('2.5pt');
self::assertEquals('2.5pt', $comment->getMarginTop());
}
public function testSetWidth(): void
{
$comment = new Comment();
$comment->setWidth('120pt');
self::assertEquals('120pt', $comment->getWidth());
}
public function testSetHeight(): void
{
$comment = new Comment();
$comment->setHeight('60px');
self::assertEquals('60px', $comment->getHeight());
}
public function testSetFillColor(): void
{
$comment = new Comment();
$comment->setFillColor(new Color('RED'));
self::assertEquals(Color::COLOR_RED, $comment->getFillColor()->getARGB());
}
public function testSetAlignment(): void
{
$comment = new Comment();
$comment->setAlignment(Alignment::HORIZONTAL_CENTER);
self::assertEquals(Alignment::HORIZONTAL_CENTER, $comment->getAlignment());
}
public function testSetText(): void
{
$comment = new Comment();
$test = new RichText();
$test->addText(new TextElement('This is a test comment'));
$comment->setText($test);
self::assertEquals('This is a test comment', (string) $comment);
}
public function testRemoveComment(): void
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->getComment('A2')->getText()->createText('Comment to delete');
$comments1 = $sheet->getComments();
self::assertArrayHasKey('A2', $comments1);
$sheet->removeComment('A2');
self::assertEmpty($sheet->getComments());
$spreadsheet->disconnectWorksheets();
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/NamedRangeTest.php | tests/PhpSpreadsheetTests/NamedRangeTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests;
use PhpOffice\PhpSpreadsheet\NamedRange;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use PHPUnit\Framework\TestCase;
class NamedRangeTest extends TestCase
{
private Spreadsheet $spreadsheet;
protected function setUp(): void
{
parent::setUp();
$this->spreadsheet = new Spreadsheet();
$this->spreadsheet->getActiveSheet()
->setTitle('Sheet #1');
$worksheet2 = new Worksheet();
$worksheet2->setTitle('Sheet #2');
$this->spreadsheet->addSheet($worksheet2);
$this->spreadsheet->setActiveSheetIndex(0);
}
public function testAddNamedRange(): void
{
$this->spreadsheet->addNamedRange(
new NamedRange('Foo', $this->spreadsheet->getActiveSheet(), '=A1')
);
self::assertCount(1, $this->spreadsheet->getDefinedNames());
self::assertCount(1, $this->spreadsheet->getNamedRanges());
self::assertCount(0, $this->spreadsheet->getNamedFormulae());
}
public function testAddDuplicateNamedRange(): void
{
$this->spreadsheet->addNamedRange(
new NamedRange('Foo', $this->spreadsheet->getActiveSheet(), '=A1')
);
$this->spreadsheet->addNamedRange(
new NamedRange('FOO', $this->spreadsheet->getActiveSheet(), '=B1')
);
self::assertCount(1, $this->spreadsheet->getNamedRanges());
$range = $this->spreadsheet->getNamedRange('foo', $this->spreadsheet->getActiveSheet());
self::assertNotNull($range);
self::assertSame(
'=B1',
$range->getValue()
);
}
public function testAddScopedNamedRangeWithSameName(): void
{
$this->spreadsheet->addNamedRange(
new NamedRange('Foo', $this->spreadsheet->getActiveSheet(), '=A1')
);
$this->spreadsheet->addNamedRange(
new NamedRange('FOO', $this->spreadsheet->getSheetByNameOrThrow('Sheet #2'), '=B1', true)
);
self::assertCount(2, $this->spreadsheet->getNamedRanges());
$range = $this->spreadsheet->getNamedRange('foo', $this->spreadsheet->getActiveSheet());
self::assertNotNull($range);
self::assertSame(
'=A1',
$range->getValue()
);
$range = $this->spreadsheet->getNamedRange('foo', $this->spreadsheet->getSheetByNameOrThrow('Sheet #2'));
self::assertNotNull($range);
self::assertSame(
'=B1',
$range->getValue()
);
}
public function testRemoveNamedRange(): void
{
$this->spreadsheet->addDefinedName(
new NamedRange('Foo', $this->spreadsheet->getActiveSheet(), '=A1')
);
$this->spreadsheet->addDefinedName(
new NamedRange('Bar', $this->spreadsheet->getActiveSheet(), '=B1')
);
$this->spreadsheet->removeNamedRange('Foo', $this->spreadsheet->getActiveSheet());
self::assertCount(1, $this->spreadsheet->getNamedRanges());
}
public function testRemoveGlobalNamedRangeWhenDuplicateNames(): void
{
$this->spreadsheet->addNamedRange(
new NamedRange('Foo', $this->spreadsheet->getActiveSheet(), '=A1')
);
$this->spreadsheet->addNamedRange(
new NamedRange('FOO', $this->spreadsheet->getSheetByNameOrThrow('Sheet #2'), '=B1', true)
);
$this->spreadsheet->removeNamedRange('Foo', $this->spreadsheet->getActiveSheet());
self::assertCount(1, $this->spreadsheet->getNamedRanges());
$sheet = $this->spreadsheet->getNamedRange('foo', $this->spreadsheet->getSheetByNameOrThrow('Sheet #2'));
self::assertNotNull($sheet);
self::assertSame(
'=B1',
$sheet->getValue()
);
}
public function testRemoveScopedNamedRangeWhenDuplicateNames(): void
{
$this->spreadsheet->addNamedRange(
new NamedRange('Foo', $this->spreadsheet->getActiveSheet(), '=A1')
);
$this->spreadsheet->addNamedRange(
new NamedRange('FOO', $this->spreadsheet->getSheetByNameOrThrow('Sheet #2'), '=B1', true)
);
$this->spreadsheet->removeNamedRange('Foo', $this->spreadsheet->getSheetByNameOrThrow('Sheet #2'));
self::assertCount(1, $this->spreadsheet->getNamedRanges());
$range = $this->spreadsheet->getNamedRange('foo');
self::AssertNotNull($range);
self::assertSame(
'=A1',
$range->getValue()
);
}
public function testRemoveNonExistentNamedRange(): void
{
self::assertCount(0, $this->spreadsheet->getNamedRanges());
$this->spreadsheet->removeNamedRange('Any');
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/DefinedNameTest.php | tests/PhpSpreadsheetTests/DefinedNameTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests;
use PhpOffice\PhpSpreadsheet\DefinedName;
use PhpOffice\PhpSpreadsheet\NamedRange;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use PHPUnit\Framework\TestCase;
class DefinedNameTest extends TestCase
{
private Spreadsheet $spreadsheet;
protected function setUp(): void
{
parent::setUp();
$this->spreadsheet = new Spreadsheet();
$this->spreadsheet->getActiveSheet()
->setTitle('Sheet #1');
$worksheet2 = new Worksheet();
$worksheet2->setTitle('Sheet #2');
$this->spreadsheet->addSheet($worksheet2);
$this->spreadsheet->setActiveSheetIndex(0);
}
public function testAddDefinedName(): void
{
$this->spreadsheet->addDefinedName(
DefinedName::createInstance('Foo', $this->spreadsheet->getActiveSheet(), '=A1')
);
self::assertCount(1, $this->spreadsheet->getDefinedNames());
}
public function testAddDuplicateDefinedName(): void
{
$this->spreadsheet->addDefinedName(
DefinedName::createInstance('Foo', $this->spreadsheet->getActiveSheet(), '=A1')
);
$this->spreadsheet->addDefinedName(
DefinedName::createInstance('FOO', $this->spreadsheet->getActiveSheet(), '=B1')
);
self::assertCount(1, $this->spreadsheet->getDefinedNames());
$definedName = $this->spreadsheet->getDefinedName('foo', $this->spreadsheet->getActiveSheet());
self::assertNotNull($definedName);
self::assertSame('=B1', $definedName->getValue());
}
public function testAddScopedDefinedNameWithSameName(): void
{
$this->spreadsheet->addDefinedName(
DefinedName::createInstance('Foo', $this->spreadsheet->getActiveSheet(), '=A1')
);
$this->spreadsheet->addDefinedName(
DefinedName::createInstance('FOO', $this->spreadsheet->getSheetByNameOrThrow('Sheet #2'), '=B1', true)
);
self::assertCount(2, $this->spreadsheet->getDefinedNames());
$definedName1 = $this->spreadsheet->getDefinedName('foo', $this->spreadsheet->getActiveSheet());
self::assertNotNull($definedName1);
self::assertSame('=A1', $definedName1->getValue());
$definedName2 = $this->spreadsheet->getDefinedName('foo', $this->spreadsheet->getSheetByNameOrThrow('Sheet #2'));
self::assertNotNull($definedName2);
self::assertSame('=B1', $definedName2->getValue());
}
public function testRemoveDefinedName(): void
{
$this->spreadsheet->addDefinedName(
DefinedName::createInstance('Foo', $this->spreadsheet->getActiveSheet(), '=A1')
);
$this->spreadsheet->addDefinedName(
DefinedName::createInstance('Bar', $this->spreadsheet->getActiveSheet(), '=B1')
);
$this->spreadsheet->removeDefinedName('Foo', $this->spreadsheet->getActiveSheet());
self::assertCount(1, $this->spreadsheet->getDefinedNames());
}
public function testRemoveGlobalDefinedName(): void
{
$this->spreadsheet->addDefinedName(
DefinedName::createInstance('Any', $this->spreadsheet->getActiveSheet(), '=A1')
);
self::assertCount(1, $this->spreadsheet->getDefinedNames());
$this->spreadsheet->removeDefinedName('Any');
self::assertCount(0, $this->spreadsheet->getDefinedNames());
$this->spreadsheet->removeDefinedName('Other');
}
public function testRemoveGlobalDefinedNameWhenDuplicateNames(): void
{
$this->spreadsheet->addDefinedName(
DefinedName::createInstance('Foo', $this->spreadsheet->getActiveSheet(), '=A1')
);
$this->spreadsheet->addDefinedName(
DefinedName::createInstance('FOO', $this->spreadsheet->getSheetByNameOrThrow('Sheet #2'), '=B1', true)
);
$this->spreadsheet->removeDefinedName('Foo', $this->spreadsheet->getActiveSheet());
self::assertCount(1, $this->spreadsheet->getDefinedNames());
$definedName = $this->spreadsheet->getDefinedName('foo', $this->spreadsheet->getSheetByNameOrThrow('Sheet #2'));
self::assertNotNull($definedName);
self::assertSame('=B1', $definedName->getValue());
}
public function testRemoveScopedDefinedNameWhenDuplicateNames(): void
{
$this->spreadsheet->addDefinedName(
DefinedName::createInstance('Foo', $this->spreadsheet->getActiveSheet(), '=A1')
);
$this->spreadsheet->addDefinedName(
DefinedName::createInstance('FOO', $this->spreadsheet->getSheetByNameOrThrow('Sheet #2'), '=B1', true)
);
$this->spreadsheet->removeDefinedName('Foo', $this->spreadsheet->getSheetByNameOrThrow('Sheet #2'));
self::assertCount(1, $this->spreadsheet->getDefinedNames());
$definedName = $this->spreadsheet->getDefinedName('foo');
self::assertNotNull($definedName);
self::assertSame('=A1', $definedName->getValue());
}
public function testDefinedNameNoWorksheetNoScope(): void
{
$this->expectException(\PhpOffice\PhpSpreadsheet\Exception::class);
new NamedRange('xyz');
}
public function testSetAndGetRange(): void
{
$this->spreadsheet->addDefinedName(
DefinedName::createInstance('xyz', $this->spreadsheet->getActiveSheet(), 'A1')
);
$namedRange = $this->spreadsheet->getDefinedName('XYZ');
self::assertInstanceOf(NamedRange::class, $namedRange);
self::assertEquals('A1', $namedRange->getRange());
self::assertEquals('A1', $namedRange->getValue());
$namedRange->setRange('A2');
self::assertEquals('A2', $namedRange->getValue());
}
public function testChangeWorksheet(): void
{
$sheet1 = $this->spreadsheet->getSheetByNameOrThrow('Sheet #1');
$sheet2 = $this->spreadsheet->getSheetByNameOrThrow('Sheet #2');
$sheet1->getCell('A1')->setValue(1);
$sheet2->getCell('A1')->setValue(2);
$namedRange = new NamedRange('xyz', $sheet2, '$A$1');
$namedRange->setWorksheet($sheet1);
$this->spreadsheet->addNamedRange($namedRange);
$sheet1->getCell('B2')->setValue('=XYZ');
self::assertEquals(1, $sheet1->getCell('B2')->getCalculatedValue());
$sheet2->getCell('B2')->setValue('=XYZ');
self::assertEquals(1, $sheet2->getCell('B2')->getCalculatedValue());
}
public function testLocalOnly(): void
{
$sheet1 = $this->spreadsheet->getSheetByNameOrThrow('Sheet #1');
$sheet2 = $this->spreadsheet->getSheetByNameOrThrow('Sheet #2');
$sheet1->getCell('A1')->setValue(1);
$sheet2->getCell('A1')->setValue(2);
$namedRange = new NamedRange('abc', $sheet2, '$A$1');
$namedRange->setWorksheet($sheet1)->setLocalOnly(true);
$this->spreadsheet->addNamedRange($namedRange);
$sheet1->getCell('C2')->setValue('=ABC');
self::assertEquals(1, $sheet1->getCell('C2')->getCalculatedValue());
$sheet2->getCell('C2')->setValue('=ABC');
self::assertEquals('#NAME?', $sheet2->getCell('C2')->getCalculatedValue());
}
public function testScope(): void
{
$sheet1 = $this->spreadsheet->getSheetByNameOrThrow('Sheet #1');
$sheet2 = $this->spreadsheet->getSheetByNameOrThrow('Sheet #2');
$sheet1->getCell('A1')->setValue(1);
$sheet2->getCell('A1')->setValue(2);
$namedRange = new NamedRange('abc', $sheet2, '$A$1');
$namedRange->setScope($sheet1);
$this->spreadsheet->addNamedRange($namedRange);
$sheet1->getCell('C2')->setValue('=ABC');
self::assertEquals(2, $sheet1->getCell('C2')->getCalculatedValue());
$sheet2->getCell('C2')->setValue('=ABC');
self::assertEquals('#NAME?', $sheet2->getCell('C2')->getCalculatedValue());
}
public function testClone(): void
{
$sheet1 = $this->spreadsheet->getSheetByNameOrThrow('Sheet #1');
$sheet2 = $this->spreadsheet->getSheetByNameOrThrow('Sheet #2');
$sheet1->getCell('A1')->setValue(1);
$sheet2->getCell('A1')->setValue(2);
$namedRange = new NamedRange('abc', $sheet2, '$A$1');
$namedRangeClone = clone $namedRange;
$ss1 = $namedRange->getWorksheet();
$ss2 = $namedRangeClone->getWorksheet();
self::assertNotNull($ss1);
self::assertNotNull($ss2);
self::assertNotSame($ss1, $ss2);
self::assertEquals($ss1->getTitle(), $ss2->getTitle());
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/A1LocaleGeneratorTest.php | tests/PhpSpreadsheetTests/A1LocaleGeneratorTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PhpOffice\PhpSpreadsheetInfra\LocaleGenerator;
use PHPUnit\Framework\TestCase;
class A1LocaleGeneratorTest extends TestCase
{
public function testLocaleGenerator(): void
{
$directory = realpath(__DIR__ . '/../../src/PhpSpreadsheet/Calculation/locale/') ?: '';
self::assertNotEquals('', $directory);
$phpSpreadsheetFunctions = Calculation::getFunctions();
$localeGenerator = new LocaleGenerator(
$directory . DIRECTORY_SEPARATOR,
'Translations.xlsx',
$phpSpreadsheetFunctions
);
$localeGenerator->generateLocales();
$testLocales = [
'bg',
'cs',
'da',
'de',
'en',
'es',
'fi',
'fr',
'hu',
'it',
'nb',
'nl',
'pl',
'pt',
'ru',
'sv',
'tr',
];
$count = count(glob($directory . DIRECTORY_SEPARATOR . '*') ?: []) - 1; // exclude Translations.xlsx
self::assertCount($count, $testLocales);
$testLocales[] = 'pt_br';
$testLocales[] = 'en_uk';
$noconfig = ['en'];
$nofunctions = ['en', 'en_uk'];
foreach ($testLocales as $originalLocale) {
$locale = str_replace('_', DIRECTORY_SEPARATOR, $originalLocale);
$path = $directory . DIRECTORY_SEPARATOR . $locale;
if (in_array($originalLocale, $noconfig, true)) {
self::assertFileDoesNotExist($path . DIRECTORY_SEPARATOR . 'config');
} else {
self::assertFileExists($path . DIRECTORY_SEPARATOR . 'config');
}
if (in_array($originalLocale, $nofunctions, true)) {
self::assertFileDoesNotExist($path . DIRECTORY_SEPARATOR . 'functions');
} else {
self::assertFileExists($path . DIRECTORY_SEPARATOR . 'functions');
}
}
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/ReferenceHelper2Test.php | tests/PhpSpreadsheetTests/ReferenceHelper2Test.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests;
use PhpOffice\PhpSpreadsheet\Exception as SpreadsheetException;
use PhpOffice\PhpSpreadsheet\ReferenceHelper;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PHPUnit\Framework\TestCase;
class ReferenceHelper2Test extends TestCase
{
public function testNoClone(): void
{
$this->expectException(SpreadsheetException::class);
$this->expectExceptionMessage('Cloning a Singleton');
$referenceHelper = ReferenceHelper::getInstance();
$x = clone $referenceHelper;
$x->updateFormulaReferences();
}
public function testRenamedWorksheetInFormula(): void
{
$spreadsheet = new Spreadsheet();
$sheet1 = $spreadsheet->getActiveSheet();
$referenceHelper = ReferenceHelper::getInstance();
$referenceHelper->updateNamedFormulae($spreadsheet); // no-op
$sheet2 = $spreadsheet->createSheet();
$sheet2->setTitle('Sheet2');
$title2 = $sheet2->getTitle();
$sheet2->getCell('A1')->setValue(10);
$sheet2->getCell('A2')->setValue(20);
$sheet3 = $spreadsheet->createSheet();
$sheet3->setTitle('Sheet3');
$title3 = $sheet3->getTitle();
$sheet3->getCell('A1')->setValue(30);
$sheet3->getCell('A2')->setValue(40);
$sheet1->getCell('A1')->setValue("=$title2!A1");
$sheet1->getCell('A2')->setValue("='$title2'!A2");
$sheet1->getCell('B1')->setValue("=$title3!A1");
$sheet1->getCell('B2')->setValue("='$title3'!A2");
$newTitle2 = 'renamedSheet2';
$sheet2->setTitle($newTitle2);
self::assertSame("=$newTitle2!A1", $sheet1->getCell('A1')->getValue());
self::assertSame("='$newTitle2'!A2", $sheet1->getCell('A2')->getValue());
self::assertSame("=$title3!A1", $sheet1->getCell('B1')->getValue());
self::assertSame("='$title3'!A2", $sheet1->getCell('B2')->getValue());
self::assertSame([[10, 30], [20, 40]], $sheet1->toArray(null, true, false));
$spreadsheet->disconnectWorksheets();
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/ReferenceHelperDVTest.php | tests/PhpSpreadsheetTests/ReferenceHelperDVTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests;
use PhpOffice\PhpSpreadsheet\Cell\DataValidation;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use PHPUnit\Framework\TestCase;
class ReferenceHelperDVTest extends TestCase
{
public function testInsertRowsWithDataValidation(): void
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->fromArray([['First'], ['Second'], ['Third'], ['Fourth']], null, 'A5', true);
$cellAddress = 'E5';
$this->setDataValidation($sheet, $cellAddress);
$sheet->insertNewRowBefore(2, 2);
self::assertFalse(
$sheet->getCell($cellAddress)->hasDataValidation()
);
self::assertTrue($sheet->getCell('E7')->hasDataValidation());
self::assertSame('E7', $sheet->getDataValidation('E7')->getSqref());
self::assertSame('$A$7:$A$10', $sheet->getDataValidation('E7')->getFormula1());
$spreadsheet->disconnectWorksheets();
}
public function testDeleteRowsWithDataValidation(): void
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->fromArray([['First'], ['Second'], ['Third'], ['Fourth']], null, 'A5', true);
$cellAddress = 'E5';
$this->setDataValidation($sheet, $cellAddress);
$sheet->removeRow(2, 2);
self::assertFalse(
$sheet->getCell($cellAddress)->hasDataValidation()
);
self::assertTrue($sheet->getCell('E3')->hasDataValidation());
self::assertSame('E3', $sheet->getDataValidation('E3')->getSqref());
self::assertSame('$A$3:$A$6', $sheet->getDataValidation('E3')->getFormula1());
$spreadsheet->disconnectWorksheets();
}
public function testDeleteColumnsWithDataValidation(): void
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->fromArray([['First'], ['Second'], ['Third'], ['Fourth']], null, 'A5', true);
$cellAddress = 'E5';
$this->setDataValidation($sheet, $cellAddress);
$sheet->removeColumn('B', 2);
self::assertFalse(
$sheet->getCell($cellAddress)->hasDataValidation()
);
self::assertTrue($sheet->getCell('C5')->hasDataValidation());
self::assertSame('C5', $sheet->getDataValidation('C5')->getSqref());
self::assertSame('$A$5:$A$8', $sheet->getDataValidation('C5')->getFormula1());
$spreadsheet->disconnectWorksheets();
}
public function testInsertColumnsWithDataValidation(): void
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->fromArray([['First'], ['Second'], ['Third'], ['Fourth']], null, 'A5', true);
$cellAddress = 'E5';
$this->setDataValidation($sheet, $cellAddress);
$sheet->insertNewColumnBefore('C', 2);
self::assertFalse(
$sheet->getCell($cellAddress)->hasDataValidation()
);
self::assertTrue($sheet->getCell('G5')->hasDataValidation());
self::assertSame('G5', $sheet->getDataValidation('G5')->getSqref());
self::assertSame('$A$5:$A$8', $sheet->getDataValidation('G5')->getFormula1());
$spreadsheet->disconnectWorksheets();
}
public function testInsertColumnsWithDataValidation2(): void
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->fromArray([['First'], ['Second'], ['Third'], ['Fourth']], null, 'A5', true);
$cellAddress = 'E5';
$this->setDataValidation($sheet, $cellAddress);
$sheet->insertNewColumnBefore('A', 2);
self::assertFalse(
$sheet->getCell($cellAddress)->hasDataValidation()
);
self::assertTrue($sheet->getCell('G5')->hasDataValidation());
self::assertSame('G5', $sheet->getDataValidation('G5')->getSqref());
self::assertSame('$C$5:$C$8', $sheet->getDataValidation('G5')->getFormula1());
$spreadsheet->disconnectWorksheets();
}
private function setDataValidation(Worksheet $sheet, string $cellAddress): void
{
$validation = $sheet->getCell($cellAddress)
->getDataValidation();
$validation->setType(DataValidation::TYPE_LIST);
$validation->setErrorStyle(
DataValidation::STYLE_STOP
);
$validation->setAllowBlank(false);
$validation->setShowInputMessage(true);
$validation->setShowErrorMessage(true);
$validation->setShowDropDown(true);
$validation->setErrorTitle('Input error');
$validation->setError('Value is not in list.');
$validation->setPromptTitle('Pick from list');
$validation->setPrompt('Please pick a value from the drop-down list.');
$validation->setFormula1('$A$5:$A$8');
}
public function testMultipleRanges(): void
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->getCell('C1')->setValue(1);
$sheet->getCell('C2')->setValue(2);
$sheet->getCell('C3')->setValue(3);
$dv = $sheet->getDataValidation('A1:A4 D5 E6:E7');
$dv->setType(DataValidation::TYPE_LIST)
->setShowDropDown(true)
->setFormula1('$C$1:$C$3')
->setErrorStyle(DataValidation::STYLE_STOP)
->setShowErrorMessage(true)
->setErrorTitle('Input Error')
->setError('Value is not a member of allowed list');
$sheet->insertNewColumnBefore('B');
$dvs = $sheet->getDataValidationCollection();
self::assertCount(1, $dvs);
$expected = 'A1:A4 E5 F6:F7';
self::assertSame([$expected], array_keys($dvs));
$dv = $dvs[$expected];
self::assertSame($expected, $dv->getSqref());
self::assertSame('$D$1:$D$3', $dv->getFormula1());
$sheet->getCell('A3')->setValue(8);
self::assertFalse($sheet->getCell('A3')->hasValidValue());
$sheet->getCell('E5')->setValue(7);
self::assertFalse($sheet->getCell('E5')->hasValidValue());
$sheet->getCell('F6')->setValue(7);
self::assertFalse($sheet->getCell('F6')->hasValidValue());
$sheet->getCell('F7')->setValue(1);
self::assertTrue($sheet->getCell('F7')->hasValidValue());
$spreadsheet->disconnectWorksheets();
}
public function testWholeColumn(): void
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$dv = new DataValidation();
$dv->setType(DataValidation::TYPE_NONE);
$sheet->setDataValidation('A5:A7', $dv);
$dv = new DataValidation();
$dv->setType(DataValidation::TYPE_LIST)
->setShowDropDown(true)
->setFormula1('"Item A,Item B,Item C"')
->setErrorStyle(DataValidation::STYLE_STOP)
->setShowErrorMessage(true)
->setErrorTitle('Input Error')
->setError('Value is not a member of allowed list');
$sheet->setDataValidation('A:A', $dv);
$dv = new DataValidation();
$dv->setType(DataValidation::TYPE_NONE);
$sheet->setDataValidation('A9', $dv);
self::assertSame(DataValidation::TYPE_LIST, $sheet->getDataValidation('A4')->getType());
self::assertSame(DataValidation::TYPE_LIST, $sheet->getDataValidation('A10')->getType());
self::assertSame(DataValidation::TYPE_NONE, $sheet->getDataValidation('A6')->getType());
self::assertSame(DataValidation::TYPE_NONE, $sheet->getDataValidation('A9')->getType());
$spreadsheet->disconnectWorksheets();
}
public function testWholeRow(): void
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$dv = new DataValidation();
$dv->setType(DataValidation::TYPE_NONE);
$sheet->setDataValidation('C1:F1', $dv);
$dv = new DataValidation();
$dv->setType(DataValidation::TYPE_LIST)
->setShowDropDown(true)
->setFormula1('"Item A,Item B,Item C"')
->setErrorStyle(DataValidation::STYLE_STOP)
->setShowErrorMessage(true)
->setErrorTitle('Input Error')
->setError('Value is not a member of allowed list');
$sheet->setDataValidation('1:1', $dv);
$dv = new DataValidation();
$dv->setType(DataValidation::TYPE_NONE);
$sheet->setDataValidation('H1', $dv);
self::assertSame(DataValidation::TYPE_LIST, $sheet->getDataValidation('B1')->getType());
self::assertSame(DataValidation::TYPE_LIST, $sheet->getDataValidation('J1')->getType());
self::assertSame(DataValidation::TYPE_NONE, $sheet->getDataValidation('D1')->getType());
self::assertSame(DataValidation::TYPE_NONE, $sheet->getDataValidation('H1')->getType());
$spreadsheet->disconnectWorksheets();
}
public function testFormula2(): void
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->getCell('A1')->setValue(5);
$sheet->getCell('A5')->setValue(9);
$dv = new DataValidation();
$dv->setType(DataValidation::TYPE_WHOLE)
->setOperator(DataValidation::OPERATOR_BETWEEN)
->setFormula1('$A$1')
->setFormula2('$A$5')
->setErrorStyle(DataValidation::STYLE_STOP)
->setShowErrorMessage(true)
->setErrorTitle('Input Error')
->setError('Value is not whole number within bounds');
$sheet->setDataValidation('B2', $dv);
$sheet->insertNewRowBefore(2);
$dv2 = $sheet->getCell('B3')->getDataValidation();
self::assertSame('$A$1', $dv2->getFormula1());
self::assertSame('$A$6', $dv2->getFormula2());
$sheet->getCell('B3')->setValue(7);
self::assertTrue($sheet->getCell('B3')->hasValidValue());
$sheet->getCell('B3')->setValue(1);
self::assertFalse($sheet->getCell('B3')->hasValidValue());
$spreadsheet->disconnectWorksheets();
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/SettingsTest.php | tests/PhpSpreadsheetTests/SettingsTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests;
use PhpOffice\PhpSpreadsheet\Exception as SpException;
use PhpOffice\PhpSpreadsheet\Settings;
use PHPUnit\Framework\TestCase;
class SettingsTest extends TestCase
{
protected function tearDown(): void
{
Settings::setCache(null);
}
public function testInvalidChartRenderer(): void
{
$this->expectException(SpException::class);
$this->expectExceptionMessage('Chart renderer must implement');
// @phpstan-ignore-next-line
Settings::setChartRenderer(self::class);
}
public function testCache(): void
{
$cache1 = Settings::getCache();
Settings::setCache(null);
$cache2 = Settings::getCache();
self::assertEquals($cache1, $cache2);
self::assertNotSame($cache1, $cache2);
$array = ['A1' => 10, 'B2' => 20];
$cache2->setMultiple($array);
self::assertSame($array, $cache2->getMultiple(array_keys($array)));
self::assertNull($cache2->get('C3'));
$cache2->clear();
self::assertNull($cache2->get('A1'));
self::assertNull($cache2->get('B2'));
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/SpreadsheetTest.php | tests/PhpSpreadsheetTests/SpreadsheetTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests;
use PhpOffice\PhpSpreadsheet\Exception;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use PHPUnit\Framework\TestCase;
class SpreadsheetTest extends TestCase
{
private ?Spreadsheet $spreadsheet = null;
protected function tearDown(): void
{
if ($this->spreadsheet !== null) {
$this->spreadsheet->disconnectWorksheets();
$this->spreadsheet = null;
}
}
private function getSpreadsheet(): Spreadsheet
{
$this->spreadsheet = $spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setTitle('someSheet1');
$sheet = new Worksheet();
$sheet->setTitle('someSheet2');
$spreadsheet->addSheet($sheet);
$sheet = new Worksheet();
$sheet->setTitle('someSheet 3');
$spreadsheet->addSheet($sheet);
return $spreadsheet;
}
public static function dataProviderForSheetNames(): array
{
$array = [
[0, 'someSheet1'],
[0, "'someSheet1'"],
[1, 'someSheet2'],
[1, "'someSheet2'"],
[2, 'someSheet 3'],
[2, "'someSheet 3'"],
[null, 'someSheet 33'],
];
return $array;
}
#[\PHPUnit\Framework\Attributes\DataProvider('dataProviderForSheetNames')]
public function testGetSheetByName(?int $index, string $sheetName): void
{
$spreadsheet = $this->getSpreadsheet();
if ($index === null) {
self::assertNull($spreadsheet->getSheetByName($sheetName));
} else {
self::assertSame($spreadsheet->getSheet($index), $spreadsheet->getSheetByName($sheetName));
}
}
public function testAddSheetDuplicateTitle(): void
{
$spreadsheet = $this->getSpreadsheet();
$this->expectException(Exception::class);
$this->expectExceptionMessage("Workbook already contains a worksheet named 'someSheet2'. Rename this worksheet first.");
$sheet = new Worksheet();
$sheet->setTitle('someSheet2');
$spreadsheet->addSheet($sheet);
}
public function testAddSheetDuplicateTitleWithDifferentCase(): void
{
$spreadsheet = $this->getSpreadsheet();
$this->expectException(Exception::class);
$this->expectExceptionMessage("Workbook already contains a worksheet named 'SomeSheet2'. Rename this worksheet first.");
$sheet = new Worksheet();
$sheet->setTitle('SomeSheet2');
$spreadsheet->addSheet($sheet);
}
public function testAddSheetNoAdjustActive(): void
{
$spreadsheet = $this->getSpreadsheet();
$spreadsheet->setActiveSheetIndex(2);
self::assertEquals(2, $spreadsheet->getActiveSheetIndex());
$sheet = new Worksheet();
$sheet->setTitle('someSheet4');
$spreadsheet->addSheet($sheet);
self::assertEquals(2, $spreadsheet->getActiveSheetIndex());
}
public function testAddSheetAdjustActive(): void
{
$spreadsheet = $this->getSpreadsheet();
$spreadsheet->setActiveSheetIndex(2);
self::assertEquals(2, $spreadsheet->getActiveSheetIndex());
$sheet = new Worksheet();
$sheet->setTitle('someSheet0');
$spreadsheet->addSheet($sheet, 0);
self::assertEquals(3, $spreadsheet->getActiveSheetIndex());
}
public function testRemoveSheetIndexTooHigh(): void
{
$spreadsheet = $this->getSpreadsheet();
$this->expectException(Exception::class);
$this->expectExceptionMessage('You tried to remove a sheet by the out of bounds index: 4. The actual number of sheets is 3.');
$spreadsheet->removeSheetByIndex(4);
}
public function testRemoveSheetNoAdjustActive(): void
{
$spreadsheet = $this->getSpreadsheet();
$spreadsheet->setActiveSheetIndex(1);
self::assertEquals(1, $spreadsheet->getActiveSheetIndex());
$spreadsheet->removeSheetByIndex(2);
self::assertEquals(1, $spreadsheet->getActiveSheetIndex());
}
public function testRemoveSheetAdjustActive(): void
{
$spreadsheet = $this->getSpreadsheet();
$spreadsheet->setActiveSheetIndex(2);
self::assertEquals(2, $spreadsheet->getActiveSheetIndex());
$spreadsheet->removeSheetByIndex(1);
self::assertEquals(1, $spreadsheet->getActiveSheetIndex());
}
public function testGetSheetIndexTooHigh(): void
{
$spreadsheet = $this->getSpreadsheet();
$this->expectException(Exception::class);
$this->expectExceptionMessage('Your requested sheet index: 4 is out of bounds. The actual number of sheets is 3.');
$spreadsheet->getSheet(4);
}
public function testGetIndexNonExistent(): void
{
$spreadsheet = $this->getSpreadsheet();
$this->expectException(Exception::class);
$this->expectExceptionMessage('Sheet does not exist.');
$sheet = new Worksheet();
$sheet->setTitle('someSheet4');
$spreadsheet->getIndex($sheet);
}
public function testSetIndexByName(): void
{
$spreadsheet = $this->getSpreadsheet();
$spreadsheet->setIndexByName('someSheet1', 1);
self::assertEquals('someSheet2', $spreadsheet->getSheet(0)->getTitle());
self::assertEquals('someSheet1', $spreadsheet->getSheet(1)->getTitle());
self::assertEquals('someSheet 3', $spreadsheet->getSheet(2)->getTitle());
}
public function testRemoveAllSheets(): void
{
$spreadsheet = $this->getSpreadsheet();
$spreadsheet->setActiveSheetIndex(2);
self::assertEquals(2, $spreadsheet->getActiveSheetIndex());
$spreadsheet->removeSheetByIndex(0);
self::assertEquals(1, $spreadsheet->getActiveSheetIndex());
$spreadsheet->removeSheetByIndex(0);
self::assertEquals(0, $spreadsheet->getActiveSheetIndex());
$spreadsheet->removeSheetByIndex(0);
self::assertEquals(-1, $spreadsheet->getActiveSheetIndex());
$sheet = new Worksheet();
$sheet->setTitle('someSheet4');
$spreadsheet->addSheet($sheet);
self::assertEquals(0, $spreadsheet->getActiveSheetIndex());
}
public function testBug1735(): void
{
$spreadsheet1 = new Spreadsheet();
$spreadsheet1->createSheet()->setTitle('addedsheet');
$spreadsheet1->setActiveSheetIndex(1);
$spreadsheet1->removeSheetByIndex(0);
$sheet = $spreadsheet1->getActiveSheet();
self::assertEquals('addedsheet', $sheet->getTitle());
}
public function testSetActiveSheetIndexTooHigh(): void
{
$spreadsheet = $this->getSpreadsheet();
$this->expectException(Exception::class);
$this->expectExceptionMessage('You tried to set a sheet active by the out of bounds index: 4. The actual number of sheets is 3.');
$spreadsheet->setActiveSheetIndex(4);
}
public function testSetActiveSheetNoSuchName(): void
{
$spreadsheet = $this->getSpreadsheet();
$this->expectException(Exception::class);
$this->expectExceptionMessage('Workbook does not contain sheet:unknown');
$spreadsheet->setActiveSheetIndexByName('unknown');
}
public function testAddExternal(): void
{
$spreadsheet = $this->getSpreadsheet();
$spreadsheet1 = new Spreadsheet();
$sheet = $spreadsheet1->createSheet()->setTitle('someSheet19');
$sheet->getCell('A1')->setValue(1);
$sheet->getCell('A1')->getStyle()->getFont()->setBold(true);
$sheet->getCell('B1')->getStyle()->getFont()->setSuperscript(true);
$sheet->getCell('C1')->getStyle()->getFont()->setSubscript(true);
self::assertCount(4, $spreadsheet1->getCellXfCollection());
self::assertEquals(1, $sheet->getCell('A1')->getXfIndex());
$spreadsheet->getActiveSheet()->getCell('A1')->getStyle()->getFont()->setBold(true);
self::assertCount(2, $spreadsheet->getCellXfCollection());
$sheet3 = $spreadsheet->addExternalSheet($sheet);
self::assertCount(6, $spreadsheet->getCellXfCollection());
self::assertEquals('someSheet19', $sheet3->getTitle());
self::assertEquals(1, $sheet3->getCell('A1')->getValue());
self::assertTrue($sheet3->getCell('A1')->getStyle()->getFont()->getBold());
// Prove Xf index changed although style is same.
self::assertEquals(3, $sheet3->getCell('A1')->getXfIndex());
}
public function testAddExternalDuplicateName(): void
{
$this->expectException(Exception::class);
$this->expectExceptionMessage("Workbook already contains a worksheet named 'someSheet1'. Rename the external sheet first.");
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->createSheet()->setTitle('someSheet1');
$sheet->getCell('A1')->setValue(1);
$sheet->getCell('A1')->getStyle()->getFont()->setBold(true);
$spreadsheet->addExternalSheet($sheet);
}
public function testAddExternalColumnDimensionStyles(): void
{
$spreadsheet1 = new Spreadsheet();
$sheet1 = $spreadsheet1->createSheet()->setTitle('sheetWithColumnDimension');
$sheet1->getCell('A1')->setValue(1);
$sheet1->getCell('A1')->getStyle()->getFont()->setItalic(true);
$sheet1->getColumnDimension('B')->setWidth(10)->setXfIndex($sheet1->getCell('A1')->getXfIndex());
$index = $sheet1->getColumnDimension('B')->getXfIndex();
self::assertEquals(1, $index);
self::assertCount(2, $spreadsheet1->getCellXfCollection());
$spreadsheet2 = new Spreadsheet();
$sheet2 = $spreadsheet2->createSheet()->setTitle('sheetWithTwoStyles');
$sheet2->getCell('A1')->setValue(1);
$sheet2->getCell('A1')->getStyle()->getFont()->setBold(true);
$sheet2->getCell('B2')->getStyle()->getFont()->setSuperscript(true);
$countXfs = count($spreadsheet2->getCellXfCollection());
self::assertEquals(3, $countXfs);
$sheet3 = $spreadsheet2->addExternalSheet($sheet1);
self::assertCount(5, $spreadsheet2->getCellXfCollection());
self::assertTrue($sheet3->getCell('A1')->getStyle()->getFont()->getItalic());
self::assertTrue($sheet3->getCell('B1')->getStyle()->getFont()->getItalic());
self::assertFalse($sheet3->getCell('B1')->getStyle()->getFont()->getBold());
// Prove Xf index changed although style is same.
self::assertEquals($countXfs + $index, $sheet3->getCell('B1')->getXfIndex());
self::assertEquals($countXfs + $index, $sheet3->getColumnDimension('B')->getXfIndex());
}
public function testAddExternalRowDimensionStyles(): void
{
$spreadsheet1 = new Spreadsheet();
$sheet1 = $spreadsheet1->createSheet()->setTitle('sheetWithColumnDimension');
$sheet1->getCell('A1')->setValue(1);
$sheet1->getCell('A1')->getStyle()->getFont()->setItalic(true);
$sheet1->getRowDimension(2)->setXfIndex($sheet1->getCell('A1')->getXfIndex());
$index = $sheet1->getRowDimension(2)->getXfIndex();
self::assertEquals(1, $index);
self::assertCount(2, $spreadsheet1->getCellXfCollection());
$spreadsheet2 = new Spreadsheet();
$sheet2 = $spreadsheet2->createSheet()->setTitle('sheetWithTwoStyles');
$sheet2->getCell('A1')->setValue(1);
$sheet2->getCell('A1')->getStyle()->getFont()->setBold(true);
$sheet2->getCell('B2')->getStyle()->getFont()->setSuperscript(true);
$countXfs = count($spreadsheet2->getCellXfCollection());
self::assertEquals(3, $countXfs);
$sheet3 = $spreadsheet2->addExternalSheet($sheet1);
self::assertCount(5, $spreadsheet2->getCellXfCollection());
self::assertTrue($sheet3->getCell('A1')->getStyle()->getFont()->getItalic());
self::assertTrue($sheet3->getCell('A2')->getStyle()->getFont()->getItalic());
self::assertFalse($sheet3->getCell('A2')->getStyle()->getFont()->getBold());
// Prove Xf index changed although style is same.
self::assertEquals($countXfs + $index, $sheet3->getCell('A2')->getXfIndex());
self::assertEquals($countXfs + $index, $sheet3->getRowDimension(2)->getXfIndex());
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/RefRangeTest.php | tests/PhpSpreadsheetTests/RefRangeTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PHPUnit\Framework\TestCase;
class RefRangeTest extends TestCase
{
#[\PHPUnit\Framework\Attributes\DataProvider('providerRefRange')]
public function testRefRange(int|string $expectedResult, string $rangeString): void
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->getCell('A1')->setValue("=SUM($rangeString)");
self::assertSame($expectedResult, $sheet->getCell('A1')->getCalculatedValue());
$spreadsheet->disconnectWorksheets();
}
public static function providerRefRange(): array
{
return [
'normal range' => [0, 'B1:B2'],
'ref as end of range' => ['#REF!', 'B1:#REF!'],
'ref as start of range' => ['#REF!', '#REF!:B2'],
'ref as both parts of range' => ['#REF!', '#REF!:#REF!'],
'using indirect for ref' => ['#REF!', 'B1:INDIRECT("XYZ")'],
];
}
public function testRefRangeRead(): void
{
$reader = new Xlsx();
$spreadsheet = $reader->load('tests/data/Reader/XLSX/issue.3453.xlsx');
$sheet = $spreadsheet->getActiveSheet();
self::assertSame(0, $sheet->getCell('H1')->getCalculatedValue());
self::assertSame('#REF!', $sheet->getCell('H2')->getCalculatedValue());
$spreadsheet->disconnectWorksheets();
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Issue4521Test.php | tests/PhpSpreadsheetTests/Issue4521Test.php | <?php
namespace PhpOffice\PhpSpreadsheetTests;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Shared\File;
use PHPUnit\Framework\TestCase;
class Issue4521Test extends TestCase
{
private string $outfile = '';
protected int $weirdMimetypeMajor = 8;
protected int $weirdMimetypeMinor1 = 1;
protected int $weirdMimetypeMinor2 = 2;
protected function tearDown(): void
{
if ($this->outfile !== '') {
unlink($this->outfile);
$this->outfile = '';
}
}
public function testEmptyFile(): void
{
$this->outfile = File::temporaryFilename();
file_put_contents($this->outfile, '');
$spreadsheet = IOFactory::load($this->outfile);
$sheet = $spreadsheet->getActiveSheet();
self::assertSame('A', $sheet->getHighestColumn());
self::assertSame(1, $sheet->getHighestRow());
$spreadsheet->disconnectWorksheets();
}
public function testCrlfFile(): void
{
if (PHP_MAJOR_VERSION === $this->weirdMimetypeMajor) {
if (
PHP_MINOR_VERSION === $this->weirdMimetypeMinor1
|| PHP_MINOR_VERSION === $this->weirdMimetypeMinor2
) {
self::markTestSkipped('Php mimetype bug with this release');
}
}
$this->outfile = File::temporaryFilename();
file_put_contents($this->outfile, "\r\n");
$spreadsheet = IOFactory::load($this->outfile);
$sheet = $spreadsheet->getActiveSheet();
self::assertSame('A', $sheet->getHighestColumn());
self::assertSame(1, $sheet->getHighestRow());
$spreadsheet->disconnectWorksheets();
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Style/ConditionalBoolTest.php | tests/PhpSpreadsheetTests/Style/ConditionalBoolTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Style;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx as XlsxReader;
use PhpOffice\PhpSpreadsheet\Shared\File;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Conditional;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx as XlsxWriter;
use PHPUnit\Framework\TestCase;
class ConditionalBoolTest extends TestCase
{
private string $outfile = '';
protected function tearDown(): void
{
if ($this->outfile !== '') {
unlink($this->outfile);
$this->outfile = '';
}
}
public function testBool(): void
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$condition1 = new Conditional();
$condition1->setConditionType(Conditional::CONDITION_CELLIS);
$condition1->setOperatorType(Conditional::OPERATOR_EQUAL);
$condition1->addCondition(false);
$condition1->getStyle()->getFill()
->setFillType(Fill::FILL_SOLID)
->getStartColor()->setARGB('FFFFFF00');
$conditionalStyles = $sheet->getStyle('A1:A10')->getConditionalStyles();
$conditionalStyles[] = $condition1;
$sheet->getStyle('A1:A20')->setConditionalStyles($conditionalStyles);
$sheet->setCellValue('A1', 1);
$sheet->setCellValue('A2', true);
$sheet->setCellValue('A3', false);
$sheet->setCellValue('A4', 0.6);
$sheet->setCellValue('A6', 0);
$sheet->setSelectedCell('B1');
$sheet = $spreadsheet->createSheet();
$condition1 = new Conditional();
$condition1->setConditionType(Conditional::CONDITION_CELLIS);
$condition1->setOperatorType(Conditional::OPERATOR_EQUAL);
$condition1->addCondition(true);
$condition1->getStyle()->getFill()
->setFillType(Fill::FILL_SOLID)
->getStartColor()->setARGB('FF00FF00');
$conditionalStyles = $sheet->getStyle('A1:A10')->getConditionalStyles();
$conditionalStyles[] = $condition1;
$sheet->getStyle('A1:A20')->setConditionalStyles($conditionalStyles);
$sheet->setCellValue('A1', 1);
$sheet->setCellValue('A2', true);
$sheet->setCellValue('A3', false);
$sheet->setCellValue('A4', 0.6);
$sheet->setCellValue('A6', 0);
$sheet->setSelectedCell('B1');
$writer = new XlsxWriter($spreadsheet);
$this->outfile = File::temporaryFilename();
$writer->save($this->outfile);
$spreadsheet->disconnectWorksheets();
$file = 'zip://' . $this->outfile . '#xl/worksheets/sheet1.xml';
$contents = file_get_contents($file);
self::assertNotFalse($contents);
self::assertStringContainsString('<formula>FALSE</formula>', $contents);
$file = 'zip://' . $this->outfile . '#xl/worksheets/sheet2.xml';
$contents = file_get_contents($file);
self::assertNotFalse($contents);
self::assertStringContainsString('<formula>TRUE</formula>', $contents);
$reader = new XlsxReader();
$spreadsheet2 = $reader->load($this->outfile);
$sheet1 = $spreadsheet2->getSheet(0);
$condArray = $sheet1->getStyle('A1:A20')->getConditionalStyles();
self::assertNotEmpty($condArray);
$cond1 = $condArray[0];
self::assertSame(Conditional::CONDITION_CELLIS, $cond1->getConditionType());
self::assertSame(Conditional::OPERATOR_EQUAL, $cond1->getOperatorType());
self::assertFalse(($cond1->getConditions())[0]);
$sheet2 = $spreadsheet2->getSheet(1);
$condArray = $sheet2->getStyle('A1:A20')->getConditionalStyles();
self::assertNotEmpty($condArray);
$cond1 = $condArray[0];
self::assertSame(Conditional::CONDITION_CELLIS, $cond1->getConditionType());
self::assertSame(Conditional::OPERATOR_EQUAL, $cond1->getOperatorType());
self::assertTrue(($cond1->getConditions())[0]);
$spreadsheet2->disconnectWorksheets();
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Style/ExportArrayTest.php | tests/PhpSpreadsheetTests/Style/ExportArrayTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Style;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Style\Color;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Style\Font;
use PhpOffice\PhpSpreadsheet\Style\Protection;
use PHPUnit\Framework\TestCase;
class ExportArrayTest extends TestCase
{
public function testStyleCopy(): void
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$cell1 = $sheet->getCell('A1');
$cell1->setValue('Cell A1');
$cell1style = $cell1->getStyle();
$cell1style->getAlignment()->setHorizontal(Alignment::HORIZONTAL_RIGHT);
$cell1style->getFont()->getColor()->setARGB('FFFF0000');
$cell1style->getFont()->setBold(true);
$cell1style->getFill()->setFillType(Fill::FILL_PATTERN_GRAY125);
$cell1style->getFill()->setStartColor(new Color('FF0000FF'));
$cell1style->getFill()->setEndColor(new Color('FF00FF00'));
$cell1style->getFont()->setUnderline(true);
self::assertEquals(Font::UNDERLINE_SINGLE, $cell1style->getFont()->getUnderline());
$cell1style->getProtection()->setHidden(Protection::PROTECTION_UNPROTECTED);
$cell1style->getProtection()->setLocked(Protection::PROTECTION_UNPROTECTED);
/** @var mixed[][] */
$styleArray = $cell1style->exportArray();
$cell2 = $sheet->getCell('B1');
$cell2->setValue('Cell B1');
$cell2style = $cell2->getStyle();
$cell2style->applyFromArray($styleArray);
self::AssertEquals($cell1style->getAlignment()->getHorizontal(), $cell2style->getAlignment()->getHorizontal());
self::AssertEquals($cell1style->getFont()->getColor()->getARGB(), $cell2style->getFont()->getColor()->getARGB());
self::AssertEquals($cell1style->getFont()->getBold(), $cell2style->getFont()->getBold());
self::AssertEquals($cell1style->getFont()->getUnderline(), $cell2style->getFont()->getUnderline());
self::AssertEquals($cell1style->getFill()->getFillType(), $cell2style->getFill()->getFillType());
self::AssertEquals($cell1style->getFill()->getStartColor()->getARGB(), $cell2style->getFill()->getStartColor()->getARGB());
self::AssertEquals($cell1style->getFill()->getEndColor()->getARGB(), $cell2style->getFill()->getEndColor()->getARGB());
self::AssertEquals($cell1style->getProtection()->getLocked(), $cell2style->getProtection()->getLocked());
self::AssertEquals($cell1style->getProtection()->getHidden(), $cell2style->getProtection()->getHidden());
self::AssertEquals($cell1style->getHashCode(), $cell2style->getHashCode());
self::AssertEquals($cell1style->getAlignment()->getHashCode(), $cell2style->getAlignment()->getHashCode());
self::AssertEquals($cell1style->getFont()->getHashCode(), $cell2style->getFont()->getHashCode());
self::AssertEquals($cell1style->getFill()->getHashCode(), $cell2style->getFill()->getHashCode());
self::AssertEquals($cell1style->getProtection()->getHashCode(), $cell2style->getProtection()->getHashCode());
$spreadsheet->disconnectWorksheets();
}
public function testStyleFromArrayCopy(): void
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$cell1 = $sheet->getCell('A1');
$cell1->setValue('Cell A1');
$cell1style = $cell1->getStyle();
$cell1style->getAlignment()->applyFromArray(['horizontal' => Alignment::HORIZONTAL_RIGHT]);
$cell1style->getFont()->getColor()->setARGB('FFFF0000');
$cell1style->getFont()->applyFromArray(['bold' => true]);
$cell1style->getFill()->applyFromArray(['fillType' => Fill::FILL_PATTERN_GRAY125]);
$cell1style->getFill()->getStartColor()->applyFromArray(['argb' => 'FF0000FF']);
$cell1style->getFill()->getEndColor()->setRGB('00FF00');
$cell1style->getFill()->setRotation(45);
$cell1style->getFont()->setUnderline(true);
self::assertEquals(Font::UNDERLINE_SINGLE, $cell1style->getFont()->getUnderline());
$cell1style->getProtection()->applyFromArray(['hidden' => Protection::PROTECTION_UNPROTECTED, 'locked' => Protection::PROTECTION_UNPROTECTED]);
/** @var mixed[][] */
$styleArray = $cell1style->exportArray();
$cell2 = $sheet->getCell('B1');
$cell2->setValue('Cell B1');
$cell2style = $cell2->getStyle();
$cell2style->applyFromArray($styleArray);
self::AssertEquals($cell1style->getAlignment()->getHorizontal(), $cell2style->getAlignment()->getHorizontal());
self::AssertEquals($cell1style->getFont()->getColor()->getARGB(), $cell2style->getFont()->getColor()->getARGB());
self::AssertEquals($cell1style->getFont()->getBold(), $cell2style->getFont()->getBold());
self::AssertEquals($cell1style->getFont()->getUnderline(), $cell2style->getFont()->getUnderline());
self::AssertEquals($cell1style->getFill()->getFillType(), $cell2style->getFill()->getFillType());
self::AssertEquals($cell1style->getFill()->getRotation(), $cell2style->getFill()->getRotation());
self::AssertEquals($cell1style->getFill()->getStartColor()->getARGB(), $cell2style->getFill()->getStartColor()->getARGB());
self::AssertEquals($cell1style->getFill()->getEndColor()->getARGB(), $cell2style->getFill()->getEndColor()->getARGB());
self::AssertEquals($cell1style->getProtection()->getLocked(), $cell2style->getProtection()->getLocked());
self::AssertEquals($cell1style->getProtection()->getHidden(), $cell2style->getProtection()->getHidden());
self::AssertEquals($cell1style->getFill()->getStartColor()->getHashCode(), $cell2style->getFill()->getStartColor()->getHashCode());
self::AssertEquals($cell1style->getFill()->getEndColor()->getHashCode(), $cell2style->getFill()->getEndColor()->getHashCode());
$spreadsheet->disconnectWorksheets();
}
public function testNumberFormat(): void
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$cell1 = $sheet->getCell('A1');
$cell1style = $cell1->getStyle();
$fmt2 = '$ #,##0.000';
$cell1style->getNumberFormat()->setFormatCode($fmt2);
$cell1style->getFont()->setUnderline('');
self::assertEquals(Font::UNDERLINE_NONE, $cell1style->getFont()->getUnderline());
$cell1->setValue(2345.679);
/** @var mixed[][] */
$styleArray = $cell1style->exportArray();
self::assertEquals('$ 2,345.679', $cell1->getFormattedValue());
$cell2 = $sheet->getCell('B1');
$cell2->setValue(12345.679);
$cell2style = $cell2->getStyle();
$cell2style->applyFromArray($styleArray);
self::assertEquals('$ 12,345.679', $cell2->getFormattedValue());
self::AssertEquals($cell1style->getNumberFormat()->getHashCode(), $cell2style->getNumberFormat()->getHashCode());
$spreadsheet->disconnectWorksheets();
}
public function testNumberFormatFromArray(): void
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$cell1 = $sheet->getCell('A1');
$cell1style = $cell1->getStyle();
$fmt2 = '$ #,##0.000';
$cell1style->getNumberFormat()->applyFromArray(['formatCode' => $fmt2]);
$cell1style->getFont()->setUnderline('');
self::assertEquals(Font::UNDERLINE_NONE, $cell1style->getFont()->getUnderline());
$cell1style->getBorders()->getTop()->setBorderStyle(Border::BORDER_THIN);
$cell1->setValue(2345.679);
/** @var mixed[][] */
$styleArray = $cell1style->exportArray();
self::assertEquals('$ 2,345.679', $cell1->getFormattedValue());
$cell2 = $sheet->getCell('B1');
$cell2->setValue(12345.679);
$cell2style = $cell2->getStyle();
$cell2style->applyFromArray($styleArray);
self::assertEquals('$ 12,345.679', $cell2->getFormattedValue());
self::AssertEquals($cell1style->getNumberFormat()->getHashCode(), $cell2style->getNumberFormat()->getHashCode());
self::AssertEquals($cell1style->getBorders()->getHashCode(), $cell2style->getBorders()->getHashCode());
self::AssertEquals($cell1style->getBorders()->getTop()->getHashCode(), $cell2style->getBorders()->getTop()->getHashCode());
self::AssertEquals($cell1style->getBorders()->getTop()->getBorderStyle(), $cell2style->getBorders()->getTop()->getBorderStyle());
$spreadsheet->disconnectWorksheets();
}
public function testStackedRotation(): void
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$cell1 = $sheet->getCell('A1');
$cell1->setValue('Cell A1');
$cell1style = $cell1->getStyle();
$cell1style->getAlignment()->setTextRotation(Alignment::TEXTROTATION_STACK_EXCEL);
self::assertEquals(Alignment::TEXTROTATION_STACK_PHPSPREADSHEET, $cell1style->getAlignment()->getTextRotation());
/** @var mixed[][] */
$styleArray = $cell1style->exportArray();
$cell2 = $sheet->getCell('B1');
$cell2->setValue('Cell B1');
$cell2style = $cell2->getStyle();
$cell2style->applyFromArray($styleArray);
self::AssertEquals($cell1style->getAlignment()->getTextRotation(), $cell2style->getAlignment()->getTextRotation());
$spreadsheet->disconnectWorksheets();
}
public function testFillColors(): void
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$cell1 = $sheet->getCell('A2');
$cell1style = $cell1->getStyle();
$cell1style->getFill()
->setFillType(Fill::FILL_PATTERN_GRAY125);
$cell1style->getFill()->getStartColor()
->setArgb('FF112233');
$styleArray = $cell1style->exportArray();
self::assertEquals(
[
'fillType' => Fill::FILL_PATTERN_GRAY125,
'rotation' => 0.0,
'endColor' => ['argb' => 'FF000000', 'theme' => -1],
'startColor' => ['argb' => 'FF112233', 'theme' => -1],
],
$styleArray['fill'],
'changed start color with setArgb'
);
$cell1 = $sheet->getCell('A1');
$cell1style = $cell1->getStyle();
$cell1style->getFill()->setFillType(Fill::FILL_PATTERN_GRAY125);
$styleArray = $cell1style->exportArray();
self::assertEquals(
[
'fillType' => Fill::FILL_PATTERN_GRAY125,
'rotation' => 0.0,
],
$styleArray['fill'],
'default colors'
);
$cell1 = $sheet->getCell('A3');
$cell1style = $cell1->getStyle();
$cell1style->getFill()
->setFillType(Fill::FILL_PATTERN_GRAY125);
$cell1style->getFill()->getEndColor()->setArgb('FF112233');
$styleArray = $cell1style->exportArray();
self::assertEquals(
[
'fillType' => Fill::FILL_PATTERN_GRAY125,
'rotation' => 0.0,
'endColor' => ['argb' => 'FF112233', 'theme' => -1],
'startColor' => ['argb' => 'FFFFFFFF', 'theme' => -1],
],
$styleArray['fill'],
'changed end color with setArgb'
);
$cell1 = $sheet->getCell('A4');
$cell1style = $cell1->getStyle();
$cell1style->getFill()
->setFillType(Fill::FILL_PATTERN_GRAY125);
$cell1style->getFill()->setEndColor(new Color('FF0000FF'));
$styleArray = $cell1style->exportArray();
self::assertEquals(
[
'fillType' => Fill::FILL_PATTERN_GRAY125,
'rotation' => 0.0,
'endColor' => ['argb' => 'FF0000FF', 'theme' => -1],
'startColor' => ['argb' => 'FFFFFFFF', 'theme' => -1],
],
$styleArray['fill'],
'changed end color with setEndColor'
);
$cell1 = $sheet->getCell('A5');
$cell1style = $cell1->getStyle();
$cell1style->getFill()->setFillType(Fill::FILL_PATTERN_GRAY125);
$cell1style->getFill()
->setStartColor(new Color('FF0000FF'));
$styleArray = $cell1style->exportArray();
self::assertEquals(
[
'fillType' => Fill::FILL_PATTERN_GRAY125,
'rotation' => 0.0,
'startColor' => ['argb' => 'FF0000FF', 'theme' => -1],
'endColor' => ['argb' => 'FF000000', 'theme' => -1],
],
$styleArray['fill'],
'changed start color with setStartColor'
);
$cell1 = $sheet->getCell('A6');
$cell1->getStyle()->getFill()->applyFromArray(
[
'fillType' => Fill::FILL_PATTERN_GRAY125,
'rotation' => 45.0,
'startColor' => ['argb' => 'FF00FFFF', 'theme' => -1],
]
);
$cell1style = $cell1->getStyle();
$styleArray = $cell1style->exportArray();
self::assertEquals(
[
'fillType' => Fill::FILL_PATTERN_GRAY125,
'rotation' => 45.0,
'startColor' => ['argb' => 'FF00FFFF', 'theme' => -1],
'endColor' => ['argb' => 'FF000000', 'theme' => -1],
],
$styleArray['fill'],
'applyFromArray with startColor'
);
$cell1 = $sheet->getCell('A7');
$cell1->getStyle()->getFill()->applyFromArray(
[
'fillType' => Fill::FILL_PATTERN_GRAY125,
]
);
$cell1style = $cell1->getStyle();
$styleArray = $cell1style->exportArray();
self::assertEquals(
[
'fillType' => Fill::FILL_PATTERN_GRAY125,
'rotation' => 0.0,
],
$styleArray['fill'],
'applyFromArray without start/endColor'
);
$spreadsheet->disconnectWorksheets();
}
public function testQuotePrefix(): void
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->getCell('A1')
->setValueExplicit('=1+2', DataType::TYPE_STRING);
self::assertSame('=1+2', $sheet->getCell('A1')->getCalculatedValue());
self::assertTrue($sheet->getStyle('A1')->getQuotePrefix());
$sheet->getCell('A2')->setValue('=1+2');
self::assertSame(3, $sheet->getCell('A2')->getCalculatedValue());
self::assertFalse($sheet->getStyle('A2')->getQuotePrefix());
/** @var mixed[][] */
$styleArray1 = $sheet->getStyle('A1')->exportArray();
/** @var mixed[][] */
$styleArray2 = $sheet->getStyle('A2')->exportArray();
$sheet->getStyle('B1')->applyFromArray($styleArray1);
$sheet->getStyle('B2')->applyFromArray($styleArray2);
self::assertTrue($sheet->getStyle('B1')->getQuotePrefix());
self::assertFalse($sheet->getStyle('B2')->getQuotePrefix());
$spreadsheet->disconnectWorksheets();
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Style/FontTest.php | tests/PhpSpreadsheetTests/Style/FontTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Style;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Font;
use PHPUnit\Framework\TestCase;
class FontTest extends TestCase
{
public function testSuperSubScript(): void
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$cell = $sheet->getCell('A1');
$cell->setValue('Cell A1');
$font = $cell->getStyle()->getFont();
$font->setSuperscript(true);
$font->setSubscript(true);
self::assertFalse($font->getSuperscript(), 'Earlier set true loses');
self::assertTrue($font->getSubscript(), 'Last set true wins');
$font->setSubscript(true);
$font->setSuperscript(true);
self::assertTrue($font->getSuperscript(), 'Last set true wins');
self::assertFalse($font->getSubscript(), 'Earlier set true loses');
$font->setSuperscript(false);
$font->setSubscript(false);
self::assertFalse($font->getSuperscript(), 'False remains unchanged');
self::assertFalse($font->getSubscript(), 'False remains unchanged');
$font->setSubscript(false);
$font->setSuperscript(false);
self::assertFalse($font->getSuperscript(), 'False remains unchanged');
self::assertFalse($font->getSubscript(), 'False remains unchanged');
$font->setSubscript(true);
$font->setSuperscript(false);
self::assertFalse($font->getSuperscript(), 'False remains unchanged');
self::assertTrue($font->getSubscript(), 'True remains unchanged');
$font->setSubscript(false);
$font->setSuperscript(true);
self::assertTrue($font->getSuperscript());
self::assertFalse($font->getSubscript(), 'False remains unchanged');
$spreadsheet->disconnectWorksheets();
}
public function testSize(): void
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$cell = $sheet->getCell('A1');
$cell->setValue('Cell A1');
$font = $cell->getStyle()->getFont();
self::assertEquals(11, $font->getSize(), 'The default is 11');
$font->setSize(12);
self::assertEquals(12, $font->getSize(), 'Accepted new font size');
$invalidFontSizeValues = [
'',
false,
true,
'non_numeric_string',
'-1.0',
-1.0,
0,
[],
(object) [],
null,
];
foreach ($invalidFontSizeValues as $invalidFontSizeValue) {
$font->setSize(12);
$font->setSize($invalidFontSizeValue);
self::assertEquals(10, $font->getSize(), 'Set to 10 after trying to set an invalid value.');
}
$spreadsheet->disconnectWorksheets();
}
public function testName(): void
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$cell = $sheet->getCell('A1');
$cell->setValue('Cell A1');
$font = $cell->getStyle()->getFont();
self::assertEquals('Calibri', $font->getName(), 'The default is Calibri');
$font->setName('whatever');
self::assertEquals('whatever', $font->getName(), 'The default is Calibri');
$font->setName('');
self::assertEquals('Calibri', $font->getName(), 'Null string changed to default');
$spreadsheet->disconnectWorksheets();
}
public function testUnderlineHash(): void
{
$font1 = new Font();
$font2 = new Font();
$font2aHash = $font2->getHashCode();
self::assertSame($font1->getHashCode(), $font2aHash);
$font2->setUnderlineColor(
[
'type' => 'srgbClr',
'value' => 'FF0000',
'alpha' => null,
]
);
$font2bHash = $font2->getHashCode();
self::assertNotEquals($font1->getHashCode(), $font2bHash);
}
public function testAutoColorSupervisor(): void
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->getStyle('A1')->getFont()->setAutoColor(true);
self::assertTrue($sheet->getStyle('A1')->getFont()->getAutoColor());
$spreadsheet->disconnectWorksheets();
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Style/BorderRangeTest.php | tests/PhpSpreadsheetTests/Style/BorderRangeTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Style;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Style\Color;
use PHPUnit\Framework\TestCase;
class BorderRangeTest extends TestCase
{
public function testBorderRangeInAction(): void
{
// testcase for the initial bug problem: setting border+color fails
// set red borders aroundlA1:B3 square. Verify that the borders set are actually correct
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$argb = 'FFFF0000';
$color = new Color($argb);
$sheet->getStyle('A1:C1')->getBorders()->getTop()->setBorderStyle(Border::BORDER_THIN)->setColor($color);
$sheet->getStyle('A1:A3')->getBorders()->getLeft()->setBorderStyle(Border::BORDER_THIN)->setColor($color);
$sheet->getStyle('C1:C3')->getBorders()->getRight()->setBorderStyle(Border::BORDER_THIN)->setColor($color);
$sheet->getStyle('A3:C3')->getBorders()->getBottom()->setBorderStyle(Border::BORDER_THIN)->setColor($color);
// upper row
$expectations = [
// cell => Left/Right/Top/Bottom
'A1' => 'LT',
'B1' => 'T',
'C1' => 'RT',
'A2' => 'L',
'B2' => '',
'C2' => 'R',
'A3' => 'LB',
'B3' => 'B',
'C3' => 'RB',
];
$sides = [
'L' => 'Left',
'R' => 'Right',
'T' => 'Top',
'B' => 'Bottom',
];
foreach ($expectations as $cell => $borders) {
$bs = $sheet->getStyle($cell)->getBorders();
foreach ($sides as $sidekey => $side) {
$assertion = "setBorderStyle on a range of cells, $cell $side";
$func = "get$side";
$b = $bs->$func(); // boo
if (!str_contains($borders, $sidekey)) {
self::assertSame(Border::BORDER_NONE, $b->getBorderStyle(), $assertion);
} else {
self::assertSame(Border::BORDER_THIN, $b->getBorderStyle(), $assertion);
self::assertSame($argb, $b->getColor()->getARGB(), $assertion);
}
}
}
$spreadsheet->disconnectWorksheets();
}
public function testBorderRangeDirectly(): void
{
// testcase for the underlying problem directly
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$style = $sheet->getStyle('A1:C1')->getBorders()->getTop()->setBorderStyle(Border::BORDER_THIN);
self::assertSame('A1:C1', $style->getSelectedCells(), 'getSelectedCells should not change after a style operation on a border range');
$spreadsheet->disconnectWorksheets();
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Style/ColorTest.php | tests/PhpSpreadsheetTests/Style/ColorTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Style;
use PhpOffice\PhpSpreadsheet\Style\Color;
use PHPUnit\Framework\TestCase;
class ColorTest extends TestCase
{
public function testNewColor(): void
{
$color = new Color('FF123456');
self::assertEquals('FF123456', $color->getARGB());
self::assertEquals('123456', $color->getRGB());
}
public function testARGBSetter(): void
{
$color = new Color();
$color->setARGB('80123456');
self::assertEquals('80123456', $color->getARGB());
self::assertEquals('123456', $color->getRGB());
}
public function testARGBSetterEmpty(): void
{
$color = new Color();
$color->setARGB();
self::assertEquals(Color::COLOR_BLACK, $color->getARGB());
}
public function testARGBSetterInvalid(): void
{
$color = new Color('80123456');
$color->setARGB('INVALID COLOR');
self::assertEquals('80123456', $color->getARGB());
}
public function testRGBSetter(): void
{
$color = new Color();
$color->setRGB('123456');
self::assertEquals('123456', $color->getRGB());
self::assertEquals('FF123456', $color->getARGB());
}
public function testRGBSetterEmpty(): void
{
$color = new Color();
$color->setRGB();
self::assertEquals(Color::COLOR_BLACK, $color->getARGB());
}
public function testRGBSetterInvalid(): void
{
$color = new Color('80123456');
$color->setRGB('INVALID COLOR');
self::assertEquals('123456', $color->getRGB());
}
public function testARGBFromArray(): void
{
$color = new Color();
$color->applyFromArray(['argb' => '80123456']);
self::assertEquals('80123456', $color->getARGB());
self::assertEquals('123456', $color->getRGB());
}
public function testRGBFromArray(): void
{
$color = new Color();
$color->applyFromArray(['rgb' => '123456']);
self::assertEquals('123456', $color->getRGB());
self::assertEquals('FF123456', $color->getARGB());
}
#[\PHPUnit\Framework\Attributes\DataProvider('providerColorGetRed')]
public function testGetRed(mixed $expectedResult, string $color, ?bool $bool = null): void
{
if ($bool === null) {
$result = Color::getRed($color);
} else {
$result = Color::getRed($color, $bool);
}
self::assertEquals($expectedResult, $result);
}
public static function providerColorGetRed(): array
{
return require 'tests/data/Style/Color/ColorGetRed.php';
}
#[\PHPUnit\Framework\Attributes\DataProvider('providerColorGetGreen')]
public function testGetGreen(mixed $expectedResult, string $color, ?bool $bool = null): void
{
if ($bool === null) {
$result = Color::getGreen($color);
} else {
$result = Color::getGreen($color, $bool);
}
self::assertEquals($expectedResult, $result);
}
public static function providerColorGetGreen(): array
{
return require 'tests/data/Style/Color/ColorGetGreen.php';
}
#[\PHPUnit\Framework\Attributes\DataProvider('providerColorGetBlue')]
public function testGetBlue(mixed $expectedResult, string $color, ?bool $bool = null): void
{
if ($bool === null) {
$result = Color::getBlue($color);
} else {
$result = Color::getBlue($color, $bool);
}
self::assertEquals($expectedResult, $result);
}
public static function providerColorGetBlue(): array
{
return require 'tests/data/Style/Color/ColorGetBlue.php';
}
#[\PHPUnit\Framework\Attributes\DataProvider('providerColorChangeBrightness')]
public function testChangeBrightness(string $expectedResult, string $hexColorValue, float $adjustPercentages): void
{
$result = Color::changeBrightness($hexColorValue, $adjustPercentages);
self::assertEquals($expectedResult, $result);
}
public static function providerColorChangeBrightness(): array
{
return require 'tests/data/Style/Color/ColorChangeBrightness.php';
}
public function testDefaultColor(): void
{
$color = new Color();
$color->setARGB('FFFF0000');
self::assertEquals('FFFF0000', $color->getARGB());
self::assertEquals('FF0000', $color->getRGB());
$color->setARGB('');
self::assertEquals(Color::COLOR_BLACK, $color->getARGB());
self::assertEquals('000000', $color->getRGB());
$color->setARGB('FFFF0000');
self::assertEquals('FFFF0000', $color->getARGB());
self::assertEquals('FF0000', $color->getRGB());
$color->setRGB('');
self::assertEquals(Color::COLOR_BLACK, $color->getARGB());
self::assertEquals('000000', $color->getRGB());
}
public function testNamedColors(): void
{
$color = new Color();
$color->setARGB('Blue');
self::assertEquals(Color::COLOR_BLUE, $color->getARGB());
$color->setARGB('black');
self::assertEquals(Color::COLOR_BLACK, $color->getARGB());
$color->setARGB('wHite');
self::assertEquals(Color::COLOR_WHITE, $color->getARGB());
$color->setRGB('reD');
self::assertEquals(Color::COLOR_RED, $color->getARGB());
$color->setRGB('GREEN');
self::assertEquals(Color::COLOR_GREEN, $color->getARGB());
$color->setRGB('magenta');
self::assertEquals(Color::COLOR_MAGENTA, $color->getARGB());
$color->setRGB('YeLlOw');
self::assertEquals(Color::COLOR_YELLOW, $color->getARGB());
$color->setRGB('CYAN');
self::assertEquals(Color::COLOR_CYAN, $color->getARGB());
$color->setRGB('123456ab');
self::assertEquals('123456ab', $color->getARGB());
self::assertEquals('3456ab', $color->getRGB());
$color->setARGB('3456cd');
self::assertEquals('FF3456cd', $color->getARGB());
self::assertEquals('3456cd', $color->getRGB());
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Style/AlignmentTest.php | tests/PhpSpreadsheetTests/Style/AlignmentTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Style;
use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PHPUnit\Framework\TestCase;
class AlignmentTest extends TestCase
{
private ?Spreadsheet $spreadsheet = null;
protected function tearDown(): void
{
if ($this->spreadsheet !== null) {
$this->spreadsheet->disconnectWorksheets();
$this->spreadsheet = null;
}
}
public function testAlignment(): void
{
$this->spreadsheet = new Spreadsheet();
$sheet = $this->spreadsheet->getActiveSheet();
$cell1 = $sheet->getCell('A1');
$cell1->setValue('Cell1');
$cell1->getStyle()->getAlignment()->setTextRotation(45);
self::assertEquals(45, $cell1->getStyle()->getAlignment()->getTextRotation());
$cell2 = $sheet->getCell('A2');
$cell2->setValue('Cell2');
$cell2->getStyle()->getAlignment()->setTextRotation(-45);
self::assertEquals(-45, $cell2->getStyle()->getAlignment()->getTextRotation());
// special value for stacked
$cell3 = $sheet->getCell('A3');
$cell3->setValue('Cell3');
$cell3->getStyle()->getAlignment()->setTextRotation(255);
self::assertEquals(-165, $cell3->getStyle()->getAlignment()->getTextRotation());
}
public function testRotationTooHigh(): void
{
$this->expectException(PhpSpreadsheetException::class);
$this->spreadsheet = new Spreadsheet();
$sheet = $this->spreadsheet->getActiveSheet();
$cell1 = $sheet->getCell('A1');
$cell1->setValue('Cell1');
$cell1->getStyle()->getAlignment()->setTextRotation(91);
self::assertEquals(0, $cell1->getStyle()->getAlignment()->getTextRotation());
}
public function testRotationTooLow(): void
{
$this->expectException(PhpSpreadsheetException::class);
$this->spreadsheet = new Spreadsheet();
$sheet = $this->spreadsheet->getActiveSheet();
$cell1 = $sheet->getCell('A1');
$cell1->setValue('Cell1');
$cell1->getStyle()->getAlignment()->setTextRotation(-91);
self::assertEquals(0, $cell1->getStyle()->getAlignment()->getTextRotation());
}
public function testHorizontal(): void
{
$this->spreadsheet = new Spreadsheet();
$sheet = $this->spreadsheet->getActiveSheet();
$cell1 = $sheet->getCell('A1');
$cell1->setValue('X');
$cell1->getStyle()->getAlignment()->setHorizontal(Alignment::HORIZONTAL_LEFT)->setIndent(1);
self::assertEquals(Alignment::HORIZONTAL_LEFT, $cell1->getStyle()->getAlignment()->getHorizontal());
self::assertEquals(1, $cell1->getStyle()->getAlignment()->getIndent());
$cell2 = $sheet->getCell('A2');
$cell2->setValue('Y');
$cell2->getStyle()->getAlignment()->setHorizontal(Alignment::HORIZONTAL_RIGHT)->setIndent(2);
self::assertEquals(Alignment::HORIZONTAL_RIGHT, $cell2->getStyle()->getAlignment()->getHorizontal());
self::assertEquals(2, $cell2->getStyle()->getAlignment()->getIndent());
$cell3 = $sheet->getCell('A3');
$cell3->setValue('Z');
// indent not supported for next style - changed to 0
$cell3->getStyle()->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER_CONTINUOUS)->setIndent(3);
self::assertEquals(Alignment::HORIZONTAL_CENTER_CONTINUOUS, $cell3->getStyle()->getAlignment()->getHorizontal());
self::assertEquals(0, $cell3->getStyle()->getAlignment()->getIndent());
}
public function testJustifyLastLine(): void
{
$this->spreadsheet = new Spreadsheet();
$sheet = $this->spreadsheet->getActiveSheet();
$cell1 = $sheet->getCell('A1');
$cell1->setValue('ABC');
$cell1->getStyle()->getAlignment()->setHorizontal(Alignment::HORIZONTAL_DISTRIBUTED);
$cell1->getStyle()->getAlignment()->setJustifyLastLine(true);
self::assertTrue($cell1->getStyle()->getAlignment()->getJustifyLastLine());
}
public function testReadOrder(): void
{
$this->spreadsheet = new Spreadsheet();
$sheet = $this->spreadsheet->getActiveSheet();
$cell1 = $sheet->getCell('A1');
$cell1->setValue('ABC');
$cell1->getStyle()->getAlignment()->setReadOrder(0);
self::assertEquals(0, $cell1->getStyle()->getAlignment()->getReadOrder());
$cell1->getStyle()->getAlignment()->setReadOrder(1);
self::assertEquals(1, $cell1->getStyle()->getAlignment()->getReadOrder());
// following not supported - zero is used instead
$cell1->getStyle()->getAlignment()->setReadOrder(-1);
self::assertEquals(0, $cell1->getStyle()->getAlignment()->getReadOrder());
$cell1->getStyle()->getAlignment()->setReadOrder(2);
self::assertEquals(2, $cell1->getStyle()->getAlignment()->getReadOrder());
// following not supported - zero is used instead
$cell1->getStyle()->getAlignment()->setReadOrder(3);
self::assertEquals(0, $cell1->getStyle()->getAlignment()->getReadOrder());
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Style/ColorIndexTest.php | tests/PhpSpreadsheetTests/Style/ColorIndexTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Style;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx\Styles;
use PHPUnit\Framework\TestCase;
class ColorIndexTest extends TestCase
{
#[\PHPUnit\Framework\Attributes\DataProvider('providerColorIndexes')]
public function testColorIndex(string $expectedResult, string $xml, bool $background = false): void
{
$sxml = simplexml_load_string($xml);
if ($sxml === false) {
self::fail('Unable to parse xml');
} else {
$styles = new Styles();
$result = $styles->readColor($sxml, $background);
self::assertSame($expectedResult, $result);
}
}
public static function providerColorIndexes(): array
{
return [
'subtract 7 to return system color 4' => ['FF00FF00', '<fgColor indexed="11"/>'],
'default foreground color when out of range' => ['FF000000', '<color indexed="81"/>'],
'default background color when out of range' => ['FFFFFFFF', '<bgColor indexed="81"/>', true],
'rgb specified' => ['FF123456', '<bgColor rgb="FF123456"/>', true],
];
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Style/NumberFormatRoundTest.php | tests/PhpSpreadsheetTests/Style/NumberFormatRoundTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Style;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PHPUnit\Framework\TestCase;
class NumberFormatRoundTest extends TestCase
{
public static function testRound(): void
{
// Inconsistent rounding due to letting sprintf do it rather than round.
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->getStyle('A1:H2')->getNumberFormat()->setFormatCode('0');
$sheet->getStyle('A3:H3')->getNumberFormat()->setFormatCode('0.0');
$sheet->fromArray(
[
[-3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5],
[-3.1, -2.9, -1.4, -0.3, 0.7, 1.6, 2.4, 3.7],
[-3.15, -2.85, -1.43, -0.87, 0.72, 1.60, 2.45, 3.75],
]
);
$expected = [
[-4, -3, -2, -1, 1, 2, 3, 4],
[-3, -3, -1, 0, 1, 2, 2, 4],
[-3.2, -2.9, -1.4, -0.9, 0.7, 1.6, 2.5, 3.8],
];
self::assertEquals($expected, $sheet->toArray());
$spreadsheet->disconnectWorksheets();
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Style/NumberFormatTest.php | tests/PhpSpreadsheetTests/Style/NumberFormatTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Style;
use PhpOffice\PhpSpreadsheet\Calculation\Functions;
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat\NumberFormatter;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
class NumberFormatTest extends TestCase
{
private string $compatibilityMode;
protected function setUp(): void
{
StringHelper::setDecimalSeparator('.');
StringHelper::setThousandsSeparator(',');
$this->compatibilityMode = Functions::getCompatibilityMode();
}
protected function tearDown(): void
{
StringHelper::setCurrencyCode(null);
StringHelper::setDecimalSeparator(null);
StringHelper::setThousandsSeparator(null);
Functions::setCompatibilityMode($this->compatibilityMode);
}
/**
* @param null|bool|float|int|string $args string to be formatted
*/
#[DataProvider('providerNumberFormat')]
public function testFormatValueWithMask(mixed $expectedResult, mixed ...$args): void
{
$result = NumberFormat::toFormattedString(...$args);
self::assertSame($expectedResult, $result);
}
public static function providerNumberFormat(): array
{
return require 'tests/data/Style/NumberFormat.php';
}
/**
* @param null|bool|float|int|string $args string to be formatted
*/
#[DataProvider('providerNumberFormatFractions')]
public function testFormatValueWithMaskFraction(mixed $expectedResult, mixed ...$args): void
{
$result = NumberFormat::toFormattedString(...$args);
self::assertEquals($expectedResult, $result);
}
public static function providerNumberFormatFractions(): array
{
return require 'tests/data/Style/NumberFormatFractions.php';
}
/**
* @param null|bool|float|int|string $args string to be formatted
*/
#[DataProvider('providerNumberFormatDates')]
public function testFormatValueWithMaskDate(mixed $expectedResult, mixed ...$args): void
{
$result = NumberFormat::toFormattedString(...$args);
self::assertEquals($expectedResult, $result);
}
public static function providerNumberFormatDates(): array
{
return require 'tests/data/Style/NumberFormatDates.php';
}
public function testDatesOpenOfficeGnumericNonPositive(): void
{
Functions::setCompatibilityMode(
Functions::COMPATIBILITY_OPENOFFICE
);
$fmt1 = 'yyyy-mm-dd';
$rslt = NumberFormat::toFormattedString(0, $fmt1);
self::assertSame('1899-12-30', $rslt);
$rslt = NumberFormat::toFormattedString(-2, $fmt1);
self::assertSame('1899-12-28', $rslt);
$rslt = NumberFormat::toFormattedString(-2.4, $fmt1);
self::assertSame('1899-12-27', $rslt);
$fmt2 = 'yyyy-mm-dd hh:mm:ss AM/PM';
$rslt = NumberFormat::toFormattedString(-2.4, $fmt2);
self::assertSame('1899-12-27 02:24:00 PM', $rslt);
}
public function testCurrencyCode(): void
{
// "Currency symbol" replaces $ in some cases, not in others
$cur = StringHelper::getCurrencyCode();
StringHelper::setCurrencyCode('€');
$fmt1 = '#,##0.000\ [$]';
$rslt = NumberFormat::toFormattedString(12345.679, $fmt1);
self::assertEquals($rslt, '12,345.679 €');
$fmt2 = '$ #,##0.000';
$rslt = NumberFormat::toFormattedString(12345.679, $fmt2);
self::assertEquals($rslt, '$ 12,345.679');
StringHelper::setCurrencyCode($cur);
}
#[DataProvider('providerNoScientific')]
public function testNoScientific(string $expectedResult, string $numericString): void
{
$result = NumberFormatter::floatStringConvertScientific($numericString);
self::assertSame($expectedResult, $result);
}
public static function providerNoScientific(): array
{
return [
'large number' => ['92' . str_repeat('0', 16), '9.2E+17'],
'no decimal portion' => ['16', '1.6E1'],
'retain decimal 0 if supplied in string' => ['16.0', '1.60E1'],
'exponent 0' => ['2.3', '2.3E0'],
'whole and decimal' => ['16.5', '1.65E1'],
'plus signs' => ['165000', '+1.65E+5'],
'e2 one decimal' => ['489.7', '4.897E2'],
'e2 no decimal' => ['-489', '-4.89E2'],
'e2 fill units position' => ['480', '4.8E+2'],
'no scientific notation' => ['3.14159', '3.14159'],
'non-zero in first decimal' => ['0.165', '1.65E-1'],
'one leading zero in decimal' => ['0.0165', '1.65E-2'],
'four leading zeros in decimal' => ['-0.0000165', '-1.65E-5'],
'small number' => ['0.' . str_repeat('0', 16) . '1', '1E-17'],
'very small number' => ['0.' . str_repeat('0', 69) . '1', '1E-70'],
];
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Style/NumberFormatBuiltinTest.php | tests/PhpSpreadsheetTests/Style/NumberFormatBuiltinTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Style;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
use PHPUnit\Framework\TestCase;
class NumberFormatBuiltinTest extends TestCase
{
public function testBuiltinCodes(): void
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$cell1 = $sheet->getCell('A1');
$cell1->setValue(1);
$cell1->getStyle()->getNumberFormat()->setBuiltInFormatCode(2); // 0.00
self::assertEquals('1.00', $cell1->getFormattedValue());
$cell2 = $sheet->getCell('A2');
$cell2->setValue(1234);
$cell2->getStyle()->getNumberFormat()->setFormatCode('#,##0'); // builtin 3
self::assertEquals(3, $cell2->getStyle()->getNumberFormat()->getBuiltinFormatCode());
self::assertEquals('1,234', $cell2->getFormattedValue());
$cell3 = $sheet->getCell('A3');
$cell3->setValue(1234);
$cell3->getStyle()->getNumberFormat()->setFormatCode(''); // General
self::assertEquals(NumberFormat::FORMAT_GENERAL, $cell3->getStyle()->getNumberFormat()->getFormatCode());
self::assertEquals(0, $cell3->getStyle()->getNumberFormat()->getBuiltinFormatCode());
self::assertEquals('1234', $cell3->getFormattedValue());
// non-supervisor
$numberFormat = new NumberFormat();
$numberFormat->setBuiltInFormatCode(4);
self::assertEquals('#,##0.00', $numberFormat->getFormatCode());
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Style/NumberFormatSystemDateTimeTest.php | tests/PhpSpreadsheetTests/Style/NumberFormatSystemDateTimeTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Style;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
use PHPUnit\Framework\TestCase;
class NumberFormatSystemDateTimeTest extends TestCase
{
private string $shortDateFormat;
private string $longDateFormat;
private string $dateTimeFormat;
private string $timeFormat;
protected function setUp(): void
{
$this->shortDateFormat = NumberFormat::getShortDateFormat();
$this->longDateFormat = NumberFormat::getLongDateFormat();
$this->dateTimeFormat = NumberFormat::getDateTimeFormat();
$this->timeFormat = NumberFormat::getTimeFormat();
}
protected function tearDown(): void
{
NumberFormat::setShortDateFormat($this->shortDateFormat);
NumberFormat::setLongDateFormat($this->longDateFormat);
NumberFormat::setDateTimeFormat($this->dateTimeFormat);
NumberFormat::setTimeFormat($this->timeFormat);
}
public function testOverrides(): void
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$formula = '=DATEVALUE("2024-02-29")+TIMEVALUE("8:12:15 AM")';
$sheet->getCell('A1')->setValue($formula);
$sheet->getCell('A2')->setValue($formula);
$sheet->getStyle('A2')->getNumberFormat()
->setBuiltinFormatCode(14);
$sheet->getCell('A3')->setValue($formula);
$sheet->getStyle('A3')->getNumberFormat()
->setBuiltinFormatCode(15);
$sheet->getCell('A4')->setValue($formula);
$sheet->getStyle('A4')->getNumberFormat()
->setBuiltinFormatCode(22);
$sheet->getCell('A5')->setValue($formula);
$sheet->getStyle('A5')->getNumberFormat()
->setFormatCode('[$-F800]');
$sheet->getCell('A6')->setValue($formula);
$sheet->getStyle('A6')->getNumberFormat()
->setFormatCode('[$-F400]');
$sheet->getCell('A7')->setValue($formula);
$sheet->getStyle('A7')->getNumberFormat()
->setFormatCode('[$-x-sysdate]');
$sheet->getCell('A8')->setValue($formula);
$sheet->getStyle('A8')->getNumberFormat()
->setFormatCode('[$-x-systime]');
$sheet->getCell('A9')->setValue($formula);
$sheet->getStyle('A9')->getNumberFormat()
->setFormatCode('hello' . NumberFormat::FORMAT_SYSDATE_F800 . 'goodbye');
NumberFormat::setShortDateFormat('yyyy/mm/dd');
NumberFormat::setDateTimeFormat('yyyy/mm/dd hh:mm AM/PM');
NumberFormat::setLongDateFormat('dddd d mmm yyyy');
NumberFormat::setTimeFormat('h:mm');
self::assertSame('2024/02/29', $sheet->getCell('A2')->getformattedValue());
self::assertSame('2024/02/29 08:12 AM', $sheet->getCell('A4')->getformattedValue());
self::assertSame('Thursday 29 Feb 2024', $sheet->getCell('A5')->getformattedValue());
self::assertSame('8:12', $sheet->getCell('A6')->getformattedValue());
self::assertSame('Thursday 29 Feb 2024', $sheet->getCell('A7')->getformattedValue());
self::assertSame('8:12', $sheet->getCell('A8')->getformattedValue());
self::assertSame('Thursday 29 Feb 2024', $sheet->getCell('A9')->getformattedValue());
$spreadsheet->disconnectWorksheets();
}
public function testDefaults(): void
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$formula = '=DATEVALUE("2024-02-29")+TIMEVALUE("8:12:15 AM")';
$sheet->getCell('A1')->setValue($formula);
$sheet->getCell('A2')->setValue($formula);
$sheet->getStyle('A2')->getNumberFormat()
->setBuiltinFormatCode(14);
$sheet->getCell('A3')->setValue($formula);
$sheet->getStyle('A3')->getNumberFormat()
->setBuiltinFormatCode(15);
$sheet->getCell('A4')->setValue($formula);
$sheet->getStyle('A4')->getNumberFormat()
->setBuiltinFormatCode(22);
$sheet->getCell('A5')->setValue($formula);
$sheet->getStyle('A5')->getNumberFormat()
->setFormatCode('[$-F800]');
$sheet->getCell('A6')->setValue($formula);
$sheet->getStyle('A6')->getNumberFormat()
->setFormatCode('[$-F400]');
$sheet->getCell('A7')->setValue($formula);
$sheet->getStyle('A7')->getNumberFormat()
->setFormatCode('[$-x-sysdate]');
$sheet->getCell('A8')->setValue($formula);
$sheet->getStyle('A8')->getNumberFormat()
->setFormatCode('[$-x-systime]');
$sheet->getCell('A9')->setValue($formula);
$sheet->getStyle('A9')->getNumberFormat()
->setFormatCode('hello' . NumberFormat::FORMAT_SYSDATE_F800 . 'goodbye');
self::assertSame('2/29/2024', $sheet->getCell('A2')->getformattedValue());
self::assertSame('2/29/2024 8:12', $sheet->getCell('A4')->getformattedValue());
self::assertSame('Thursday, February 29, 2024', $sheet->getCell('A5')->getformattedValue());
self::assertSame('8:12:15 AM', $sheet->getCell('A6')->getformattedValue());
self::assertSame('Thursday, February 29, 2024', $sheet->getCell('A7')->getformattedValue());
self::assertSame('8:12:15 AM', $sheet->getCell('A8')->getformattedValue());
self::assertSame('Thursday, February 29, 2024', $sheet->getCell('A9')->getformattedValue());
$spreadsheet->disconnectWorksheets();
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Style/FillTest.php | tests/PhpSpreadsheetTests/Style/FillTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Style;
use PhpOffice\PhpSpreadsheet\Style\Color;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PHPUnit\Framework\TestCase;
class FillTest extends TestCase
{
public function testNonSupervisorColor(): void
{
$fill = new Fill();
$startColor = new Color('FFFF0000');
$endColor = new Color('FF00FFFF');
$fill->setFillType(Fill::FILL_PATTERN_GRAY125);
$fill->setStartColor($startColor);
$fill->setEndColor($endColor);
self::assertEquals('FF0000', $fill->getStartColor()->getRGB());
self::assertEquals('00FFFF', $fill->getEndColor()->getRGB());
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Style/ConditionalTest.php | tests/PhpSpreadsheetTests/Style/ConditionalTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Style;
use PhpOffice\PhpSpreadsheet\Style\Conditional;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PHPUnit\Framework\TestCase;
class ConditionalTest extends TestCase
{
public function testClone(): void
{
$condition1 = new Conditional();
$condition1->setConditionType(Conditional::CONDITION_CELLIS);
$condition1->setOperatorType(Conditional::OPERATOR_LESSTHAN);
$condition1->addCondition(0.6);
$condition1->getStyle()->getFill()
->setFillType(Fill::FILL_SOLID)
->getStartColor()->setARGB('FFFF0000');
$conditionclone = clone $condition1;
self::AssertEquals($condition1, $conditionclone);
self::AssertEquals($condition1->getStyle(), $conditionclone->getStyle());
self::AssertNotSame($condition1->getStyle(), $conditionclone->getStyle());
}
public function testVariousAdds(): void
{
$condition1 = new Conditional();
$condition1->setConditionType(Conditional::CONDITION_CELLIS);
$condition1->setOperatorType(Conditional::OPERATOR_LESSTHAN);
$condition1->addCondition(0.6);
$condition1->getStyle()->getFill()
->setFillType(Fill::FILL_SOLID)
->getStartColor()->setARGB('FFFF0000');
$condition2 = new Conditional();
$condition2->setConditionType(Conditional::CONDITION_CELLIS);
$condition2->setOperatorType(Conditional::OPERATOR_LESSTHAN);
$condition2->setConditions(0.6);
$condition2->getStyle()->getFill()
->setFillType(Fill::FILL_SOLID)
->getStartColor()->setARGB('FFFF0000');
$condition3 = new Conditional();
$condition3->setConditionType(Conditional::CONDITION_CELLIS);
$condition3->setOperatorType(Conditional::OPERATOR_LESSTHAN);
$condition3->setConditions([0.6]);
$condition3->getStyle()->getFill()
->setFillType(Fill::FILL_SOLID)
->getStartColor()->setARGB('FFFF0000');
self::AssertEquals($condition1, $condition2);
self::AssertEquals($condition1, $condition3);
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Style/AlignmentMiddleTest.php | tests/PhpSpreadsheetTests/Style/AlignmentMiddleTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Style;
use PhpOffice\PhpSpreadsheet\Shared\File;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Writer\Html;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PHPUnit\Framework\TestCase;
use ZipArchive;
class AlignmentMiddleTest extends TestCase
{
private ?Spreadsheet $spreadsheet = null;
private string $outputFileName = '';
protected function tearDown(): void
{
if ($this->spreadsheet !== null) {
$this->spreadsheet->disconnectWorksheets();
$this->spreadsheet = null;
}
if ($this->outputFileName !== '') {
unlink($this->outputFileName);
$this->outputFileName = '';
}
}
public function testCenterWriteHtml(): void
{
// Html Writer changes vertical align center to middle
$this->spreadsheet = new Spreadsheet();
$sheet = $this->spreadsheet->getActiveSheet();
$sheet->getCell('A1')->setValue('Cell1');
$sheet->getStyle('A1')
->getAlignment()
->setVertical(Alignment::VERTICAL_CENTER);
$writer = new Html($this->spreadsheet);
$html = $writer->generateHtmlAll();
self::assertStringContainsString('vertical-align:middle', $html);
self::assertStringNotContainsString('vertical-align:center', $html);
}
public function testCenterWriteXlsx(): void
{
// Xlsx Writer uses vertical align center unchanged
$this->spreadsheet = new Spreadsheet();
$sheet = $this->spreadsheet->getActiveSheet();
$sheet->getCell('A1')->setValue('Cell1');
$sheet->getStyle('A1')
->getAlignment()
->setVertical(Alignment::VERTICAL_CENTER);
$this->outputFileName = File::temporaryFilename();
$writer = new Xlsx($this->spreadsheet);
$writer->save($this->outputFileName);
$zip = new ZipArchive();
$zip->open($this->outputFileName);
$html = $zip->getFromName('xl/styles.xml');
$zip->close();
self::assertStringContainsString('vertical="center"', $html);
self::assertStringNotContainsString('vertical="middle"', $html);
}
public function testCenterWriteXlsx2(): void
{
// Xlsx Writer changes vertical align middle to center
$this->spreadsheet = new Spreadsheet();
$sheet = $this->spreadsheet->getActiveSheet();
$sheet->getCell('A1')->setValue('Cell1');
$sheet->getStyle('A1')
->getAlignment()
->setVertical('middle');
$this->outputFileName = File::temporaryFilename();
$writer = new Xlsx($this->spreadsheet);
$writer->save($this->outputFileName);
$zip = new ZipArchive();
$zip->open($this->outputFileName);
$html = $zip->getFromName('xl/styles.xml');
$zip->close();
self::assertStringContainsString('vertical="center"', $html);
self::assertStringNotContainsString('vertical="middle"', $html);
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Style/BorderTest.php | tests/PhpSpreadsheetTests/Style/BorderTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Style;
use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Style\Borders;
use PhpOffice\PhpSpreadsheet\Style\Color;
use PHPUnit\Framework\TestCase;
class BorderTest extends TestCase
{
public function testAllBorders(): void
{
$spreadsheet = new Spreadsheet();
$borders = $spreadsheet->getActiveSheet()->getStyle('A1')->getBorders();
$allBorders = $borders->getAllBorders();
$bottom = $borders->getBottom();
$actual = $bottom->getBorderStyle();
self::assertSame(Border::BORDER_NONE, $actual, 'should default to none');
$allBorders->setBorderStyle(Border::BORDER_THIN);
$actual = $bottom->getBorderStyle();
self::assertSame(Border::BORDER_THIN, $actual, 'should have been set via allBorders');
self::assertSame(Border::BORDER_THIN, $borders->getTop()->getBorderStyle());
self::assertSame(Border::BORDER_THIN, $borders->getRight()->getBorderStyle());
self::assertSame(Border::BORDER_THIN, $borders->getLeft()->getBorderStyle());
self::assertSame(Border::BORDER_NONE, $borders->getDiagonal()->getBorderStyle());
$spreadsheet->disconnectWorksheets();
}
public function testAllBordersArray(): void
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->getStyle('A1')->getBorders()->applyFromArray(['allBorders' => ['borderStyle' => Border::BORDER_THIN]]);
$borders = $sheet->getCell('A1')->getStyle()->getBorders();
self::assertSame(Border::BORDER_THIN, $borders->getBottom()->getBorderStyle());
self::assertSame(Border::BORDER_THIN, $borders->getTop()->getBorderStyle());
self::assertSame(Border::BORDER_THIN, $borders->getRight()->getBorderStyle());
self::assertSame(Border::BORDER_THIN, $borders->getLeft()->getBorderStyle());
self::assertSame(Border::BORDER_NONE, $borders->getDiagonal()->getBorderStyle());
$spreadsheet->disconnectWorksheets();
}
public function testAllBordersArrayNotSupervisor(): void
{
$borders = new Borders();
$borders->applyFromArray(['allBorders' => ['borderStyle' => Border::BORDER_THIN]]);
self::assertSame(Border::BORDER_THIN, $borders->getBottom()->getBorderStyle());
self::assertSame(Border::BORDER_THIN, $borders->getTop()->getBorderStyle());
self::assertSame(Border::BORDER_THIN, $borders->getRight()->getBorderStyle());
self::assertSame(Border::BORDER_THIN, $borders->getLeft()->getBorderStyle());
self::assertSame(Border::BORDER_NONE, $borders->getDiagonal()->getBorderStyle());
}
public function testOutline(): void
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$borders = $sheet->getStyle('A1:B2')->getBorders();
$outline = $borders->getOutline();
$outline->setBorderStyle(Border::BORDER_THIN);
self::assertSame(Border::BORDER_THIN, $sheet->getCell('A1')->getStyle()->getBorders()->getLeft()->getBorderStyle());
self::assertSame(Border::BORDER_THIN, $sheet->getCell('A1')->getStyle()->getBorders()->getTop()->getBorderStyle());
self::assertSame(Border::BORDER_NONE, $sheet->getCell('A1')->getStyle()->getBorders()->getRight()->getBorderStyle());
self::assertSame(Border::BORDER_NONE, $sheet->getCell('A1')->getStyle()->getBorders()->getBottom()->getBorderStyle());
self::assertSame(Border::BORDER_THIN, $sheet->getCell('A2')->getStyle()->getBorders()->getLeft()->getBorderStyle());
self::assertSame(Border::BORDER_THIN, $sheet->getCell('A2')->getStyle()->getBorders()->getBottom()->getBorderStyle());
self::assertSame(Border::BORDER_NONE, $sheet->getCell('A2')->getStyle()->getBorders()->getRight()->getBorderStyle());
self::assertSame(Border::BORDER_NONE, $sheet->getCell('A2')->getStyle()->getBorders()->getTop()->getBorderStyle());
self::assertSame(Border::BORDER_THIN, $sheet->getCell('B1')->getStyle()->getBorders()->getRight()->getBorderStyle());
self::assertSame(Border::BORDER_THIN, $sheet->getCell('B1')->getStyle()->getBorders()->getTop()->getBorderStyle());
self::assertSame(Border::BORDER_NONE, $sheet->getCell('B1')->getStyle()->getBorders()->getLeft()->getBorderStyle());
self::assertSame(Border::BORDER_NONE, $sheet->getCell('B1')->getStyle()->getBorders()->getBottom()->getBorderStyle());
self::assertSame(Border::BORDER_THIN, $sheet->getCell('B2')->getStyle()->getBorders()->getRight()->getBorderStyle());
self::assertSame(Border::BORDER_THIN, $sheet->getCell('B2')->getStyle()->getBorders()->getBottom()->getBorderStyle());
self::assertSame(Border::BORDER_NONE, $sheet->getCell('B2')->getStyle()->getBorders()->getLeft()->getBorderStyle());
self::assertSame(Border::BORDER_NONE, $sheet->getCell('B2')->getStyle()->getBorders()->getTop()->getBorderStyle());
$spreadsheet->disconnectWorksheets();
}
public function testInside(): void
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$borders = $sheet->getStyle('A1:B2')->getBorders();
$inside = $borders->getInside();
$inside->setBorderStyle(Border::BORDER_THIN);
self::assertSame(Border::BORDER_NONE, $sheet->getCell('A1')->getStyle()->getBorders()->getLeft()->getBorderStyle());
self::assertSame(Border::BORDER_NONE, $sheet->getCell('A1')->getStyle()->getBorders()->getTop()->getBorderStyle());
self::assertSame(Border::BORDER_THIN, $sheet->getCell('A1')->getStyle()->getBorders()->getRight()->getBorderStyle());
self::assertSame(Border::BORDER_THIN, $sheet->getCell('A1')->getStyle()->getBorders()->getBottom()->getBorderStyle());
self::assertSame(Border::BORDER_NONE, $sheet->getCell('A2')->getStyle()->getBorders()->getLeft()->getBorderStyle());
self::assertSame(Border::BORDER_NONE, $sheet->getCell('A2')->getStyle()->getBorders()->getBottom()->getBorderStyle());
self::assertSame(Border::BORDER_THIN, $sheet->getCell('A2')->getStyle()->getBorders()->getRight()->getBorderStyle());
self::assertSame(Border::BORDER_THIN, $sheet->getCell('A2')->getStyle()->getBorders()->getTop()->getBorderStyle());
self::assertSame(Border::BORDER_NONE, $sheet->getCell('B1')->getStyle()->getBorders()->getRight()->getBorderStyle());
self::assertSame(Border::BORDER_NONE, $sheet->getCell('B1')->getStyle()->getBorders()->getTop()->getBorderStyle());
self::assertSame(Border::BORDER_THIN, $sheet->getCell('B1')->getStyle()->getBorders()->getLeft()->getBorderStyle());
self::assertSame(Border::BORDER_THIN, $sheet->getCell('B1')->getStyle()->getBorders()->getBottom()->getBorderStyle());
self::assertSame(Border::BORDER_NONE, $sheet->getCell('B2')->getStyle()->getBorders()->getRight()->getBorderStyle());
self::assertSame(Border::BORDER_NONE, $sheet->getCell('B2')->getStyle()->getBorders()->getBottom()->getBorderStyle());
self::assertSame(Border::BORDER_THIN, $sheet->getCell('B2')->getStyle()->getBorders()->getLeft()->getBorderStyle());
self::assertSame(Border::BORDER_THIN, $sheet->getCell('B2')->getStyle()->getBorders()->getTop()->getBorderStyle());
$spreadsheet->disconnectWorksheets();
}
public function testHorizontal(): void
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$borders = $sheet->getStyle('A1:B2')->getBorders();
$horizontal = $borders->getHorizontal();
$horizontal->setBorderStyle(Border::BORDER_THIN);
self::assertSame(Border::BORDER_NONE, $sheet->getCell('A1')->getStyle()->getBorders()->getLeft()->getBorderStyle());
self::assertSame(Border::BORDER_NONE, $sheet->getCell('A1')->getStyle()->getBorders()->getTop()->getBorderStyle());
self::assertSame(Border::BORDER_NONE, $sheet->getCell('A1')->getStyle()->getBorders()->getRight()->getBorderStyle());
self::assertSame(Border::BORDER_THIN, $sheet->getCell('A1')->getStyle()->getBorders()->getBottom()->getBorderStyle());
self::assertSame(Border::BORDER_NONE, $sheet->getCell('A2')->getStyle()->getBorders()->getLeft()->getBorderStyle());
self::assertSame(Border::BORDER_NONE, $sheet->getCell('A2')->getStyle()->getBorders()->getBottom()->getBorderStyle());
self::assertSame(Border::BORDER_NONE, $sheet->getCell('A2')->getStyle()->getBorders()->getRight()->getBorderStyle());
self::assertSame(Border::BORDER_THIN, $sheet->getCell('A2')->getStyle()->getBorders()->getTop()->getBorderStyle());
self::assertSame(Border::BORDER_NONE, $sheet->getCell('B1')->getStyle()->getBorders()->getRight()->getBorderStyle());
self::assertSame(Border::BORDER_NONE, $sheet->getCell('B1')->getStyle()->getBorders()->getTop()->getBorderStyle());
self::assertSame(Border::BORDER_NONE, $sheet->getCell('B1')->getStyle()->getBorders()->getLeft()->getBorderStyle());
self::assertSame(Border::BORDER_THIN, $sheet->getCell('B1')->getStyle()->getBorders()->getBottom()->getBorderStyle());
self::assertSame(Border::BORDER_NONE, $sheet->getCell('B2')->getStyle()->getBorders()->getRight()->getBorderStyle());
self::assertSame(Border::BORDER_NONE, $sheet->getCell('B2')->getStyle()->getBorders()->getBottom()->getBorderStyle());
self::assertSame(Border::BORDER_NONE, $sheet->getCell('B2')->getStyle()->getBorders()->getLeft()->getBorderStyle());
self::assertSame(Border::BORDER_THIN, $sheet->getCell('B2')->getStyle()->getBorders()->getTop()->getBorderStyle());
$spreadsheet->disconnectWorksheets();
}
public function testVertical(): void
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$borders = $sheet->getStyle('A1:B2')->getBorders();
$vertical = $borders->getVertical();
$vertical->setBorderStyle(Border::BORDER_THIN);
self::assertSame(Border::BORDER_NONE, $sheet->getCell('A1')->getStyle()->getBorders()->getLeft()->getBorderStyle());
self::assertSame(Border::BORDER_NONE, $sheet->getCell('A1')->getStyle()->getBorders()->getTop()->getBorderStyle());
self::assertSame(Border::BORDER_THIN, $sheet->getCell('A1')->getStyle()->getBorders()->getRight()->getBorderStyle());
self::assertSame(Border::BORDER_NONE, $sheet->getCell('A1')->getStyle()->getBorders()->getBottom()->getBorderStyle());
self::assertSame(Border::BORDER_NONE, $sheet->getCell('A2')->getStyle()->getBorders()->getLeft()->getBorderStyle());
self::assertSame(Border::BORDER_NONE, $sheet->getCell('A2')->getStyle()->getBorders()->getBottom()->getBorderStyle());
self::assertSame(Border::BORDER_THIN, $sheet->getCell('A2')->getStyle()->getBorders()->getRight()->getBorderStyle());
self::assertSame(Border::BORDER_NONE, $sheet->getCell('A2')->getStyle()->getBorders()->getTop()->getBorderStyle());
self::assertSame(Border::BORDER_NONE, $sheet->getCell('B1')->getStyle()->getBorders()->getRight()->getBorderStyle());
self::assertSame(Border::BORDER_NONE, $sheet->getCell('B1')->getStyle()->getBorders()->getTop()->getBorderStyle());
self::assertSame(Border::BORDER_THIN, $sheet->getCell('B1')->getStyle()->getBorders()->getLeft()->getBorderStyle());
self::assertSame(Border::BORDER_NONE, $sheet->getCell('B1')->getStyle()->getBorders()->getBottom()->getBorderStyle());
self::assertSame(Border::BORDER_NONE, $sheet->getCell('B2')->getStyle()->getBorders()->getRight()->getBorderStyle());
self::assertSame(Border::BORDER_NONE, $sheet->getCell('B2')->getStyle()->getBorders()->getBottom()->getBorderStyle());
self::assertSame(Border::BORDER_THIN, $sheet->getCell('B2')->getStyle()->getBorders()->getLeft()->getBorderStyle());
self::assertSame(Border::BORDER_NONE, $sheet->getCell('B2')->getStyle()->getBorders()->getTop()->getBorderStyle());
$spreadsheet->disconnectWorksheets();
}
public function testNoSupervisorAllBorders(): void
{
$this->expectException(PhpSpreadsheetException::class);
$borders = new Borders();
$borders->getAllBorders();
}
public function testNoSupervisorOutline(): void
{
$this->expectException(PhpSpreadsheetException::class);
$borders = new Borders();
$borders->getOutline();
}
public function testNoSupervisorInside(): void
{
$this->expectException(PhpSpreadsheetException::class);
$borders = new Borders();
$borders->getInside();
}
public function testNoSupervisorVertical(): void
{
$this->expectException(PhpSpreadsheetException::class);
$borders = new Borders();
$borders->getVertical();
}
public function testNoSupervisorHorizontal(): void
{
$this->expectException(PhpSpreadsheetException::class);
$borders = new Borders();
$borders->getHorizontal();
}
public function testGetSharedComponentPseudo(): void
{
$this->expectException(PhpSpreadsheetException::class);
$this->expectExceptionMessage('pseudo-border');
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->getStyle('A1')->getBorders()->getHorizontal()->setBorderStyle(Border::BORDER_MEDIUM);
$sheet->getStyle('A1')->getBorders()->getHorizontal()->getSharedComponent();
}
public function testBorderStyle(): void
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->getStyle('A1')->getBorders()->getTop()->setBorderStyle(false);
$sheet->getStyle('A2')->getBorders()->getTop()->setBorderStyle(true);
self::assertEquals(Border::BORDER_NONE, $sheet->getStyle('A1')->getBorders()->getTop()->getBorderStyle());
self::assertEquals(Border::BORDER_MEDIUM, $sheet->getStyle('A2')->getBorders()->getTop()->getBorderStyle());
$sheet->getStyle('A3')->getBorders()->getTop()->applyFromArray(['borderStyle' => Border::BORDER_MEDIUM]);
self::assertEquals(Border::BORDER_MEDIUM, $sheet->getStyle('A3')->getBorders()->getTop()->getBorderStyle());
$border = new Border();
$border->setBorderStyle(Border::BORDER_THIN)->setColor(new Color('FFFF0000'));
self::assertEquals('FFFF0000', $border->getColor()->getARGB());
self::assertEquals(Border::BORDER_THIN, $border->getBorderStyle());
$spreadsheet->disconnectWorksheets();
}
public function testDiagonalDirection(): void
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->getStyle('A1')->getBorders()->getDiagonal()->setBorderStyle(Border::BORDER_MEDIUM);
$sheet->getStyle('A1')->getBorders()->setDiagonalDirection(Borders::DIAGONAL_BOTH);
$borders = $sheet->getStyle('A1')->getBorders();
self::assertSame(Border::BORDER_MEDIUM, $borders->getDiagonal()->getBorderStyle());
self::assertSame(Borders::DIAGONAL_BOTH, $borders->getDiagonalDirection());
$spreadsheet->disconnectWorksheets();
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Style/StyleTest.php | tests/PhpSpreadsheetTests/Style/StyleTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Style;
use PhpOffice\PhpSpreadsheet\Cell\CellAddress;
use PhpOffice\PhpSpreadsheet\Cell\CellRange;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
use PHPUnit\Framework\TestCase;
class StyleTest extends TestCase
{
public function testStyleOddMethods(): void
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$cellCoordinate = 'A1';
$cell1 = $sheet->getCell($cellCoordinate);
$cell1style = $cell1->getStyle();
self::assertSame($spreadsheet, $cell1style->getParent());
$styleArray = ['alignment' => ['textRotation' => 45]];
$outArray = $cell1style->getStyleArray($styleArray);
self::assertEquals($styleArray, $outArray['quotePrefix']);
$spreadsheet->disconnectWorksheets();
}
public function testStyleColumn(): void
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$cellCoordinates = 'A:B';
$styleArray = [
'font' => [
'bold' => true,
],
];
$sheet->getStyle($cellCoordinates)->applyFromArray($styleArray);
$sheet->setCellValue('A1', 'xxxa1');
$sheet->setCellValue('A2', 'xxxa2');
$sheet->setCellValue('A3', 'xxxa3');
$sheet->setCellValue('B1', 'xxxa1');
$sheet->setCellValue('B2', 'xxxa2');
$sheet->setCellValue('B3', 'xxxa3');
$sheet->setCellValue('C1', 'xxxc1');
$sheet->setCellValue('C2', 'xxxc2');
$sheet->setCellValue('C3', 'xxxc3');
$styleArray = [
'font' => [
'italic' => true,
],
];
$sheet->getStyle($cellCoordinates)->applyFromArray($styleArray);
self::assertTrue($sheet->getStyle('A1')->getFont()->getBold());
self::assertTrue($sheet->getStyle('B2')->getFont()->getBold());
self::assertFalse($sheet->getStyle('C3')->getFont()->getBold());
self::assertTrue($sheet->getStyle('A1')->getFont()->getItalic());
self::assertTrue($sheet->getStyle('B2')->getFont()->getItalic());
self::assertFalse($sheet->getStyle('C3')->getFont()->getItalic());
$spreadsheet->disconnectWorksheets();
}
public function testStyleIsReused(): void
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$styleArray = [
'font' => [
'italic' => true,
],
];
$sheet->getStyle('A1')->getFont()->setBold(true);
$sheet->getStyle('A2')->getFont()->setBold(true);
$sheet->getStyle('A3')->getFont()->setBold(true);
$sheet->getStyle('A3')->getFont()->setItalic(true);
$sheet->getStyle('A')->applyFromArray($styleArray);
self::assertCount(4, $spreadsheet->getCellXfCollection());
$spreadsheet->garbageCollect();
self::assertCount(3, $spreadsheet->getCellXfCollection());
$spreadsheet->disconnectWorksheets();
}
public function testStyleRow(): void
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$cellCoordinates = '2:3';
$styleArray = [
'font' => [
'bold' => true,
],
];
$sheet->getStyle($cellCoordinates)->applyFromArray($styleArray);
$sheet->setCellValue('A1', 'xxxa1');
$sheet->setCellValue('A2', 'xxxa2');
$sheet->setCellValue('A3', 'xxxa3');
$sheet->setCellValue('B1', 'xxxa1');
$sheet->setCellValue('B2', 'xxxa2');
$sheet->setCellValue('B3', 'xxxa3');
$sheet->setCellValue('C1', 'xxxc1');
$sheet->setCellValue('C2', 'xxxc2');
$sheet->setCellValue('C3', 'xxxc3');
$styleArray = [
'font' => [
'italic' => true,
],
];
$sheet->getStyle($cellCoordinates)->applyFromArray($styleArray);
self::assertFalse($sheet->getStyle('A1')->getFont()->getBold());
self::assertTrue($sheet->getStyle('B2')->getFont()->getBold());
self::assertTrue($sheet->getStyle('C3')->getFont()->getBold());
self::assertFalse($sheet->getStyle('A1')->getFont()->getItalic());
self::assertTrue($sheet->getStyle('B2')->getFont()->getItalic());
self::assertTrue($sheet->getStyle('C3')->getFont()->getItalic());
$spreadsheet->disconnectWorksheets();
}
public function testIssue1712A(): void
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$rgb = '4467b8';
$sheet->fromArray(['OK', 'KO']);
$spreadsheet->getActiveSheet()
->getStyle('A1')
->getFill()
->setFillType(Fill::FILL_SOLID)
->getStartColor()
->setRGB($rgb);
$spreadsheet->getActiveSheet()
->getStyle('B')
->getFill()
->setFillType(Fill::FILL_SOLID)
->getStartColor()
->setRGB($rgb);
self::assertEquals($rgb, $sheet->getCell('A1')->getStyle()->getFill()->getStartColor()->getRGB());
self::assertEquals($rgb, $sheet->getCell('B1')->getStyle()->getFill()->getStartColor()->getRGB());
$spreadsheet->disconnectWorksheets();
}
public function testIssue1712B(): void
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$rgb = '4467b8';
$spreadsheet->getActiveSheet()
->getStyle('A1')
->getFill()
->setFillType(Fill::FILL_SOLID)
->getStartColor()
->setRGB($rgb);
$spreadsheet->getActiveSheet()
->getStyle('B')
->getFill()
->setFillType(Fill::FILL_SOLID)
->getStartColor()
->setRGB($rgb);
$sheet->fromArray(['OK', 'KO']);
self::assertEquals($rgb, $sheet->getCell('A1')->getStyle()->getFill()->getStartColor()->getRGB());
self::assertEquals($rgb, $sheet->getCell('B1')->getStyle()->getFill()->getStartColor()->getRGB());
$spreadsheet->disconnectWorksheets();
}
public function testStyleLoopUpwards(): void
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$cellCoordinates = 'C5:A3';
$styleArray = [
'font' => [
'bold' => true,
],
];
$sheet->getStyle($cellCoordinates)->applyFromArray($styleArray);
$sheet->setCellValue('A1', 'xxxa1');
$sheet->setCellValue('A2', 'xxxa2');
$sheet->setCellValue('A3', 'xxxa3');
$sheet->setCellValue('B1', 'xxxa1');
$sheet->setCellValue('B2', 'xxxa2');
$sheet->setCellValue('B3', 'xxxa3');
$sheet->setCellValue('C1', 'xxxc1');
$sheet->setCellValue('C2', 'xxxc2');
$sheet->setCellValue('C3', 'xxxc3');
self::assertFalse($sheet->getStyle('A1')->getFont()->getBold());
self::assertFalse($sheet->getStyle('B2')->getFont()->getBold());
self::assertTrue($sheet->getStyle('C3')->getFont()->getBold());
$spreadsheet->disconnectWorksheets();
}
public function testStyleCellAddressObject(): void
{
$spreadsheet = new Spreadsheet();
$worksheet = $spreadsheet->getActiveSheet();
$cellAddress = new CellAddress('A1', $worksheet);
$style = $worksheet->getStyle($cellAddress);
$style->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_DATE_YYYYMMDDSLASH);
self::assertSame(NumberFormat::FORMAT_DATE_YYYYMMDDSLASH, $style->getNumberFormat()->getFormatCode());
$spreadsheet->disconnectWorksheets();
}
public function testStyleCellRangeObject(): void
{
$spreadsheet = new Spreadsheet();
$worksheet = $spreadsheet->getActiveSheet();
$cellAddress1 = new CellAddress('A1', $worksheet);
$cellAddress2 = new CellAddress('B2', $worksheet);
$cellRange = new CellRange($cellAddress1, $cellAddress2);
$style = $worksheet->getStyle($cellRange);
$style->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_DATE_YYYYMMDDSLASH);
self::assertSame(NumberFormat::FORMAT_DATE_YYYYMMDDSLASH, $style->getNumberFormat()->getFormatCode());
$spreadsheet->disconnectWorksheets();
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Style/ConditionalFormatting/CellMatcherTest.php | tests/PhpSpreadsheetTests/Style/ConditionalFormatting/CellMatcherTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Style\ConditionalFormatting;
use PhpOffice\PhpSpreadsheet\Cell\Cell;
use PhpOffice\PhpSpreadsheet\Exception as ssException;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\CellMatcher;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
class CellMatcherTest extends TestCase
{
protected ?Spreadsheet $spreadsheet = null;
protected function loadSpreadsheet(): Spreadsheet
{
$filename = 'tests/data/Style/ConditionalFormatting/CellMatcher.xlsx';
$reader = IOFactory::createReader('Xlsx');
return $reader->load($filename);
}
protected function tearDown(): void
{
if ($this->spreadsheet !== null) {
$this->spreadsheet->disconnectWorksheets();
$this->spreadsheet = null;
}
}
private function confirmString(Worksheet $worksheet, Cell $cell, string $cellAddress): string
{
$cfRange = $worksheet->getConditionalRange($cell->getCoordinate()) ?? '';
if ($cfRange === '') {
self::fail("{$cellAddress} is not in a Conditional Format range");
}
return $cfRange;
}
/** @param mixed[] $expectedMatches */
#[DataProvider('basicCellIsComparisonDataProvider')]
public function testBasicCellIsComparison(string $sheetname, string $cellAddress, array $expectedMatches): void
{
$this->spreadsheet = $this->loadSpreadsheet();
$worksheet = $this->spreadsheet->getSheetByNameOrThrow($sheetname);
$cell = $worksheet->getCell($cellAddress);
$cfRange = $this->confirmString($worksheet, $cell, $cellAddress);
$cfStyles = $worksheet->getConditionalStyles($cell->getCoordinate());
$matcher = new CellMatcher($cell, $cfRange);
foreach ($cfStyles as $cfIndex => $cfStyle) {
$match = $matcher->evaluateConditional($cfStyle);
self::assertSame($expectedMatches[$cfIndex], $match);
}
}
public static function basicCellIsComparisonDataProvider(): array
{
return [
// Less than/Equal/Greater than with Literal
'A2' => ['cellIs Comparison', 'A2', [false, false, true]],
'C3' => ['cellIs Comparison', 'C3', [false, true, false]],
'E6' => ['cellIs Comparison', 'E6', [true, false, false]],
// Less than/Equal/Greater than with Cell Reference
'A12' => ['cellIs Comparison', 'A12', [false, false, true]],
'C12' => ['cellIs Comparison', 'C12', [false, true, false]],
'E12' => ['cellIs Comparison', 'E12', [true, false, false]],
// Compare Text with Cell containing Formula
'A20' => ['cellIs Comparison', 'A20', [true]],
'B20' => ['cellIs Comparison', 'B20', [false]],
// Compare Text with Formula referencing relative cells
'A24' => ['cellIs Comparison', 'A24', [true]],
'B24' => ['cellIs Comparison', 'B24', [false]],
'A25' => ['cellIs Comparison', 'A25', [false]],
'B25' => ['cellIs Comparison', 'B25', [true]],
// Compare Cell Greater/Less with Vertical Cell Reference
'A30' => ['cellIs Comparison', 'A30', [false, true]],
'A31' => ['cellIs Comparison', 'A31', [true, false]],
'A32' => ['cellIs Comparison', 'A32', [false, true]],
'A33' => ['cellIs Comparison', 'A33', [true, false]],
'A34' => ['cellIs Comparison', 'A34', [false, false]],
'A35' => ['cellIs Comparison', 'A35', [false, true]],
'A36' => ['cellIs Comparison', 'A36', [true, false]],
'A37' => ['cellIs Comparison', 'A37', [true, false]],
];
}
public function testNotInRange(): void
{
$this->spreadsheet = $this->loadSpreadsheet();
$sheetname = 'cellIs Comparison';
$worksheet = $this->spreadsheet->getSheetByNameOrThrow($sheetname);
$cell = $worksheet->getCell('J20');
$cfRange = $worksheet->getConditionalRange($cell->getCoordinate());
self::assertNull($cfRange);
}
public function testUnknownSheet(): void
{
$this->expectException(ssException::class);
$this->spreadsheet = $this->loadSpreadsheet();
$sheetname = 'cellIs Comparisonxxx';
$this->spreadsheet->getSheetByNameOrThrow($sheetname);
}
#[DataProvider('rangeCellIsComparisonDataProvider')]
public function testRangeCellIsComparison(string $sheetname, string $cellAddress, bool $expectedMatch): void
{
$this->spreadsheet = $this->loadSpreadsheet();
$worksheet = $this->spreadsheet->getSheetByNameOrThrow($sheetname);
$cell = $worksheet->getCell($cellAddress);
$cfRange = $this->confirmString($worksheet, $cell, $cellAddress);
$cfStyle = $worksheet->getConditionalStyles($cell->getCoordinate());
$matcher = new CellMatcher($cell, $cfRange);
$match = $matcher->evaluateConditional($cfStyle[0]);
self::assertSame($expectedMatch, $match);
}
public static function rangeCellIsComparisonDataProvider(): array
{
return [
// Range between Literals
'A2' => ['cellIs Range Comparison', 'A2', false],
'A3' => ['cellIs Range Comparison', 'A3', true],
'A4' => ['cellIs Range Comparison', 'A4', true],
'A5' => ['cellIs Range Comparison', 'A5', true],
'A6' => ['cellIs Range Comparison', 'A6', false],
// Range between Cell References
'A11' => ['cellIs Range Comparison', 'A11', false],
'A12' => ['cellIs Range Comparison', 'A12', false],
'A13' => ['cellIs Range Comparison', 'A13', true],
// Range between unordered Cell References
'A17' => ['cellIs Range Comparison', 'A17', true],
'A18' => ['cellIs Range Comparison', 'A18', true],
// Range between with Formula
'A22' => ['cellIs Range Comparison', 'A22', false],
'A23' => ['cellIs Range Comparison', 'A23', true],
'A24' => ['cellIs Range Comparison', 'A24', false],
];
}
/** @param mixed[] $expectedMatches */
#[DataProvider('cellIsExpressionMultipleDataProvider')]
public function testCellIsMultipleExpression(string $sheetname, string $cellAddress, array $expectedMatches): void
{
$this->spreadsheet = $this->loadSpreadsheet();
$worksheet = $this->spreadsheet->getSheetByNameOrThrow($sheetname);
$cell = $worksheet->getCell($cellAddress);
$cfRange = $this->confirmString($worksheet, $cell, $cellAddress);
$cfStyles = $worksheet->getConditionalStyles($cell->getCoordinate());
$matcher = new CellMatcher($cell, $cfRange);
foreach ($cfStyles as $cfIndex => $cfStyle) {
$match = $matcher->evaluateConditional($cfStyle);
self::assertSame($expectedMatches[$cfIndex], $match);
}
}
public static function cellIsExpressionMultipleDataProvider(): array
{
return [
// Odd/Even
'A2' => ['cellIs Expression', 'A2', [false, true]],
'A3' => ['cellIs Expression', 'A3', [true, false]],
'B3' => ['cellIs Expression', 'B3', [false, true]],
'C3' => ['cellIs Expression', 'C3', [true, false]],
'E4' => ['cellIs Expression', 'E4', [false, true]],
'E5' => ['cellIs Expression', 'E5', [true, false]],
'E6' => ['cellIs Expression', 'E6', [false, true]],
];
}
#[DataProvider('cellIsExpressionDataProvider')]
public function testCellIsExpression(string $sheetname, string $cellAddress, bool $expectedMatch): void
{
$this->spreadsheet = $this->loadSpreadsheet();
$worksheet = $this->spreadsheet->getSheetByNameOrThrow($sheetname);
$cell = $worksheet->getCell($cellAddress);
$cfRange = $this->confirmString($worksheet, $cell, $cellAddress);
$cfStyle = $worksheet->getConditionalStyles($cell->getCoordinate());
$matcher = new CellMatcher($cell, $cfRange);
$match = $matcher->evaluateConditional($cfStyle[0]);
self::assertSame($expectedMatch, $match);
}
public static function cellIsExpressionDataProvider(): array
{
return [
// Sales Grid for Country
['cellIs Expression', 'A12', false],
['cellIs Expression', 'B12', false],
['cellIs Expression', 'C12', false],
['cellIs Expression', 'D12', false],
['cellIs Expression', 'B13', true],
['cellIs Expression', 'C13', true],
['cellIs Expression', 'B15', true],
['cellIs Expression', 'B16', true],
['cellIs Expression', 'C17', false],
// Sales Grid for Country and Quarter
['cellIs Expression', 'A22', false],
['cellIs Expression', 'B22', false],
['cellIs Expression', 'C22', false],
['cellIs Expression', 'D22', false],
['cellIs Expression', 'B23', true],
['cellIs Expression', 'C23', true],
['cellIs Expression', 'B25', false],
['cellIs Expression', 'B26', true],
['cellIs Expression', 'C27', false],
];
}
#[DataProvider('textExpressionsDataProvider')]
public function testTextExpressions(string $sheetname, string $cellAddress, bool $expectedMatch): void
{
$this->spreadsheet = $this->loadSpreadsheet();
$worksheet = $this->spreadsheet->getSheetByNameOrThrow($sheetname);
$cell = $worksheet->getCell($cellAddress);
$cfRange = $this->confirmString($worksheet, $cell, $cellAddress);
$cfStyle = $worksheet->getConditionalStyles($cell->getCoordinate());
$matcher = new CellMatcher($cell, $cfRange);
$match = $matcher->evaluateConditional($cfStyle[0]);
self::assertSame($expectedMatch, $match);
}
public static function textExpressionsDataProvider(): array
{
return [
// Text Begins With Literal
['Text Expressions', 'A2', true],
['Text Expressions', 'B2', false],
['Text Expressions', 'A3', false],
['Text Expressions', 'B3', false],
['Text Expressions', 'A4', false],
['Text Expressions', 'B4', true],
// Text Ends With Literal
['Text Expressions', 'A8', false],
['Text Expressions', 'B8', false],
['Text Expressions', 'A9', true],
['Text Expressions', 'B9', true],
['Text Expressions', 'A10', false],
['Text Expressions', 'B10', true],
// Text Contains Literal
['Text Expressions', 'A14', true],
['Text Expressions', 'B14', false],
['Text Expressions', 'A15', true],
['Text Expressions', 'B15', true],
['Text Expressions', 'A16', false],
['Text Expressions', 'B16', true],
// Text Doesn't Contain Literal
['Text Expressions', 'A20', true],
['Text Expressions', 'B20', true],
['Text Expressions', 'A21', true],
['Text Expressions', 'B21', true],
['Text Expressions', 'A22', false],
['Text Expressions', 'B22', true],
// Text Begins With Cell Reference
['Text Expressions', 'D2', true],
['Text Expressions', 'E2', false],
['Text Expressions', 'D3', false],
['Text Expressions', 'E3', false],
['Text Expressions', 'D4', false],
['Text Expressions', 'E4', true],
// Text Ends With Cell Reference
['Text Expressions', 'D8', false],
['Text Expressions', 'E8', false],
['Text Expressions', 'D9', true],
['Text Expressions', 'E9', true],
['Text Expressions', 'D10', false],
['Text Expressions', 'E10', true],
// Text Contains Cell Reference
['Text Expressions', 'D14', true],
['Text Expressions', 'E14', false],
['Text Expressions', 'D15', true],
['Text Expressions', 'E15', true],
['Text Expressions', 'D16', false],
['Text Expressions', 'E16', true],
// Text Doesn't Contain Cell Reference
['Text Expressions', 'D20', true],
['Text Expressions', 'E20', true],
['Text Expressions', 'D21', true],
['Text Expressions', 'E21', true],
['Text Expressions', 'D22', false],
['Text Expressions', 'E22', true],
// Text Begins With Formula
['Text Expressions', 'G2', true],
['Text Expressions', 'H2', false],
['Text Expressions', 'G3', false],
['Text Expressions', 'H3', false],
['Text Expressions', 'G4', false],
['Text Expressions', 'H4', true],
// Text Ends With Formula
['Text Expressions', 'G8', false],
['Text Expressions', 'H8', false],
['Text Expressions', 'G9', true],
['Text Expressions', 'H9', true],
['Text Expressions', 'G10', false],
['Text Expressions', 'H10', true],
// Text Contains Formula
['Text Expressions', 'G14', true],
['Text Expressions', 'H14', false],
['Text Expressions', 'G15', true],
['Text Expressions', 'H15', true],
['Text Expressions', 'G16', false],
['Text Expressions', 'H16', true],
// Text Doesn't Contain Formula
['Text Expressions', 'G20', true],
['Text Expressions', 'H20', true],
['Text Expressions', 'G21', true],
['Text Expressions', 'H21', true],
['Text Expressions', 'G22', false],
['Text Expressions', 'H22', true],
];
}
/** @param mixed[] $expectedMatches */
#[DataProvider('blanksDataProvider')]
public function testBlankExpressions(string $sheetname, string $cellAddress, array $expectedMatches): void
{
$this->spreadsheet = $this->loadSpreadsheet();
$worksheet = $this->spreadsheet->getSheetByNameOrThrow($sheetname);
$cell = $worksheet->getCell($cellAddress);
$cfRange = $this->confirmString($worksheet, $cell, $cellAddress);
$cfStyles = $worksheet->getConditionalStyles($cell->getCoordinate());
$matcher = new CellMatcher($cell, $cfRange);
foreach ($cfStyles as $cfIndex => $cfStyle) {
$match = $matcher->evaluateConditional($cfStyle);
self::assertSame($expectedMatches[$cfIndex], $match);
}
}
public static function blanksDataProvider(): array
{
return [
// Blank/Not Blank
'A2' => ['Blank Expressions', 'A2', [false, true]],
'B2' => ['Blank Expressions', 'B2', [true, false]],
'A3' => ['Blank Expressions', 'A3', [true, false]],
'B3' => ['Blank Expressions', 'B3', [false, true]],
];
}
/** @param mixed[] $expectedMatches */
#[DataProvider('errorDataProvider')]
public function testErrorExpressions(string $sheetname, string $cellAddress, array $expectedMatches): void
{
$this->spreadsheet = $this->loadSpreadsheet();
$worksheet = $this->spreadsheet->getSheetByNameOrThrow($sheetname);
$cell = $worksheet->getCell($cellAddress);
$cfRange = $this->confirmString($worksheet, $cell, $cellAddress);
$cfStyles = $worksheet->getConditionalStyles($cell->getCoordinate());
$matcher = new CellMatcher($cell, $cfRange);
foreach ($cfStyles as $cfIndex => $cfStyle) {
$match = $matcher->evaluateConditional($cfStyle);
self::assertSame($expectedMatches[$cfIndex], $match);
}
}
public static function errorDataProvider(): array
{
return [
// Error/Not Error
'C2' => ['Error Expressions', 'C2', [false, true]],
'C4' => ['Error Expressions', 'C4', [true, false]],
'C5' => ['Error Expressions', 'C5', [false, true]],
];
}
#[DataProvider('dateOccurringDataProvider')]
public function testDateOccurringExpressions(string $sheetname, string $cellAddress, bool $expectedMatch): void
{
$this->spreadsheet = $this->loadSpreadsheet();
$worksheet = $this->spreadsheet->getSheetByNameOrThrow($sheetname);
$cell = $worksheet->getCell($cellAddress);
$cfRange = $this->confirmString($worksheet, $cell, $cellAddress);
$cfStyle = $worksheet->getConditionalStyles($cell->getCoordinate());
$matcher = new CellMatcher($cell, $cfRange);
$match = $matcher->evaluateConditional($cfStyle[0]);
self::assertSame($expectedMatch, $match);
}
public static function dateOccurringDataProvider(): array
{
return [
// Today
['Date Expressions', 'B9', false],
['Date Expressions', 'B10', true],
['Date Expressions', 'B11', false],
// Yesterday
['Date Expressions', 'C9', true],
['Date Expressions', 'C10', false],
['Date Expressions', 'C11', false],
// Tomorrow
['Date Expressions', 'D9', false],
['Date Expressions', 'D10', false],
['Date Expressions', 'D11', true],
// Last Daye
['Date Expressions', 'E7', false],
['Date Expressions', 'E8', true],
['Date Expressions', 'E9', true],
['Date Expressions', 'E10', true],
['Date Expressions', 'E11', false],
];
}
/** @param mixed[] $expectedMatches */
#[DataProvider('duplicatesDataProvider')]
public function testDuplicatesExpressions(string $sheetname, string $cellAddress, array $expectedMatches): void
{
$this->spreadsheet = $this->loadSpreadsheet();
$worksheet = $this->spreadsheet->getSheetByNameOrThrow($sheetname);
$cell = $worksheet->getCell($cellAddress);
$cfRange = $this->confirmString($worksheet, $cell, $cellAddress);
$cfStyles = $worksheet->getConditionalStyles($cell->getCoordinate());
$matcher = new CellMatcher($cell, $cfRange);
foreach ($cfStyles as $cfIndex => $cfStyle) {
$match = $matcher->evaluateConditional($cfStyle);
self::assertSame($expectedMatches[$cfIndex], $match);
}
}
public static function duplicatesDataProvider(): array
{
return [
// Duplicate/Unique
'A2' => ['Duplicates Expressions', 'A2', [true, false]],
'B2' => ['Duplicates Expressions', 'B2', [false, true]],
'A4' => ['Duplicates Expressions', 'A4', [true, false]],
'A5' => ['Duplicates Expressions', 'A5', [false, true]],
'B5' => ['Duplicates Expressions', 'B5', [true, false]],
'A9' => ['Duplicates Expressions', 'A9', [true, false]],
'B9' => ['Duplicates Expressions', 'B9', [false, true]],
];
}
#[DataProvider('textCrossWorksheetDataProvider')]
public function testCrossWorksheetExpressions(string $sheetname, string $cellAddress, bool $expectedMatch): void
{
$this->spreadsheet = $this->loadSpreadsheet();
$worksheet = $this->spreadsheet->getSheetByNameOrThrow($sheetname);
$cell = $worksheet->getCell($cellAddress);
$cfRange = $this->confirmString($worksheet, $cell, $cellAddress);
$cfStyle = $worksheet->getConditionalStyles($cell->getCoordinate());
$matcher = new CellMatcher($cell, $cfRange);
$match = $matcher->evaluateConditional($cfStyle[0]);
self::assertSame($expectedMatch, $match);
}
public static function textCrossWorksheetDataProvider(): array
{
return [
// Relative Cell References in another Worksheet
'A1' => ['CrossSheet References', 'A1', false],
'A2' => ['CrossSheet References', 'A2', false],
'A3' => ['CrossSheet References', 'A3', true],
'A4' => ['CrossSheet References', 'A4', false],
'A5' => ['CrossSheet References', 'A5', false],
];
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Style/ConditionalFormatting/PR3946Test.php | tests/PhpSpreadsheetTests/Style/ConditionalFormatting/PR3946Test.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Style\ConditionalFormatting;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Conditional;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Style\Style;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx as XlsxWriter;
use PHPUnit\Framework\TestCase;
class PR3946Test extends TestCase
{
public function testConditionalTextInitialized(): void
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$cellRange = 'C3:E5';
$style = new Style();
$style->applyFromArray([
'fill' => [
'color' => ['argb' => 'FFFFC000'],
'fillType' => Fill::FILL_SOLID,
],
]);
$condition = new Conditional();
$condition->setConditionType(Conditional::CONDITION_CONTAINSTEXT);
$condition->setOperatorType(Conditional::OPERATOR_CONTAINSTEXT);
$condition->setStyle($style);
$sheet->setConditionalStyles($cellRange, [$condition]);
$writer = new XlsxWriter($spreadsheet);
$writerWorksheet = new XlsxWriter\Worksheet($writer);
$data = $writerWorksheet->writeWorksheet($sheet, []);
self::assertStringContainsString('<conditionalFormatting sqref="C3:E5">', $data);
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Style/ConditionalFormatting/Wizard/CellValueWizardTest.php | tests/PhpSpreadsheetTests/Style/ConditionalFormatting/Wizard/CellValueWizardTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Style\ConditionalFormatting\Wizard;
use PhpOffice\PhpSpreadsheet\Exception;
use PhpOffice\PhpSpreadsheet\Style\Conditional;
use PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\Wizard;
use PhpOffice\PhpSpreadsheet\Style\Style;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
class CellValueWizardTest extends TestCase
{
protected Style $style;
protected string $range = '$C$3:$E$5';
protected Wizard $wizardFactory;
protected function setUp(): void
{
$this->wizardFactory = new Wizard($this->range);
$this->style = new Style();
}
#[DataProvider('basicCellValueDataProvider')]
public function testBasicCellValueWizard(string $operator, mixed $operand, string $expectedOperator, mixed $expectedCondition): void
{
$ruleType = Wizard::CELL_VALUE;
/** @var Wizard\CellValue $wizard */
$wizard = $this->wizardFactory->newRule($ruleType);
$wizard->setStyle($this->style);
$wizard->$operator($operand);
$conditional = $wizard->getConditional();
self::assertSame(Conditional::CONDITION_CELLIS, $conditional->getConditionType());
self::assertSame($expectedOperator, $conditional->getOperatorType());
$conditions = $conditional->getConditions();
self::assertSame([$expectedCondition], $conditions);
$newWizard = Wizard::fromConditional($conditional, $this->range);
$newWizard->getConditional();
self::assertEquals($newWizard, $wizard, 'fromConditional() Failure');
}
public static function basicCellValueDataProvider(): array
{
return [
'=5' => ['equals', 5, Conditional::OPERATOR_EQUAL, 5],
'<>-2' => ['notEquals', -2, Conditional::OPERATOR_NOTEQUAL, -2],
'>3' => ['greaterThan', 3, Conditional::OPERATOR_GREATERTHAN, 3],
'>=5.5' => ['greaterThanOrEqual', 5.5, Conditional::OPERATOR_GREATERTHANOREQUAL, 5.5],
'<-1.5' => ['lessThan', -1.5, Conditional::OPERATOR_LESSTHAN, -1.5],
'<=22>' => ['lessThanOrEqual', 22, Conditional::OPERATOR_LESSTHANOREQUAL, 22],
'= Boolean True Value' => ['equals', true, Conditional::OPERATOR_EQUAL, 'TRUE'],
'= Boolean False Value' => ['equals', false, Conditional::OPERATOR_EQUAL, 'FALSE'],
'= Null Value' => ['equals', null, Conditional::OPERATOR_EQUAL, 'NULL'],
'= String Value' => ['equals', 'Hello World', Conditional::OPERATOR_EQUAL, '"Hello World"'],
];
}
#[DataProvider('relativeCellValueDataProvider')]
public function testRelativeCellValueWizard(mixed $operand, mixed $expectedCondition): void
{
$ruleType = Wizard::CELL_VALUE;
/** @var Wizard\CellValue $wizard */
$wizard = $this->wizardFactory->newRule($ruleType);
$wizard->setStyle($this->style);
$wizard->equals($operand, Wizard::VALUE_TYPE_CELL);
$conditional = $wizard->getConditional();
$conditions = $conditional->getConditions();
self::assertSame([$expectedCondition], $conditions);
$newWizard = Wizard::fromConditional($conditional, $this->range);
$newWizard->getConditional();
self::assertEquals($newWizard, $wizard, 'fromConditional() Failure');
}
public static function relativeCellValueDataProvider(): array
{
return [
'= Cell value unpinned' => ['A1', 'C3'],
'= Cell value pinned column' => ['$G1', '$G3'],
'= Cell value pinned row' => ['A$10', 'C$10'],
'= Cell value pinned cell' => ['$A$1', '$A$1'],
];
}
#[DataProvider('formulaCellValueDataProvider')]
public function testCellValueWizardWithFormula(mixed $operand, mixed $expectedCondition): void
{
$ruleType = Wizard::CELL_VALUE;
/** @var Wizard\CellValue $wizard */
$wizard = $this->wizardFactory->newRule($ruleType);
$wizard->setStyle($this->style);
$wizard->equals($operand, Wizard::VALUE_TYPE_FORMULA);
$conditional = $wizard->getConditional();
$conditions = $conditional->getConditions();
self::assertSame([$expectedCondition], $conditions);
$newWizard = Wizard::fromConditional($conditional, $this->range);
$newWizard->getConditional();
self::assertEquals($newWizard, $wizard, 'fromConditional() Failure');
}
public static function formulaCellValueDataProvider(): array
{
return [
'= Cell value unpinned in function' => ['SQRT(A1)', 'SQRT(C3)'],
'= Cell value pinned column in function' => ['SQRT($G1)', 'SQRT($G3)'],
'= Cell value pinned row in function' => ['SQRT(A$10)', 'SQRT(C$10)'],
'= Cell value pinned cell in function' => ['SQRT($A$1)', 'SQRT($A$1)'],
'= Cell value unpinned in expression' => ['A1+B2', 'C3+D4'],
'= Cell value pinned column in expression' => ['$G1+$H2', '$G3+$H4'],
'= Cell value pinned row in expression' => ['A$10+B$11', 'C$10+D$11'],
'= Cell value pinned cell in expression' => ['$A$1+$B$2', '$A$1+$B$2'],
];
}
/** @param mixed[] $operands */
#[DataProvider('rangeCellValueDataProvider')]
public function testRangeCellValueWizard(string $operator, array $operands, string $expectedOperator): void
{
$ruleType = Wizard::CELL_VALUE;
/** @var Wizard\CellValue */
$wizard = $this->wizardFactory->newRule($ruleType);
$wizard->setStyle($this->style);
/** @var Wizard\CellValue */
$temp = $wizard->$operator($operands[0]);
$temp->and($operands[1]);
$conditional = $wizard->getConditional();
self::assertSame(Conditional::CONDITION_CELLIS, $conditional->getConditionType());
self::assertSame($expectedOperator, $conditional->getOperatorType());
$conditions = $conditional->getConditions();
self::assertSame($operands, $conditions);
$newWizard = Wizard::fromConditional($conditional, $this->range);
$newWizard->getConditional();
self::assertEquals($newWizard, $wizard, 'fromConditional() Failure');
}
public static function rangeCellValueDataProvider(): array
{
return [
'between 5 and 10' => ['between', [5, 10], Conditional::OPERATOR_BETWEEN],
'between 10 and 5' => ['between', [10, 5], Conditional::OPERATOR_BETWEEN],
'not between 0 and 1' => ['notBetween', [0, 1], Conditional::OPERATOR_NOTBETWEEN],
];
}
/**
* @param mixed[] $operands
* @param mixed[] $expectedConditions
*/
#[DataProvider('rangeRelativeCellValueDataProvider')]
public function testRelativeRangeCellValueWizard(array $operands, array $expectedConditions): void
{
$ruleType = Wizard::CELL_VALUE;
/** @var Wizard\CellValue $wizard */
$wizard = $this->wizardFactory->newRule($ruleType);
$wizard->setStyle($this->style);
$wizard
->between($operands[0], is_string($operands[0]) ? Wizard::VALUE_TYPE_CELL : Wizard::VALUE_TYPE_LITERAL)
->and($operands[1], is_string($operands[1]) ? Wizard::VALUE_TYPE_CELL : Wizard::VALUE_TYPE_LITERAL);
$conditional = $wizard->getConditional();
self::assertSame(Conditional::CONDITION_CELLIS, $conditional->getConditionType());
$conditions = $conditional->getConditions();
self::assertSame($expectedConditions, $conditions);
$newWizard = Wizard::fromConditional($conditional, $this->range);
$newWizard->getConditional();
self::assertEquals($newWizard, $wizard, 'fromConditional() Failure');
}
public static function rangeRelativeCellValueDataProvider(): array
{
return [
'between A6 and 5' => [['A$6', 5], ['C$6', 5]],
'between -5 and C6' => [[-5, '$C6'], [-5, '$C8']],
];
}
/**
* @param mixed[] $operands
* @param mixed[] $expectedConditions
*/
#[DataProvider('rangeFormulaCellValueDataProvider')]
public function testFormulaRangeCellValueWizard(array $operands, array $expectedConditions): void
{
$ruleType = Wizard::CELL_VALUE;
/** @var Wizard\CellValue $wizard */
$wizard = $this->wizardFactory->newRule($ruleType);
$wizard->setStyle($this->style);
$wizard
->between($operands[0], is_string($operands[0]) ? Wizard::VALUE_TYPE_FORMULA : Wizard::VALUE_TYPE_LITERAL)
->and($operands[1], is_string($operands[1]) ? Wizard::VALUE_TYPE_FORMULA : Wizard::VALUE_TYPE_LITERAL);
$conditional = $wizard->getConditional();
self::assertSame(Conditional::CONDITION_CELLIS, $conditional->getConditionType());
$conditions = $conditional->getConditions();
self::assertSame($expectedConditions, $conditions);
$newWizard = Wizard::fromConditional($conditional, $this->range);
$newWizard->getConditional();
self::assertEquals($newWizard, $wizard, 'fromConditional() Failure');
}
public static function rangeFormulaCellValueDataProvider(): array
{
return [
'between yesterday and tomorrow' => [['TODAY()-1', 'TODAY()+1'], ['TODAY()-1', 'TODAY()+1']],
];
}
public function testInvalidFromConditional(): void
{
$ruleType = 'Unknown';
$this->expectException(Exception::class);
$this->expectExceptionMessage('Conditional is not a Cell Value CF Rule conditional');
$conditional = new Conditional();
$conditional->setConditionType($ruleType);
Wizard\CellValue::fromConditional($conditional);
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Style/ConditionalFormatting/Wizard/ExpressionWizardTest.php | tests/PhpSpreadsheetTests/Style/ConditionalFormatting/Wizard/ExpressionWizardTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Style\ConditionalFormatting\Wizard;
use PhpOffice\PhpSpreadsheet\Exception;
use PhpOffice\PhpSpreadsheet\Style\Conditional;
use PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\Wizard;
use PhpOffice\PhpSpreadsheet\Style\Style;
use PHPUnit\Framework\TestCase;
class ExpressionWizardTest extends TestCase
{
protected Style $style;
protected string $range = '$C$3:$E$5';
protected Wizard $wizardFactory;
protected function setUp(): void
{
$this->wizardFactory = new Wizard($this->range);
$this->style = new Style();
}
#[\PHPUnit\Framework\Attributes\DataProvider('expressionDataProvider')]
public function testExpressionWizard(string $expression, string $expectedExpression): void
{
$ruleType = Wizard::EXPRESSION;
/** @var Wizard\Expression $wizard */
$wizard = $this->wizardFactory->newRule($ruleType);
$wizard->setStyle($this->style);
$wizard->expression($expression);
$conditional = $wizard->getConditional();
self::assertSame(Conditional::CONDITION_EXPRESSION, $conditional->getConditionType());
$conditions = $conditional->getConditions();
self::assertSame([$expectedExpression], $conditions);
$newWizard = Wizard::fromConditional($conditional, $this->range);
$newWizard->getConditional();
self::assertEquals($newWizard, $wizard, 'fromConditional() Failure');
}
#[\PHPUnit\Framework\Attributes\DataProvider('expressionDataProvider')]
public function testExpressionWizardUsingAlias(string $expression, string $expectedExpression): void
{
$ruleType = Wizard::EXPRESSION;
/** @var Wizard\Expression $wizard */
$wizard = $this->wizardFactory->newRule($ruleType);
$wizard->setStyle($this->style);
$wizard->formula($expression);
$conditional = $wizard->getConditional();
self::assertSame(Conditional::CONDITION_EXPRESSION, $conditional->getConditionType());
$conditions = $conditional->getConditions();
self::assertSame([$expectedExpression], $conditions);
}
public static function expressionDataProvider(): array
{
return [
['ISODD(A1)', 'ISODD(C3)'],
['AND($A1="USA",$B1="Q4")', 'AND($A3="USA",$B3="Q4")'],
];
}
public function testInvalidFromConditional(): void
{
$ruleType = 'Unknown';
$this->expectException(Exception::class);
$this->expectExceptionMessage('Conditional is not an Expression CF Rule conditional');
$conditional = new Conditional();
$conditional->setConditionType($ruleType);
Wizard\Expression::fromConditional($conditional);
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Style/ConditionalFormatting/Wizard/BlankWizardTest.php | tests/PhpSpreadsheetTests/Style/ConditionalFormatting/Wizard/BlankWizardTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Style\ConditionalFormatting\Wizard;
use PhpOffice\PhpSpreadsheet\Exception;
use PhpOffice\PhpSpreadsheet\Style\Conditional;
use PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\Wizard;
use PhpOffice\PhpSpreadsheet\Style\Style;
use PHPUnit\Framework\TestCase;
class BlankWizardTest extends TestCase
{
protected Style $style;
protected string $range = '$C$3:$E$5';
protected Wizard $wizardFactory;
protected function setUp(): void
{
$this->wizardFactory = new Wizard($this->range);
$this->style = new Style();
}
public function testBlankWizard(): void
{
$ruleType = Wizard::BLANKS;
$wizard = $this->wizardFactory->newRule($ruleType);
self::assertInstanceOf(Wizard\Blanks::class, $wizard);
$wizard->setStyle($this->style);
$conditional = $wizard->getConditional();
self::assertSame(Conditional::CONDITION_CONTAINSBLANKS, $conditional->getConditionType());
$conditions = $conditional->getConditions();
self::assertSame(['LEN(TRIM(C3))=0'], $conditions);
$newWizard = Wizard::fromConditional($conditional, $this->range);
$newWizard->getConditional();
self::assertEquals($newWizard, $wizard, 'fromConditional() Failure');
}
public function testNonBlankWizard(): void
{
$ruleType = Wizard::NOT_BLANKS;
$wizard = $this->wizardFactory->newRule($ruleType);
self::assertInstanceOf(Wizard\Blanks::class, $wizard);
$wizard->setStyle($this->style);
$conditional = $wizard->getConditional();
self::assertSame(Conditional::CONDITION_NOTCONTAINSBLANKS, $conditional->getConditionType());
$conditions = $conditional->getConditions();
self::assertSame(['LEN(TRIM(C3))>0'], $conditions);
$newWizard = Wizard::fromConditional($conditional, $this->range);
$newWizard->getConditional();
self::assertEquals($newWizard, $wizard, 'fromConditional() Failure');
}
public function testBlankWizardWithNotBlank(): void
{
$ruleType = Wizard::BLANKS;
/** @var Wizard\Blanks $wizard */
$wizard = $this->wizardFactory->newRule($ruleType);
$wizard->setStyle($this->style);
$wizard->notBlank();
$conditional = $wizard->getConditional();
self::assertSame(Conditional::CONDITION_NOTCONTAINSBLANKS, $conditional->getConditionType());
$conditions = $conditional->getConditions();
self::assertSame(['LEN(TRIM(C3))>0'], $conditions);
$newWizard = Wizard::fromConditional($conditional, $this->range);
$newWizard->getConditional();
self::assertEquals($newWizard, $wizard, 'fromConditional() Failure');
}
public function testNonBlankWizardWithIsBlank(): void
{
$ruleType = Wizard::NOT_BLANKS;
/** @var Wizard\Blanks $wizard */
$wizard = $this->wizardFactory->newRule($ruleType);
$wizard->setStyle($this->style);
$wizard->isBlank();
$conditional = $wizard->getConditional();
self::assertSame(Conditional::CONDITION_CONTAINSBLANKS, $conditional->getConditionType());
$conditions = $conditional->getConditions();
self::assertSame(['LEN(TRIM(C3))=0'], $conditions);
$newWizard = Wizard::fromConditional($conditional, $this->range);
$newWizard->getConditional();
self::assertEquals($newWizard, $wizard, 'fromConditional() Failure');
}
public function testInvalidFromConditional(): void
{
$ruleType = 'Unknown';
$this->expectException(Exception::class);
$this->expectExceptionMessage('Conditional is not a Blanks CF Rule conditional');
$conditional = new Conditional();
$conditional->setConditionType($ruleType);
Wizard\Blanks::fromConditional($conditional);
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Style/ConditionalFormatting/Wizard/WizardFactoryTest.php | tests/PhpSpreadsheetTests/Style/ConditionalFormatting/Wizard/WizardFactoryTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Style\ConditionalFormatting\Wizard;
use PhpOffice\PhpSpreadsheet\Exception;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Style\Conditional;
use PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\Wizard;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
class WizardFactoryTest extends TestCase
{
protected Wizard $wizardFactory;
protected function setUp(): void
{
$range = '$C$3:$E$5';
$this->wizardFactory = new Wizard($range);
}
/**
* @psalm-param class-string<object> $expectedWizard
*/
#[DataProvider('basicWizardFactoryProvider')]
public function testBasicWizardFactory(string $ruleType, string $expectedWizard): void
{
$wizard = $this->wizardFactory->newRule($ruleType);
self::assertInstanceOf($expectedWizard, $wizard);
}
public static function basicWizardFactoryProvider(): array
{
return [
'CellValue Wizard' => [Wizard::CELL_VALUE, Wizard\CellValue::class],
'TextValue Wizard' => [Wizard::TEXT_VALUE, Wizard\TextValue::class],
'Blanks Wizard' => [Wizard::BLANKS, Wizard\Blanks::class],
'Blanks Wizard (NOT)' => [Wizard::NOT_BLANKS, Wizard\Blanks::class],
'Errors Wizard' => [Wizard::ERRORS, Wizard\Errors::class],
'Errors Wizard (NOT)' => [Wizard::NOT_ERRORS, Wizard\Errors::class],
'Expression Wizard' => [Wizard::EXPRESSION, Wizard\Expression::class],
'DateValue Wizard' => [Wizard::DATES_OCCURRING, Wizard\DateValue::class],
];
}
/** @param mixed[] $expectedWizards */
#[DataProvider('conditionalProvider')]
public function testWizardFromConditional(string $sheetName, string $cellAddress, array $expectedWizards): void
{
$filename = 'tests/data/Style/ConditionalFormatting/CellMatcher.xlsx';
$reader = IOFactory::createReader('Xlsx');
$spreadsheet = $reader->load($filename);
$worksheet = $spreadsheet->getSheetByNameOrThrow($sheetName);
$cell = $worksheet->getCell($cellAddress);
$cfRange = $worksheet->getConditionalRange($cell->getCoordinate());
if ($cfRange === null) {
self::markTestSkipped("{$cellAddress} is not in a Conditional Format range");
}
$conditionals = $worksheet->getConditionalStyles($cfRange);
foreach ($conditionals as $index => $conditional) {
$wizard = Wizard::fromConditional($conditional);
self::assertEquals($expectedWizards[$index], $wizard::class);
}
$spreadsheet->disconnectWorksheets();
}
public static function conditionalProvider(): array
{
return [
'cellIs Comparison A2' => ['cellIs Comparison', 'A2', [Wizard\CellValue::class, Wizard\CellValue::class, Wizard\CellValue::class]],
'cellIs Expression A2' => ['cellIs Expression', 'A2', [Wizard\Expression::class, Wizard\Expression::class]],
'Text Expressions A2' => ['Text Expressions', 'A2', [Wizard\TextValue::class]],
'Text Expressions A8' => ['Text Expressions', 'A8', [Wizard\TextValue::class]],
'Text Expressions A14' => ['Text Expressions', 'A14', [Wizard\TextValue::class]],
'Text Expressions A20' => ['Text Expressions', 'A20', [Wizard\TextValue::class]],
'Blank Expressions A2' => ['Blank Expressions', 'A2', [Wizard\Blanks::class, Wizard\Blanks::class]],
'Error Expressions C2' => ['Error Expressions', 'C2', [Wizard\Errors::class, Wizard\Errors::class]],
'Date Expressions B10' => ['Date Expressions', 'B10', [Wizard\DateValue::class]],
'Duplicates Expressions A2' => ['Duplicates Expressions', 'A2', [Wizard\Duplicates::class, Wizard\Duplicates::class]],
];
}
public function testWizardFactoryException(): void
{
$ruleType = 'Unknown';
$this->expectException(Exception::class);
$this->expectExceptionMessage('No wizard exists for this CF rule type');
$this->wizardFactory->newRule($ruleType);
$conditional = new Conditional();
$conditional->setConditionType('UNKNOWN');
Wizard::fromConditional($conditional);
}
public function testWizardFactoryFromConditionalException(): void
{
$ruleType = 'Unknown';
$this->expectException(Exception::class);
$this->expectExceptionMessage('No wizard exists for this CF rule type');
$conditional = new Conditional();
$conditional->setConditionType($ruleType);
Wizard::fromConditional($conditional);
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Style/ConditionalFormatting/Wizard/DateValueWizardTest.php | tests/PhpSpreadsheetTests/Style/ConditionalFormatting/Wizard/DateValueWizardTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Style\ConditionalFormatting\Wizard;
use PhpOffice\PhpSpreadsheet\Exception;
use PhpOffice\PhpSpreadsheet\Style\Conditional;
use PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\Wizard;
use PhpOffice\PhpSpreadsheet\Style\Style;
use PHPUnit\Framework\TestCase;
class DateValueWizardTest extends TestCase
{
protected Style $style;
protected string $range = '$C$3:$E$5';
protected Wizard $wizardFactory;
protected function setUp(): void
{
$this->wizardFactory = new Wizard($this->range);
$this->style = new Style();
}
#[\PHPUnit\Framework\Attributes\DataProvider('dateValueWizardProvider')]
public function testDateValueWizard(string $operator, string $expectedReference, string $expectedExpression): void
{
$ruleType = Wizard::DATES_OCCURRING;
/** @var Wizard\DateValue $dateWizard */
$dateWizard = $this->wizardFactory->newRule($ruleType);
$dateWizard->setStyle($this->style);
$dateWizard->$operator();
$conditional = $dateWizard->getConditional();
self::assertSame(Conditional::CONDITION_TIMEPERIOD, $conditional->getConditionType());
self:self::assertSame($expectedReference, $conditional->getText());
$conditions = $conditional->getConditions();
self::assertSame([$expectedExpression], $conditions);
$newWizard = Wizard::fromConditional($conditional, $this->range);
$newWizard->getConditional();
self::assertEquals($newWizard, $dateWizard, 'fromConditional() Failure');
}
public static function dateValueWizardProvider(): array
{
return [
['today', 'today', 'FLOOR(C3,1)=TODAY()'],
['yesterday', 'yesterday', 'FLOOR(C3,1)=TODAY()-1'],
['tomorrow', 'tomorrow', 'FLOOR(C3,1)=TODAY()+1'],
['lastSevenDays', 'last7Days', 'AND(TODAY()-FLOOR(C3,1)<=6,FLOOR(C3,1)<=TODAY())'],
];
}
public function testInvalidFromConditional(): void
{
$ruleType = 'Unknown';
$this->expectException(Exception::class);
$this->expectExceptionMessage('Conditional is not a Date Value CF Rule conditional');
$conditional = new Conditional();
$conditional->setConditionType($ruleType);
Wizard\DateValue::fromConditional($conditional);
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Style/ConditionalFormatting/Wizard/TextValueWizardTest.php | tests/PhpSpreadsheetTests/Style/ConditionalFormatting/Wizard/TextValueWizardTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Style\ConditionalFormatting\Wizard;
use PhpOffice\PhpSpreadsheet\Exception;
use PhpOffice\PhpSpreadsheet\Style\Conditional;
use PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\Wizard;
use PhpOffice\PhpSpreadsheet\Style\Style;
use PHPUnit\Framework\TestCase;
class TextValueWizardTest extends TestCase
{
protected Style $style;
protected string $range = '$C$3:$E$5';
protected Wizard $wizardFactory;
protected function setUp(): void
{
$this->wizardFactory = new Wizard($this->range);
$this->style = new Style();
}
public function testTextContainsWizardWithText(): void
{
$ruleType = Wizard::TEXT_VALUE;
$textWizard = $this->wizardFactory->newRule($ruleType);
self::assertInstanceOf(Wizard\TextValue::class, $textWizard);
$textWizard->setStyle($this->style);
$textWizard->contains('LL');
$conditional = $textWizard->getConditional();
self::assertSame(Conditional::CONDITION_CONTAINSTEXT, $conditional->getConditionType());
self::assertSame(Conditional::OPERATOR_CONTAINSTEXT, $conditional->getOperatorType());
self::assertSame('LL', $conditional->getText());
$conditions = $conditional->getConditions();
self::assertSame(['NOT(ISERROR(SEARCH("LL",C3)))'], $conditions);
$newWizard = Wizard::fromConditional($conditional, $this->range);
$newWizard->getConditional();
self::assertEquals($newWizard, $textWizard, 'fromConditional() Failure');
}
public function testTextContainsWizardWithCellReference(): void
{
$ruleType = Wizard::TEXT_VALUE;
$textWizard = $this->wizardFactory->newRule($ruleType);
self::assertInstanceOf(Wizard\TextValue::class, $textWizard);
$textWizard->setStyle($this->style);
$textWizard->contains('$A1', Wizard::VALUE_TYPE_CELL);
$conditional = $textWizard->getConditional();
self::assertSame(Conditional::CONDITION_CONTAINSTEXT, $conditional->getConditionType());
self:self::assertSame(Conditional::OPERATOR_CONTAINSTEXT, $conditional->getOperatorType());
self::assertSame('$A3', $conditional->getText());
$conditions = $conditional->getConditions();
self::assertSame(['NOT(ISERROR(SEARCH($A3,C3)))'], $conditions);
$newWizard = Wizard::fromConditional($conditional, $this->range);
$newWizard->getConditional();
self::assertEquals($newWizard, $textWizard, 'fromConditional() Failure');
}
public function testTextNotContainsWizardWithText(): void
{
$ruleType = Wizard::TEXT_VALUE;
$textWizard = $this->wizardFactory->newRule($ruleType);
self::assertInstanceOf(Wizard\TextValue::class, $textWizard);
$textWizard->setStyle($this->style);
$textWizard->doesNotContain('LL');
$conditional = $textWizard->getConditional();
self::assertSame(Conditional::CONDITION_NOTCONTAINSTEXT, $conditional->getConditionType());
self:self::assertSame(Conditional::OPERATOR_NOTCONTAINS, $conditional->getOperatorType());
self::assertSame('LL', $conditional->getText());
$conditions = $conditional->getConditions();
self::assertSame(['ISERROR(SEARCH("LL",C3))'], $conditions);
$newWizard = Wizard::fromConditional($conditional, $this->range);
$newWizard->getConditional();
self::assertEquals($newWizard, $textWizard, 'fromConditional() Failure');
}
public function testTextBeginsWithWizardWithText(): void
{
$ruleType = Wizard::TEXT_VALUE;
$textWizard = $this->wizardFactory->newRule($ruleType);
self::assertInstanceOf(Wizard\TextValue::class, $textWizard);
$textWizard->setStyle($this->style);
$textWizard->beginsWith('LL');
$conditional = $textWizard->getConditional();
self::assertSame(Conditional::CONDITION_BEGINSWITH, $conditional->getConditionType());
self:self::assertSame(Conditional::OPERATOR_BEGINSWITH, $conditional->getOperatorType());
self::assertSame('LL', $conditional->getText());
$conditions = $conditional->getConditions();
self::assertSame(['LEFT(C3,LEN("LL"))="LL"'], $conditions);
$newWizard = Wizard::fromConditional($conditional, $this->range);
$newWizard->getConditional();
self::assertEquals($newWizard, $textWizard, 'fromConditional() Failure');
}
public function testTextEndsWithWizardWithText(): void
{
$ruleType = Wizard::TEXT_VALUE;
$textWizard = $this->wizardFactory->newRule($ruleType);
self::assertInstanceOf(Wizard\TextValue::class, $textWizard);
$textWizard->setStyle($this->style);
$textWizard->endsWith('LL');
$conditional = $textWizard->getConditional();
self::assertSame(Conditional::CONDITION_ENDSWITH, $conditional->getConditionType());
self:self::assertSame(Conditional::OPERATOR_ENDSWITH, $conditional->getOperatorType());
$conditions = $conditional->getConditions();
self::assertSame(['RIGHT(C3,LEN("LL"))="LL"'], $conditions);
$newWizard = Wizard::fromConditional($conditional, $this->range);
$newWizard->getConditional();
self::assertEquals($newWizard, $textWizard, 'fromConditional() Failure');
}
public function testInvalidFromConditional(): void
{
$ruleType = 'Unknown';
$this->expectException(Exception::class);
$this->expectExceptionMessage('Conditional is not a Text Value CF Rule conditional');
$conditional = new Conditional();
$conditional->setConditionType($ruleType);
Wizard\TextValue::fromConditional($conditional);
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Style/ConditionalFormatting/Wizard/DuplicatesWizardTest.php | tests/PhpSpreadsheetTests/Style/ConditionalFormatting/Wizard/DuplicatesWizardTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Style\ConditionalFormatting\Wizard;
use PhpOffice\PhpSpreadsheet\Exception;
use PhpOffice\PhpSpreadsheet\Style\Conditional;
use PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\Wizard;
use PhpOffice\PhpSpreadsheet\Style\Style;
use PHPUnit\Framework\TestCase;
class DuplicatesWizardTest extends TestCase
{
protected Style $style;
protected string $range = '$C$3:$E$5';
protected Wizard $wizardFactory;
protected function setUp(): void
{
$this->wizardFactory = new Wizard($this->range);
$this->style = new Style();
}
public function testDuplicateWizard(): void
{
$ruleType = Wizard::DUPLICATES;
$wizard = $this->wizardFactory->newRule($ruleType);
self::assertInstanceOf(Wizard\Duplicates::class, $wizard);
$wizard->setStyle($this->style);
$conditional = $wizard->getConditional();
self::assertSame(Conditional::CONDITION_DUPLICATES, $conditional->getConditionType());
$newWizard = Wizard::fromConditional($conditional, $this->range);
$newWizard->getConditional();
self::assertEquals($newWizard, $wizard, 'fromConditional() Failure');
}
public function testUniqueWizard(): void
{
$ruleType = Wizard::UNIQUE;
$wizard = $this->wizardFactory->newRule($ruleType);
self::assertInstanceOf(Wizard\Duplicates::class, $wizard);
$wizard->setStyle($this->style);
$conditional = $wizard->getConditional();
self::assertSame(Conditional::CONDITION_UNIQUE, $conditional->getConditionType());
$newWizard = Wizard::fromConditional($conditional, $this->range);
$newWizard->getConditional();
self::assertEquals($newWizard, $wizard, 'fromConditional() Failure');
}
public function testDuplicateWizardUnique(): void
{
$ruleType = Wizard::DUPLICATES;
/** @var Wizard\Duplicates $wizard */
$wizard = $this->wizardFactory->newRule($ruleType);
$wizard->setStyle($this->style);
$wizard->unique();
$conditional = $wizard->getConditional();
self::assertSame(Conditional::CONDITION_UNIQUE, $conditional->getConditionType());
$newWizard = Wizard::fromConditional($conditional, $this->range);
$newWizard->getConditional();
self::assertEquals($newWizard, $wizard, 'fromConditional() Failure');
}
public function testUniqueWizardDuplicates(): void
{
$ruleType = Wizard::UNIQUE;
/** @var Wizard\Duplicates $wizard */
$wizard = $this->wizardFactory->newRule($ruleType);
$wizard->setStyle($this->style);
$wizard->duplicates();
$conditional = $wizard->getConditional();
self::assertSame(Conditional::CONDITION_DUPLICATES, $conditional->getConditionType());
$newWizard = Wizard::fromConditional($conditional, $this->range);
$newWizard->getConditional();
self::assertEquals($newWizard, $wizard, 'fromConditional() Failure');
}
public function testInvalidFromConditional(): void
{
$ruleType = 'Unknown';
$this->expectException(Exception::class);
$this->expectExceptionMessage('Conditional is not a Duplicates CF Rule conditional');
$conditional = new Conditional();
$conditional->setConditionType($ruleType);
Wizard\Duplicates::fromConditional($conditional);
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Style/ConditionalFormatting/Wizard/ErrorWizardTest.php | tests/PhpSpreadsheetTests/Style/ConditionalFormatting/Wizard/ErrorWizardTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Style\ConditionalFormatting\Wizard;
use PhpOffice\PhpSpreadsheet\Exception;
use PhpOffice\PhpSpreadsheet\Style\Conditional;
use PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\Wizard;
use PhpOffice\PhpSpreadsheet\Style\Style;
use PHPUnit\Framework\TestCase;
class ErrorWizardTest extends TestCase
{
protected Style $style;
protected string $range = '$C$3:$E$5';
protected Wizard $wizardFactory;
protected function setUp(): void
{
$this->wizardFactory = new Wizard($this->range);
$this->style = new Style();
}
public function testErrorWizard(): void
{
$ruleType = Wizard::ERRORS;
$wizard = $this->wizardFactory->newRule($ruleType);
self::assertInstanceOf(Wizard\Errors::class, $wizard);
$wizard->setStyle($this->style);
$conditional = $wizard->getConditional();
self::assertSame(Conditional::CONDITION_CONTAINSERRORS, $conditional->getConditionType());
$conditions = $conditional->getConditions();
self::assertSame(['ISERROR(C3)'], $conditions);
$newWizard = Wizard::fromConditional($conditional, $this->range);
$newWizard->getConditional();
self::assertEquals($newWizard, $wizard, 'fromConditional() Failure');
}
public function testNonErrorWizard(): void
{
$ruleType = Wizard::NOT_ERRORS;
$wizard = $this->wizardFactory->newRule($ruleType);
self::assertInstanceOf(Wizard\Errors::class, $wizard);
$wizard->setStyle($this->style);
$conditional = $wizard->getConditional();
self::assertSame(Conditional::CONDITION_NOTCONTAINSERRORS, $conditional->getConditionType());
$conditions = $conditional->getConditions();
self::assertSame(['NOT(ISERROR(C3))'], $conditions);
$newWizard = Wizard::fromConditional($conditional, $this->range);
$newWizard->getConditional();
self::assertEquals($newWizard, $wizard, 'fromConditional() Failure');
}
public function testErrorWizardNotError(): void
{
$ruleType = Wizard::ERRORS;
/** @var Wizard\Errors $wizard */
$wizard = $this->wizardFactory->newRule($ruleType);
$wizard->setStyle($this->style);
$wizard->notError();
$conditional = $wizard->getConditional();
self::assertSame(Conditional::CONDITION_NOTCONTAINSERRORS, $conditional->getConditionType());
$conditions = $conditional->getConditions();
self::assertSame(['NOT(ISERROR(C3))'], $conditions);
$newWizard = Wizard::fromConditional($conditional, $this->range);
$newWizard->getConditional();
self::assertEquals($newWizard, $wizard, 'fromConditional() Failure');
}
public function testErrorWizardIsError(): void
{
$ruleType = Wizard::NOT_ERRORS;
/** @var Wizard\Errors $wizard */
$wizard = $this->wizardFactory->newRule($ruleType);
$wizard->setStyle($this->style);
$wizard->isError();
$conditional = $wizard->getConditional();
self::assertSame(Conditional::CONDITION_CONTAINSERRORS, $conditional->getConditionType());
$conditions = $conditional->getConditions();
self::assertSame(['ISERROR(C3)'], $conditions);
$newWizard = Wizard::fromConditional($conditional, $this->range);
$newWizard->getConditional();
self::assertEquals($newWizard, $wizard, 'fromConditional() Failure');
}
public function testInvalidFromConditional(): void
{
$ruleType = 'Unknown';
$this->expectException(Exception::class);
$this->expectExceptionMessage('Conditional is not an Errors CF Rule conditional');
$conditional = new Conditional();
$conditional->setConditionType($ruleType);
Wizard\Errors::fromConditional($conditional);
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Style/NumberFormat/Wizard/DateTimeTest.php | tests/PhpSpreadsheetTests/Style/NumberFormat/Wizard/DateTimeTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Style\NumberFormat\Wizard;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat\Wizard\Date;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat\Wizard\DateTime;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat\Wizard\Time;
use PHPUnit\Framework\TestCase;
class DateTimeTest extends TestCase
{
/**
* @param null|string|string[] $separators
* @param array<Date|string|Time> $formatBlocks
*/
#[\PHPUnit\Framework\Attributes\DataProvider('providerDateTime')]
public function testDateTime(string $expectedResult, string|null|array $separators, array $formatBlocks): void
{
$wizard = new DateTime($separators, ...$formatBlocks);
self::assertSame($expectedResult, (string) $wizard);
}
public static function providerDateTime(): array
{
return [
['yyyy-mm-dd "at" hh:mm:ss', ' ', [new Date('-', 'yyyy', 'mm', 'dd'), 'at', new Time(':', 'hh', 'mm', 'ss')]],
['dddd \à hh "heures"', ' ', [new Date(null, 'dddd'), 'à', new Time(null, 'hh'), 'heures']],
];
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Style/NumberFormat/Wizard/DurationTest.php | tests/PhpSpreadsheetTests/Style/NumberFormat/Wizard/DurationTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Style\NumberFormat\Wizard;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat\Wizard\Duration;
use PHPUnit\Framework\TestCase;
use ReflectionMethod;
class DurationTest extends TestCase
{
/**
* @param null|string|string[] $separators
* @param string[] $formatBlocks
*/
#[\PHPUnit\Framework\Attributes\DataProvider('providerTime')]
public function testTime(string $expectedResult, string|array|null $separators = null, array $formatBlocks = []): void
{
$wizard = new Duration($separators, ...$formatBlocks);
self::assertSame($expectedResult, (string) $wizard);
}
public static function providerTime(): array
{
return [
['[h]:mm:ss', Duration::SEPARATOR_COLON, [Duration::HOURS_DURATION, Duration::MINUTES_LONG, Duration::SECONDS_LONG]],
['[h]:mm', Duration::SEPARATOR_COLON, [Duration::HOURS_DURATION, Duration::MINUTES_LONG]],
['[m]:ss', Duration::SEPARATOR_COLON, [Duration::MINUTES_DURATION, Duration::SECONDS_DURATION]],
['[h]:mm:ss', Duration::SEPARATOR_COLON, [Duration::HOURS_LONG, Duration::MINUTES_LONG, Duration::SECONDS_LONG]],
['[h]:mm', Duration::SEPARATOR_COLON, [Duration::HOURS_LONG, Duration::MINUTES_LONG]],
["d\u{a0}h:mm", [Duration::SEPARATOR_SPACE_NONBREAKING, Duration::SEPARATOR_COLON], [Duration::DAYS_DURATION, Duration::HOURS_DURATION, Duration::MINUTES_LONG]],
['[h]:mm:ss', null, [Duration::HOURS_DURATION, Duration::MINUTES_LONG, Duration::SECONDS_LONG]],
['[h]:mm:ss'],
];
}
public function testOddCase(): void
{
$wizard = new Duration(null, Duration::HOURS_DURATION, Duration::MINUTES_LONG, Duration::SECONDS_LONG);
$reflectionMethod = new ReflectionMethod($wizard, 'mapFormatBlocks');
$result = $reflectionMethod->invokeArgs($wizard, ['%%%']);
self::assertSame('"%%%"', $result);
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Style/NumberFormat/Wizard/ScientificTest.php | tests/PhpSpreadsheetTests/Style/NumberFormat/Wizard/ScientificTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Style\NumberFormat\Wizard;
use NumberFormatter;
use PhpOffice\PhpSpreadsheet\Exception;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat\Wizard\Scientific;
use PHPUnit\Framework\TestCase;
class ScientificTest extends TestCase
{
#[\PHPUnit\Framework\Attributes\DataProvider('providerScientific')]
public function testScientific(string $expectedResult, int $decimals): void
{
$wizard = new Scientific($decimals);
self::assertSame($expectedResult, (string) $wizard);
}
public static function providerScientific(): array
{
return [
['0E+00', 0],
['0.0E+00', 1],
['0.00E+00', 2],
['0.000E+00', 3],
['0E+00', -1],
['0.000000000000000000000000000000E+00', 31],
];
}
#[\PHPUnit\Framework\Attributes\DataProvider('providerScientificLocale')]
public function testScientificLocale(
string $expectedResult,
string $locale
): void {
if (class_exists(NumberFormatter::class) === false) {
self::markTestSkipped('Intl extension is not available');
}
$wizard = new Scientific(2);
$wizard->setLocale($locale);
self::assertSame($expectedResult, (string) $wizard);
}
public static function providerScientificLocale(): array
{
return [
['0.00E+00', 'en'],
['0.00E+00', 'az-AZ'],
['0.00E+00', 'az-Cyrl'],
['0.00E+00', 'az-Cyrl-AZ'],
['0.00E+00', 'az-Latn'],
['0.00E+00', 'az-Latn-AZ'],
];
}
public function testScientificLocaleInvalidFormat(): void
{
if (class_exists(NumberFormatter::class) === false) {
self::markTestSkipped('Intl extension is not available');
}
$locale = 'en-usa';
$this->expectException(Exception::class);
$this->expectExceptionMessage("Invalid locale code '{$locale}'");
$wizard = new Scientific(2);
$wizard->setLocale($locale);
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Style/NumberFormat/Wizard/CurrencyTest.php | tests/PhpSpreadsheetTests/Style/NumberFormat/Wizard/CurrencyTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Style\NumberFormat\Wizard;
use NumberFormatter;
use PhpOffice\PhpSpreadsheet\Exception;
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat\Formatter;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat\Wizard\Accounting;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat\Wizard\Currency;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat\Wizard\CurrencyNegative;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat\Wizard\Number;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
use ReflectionMethod;
class CurrencyTest extends TestCase
{
protected function tearDown(): void
{
StringHelper::setCurrencyCode(null);
StringHelper::setThousandsSeparator(null);
StringHelper::setDecimalSeparator(null);
}
#[DataProvider('providerCurrency')]
public function testCurrency(
string $expectedResultPositive,
string $expectedResultNegative,
string $expectedResultZero,
string $currencyCode,
int $decimals,
bool $thousandsSeparator,
bool $currencySymbolPosition,
bool $currencySymbolSpacing,
CurrencyNegative $negative = CurrencyNegative::minus
): void {
$wizard = new Currency($currencyCode, $decimals, $thousandsSeparator, $currencySymbolPosition, $currencySymbolSpacing, negative: $negative);
self::assertSame($expectedResultPositive, Formatter::toFormattedString(1234.56, $wizard->format()));
self::assertSame($expectedResultNegative, Formatter::toFormattedString(-1234.56, $wizard->format()));
self::assertSame($expectedResultZero, Formatter::toFormattedString(0, $wizard->format()));
}
public static function providerCurrency(): array
{
return [
[' $1235 ', ' -$1235', ' $0 ', '$', 0, Number::WITHOUT_THOUSANDS_SEPARATOR, Currency::LEADING_SYMBOL, Currency::SYMBOL_WITH_SPACING],
[' $1,235 ', ' -$1,235', ' $0 ', '$', 0, Number::WITH_THOUSANDS_SEPARATOR, Currency::LEADING_SYMBOL, Currency::SYMBOL_WITH_SPACING],
[' $1,235 ', ' -$1,235', ' $0 ', '$', 0, Number::WITH_THOUSANDS_SEPARATOR, Currency::LEADING_SYMBOL, Currency::SYMBOL_WITHOUT_SPACING],
[' 1234.56€ ', ' -1234.56€ ', ' 0.00€ ', '€', 2, Number::WITHOUT_THOUSANDS_SEPARATOR, Currency::TRAILING_SYMBOL, Currency::SYMBOL_WITH_SPACING],
[' 1,234.56€ ', ' -1,234.56€ ', ' 0.00€ ', '€', 2, Number::WITH_THOUSANDS_SEPARATOR, Currency::TRAILING_SYMBOL, Currency::SYMBOL_WITH_SPACING],
[' 1234.56€ ', ' -1234.56€ ', ' 0.00€ ', '€', 2, Number::WITHOUT_THOUSANDS_SEPARATOR, Currency::TRAILING_SYMBOL, Currency::SYMBOL_WITHOUT_SPACING],
[' 1234.56€ ', ' (1234.56)€ ', ' 0.00€ ', '€', 2, Number::WITHOUT_THOUSANDS_SEPARATOR, Currency::TRAILING_SYMBOL, Currency::SYMBOL_WITHOUT_SPACING, CurrencyNegative::parentheses],
[' 1234.56 GBP ', ' (1234.56) GBP ', ' 0.00GBP ', 'GBP', 2, Number::WITHOUT_THOUSANDS_SEPARATOR, Currency::TRAILING_SYMBOL, Currency::SYMBOL_WITHOUT_SPACING, CurrencyNegative::parentheses],
];
}
public function testSetNegative(): void
{
$expectedResultNegative = ' (1234.56)€ ';
$currencyCode = '€';
$decimals = 2;
$thousandsSeparator = Number::WITHOUT_THOUSANDS_SEPARATOR;
$currencySymbolPosition = Currency::TRAILING_SYMBOL;
$currencySymbolSpacing = Currency::SYMBOL_WITHOUT_SPACING;
$negative = CurrencyNegative::parentheses;
$wizard = new Currency($currencyCode, $decimals, $thousandsSeparator, $currencySymbolPosition, $currencySymbolSpacing);
$wizard->setNegative($negative);
self::assertSame($expectedResultNegative, Formatter::toFormattedString(-1234.56, $wizard->format()));
}
#[DataProvider('providerCurrencyLocale')]
public function testCurrencyLocale(
string $expectedResult,
string $currencyCode,
string $locale,
?bool $stripRLM = null
): void {
if (class_exists(NumberFormatter::class) === false) {
self::markTestSkipped('Intl extension is not available');
}
$wizard = new Currency($currencyCode);
if ($stripRLM !== null) {
$wizard->setStripLeadingRLM($stripRLM);
}
$wizard->setLocale($locale);
self::assertSame($expectedResult, (string) $wizard);
}
public static function providerCurrencyLocale(): array
{
// \u{a0} is non-breaking space
// \u{200e} is LRM (left-to-right mark)
return [
["[\$€-fy-NL]\u{a0}#,##0.00;[\$€-fy-NL]\u{a0}#,##0.00-", '€', 'fy-NL'], // Trailing negative
["[\$€-nl-NL]\u{a0}#,##0.00;[\$€-nl-NL]\u{a0}-#,##0.00", '€', 'nl-NL'], // Sign between currency and value
["[\$€-nl-BE]\u{a0}#,##0.00;[\$€-nl-BE]\u{a0}-#,##0.00", '€', 'NL-BE'], // Sign between currency and value
["#,##0.00\u{a0}[\$€-fr-BE]", '€', 'fr-be'], // Trailing currency code
["#,##0.00\u{a0}[\$€-el-GR]", '€', 'el-gr'], // Trailing currency code
['[$$-en-CA]#,##0.00', '$', 'en-ca'],
["#,##0.00\u{a0}[\$\$-fr-CA]", '$', 'fr-ca'], // Trailing currency code
['[$¥-ja-JP]#,##0', '¥', 'ja-JP'], // No decimals
["#,##0.000\u{a0}[\$د.ب\u{200e}-ar-BH]", "د.ب\u{200e}", 'ar-BH', true], // 3 decimals
];
}
public function testIcu721(): void
{
if (class_exists(NumberFormatter::class) === false) {
self::markTestSkipped('Intl extension is not available');
}
$currencyCode = "د.ب\u{200e}";
$locale = 'ar-BH';
$wizardFalse = new Currency($currencyCode);
$wizardFalse->setStripLeadingRLM(false);
$wizardFalse->setLocale($locale);
$stringFalse = (string) $wizardFalse;
$wizardTrue = new Currency($currencyCode);
$wizardTrue->setStripLeadingRLM(true);
$wizardTrue->setLocale($locale);
$stringTrue = (string) $wizardTrue;
$version = Accounting::icuVersion();
if ($version < 72.1) {
self::assertSame($stringFalse, $stringTrue);
} else {
self::assertSame("\u{200f}$stringTrue", $stringFalse);
}
}
#[DataProvider('providerCurrencyLocaleNoDecimals')]
public function testCurrencyLocaleNoDecimals(
string $expectedResult,
string $currencyCode,
string $locale,
?bool $stripRLM = null
): void {
if (class_exists(NumberFormatter::class) === false) {
self::markTestSkipped('Intl extension is not available');
}
$wizard = new Currency($currencyCode, 0);
if ($stripRLM !== null) {
$wizard->setStripLeadingRLM($stripRLM);
}
$wizard->setLocale($locale);
self::assertSame($expectedResult, (string) $wizard);
}
public static function providerCurrencyLocaleNoDecimals(): array
{
// \u{a0} is non-breaking space
// \u{200e} is LRM (left-to-right mark)
return [
["[\$€-fy-NL]\u{a0}#,##0;[\$€-fy-NL]\u{a0}#,##0-", '€', 'fy-NL'], // Trailing negative
["[\$€-nl-NL]\u{a0}#,##0;[\$€-nl-NL]\u{a0}-#,##0", '€', 'nl-NL'], // Sign between currency and value
["[\$€-nl-BE]\u{a0}#,##0;[\$€-nl-BE]\u{a0}-#,##0", '€', 'NL-BE'], // Sign between currency and value
["#,##0\u{a0}[\$€-fr-BE]", '€', 'fr-be'], // Trailing currency code
["#,##0\u{a0}[\$€-el-GR]", '€', 'el-gr'], // Trailing currency code
['[$$-en-CA]#,##0', '$', 'en-ca'],
["#,##0\u{a0}[\$\$-fr-CA]", '$', 'fr-ca'], // Trailing currency code
['[$¥-ja-JP]#,##0', '¥', 'ja-JP'], // No decimals to truncate
["#,##0\u{a0}[\$د.ب\u{200e}-ar-BH]", "د.ب\u{200e}", 'ar-BH', true], // 3 decimals truncated to none
];
}
public function testCurrencyLocaleInvalidFormat(): void
{
if (class_exists(NumberFormatter::class) === false) {
self::markTestSkipped('Intl extension is not available');
}
$locale = 'en-usa';
$this->expectException(Exception::class);
$this->expectExceptionMessage("Invalid locale code '{$locale}'");
$wizard = new Currency('€');
$wizard->setLocale($locale);
}
public function testCurrencyLocaleInvalidCode(): void
{
if (class_exists(NumberFormatter::class) === false) {
self::markTestSkipped('Intl extension is not available');
}
$locale = 'nl-GB';
$this->expectException(Exception::class);
$this->expectExceptionMessage("Unable to read locale data for '{$locale}'");
$wizard = new Currency('€');
$wizard->setLocale($locale);
}
public function testLocaleNull3(): void
{
$wizard = new Currency('$', 2);
$reflectionMethod = new ReflectionMethod($wizard, 'formatCurrencyCode');
$result = $reflectionMethod->invokeArgs($wizard, []);
self::assertSame('$', $result);
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Style/NumberFormat/Wizard/AccountingTest.php | tests/PhpSpreadsheetTests/Style/NumberFormat/Wizard/AccountingTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Style\NumberFormat\Wizard;
use NumberFormatter;
use PhpOffice\PhpSpreadsheet\Exception;
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat\Formatter;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat\Wizard\Accounting;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat\Wizard\Currency;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat\Wizard\CurrencyNegative;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat\Wizard\Number;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
use ReflectionMethod;
class AccountingTest extends TestCase
{
protected function tearDown(): void
{
StringHelper::setCurrencyCode(null);
StringHelper::setThousandsSeparator(null);
StringHelper::setDecimalSeparator(null);
}
#[DataProvider('providerAccounting')]
public function testAccounting(
string $expectedResultPositive,
string $expectedResultNegative,
string $expectedResultZero,
string $currencyCode,
int $decimals,
bool $thousandsSeparator,
bool $currencySymbolPosition,
bool $currencySymbolSpacing,
CurrencyNegative $negative = CurrencyNegative::minus
): void {
$wizard = new Accounting($currencyCode, $decimals, $thousandsSeparator, $currencySymbolPosition, $currencySymbolSpacing, negative: $negative);
self::assertSame($expectedResultPositive, Formatter::toFormattedString(1234.56, $wizard->format()));
self::assertSame($expectedResultNegative, Formatter::toFormattedString(-1234.56, $wizard->format()));
self::assertSame($expectedResultZero, Formatter::toFormattedString(0, $wizard->format()));
}
public static function providerAccounting(): array
{
return [
[' $ 1235 ', ' $ (1235)', ' $ - ', '$', 0, Number::WITHOUT_THOUSANDS_SEPARATOR, Currency::LEADING_SYMBOL, Currency::SYMBOL_WITH_SPACING],
[' $ 1,235 ', ' $ (1,235)', ' $ - ', '$', 0, Number::WITH_THOUSANDS_SEPARATOR, Currency::LEADING_SYMBOL, Currency::SYMBOL_WITH_SPACING],
[' $ 1,235 ', ' $ (1,235)', ' $ - ', '$', 0, Number::WITH_THOUSANDS_SEPARATOR, Currency::LEADING_SYMBOL, Currency::SYMBOL_WITHOUT_SPACING],
[' 1234.56 € ', ' (1234.56)€ ', ' - € ', '€', 2, Number::WITHOUT_THOUSANDS_SEPARATOR, Currency::TRAILING_SYMBOL, Currency::SYMBOL_WITH_SPACING],
[' 1,234.56 € ', ' (1,234.56)€ ', ' - € ', '€', 2, Number::WITH_THOUSANDS_SEPARATOR, Currency::TRAILING_SYMBOL, Currency::SYMBOL_WITH_SPACING],
[' 1234.560 € ', ' (1234.560)€ ', ' - € ', '€', 3, Number::WITHOUT_THOUSANDS_SEPARATOR, Currency::TRAILING_SYMBOL, Currency::SYMBOL_WITHOUT_SPACING],
];
}
#[DataProvider('providerAccountingLocale')]
public function testAccountingLocale(
string $expectedResult,
string $currencyCode,
string $locale,
?bool $stripRLM = null
): void {
if (class_exists(NumberFormatter::class) === false) {
self::markTestSkipped('Intl extension is not available');
}
$wizard = new Accounting($currencyCode);
if ($stripRLM !== null) {
$wizard->setStripLeadingRLM($stripRLM);
}
$wizard->setLocale($locale);
self::assertSame($expectedResult, (string) $wizard);
}
public static function providerAccountingLocale(): array
{
// \u{a0} is non-breaking space
// \u{200e} is LRM (left-to-right mark)
return [
["[\$€-fy-NL]\u{a0}#,##0.00;([\$€-fy-NL]\u{a0}#,##0.00)", '€', 'fy-NL'],
["[\$€-nl-NL]\u{a0}#,##0.00;([\$€-nl-NL]\u{a0}#,##0.00)", '€', 'nl-NL'],
["[\$€-nl-BE]\u{a0}#,##0.00;([\$€-nl-BE]\u{a0}#,##0.00)", '€', 'NL-BE'],
["#,##0.00\u{a0}[\$€-fr-BE];(#,##0.00\u{a0}[\$€-fr-BE])", '€', 'fr-be'],
["#,##0.00\u{a0}[\$€-el-GR]", '€', 'el-gr'],
['[$$-en-CA]#,##0.00;([$$-en-CA]#,##0.00)', '$', 'en-ca'],
["#,##0.00\u{a0}[\$\$-fr-CA];(#,##0.00\u{a0}[\$\$-fr-CA])", '$', 'fr-ca'],
['[$¥-ja-JP]#,##0;([$¥-ja-JP]#,##0)', '¥', 'ja-JP'], // No decimals
["#,##0.000\u{a0}[\$د.ب\u{200e}-ar-BH]", "د.ب\u{200e}", 'ar-BH', true], // 3 decimals
];
}
public function testIcu721(): void
{
if (class_exists(NumberFormatter::class) === false) {
self::markTestSkipped('Intl extension is not available');
}
$currencyCode = "د.ب\u{200e}";
$locale = 'ar-BH';
$wizardFalse = new Accounting($currencyCode);
$wizardFalse->setStripLeadingRLM(false);
$wizardFalse->setLocale($locale);
$stringFalse = (string) $wizardFalse;
$wizardTrue = new Accounting($currencyCode);
$wizardTrue->setStripLeadingRLM(true);
$wizardTrue->setLocale($locale);
$stringTrue = (string) $wizardTrue;
$version = Accounting::icuVersion();
if ($version < 72.1) {
self::assertSame($stringFalse, $stringTrue);
} else {
self::assertSame("\u{200f}$stringTrue", $stringFalse);
}
}
#[DataProvider('providerAccountingLocaleNoDecimals')]
public function testAccountingLocaleNoDecimals(
string $expectedResult,
string $currencyCode,
string $locale,
?bool $stripRLM = null
): void {
if (class_exists(NumberFormatter::class) === false) {
self::markTestSkipped('Intl extension is not available');
}
$wizard = new Accounting($currencyCode, 0);
if ($stripRLM !== null) {
$wizard->setStripLeadingRLM($stripRLM);
}
$wizard->setLocale($locale);
self::assertSame($expectedResult, (string) $wizard);
}
public static function providerAccountingLocaleNoDecimals(): array
{
// \u{a0} is non-breaking space
// \u{200e} is LRM (left-to-right mark)
return [
["[\$€-fy-NL]\u{a0}#,##0;([\$€-fy-NL]\u{a0}#,##0)", '€', 'fy-NL'],
["[\$€-nl-NL]\u{a0}#,##0;([\$€-nl-NL]\u{a0}#,##0)", '€', 'nl-NL'],
["[\$€-nl-BE]\u{a0}#,##0;([\$€-nl-BE]\u{a0}#,##0)", '€', 'NL-BE'],
["#,##0\u{a0}[\$€-fr-BE];(#,##0\u{a0}[\$€-fr-BE])", '€', 'fr-be'],
["#,##0\u{a0}[\$€-el-GR]", '€', 'el-gr'],
['[$$-en-CA]#,##0;([$$-en-CA]#,##0)', '$', 'en-ca'],
["#,##0\u{a0}[\$\$-fr-CA];(#,##0\u{a0}[\$\$-fr-CA])", '$', 'fr-ca'],
['[$¥-ja-JP]#,##0;([$¥-ja-JP]#,##0)', '¥', 'ja-JP'], // No decimals to truncate
["#,##0\u{a0}[\$د.ب\u{200e}-ar-BH]", "د.ب\u{200e}", 'ar-BH', true], // 3 decimals truncated to none
];
}
public function testAccountingLocaleInvalidFormat(): void
{
if (class_exists(NumberFormatter::class) === false) {
self::markTestSkipped('Intl extension is not available');
}
$locale = 'en-usa';
$this->expectException(Exception::class);
$this->expectExceptionMessage("Invalid locale code '{$locale}'");
$wizard = new Accounting('€');
$wizard->setLocale($locale);
}
public function testAccountingLocaleInvalidCode(): void
{
if (class_exists(NumberFormatter::class) === false) {
self::markTestSkipped('Intl extension is not available');
}
$locale = 'nl-GB';
$this->expectException(Exception::class);
$this->expectExceptionMessage("Unable to read locale data for '{$locale}'");
$wizard = new Accounting('€');
$wizard->setLocale($locale);
}
public function testLocaleNull2(): void
{
$wizard = new Accounting('$', 2);
$reflectionMethod = new ReflectionMethod($wizard, 'formatCurrencyCode');
$result = $reflectionMethod->invokeArgs($wizard, []);
self::assertSame('$*', $result);
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Style/NumberFormat/Wizard/NumberBase2.php | tests/PhpSpreadsheetTests/Style/NumberFormat/Wizard/NumberBase2.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Style\NumberFormat\Wizard;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat\Wizard\NumberBase;
class NumberBase2 extends NumberBase
{
protected function getLocaleFormat(): string
{
return 'none';
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Style/NumberFormat/Wizard/DateTest.php | tests/PhpSpreadsheetTests/Style/NumberFormat/Wizard/DateTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Style\NumberFormat\Wizard;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat\Wizard\Date;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
class DateTest extends TestCase
{
/**
* @param null|array<?string>|string $separators
* @param array<?string> $formatBlocks
*/
#[DataProvider('providerDate')]
public function testDate(string $expectedResult, string|array|null $separators = null, array $formatBlocks = []): void
{
$wizard = new Date($separators, ...$formatBlocks);
self::assertSame($expectedResult, (string) $wizard);
}
public static function providerDate(): array
{
return [
['yyyy-mm-dd', Date::SEPARATOR_DASH, [Date::YEAR_FULL, Date::MONTH_NUMBER_LONG, Date::DAY_NUMBER_LONG]],
['mm/dd/yyyy', Date::SEPARATOR_SLASH, [Date::MONTH_NUMBER_LONG, Date::DAY_NUMBER_LONG, Date::YEAR_FULL]],
['dd.mm.yyyy', Date::SEPARATOR_DOT, [Date::DAY_NUMBER_LONG, Date::MONTH_NUMBER_LONG, Date::YEAR_FULL]],
['dd-mmm-yyyy', Date::SEPARATOR_DASH, [Date::DAY_NUMBER_LONG, Date::MONTH_NAME_SHORT, Date::YEAR_FULL]],
['dd-mmm yyyy', [Date::SEPARATOR_DASH, Date::SEPARATOR_SPACE], [Date::DAY_NUMBER_LONG, Date::MONTH_NAME_SHORT, Date::YEAR_FULL]],
['dddd dd.mm.yyyy', [Date::SEPARATOR_SPACE, Date::SEPARATOR_DOT], [Date::WEEKDAY_NAME_LONG, Date::DAY_NUMBER_LONG, Date::MONTH_NUMBER_LONG, Date::YEAR_FULL]],
['dd-mm "in the year" yyyy', [Date::SEPARATOR_DASH, Date::SEPARATOR_SPACE], [Date::DAY_NUMBER_LONG, Date::MONTH_NUMBER_LONG, 'in the year', Date::YEAR_FULL]],
["yyyy-mm-dd\u{a0}(ddd)", [Date::SEPARATOR_DASH, Date::SEPARATOR_DASH, Date::SEPARATOR_SPACE_NONBREAKING, null], [Date::YEAR_FULL, Date::MONTH_NUMBER_LONG, Date::DAY_NUMBER_LONG, '(', Date::WEEKDAY_NAME_SHORT, ')']],
['yyyy-mm-dd', null, [Date::YEAR_FULL, Date::MONTH_NUMBER_LONG, Date::DAY_NUMBER_LONG]],
['yyyy-mm-dd'],
];
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Style/NumberFormat/Wizard/PercentageTest.php | tests/PhpSpreadsheetTests/Style/NumberFormat/Wizard/PercentageTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Style\NumberFormat\Wizard;
use NumberFormatter;
use PhpOffice\PhpSpreadsheet\Exception;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat\Wizard\Percentage;
use PHPUnit\Framework\TestCase;
class PercentageTest extends TestCase
{
#[\PHPUnit\Framework\Attributes\DataProvider('providerPercentage')]
public function testPercentage(string $expectedResult, int $decimals): void
{
$wizard = new Percentage($decimals);
self::assertSame($expectedResult, (string) $wizard);
}
public static function providerPercentage(): array
{
return [
['0%', 0],
['0.0%', 1],
['0.00%', 2],
['0.000%', 3],
['0%', -1],
['0.000000000000000000000000000000%', 31],
];
}
#[\PHPUnit\Framework\Attributes\DataProvider('providerPercentageLocale')]
public function testPercentageLocale(
string $expectedResult,
string $locale
): void {
if (class_exists(NumberFormatter::class) === false) {
self::markTestSkipped('Intl extension is not available');
}
$wizard = new Percentage(2);
$wizard->setLocale($locale);
self::assertSame($expectedResult, (string) $wizard);
}
public static function providerPercentageLocale(): array
{
return [
['#,##0.00%', 'fy-NL'],
['#,##0.00%', 'nl-NL'],
['#,##0.00%', 'NL-BE'],
["#,##0.00\u{a0}%", 'fr-be'],
['#,##0.00%', 'el-gr'],
['#,##0.00%', 'en-ca'],
["#,##0.00\u{a0}%", 'fr-ca'],
];
}
public function testPercentageLocaleInvalidFormat(): void
{
if (class_exists(NumberFormatter::class) === false) {
self::markTestSkipped('Intl extension is not available');
}
$locale = 'en-usa';
$this->expectException(Exception::class);
$this->expectExceptionMessage("Invalid locale code '{$locale}'");
$wizard = new Percentage(2);
$wizard->setLocale($locale);
}
public function testPercentageLocaleInvalidCode(): void
{
if (class_exists(NumberFormatter::class) === false) {
self::markTestSkipped('Intl extension is not available');
}
$locale = 'nl-GB';
$this->expectException(Exception::class);
$this->expectExceptionMessage("Unable to read locale data for '{$locale}'");
$wizard = new Percentage(2);
$wizard->setLocale($locale);
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Style/NumberFormat/Wizard/NumberTest.php | tests/PhpSpreadsheetTests/Style/NumberFormat/Wizard/NumberTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Style\NumberFormat\Wizard;
use NumberFormatter;
use PhpOffice\PhpSpreadsheet\Exception;
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat\Wizard\Number;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
class NumberTest extends TestCase
{
protected function tearDown(): void
{
StringHelper::setCurrencyCode(null);
StringHelper::setThousandsSeparator(null);
StringHelper::setDecimalSeparator(null);
}
#[DataProvider('providerNumber')]
public function testNumber(string $expectedResult, int $decimals, bool $thousandsSeparator): void
{
$wizard = new Number($decimals, $thousandsSeparator);
self::assertSame($expectedResult, (string) $wizard);
}
public static function providerNumber(): array
{
return [
['0', 0, Number::WITHOUT_THOUSANDS_SEPARATOR],
['#,##0', 0, Number::WITH_THOUSANDS_SEPARATOR],
['0.0', 1, Number::WITHOUT_THOUSANDS_SEPARATOR],
['#,##0.0', 1, Number::WITH_THOUSANDS_SEPARATOR],
['0.00', 2, Number::WITHOUT_THOUSANDS_SEPARATOR],
['#,##0.00', 2, Number::WITH_THOUSANDS_SEPARATOR],
];
}
#[DataProvider('providerNumberLocale')]
public function testNumberLocale(
string $expectedResult,
string $locale
): void {
if (class_exists(NumberFormatter::class) === false) {
self::markTestSkipped('Intl extension is not available');
}
$wizard = new Number(2);
$wizard->setLocale($locale);
self::assertSame($expectedResult, (string) $wizard);
}
public static function providerNumberLocale(): array
{
return [
['#,##0.00', 'en-us'],
];
}
public function testNumberLocaleInvalidFormat(): void
{
if (class_exists(NumberFormatter::class) === false) {
self::markTestSkipped('Intl extension is not available');
}
$locale = 'en-usa';
$this->expectException(Exception::class);
$this->expectExceptionMessage("Invalid locale code '{$locale}'");
$wizard = new Number(2);
$wizard->setLocale($locale);
}
public function testNonOverriddenFormat(): void
{
$wizard = new NumberBase2();
self::assertSame('General', $wizard->format());
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Style/NumberFormat/Wizard/TimeTest.php | tests/PhpSpreadsheetTests/Style/NumberFormat/Wizard/TimeTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Style\NumberFormat\Wizard;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat\Wizard\Time;
use PHPUnit\Framework\TestCase;
class TimeTest extends TestCase
{
/**
* @param null|string|string[] $separators
* @param string[] $formatBlocks
*/
#[\PHPUnit\Framework\Attributes\DataProvider('providerTime')]
public function testTime(string $expectedResult, string|array|null $separators = null, array $formatBlocks = []): void
{
$wizard = new Time($separators, ...$formatBlocks);
self::assertSame($expectedResult, (string) $wizard);
}
public static function providerTime(): array
{
return [
['hh:mm:ss', Time::SEPARATOR_COLON, [Time::HOURS_LONG, Time::MINUTES_LONG, Time::SECONDS_LONG]],
['hh:mm', Time::SEPARATOR_COLON, [Time::HOURS_LONG, Time::MINUTES_LONG]],
["hh:mm\u{a0}AM/PM", [Time::SEPARATOR_COLON, Time::SEPARATOR_SPACE_NONBREAKING], [Time::HOURS_LONG, Time::MINUTES_LONG, Time::MORNING_AFTERNOON]],
['h "hours and" m "minutes past midnight"', Time::SEPARATOR_SPACE, [Time::HOURS_SHORT, 'hours and', Time::MINUTES_SHORT, 'minutes past midnight']],
['hh:mm:ss', null, [Time::HOURS_LONG, Time::MINUTES_LONG, Time::SECONDS_LONG]],
['hh:mm:ss'],
];
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Calculation/ArrayFormulaTest.php | tests/PhpSpreadsheetTests/Calculation/ArrayFormulaTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Calculation;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
class ArrayFormulaTest extends TestCase
{
#[DataProvider('providerArrayFormulae')]
public function testArrayFormula(string $formula, mixed $expectedResult): void
{
$result = Calculation::getInstance()->calculateFormula($formula);
self::assertEquals($expectedResult, $result);
}
public static function providerArrayFormulae(): array
{
return [
[
'=MAX(ABS({-3, 4, -2; 6, -3, -12}))',
12,
],
'unary operator applied to function' => [
'=MAX(-ABS({-3, 4, -2; 6, -3, -12}))',
-2,
],
[
'=SUM(SEQUENCE(3,3,0,1))',
36,
],
[
'=IFERROR({5/2, 5/0}, MAX(ABS({-2,4,-6})))',
[[2.5, 6]],
],
[
'=MAX(IFERROR({5/2, 5/0}, 2.1))',
2.5,
],
[
'=IF(FALSE,{1,2,3},{4,5,6})',
[[4, 5, 6]],
],
[
'=IFS(FALSE, {1,2,3}, TRUE, {4,5,6})',
[[4, 5, 6]],
],
'some invalid values' => [
'=ABS({1,-2,"X3"; "B4",5,6})',
[[1, 2, '#VALUE!'], ['#VALUE!', 5, 6]],
],
'some invalid values with unary minus' => [
'=-({1,-2,"X3"; "B4",5,6})',
[[-1, 2, '#VALUE!'], ['#VALUE!', -5, -6]],
],
];
}
public function testArrayFormulaUsingCells(): void
{
$spreadsheet = new Spreadsheet();
$calculation = Calculation::getInstance($spreadsheet);
$calculation->setInstanceArrayReturnType(
Calculation::RETURN_ARRAY_AS_VALUE
);
$sheet = $spreadsheet->getActiveSheet();
$sheet->getCell('A4')->setValue(-3);
$sheet->getCell('B4')->setValue(4);
$sheet->getCell('C4')->setValue(-2);
$sheet->getCell('A5')->setValue(6);
$sheet->getCell('B5')->setValue(-3);
$sheet->getCell('C5')->setValue(-12);
$sheet->getCell('E4')->setValue('=MAX(-ABS(A4:C5))');
self::assertSame(-2, $sheet->getCell('E4')->getCalculatedValue());
$sheet->getCell('C4')->setValue('XYZ');
$sheet->getCell('F4')->setValue('=MAX(-ABS(A4:C5))');
self::assertSame('#VALUE!', $sheet->getCell('F4')->getCalculatedValue());
$sheet->getCell('G4')->setValue('=-C4:E4');
self::assertSame('#VALUE!', $sheet->getCell('G4')->getCalculatedValue());
$sheet->getCell('H4')->setValue('=-A4:B4');
self::assertSame(3, $sheet->getCell('H4')->getCalculatedValue());
$sheet->getCell('I4')->setValue('=25%');
self::assertEqualsWithDelta(0.25, $sheet->getCell('I4')->getCalculatedValue(), 1.0E-8);
$spreadsheet->disconnectWorksheets();
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Calculation/FormulaParserTest.php | tests/PhpSpreadsheetTests/Calculation/FormulaParserTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Calculation;
use PhpOffice\PhpSpreadsheet\Calculation\Exception as CalcException;
use PhpOffice\PhpSpreadsheet\Calculation\FormulaParser;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
class FormulaParserTest extends TestCase
{
public function testNullFormula(): void
{
$this->expectException(CalcException::class);
$this->expectExceptionMessage('Invalid parameter passed: formula');
new FormulaParser(null);
}
public function testInvalidTokenId(): void
{
$this->expectException(CalcException::class);
$this->expectExceptionMessage('Token with id 1 does not exist.');
$result = new FormulaParser('=2');
$result->getToken(1);
}
public function testNoFormula(): void
{
$result = new FormulaParser('');
self::assertSame(0, $result->getTokenCount());
}
/** @param mixed[][] $expectedResult */
#[DataProvider('providerFormulaParser')]
public function testFormulaParser(string $formula, array $expectedResult): void
{
$formula = "=$formula";
$result = new FormulaParser($formula);
self::assertSame($formula, $result->getFormula());
self::assertSame(count($expectedResult), $result->getTokenCount());
$tokens = $result->getTokens();
$token0 = $result->getToken(0);
self::assertSame($tokens[0], $token0);
$idx = -1;
foreach ($expectedResult as $resultArray) {
++$idx;
self::assertSame($resultArray[0], $tokens[$idx]->getValue());
self::assertSame($resultArray[1], $tokens[$idx]->getTokenType());
self::assertSame($resultArray[2], $tokens[$idx]->getTokenSubType());
}
}
public static function providerFormulaParser(): array
{
return [
['5%*(2+(-3))+A3',
[
['5', 'Operand', 'Number'],
['%', 'OperatorPostfix', 'Nothing'],
['*', 'OperatorInfix', 'Math'],
['', 'Subexpression', 'Start'],
['2', 'Operand', 'Number'],
['+', 'OperatorInfix', 'Math'],
['', 'Subexpression', 'Start'],
['-', 'OperatorPrefix', 'Nothing'],
['3', 'Operand', 'Number'],
['', 'Subexpression', 'Stop'],
['', 'Subexpression', 'Stop'],
['+', 'OperatorInfix', 'Math'],
['A3', 'Operand', 'Range'],
],
],
['"hello" & "goodbye"',
[
['hello', 'Operand', 'Text'],
['&', 'OperatorInfix', 'Concatenation'],
['goodbye', 'Operand', 'Text'],
],
],
['+1.23E5',
[
['1.23E5', 'Operand', 'Number'],
],
],
['#DIV/0!',
[
['#DIV/0!', 'Operand', 'Error'],
],
],
['"HE""LLO"',
[
['HE"LLO', 'Operand', 'Text'],
],
],
['MINVERSE({3,1;4,2})',
[
['MINVERSE', 'Function', 'Start'],
['ARRAY', 'Function', 'Start'],
['ARRAYROW', 'Function', 'Start'],
['3', 'Operand', 'Number'],
[',', 'OperatorInfix', 'Union'],
['1', 'Operand', 'Number'],
['', 'Function', 'Stop'],
[',', 'Argument', 'Nothing'],
['ARRAYROW', 'Function', 'Start'],
['4', 'Operand', 'Number'],
[',', 'OperatorInfix', 'Union'],
['2', 'Operand', 'Number'],
['', 'Function', 'Stop'],
['', 'Function', 'Stop'],
['', 'Function', 'Stop'],
],
],
['[1,1]*5',
[
['[1,1]', 'Operand', 'Range'],
['*', 'OperatorInfix', 'Math'],
['5', 'Operand', 'Number'],
],
],
['IF(A1>=0,2,3)',
[
['IF', 'Function', 'Start'],
['A1', 'Operand', 'Range'],
['>=', 'OperatorInfix', 'Logical'],
['0', 'Operand', 'Number'],
[',', 'OperatorInfix', 'Union'],
['2', 'Operand', 'Number'],
[',', 'OperatorInfix', 'Union'],
['3', 'Operand', 'Number'],
['', 'Function', 'Stop'],
],
],
["'Worksheet'!A1:A3",
[
['Worksheet!A1:A3', 'Operand', 'Range'],
],
],
["'Worksh''eet'!A1:A3",
[
['Worksh\'eet!A1:A3', 'Operand', 'Range'],
],
],
['true',
[
['true', 'Operand', 'Logical'],
],
],
];
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Calculation/ArrayTest.php | tests/PhpSpreadsheetTests/Calculation/ArrayTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Calculation;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PhpOffice\PhpSpreadsheet\Calculation\Functions;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use PHPUnit\Framework\TestCase;
class ArrayTest extends TestCase
{
private string $originalArrayReturnType;
protected function setUp(): void
{
$this->originalArrayReturnType = Calculation::getArrayReturnType();
}
protected function tearDown(): void
{
Calculation::setArrayReturnType($this->originalArrayReturnType);
}
private function setupMatrix(Worksheet $sheet): void
{
$sheet->setCellValue('A1', 2.0);
$sheet->setCellValue('A2', 0.0);
$sheet->setCellValue('B1', 0.0);
$sheet->setCellValue('B2', 1.0);
}
public function testMultiDimensionalArrayIsFlattened(): void
{
$array = [
0 => [
0 => [
32 => [
'B' => 'PHP',
],
],
],
1 => [
0 => [
32 => [
'C' => 'Spreadsheet',
],
],
],
];
$values = Functions::flattenArray($array);
self::assertCount(2, $values);
self::assertSame('PHP', $values[0]);
self::assertSame('Spreadsheet', $values[1]);
}
public function testSetArrayReturnTypeWithValidValue(): void
{
self::assertTrue(Calculation::setArrayReturnType(Calculation::RETURN_ARRAY_AS_ARRAY));
self::assertSame(Calculation::RETURN_ARRAY_AS_ARRAY, Calculation::getArrayReturnType());
}
public function testSetArrayReturnTypeWithInvalidValue(): void
{
$originalType = Calculation::getArrayReturnType();
self::assertFalse(Calculation::setArrayReturnType('xxx'));
self::assertSame($originalType, Calculation::getArrayReturnType());
}
public function testInstanceArrayReturnTypeInheritsFromStatic(): void
{
Calculation::setArrayReturnType(Calculation::RETURN_ARRAY_AS_ARRAY);
$calculation = new Calculation();
self::assertSame(Calculation::RETURN_ARRAY_AS_ARRAY, $calculation->getInstanceArrayReturnType());
}
public function testInstanceArrayReturnTypeCanBeOverridden(): void
{
Calculation::setArrayReturnType(Calculation::RETURN_ARRAY_AS_ARRAY);
$calculation = new Calculation();
self::assertTrue($calculation->setInstanceArrayReturnType(Calculation::RETURN_ARRAY_AS_ERROR));
self::assertSame(Calculation::RETURN_ARRAY_AS_ARRAY, Calculation::getArrayReturnType());
self::assertSame(Calculation::RETURN_ARRAY_AS_ERROR, $calculation->getInstanceArrayReturnType());
}
public function testSetInstanceArrayReturnTypeWithInvalidValue(): void
{
$calculation = new Calculation();
self::assertFalse($calculation->setInstanceArrayReturnType('xxx'));
}
public function testReturnTypeAsError(): void
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$calculation = Calculation::getInstance($spreadsheet);
$this->setupMatrix($sheet);
$sheet->setCellValue('D1', '=MINVERSE(A1:B2)');
$calculation->setInstanceArrayReturnType(Calculation::RETURN_ARRAY_AS_ERROR);
self::assertSame('#VALUE!', $sheet->getCell('D1')->getCalculatedValue());
$spreadsheet->disconnectWorksheets();
}
public function testReturnTypeAsValue(): void
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$calculation = Calculation::getInstance($spreadsheet);
$this->setupMatrix($sheet);
$sheet->setCellValue('D1', '=MINVERSE(A1:B2)');
$calculation->setInstanceArrayReturnType(Calculation::RETURN_ARRAY_AS_VALUE);
self::assertSame(0.5, $sheet->getCell('D1')->getCalculatedValue());
$spreadsheet->disconnectWorksheets();
}
public function testReturnTypeAsArray(): void
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$calculation = Calculation::getInstance($spreadsheet);
$this->setupMatrix($sheet);
$sheet->setCellValue('D1', '=MINVERSE(A1:B2)');
$calculation->setInstanceArrayReturnType(Calculation::RETURN_ARRAY_AS_ARRAY);
self::assertSame([[0.5, 0.0], [0.0, 1.0]], $sheet->getCell('D1')->getCalculatedValue());
$spreadsheet->disconnectWorksheets();
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Calculation/MergedCellTest.php | tests/PhpSpreadsheetTests/Calculation/MergedCellTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Calculation;
use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError;
use PhpOffice\PhpSpreadsheet\Exception as SpreadException;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use PHPUnit\Framework\TestCase;
class MergedCellTest extends TestCase
{
#[\PHPUnit\Framework\Attributes\DataProvider('providerWorksheetFormulaeColumns')]
public function testMergedCellColumns(string $formula, mixed $expectedResult): void
{
$spreadSheet = new Spreadsheet();
$dataSheet = $spreadSheet->getActiveSheet();
$dataSheet->setCellValue('A5', 3.3);
$dataSheet->setCellValue('A3', 3.3);
$dataSheet->setCellValue('A2', 2.2);
$dataSheet->setCellValue('A1', 1.1);
$dataSheet->setCellValue('B2', 2.2);
$dataSheet->setCellValue('B1', 1.1);
$dataSheet->setCellValue('C2', 4.4);
$dataSheet->setCellValue('C1', 3.3);
$dataSheet->mergeCells('A2:A4');
$dataSheet->mergeCells('B:B');
$worksheet = $spreadSheet->getActiveSheet();
$worksheet->setCellValue('A7', $formula);
$result = $worksheet->getCell('A7')->getCalculatedValue();
self::assertSame($expectedResult, $result);
$spreadSheet->disconnectWorksheets();
}
public static function providerWorksheetFormulaeColumns(): array
{
return [
['=SUM(A1:A5)', 6.6],
['=COUNT(A1:A5)', 3],
['=COUNTA(A1:A5)', 3],
['=SUM(A3:A4)', 0],
['=A2+A3+A4', 2.2],
['=A2/A3', ExcelError::DIV0()],
['=SUM(B1:C2)', 8.8],
];
}
#[\PHPUnit\Framework\Attributes\DataProvider('providerWorksheetFormulaeRows')]
public function testMergedCellRows(string $formula, mixed $expectedResult): void
{
$spreadSheet = new Spreadsheet();
$dataSheet = $spreadSheet->getActiveSheet();
$dataSheet->setCellValue('A1', 1.1);
$dataSheet->setCellValue('B1', 2.2);
$dataSheet->setCellValue('C1', 3.3);
$dataSheet->setCellValue('E1', 3.3);
$dataSheet->setCellValue('A2', 1.1);
$dataSheet->setCellValue('B2', 2.2);
$dataSheet->setCellValue('A3', 3.3);
$dataSheet->setCellValue('B3', 4.4);
$dataSheet->mergeCells('B1:D1');
$dataSheet->mergeCells('A2:B2');
$worksheet = $spreadSheet->getActiveSheet();
$worksheet->setCellValue('A7', $formula);
$result = $worksheet->getCell('A7')->getCalculatedValue();
self::assertSame($expectedResult, $result);
$spreadSheet->disconnectWorksheets();
}
public static function providerWorksheetFormulaeRows(): array
{
return [
['=SUM(A1:E1)', 6.6],
['=COUNT(A1:E1)', 3],
['=COUNTA(A1:E1)', 3],
['=SUM(C1:D1)', 0],
['=B1+C1+D1', 2.2],
['=B1/C1', ExcelError::DIV0()],
['=SUM(A2:B3)', 8.8],
];
}
private function setBadRange(Worksheet $sheet, string $range): void
{
try {
$sheet->mergeCells($range);
self::fail("Expected invalid merge range $range");
} catch (SpreadException $e) {
self::assertSame('Merge must be on a valid range of cells.', $e->getMessage());
}
}
public function testMergedBadRange(): void
{
$spreadSheet = new Spreadsheet();
$dataSheet = $spreadSheet->getActiveSheet();
// TODO - Reinstate full validation and disallow single cell merging for version 2.0
// $this->setBadRange($dataSheet, 'B1');
$this->setBadRange($dataSheet, 'Invalid');
$this->setBadRange($dataSheet, '1');
$this->setBadRange($dataSheet, 'C');
$this->setBadRange($dataSheet, 'B1:C');
$this->setBadRange($dataSheet, 'B:C2');
$spreadSheet->disconnectWorksheets();
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Calculation/MissingArgumentsTest.php | tests/PhpSpreadsheetTests/Calculation/MissingArgumentsTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Calculation;
use PhpOffice\PhpSpreadsheet\Calculation\Exception as CalcExp;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PHPUnit\Framework\TestCase;
class MissingArgumentsTest extends TestCase
{
#[\PHPUnit\Framework\Attributes\DataProvider('providerMissingArguments')]
public function testMissingArguments(mixed $expected, string $formula): void
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->getCell('A1')->setValue($formula);
$sheet->getCell('B1')->setValue(1);
try {
self::assertSame($expected, $sheet->getCell('A1')->getCalculatedValue());
} catch (CalcExp $e) {
self::assertSame('exception', $expected);
}
$spreadsheet->disconnectWorksheets();
}
public static function providerMissingArguments(): array
{
return [
'argument missing at end' => [0, '=min(3,2,)'],
'argument missing at beginning' => [0, '=mina(,3,2)'],
'argument missing in middle' => [0, '=min(3,,2)'],
'missing argument is not result' => [-2, '=min(3,-2,)'],
'max with missing argument' => [0, '=max(-3,-2,)'],
'maxa with missing argument' => [0, '=maxa(-3,-2,)'],
'max with null cell' => [-2, '=max(-3,-2,Z1)'],
'min with null cell' => [2, '=min(3,2,Z1)'],
'product ignores null argument' => [6.0, '=product(3,2,)'],
'embedded function' => [5, '=sum(3,2,min(3,2,))'],
'unaffected embedded function' => [8, '=sum(3,2,max(3,2,))'],
'if true missing at end' => [0, '=if(b1=1,min(3,2,),product(3,2,))'],
'if false missing at end' => [6.0, '=if(b1=2,min(3,2,),product(3,2,))'],
'if true missing in middle' => [0, '=if(b1=1,min(3,,2),product(3,,2))'],
'if false missing in middle' => [6.0, '=if(b1=2,min(3,,2),product(3,,2))'],
'if true missing at beginning' => [0, '=if(b1=1,min(,3,2),product(,3,2))'],
'if false missing at beginning' => [6.0, '=if(b1=2,min(,3,2),product(,3,2))'],
'if true nothing missing' => [2, '=if(b1=1,min(3,2),product(3,2))'],
'if false nothing missing' => [6.0, '=if(b1=2,min(3,2),product(3,2))'],
'if true empty arg' => [0, '=if(b1=1,)'],
'if true omitted args' => ['exception', '=if(b1=1)'],
'if true missing arg' => [0, '=if(b1=1,,6)'],
'if false missing arg' => [0, '=if(b1=2,6,)'],
'if false omitted arg' => [false, '=if(b1=2,6)'],
'multiple ifs and omissions' => [0, '=IF(0<9,,IF(0=0,,1))'],
];
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Calculation/RefErrorTest.php | tests/PhpSpreadsheetTests/Calculation/RefErrorTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Calculation;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PHPUnit\Framework\TestCase;
class RefErrorTest extends TestCase
{
#[\PHPUnit\Framework\Attributes\DataProvider('providerRefError')]
public function testRefError(mixed $expected, string $formula): void
{
$spreadsheet = new Spreadsheet();
$sheet1 = $spreadsheet->getActiveSheet();
$sheet1->setTitle('Sheet1');
$sheet2 = $spreadsheet->createSheet();
$sheet2->setTitle('Sheet2');
$sheet2->getCell('A1')->setValue(5);
$sheet1->getCell('A1')->setValue(9);
$sheet1->getCell('A2')->setValue(2);
$sheet1->getCell('A3')->setValue(4);
$sheet1->getCell('A4')->setValue(6);
$sheet1->getCell('A5')->setValue(7);
$sheet1->getRowDimension(5)->setVisible(false);
$sheet1->getCell('B1')->setValue('=1/0');
$sheet1->getCell('C1')->setValue('=Sheet99!A1');
$sheet1->getCell('C2')->setValue('=Sheet2!A1');
$sheet1->getCell('C3')->setValue('=Sheet2!A2');
$sheet1->getCell('H1')->setValue($formula);
self::assertSame($expected, $sheet1->getCell('H1')->getCalculatedValue());
$spreadsheet->disconnectWorksheets();
}
public static function providerRefError(): array
{
return [
'Subtotal9 Ok' => [12, '=SUBTOTAL(A1,A2:A4)'],
'Subtotal9 REF' => ['#REF!', '=SUBTOTAL(A1,A2:A4,C1)'],
'Subtotal9 with literal and cells' => [111, '=SUBTOTAL(A1,A2:A4,99)'],
'Subtotal9 with literal no rows hidden' => [111, '=SUBTOTAL(109,A2:A4,99)'],
'Subtotal9 with literal ignoring hidden row' => [111, '=SUBTOTAL(109,A2:A5,99)'],
'Subtotal9 with literal using hidden row' => [118, '=SUBTOTAL(9,A2:A5,99)'],
'Subtotal9 with Null same sheet' => [12, '=SUBTOTAL(A1,A2:A4,A99)'],
'Subtotal9 with Null Different sheet' => [12, '=SUBTOTAL(A1,A2:A4,C3)'],
'Subtotal9 with NonNull Different sheet' => [17, '=SUBTOTAL(A1,A2:A4,C2)'],
'Product DIV0' => ['#DIV/0!', '=PRODUCT(2, 3, B1)'],
'Sqrt REF' => ['#REF!', '=SQRT(C1)'],
'Sum NUM' => ['#NUM!', '=SUM(SQRT(-1), A2:A4)'],
'Sum with literal and cells' => [111, '=SUM(A2:A4, 99)'],
'Sum REF' => ['#REF!', '=SUM(A2:A4, C1)'],
'Tan DIV0' => ['#DIV/0!', '=TAN(B1)'],
];
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Calculation/StructuredReferenceFormulaTest.php | tests/PhpSpreadsheetTests/Calculation/StructuredReferenceFormulaTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Calculation;
use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Worksheet\Table;
use PHPUnit\Framework\TestCase;
class StructuredReferenceFormulaTest extends TestCase
{
#[\PHPUnit\Framework\Attributes\DataProvider('structuredReferenceProvider')]
public function testStructuredReferences(float $expectedValue, string $cellAddress): void
{
$inputFileType = 'Xlsx';
$inputFileName = __DIR__ . '/../../data/Calculation/TableFormulae.xlsx';
$reader = IOFactory::createReader($inputFileType);
$spreadsheet = $reader->load($inputFileName);
$calculatedCellValue = $spreadsheet->getActiveSheet()->getCell($cellAddress)->getCalculatedValue();
self::assertEqualsWithDelta($expectedValue, $calculatedCellValue, 1.0e-14, "Failed calculation for cell {$cellAddress}");
}
public function testStructuredReferenceHiddenHeaders(): void
{
$inputFileType = 'Xlsx';
$inputFileName = __DIR__ . '/../../data/Calculation/TableFormulae.xlsx';
$reader = IOFactory::createReader($inputFileType);
$spreadsheet = $reader->load($inputFileName);
/** @var Table $table */
$table = $spreadsheet->getActiveSheet()->getTableByName('DeptSales');
$cellAddress = 'G8';
$spreadsheet->getActiveSheet()->getCell($cellAddress)->setValue('=DeptSales[[#Headers][Region]]');
$result = $spreadsheet->getActiveSheet()->getCell($cellAddress)->getCalculatedValue();
self::assertSame('Region', $result);
$spreadsheet->getCalculationEngine()->flushInstance();
$table->setShowHeaderRow(false);
$result = $spreadsheet->getActiveSheet()->getCell($cellAddress)->getCalculatedValue();
self::assertSame(ExcelError::REF(), $result);
}
public function testStructuredReferenceInvalidColumn(): void
{
$inputFileType = 'Xlsx';
$inputFileName = __DIR__ . '/../../data/Calculation/TableFormulae.xlsx';
$reader = IOFactory::createReader($inputFileType);
$spreadsheet = $reader->load($inputFileName);
$cellAddress = 'E2';
$spreadsheet->getActiveSheet()->getCell($cellAddress)->setValue('=[@Sales Amount]*[@[%age Commission]]');
$result = $spreadsheet->getActiveSheet()->getCell($cellAddress)->getCalculatedValue();
self::assertSame(ExcelError::REF(), $result);
}
public static function structuredReferenceProvider(): array
{
return [
[26.0, 'E2'],
[99.0, 'E3'],
[141.0, 'E4'],
[49.2, 'E5'],
[120.0, 'E6'],
[135.0, 'E7'],
[570.2, 'E8'],
[3970.0, 'C8'],
];
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Calculation/CustomFunction.php | tests/PhpSpreadsheetTests/Calculation/CustomFunction.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Calculation;
use PhpOffice\PhpSpreadsheet\Calculation\Exception as CalcException;
use PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Helpers;
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
class CustomFunction
{
public static function fourthPower(mixed $number): float|int|string
{
try {
$number = Helpers::validateNumericNullBool($number);
} catch (CalcException $e) {
return $e->getMessage();
}
return $number ** 4;
}
/**
* ASC.
* Converts full-width (double-byte) characters to half-width (single-byte) characters.
* There are many difficulties with implementing this into PhpSpreadsheet.
*/
public static function ASC(mixed $stringValue): string
{
/*if (is_array($stringValue)) {
return self::evaluateSingleArgumentArray([self::class, __FUNCTION__], $stringValue);
}*/
$stringValue = StringHelper::convertToString($stringValue, convertBool: true);
if (function_exists('mb_convert_kana')) {
return mb_convert_kana($stringValue, 'a', 'UTF-8');
}
// Fallback if mb_convert_kana is not available.
// PhpSpreadsheet heavily relies on mbstring, so this is more of a theoretical fallback.
// A comprehensive manual conversion is extensive.
return $stringValue;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Calculation/Issue4451Test.php | tests/PhpSpreadsheetTests/Calculation/Issue4451Test.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Calculation;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PHPUnit\Framework\TestCase;
use ReflectionMethod;
class Issue4451Test extends TestCase
{
public static function testReflectExtend1(): void
{
// Sample matrices to test with
$matrix1 = [[1], [3]];
$matrix2 = [[5], [8], [11]];
// Use reflection to make the protected method accessible
$calculation = new Calculation();
$reflectionMethod = new ReflectionMethod(Calculation::class, 'resizeMatricesExtend');
// Call the method using reflection
$reflectionMethod->invokeArgs($calculation, [&$matrix1, &$matrix2, count($matrix1), 1, count($matrix2), 1]);
self::assertSame([[1], [3], [null]], $matrix1); //* @phpstan-ignore-line
}
public static function testReflectExtend2(): void
{
// Sample matrices to test with
$matrix1 = [[1], [3]];
$matrix2 = [[5, 6], [8, 9], [11, 12]];
// Use reflection to make the protected method accessible
$calculation = new Calculation();
$reflectionMethod = new ReflectionMethod(Calculation::class, 'resizeMatricesExtend');
// Call the method using reflection
$reflectionMethod->invokeArgs($calculation, [&$matrix1, &$matrix2, count($matrix1), 1, count($matrix2), 2]);
self::assertSame([[1, 1], [3, 3], [null, null]], $matrix1); //* @phpstan-ignore-line
}
public static function testReflectShrink1(): void
{
// Sample matrices to test with
$matrix1 = [[10, 20], [30, 40]];
$matrix2 = [[50, 60, 70], [80, 90, 100], [110, 120, 130]];
// Use reflection to make the protected method accessible
$calculation = new Calculation();
$reflectionMethod = new ReflectionMethod(Calculation::class, 'resizeMatricesShrink');
// Call the method using reflection
$reflectionMethod->invokeArgs($calculation, [&$matrix1, &$matrix2, count($matrix1), count($matrix1), count($matrix2), count($matrix2)]);
self::assertSame([[10, 20], [30, 40]], $matrix1); //* @phpstan-ignore-line
self::assertSame([[50, 60], [80, 90]], $matrix2); //* @phpstan-ignore-line
}
public static function testReflectShrink2(): void
{
// Sample matrices to test with
$matrix2 = [[10, 20], [30, 40]];
$matrix1 = [[50, 60, 70], [80, 90, 100], [110, 120, 130]];
// Use reflection to make the protected method accessible
$calculation = new Calculation();
$reflectionMethod = new ReflectionMethod(Calculation::class, 'resizeMatricesShrink');
// Call the method using reflection
$reflectionMethod->invokeArgs($calculation, [&$matrix1, &$matrix2, count($matrix1), count($matrix1), count($matrix2), count($matrix2)]);
self::assertSame([[10, 20], [30, 40]], $matrix2); //* @phpstan-ignore-line
self::assertSame([[50, 60], [80, 90]], $matrix1); //* @phpstan-ignore-line
}
/**
* These 2 tests are contrived. They prove that method
* works as desired, but Excel will actually return
* a CALC error, a result I don't know how to duplicate.
*/
public static function testExtendFirstColumn(): void
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setTitle('Products');
$calculationEngine = Calculation::getInstance($spreadsheet);
$calculationEngine->setInstanceArrayReturnType(
Calculation::RETURN_ARRAY_AS_ARRAY
);
$sheet->getCell('D5')->setValue(5);
$sheet->getCell('E5')->setValue(20);
$sheet->fromArray(
[
[5, 20, 'Apples'],
[10, 20, 'Bananas'],
[5, 20, 'Cherries'],
[5, 40, 'Grapes'],
[25, 50, 'Peaches'],
[30, 60, 'Pears'],
[35, 70, 'Papayas'],
[40, 80, 'Mangos'],
[null, 20, 'Unknown'],
],
null,
'K1',
true
);
$kRows = $sheet->getHighestDataRow('K');
self::assertSame(8, $kRows);
$lRows = $sheet->getHighestDataRow('L');
self::assertSame(9, $lRows);
$mRows = $sheet->getHighestDataRow('M');
self::assertSame(9, $mRows);
$sheet->getCell('A1')
->setValue(
"=FILTER(Products!M1:M$mRows,"
. "(Products!K1:K$kRows=D5)"
. "*(Products!L1:L$lRows=E5))"
);
$result = $sheet->getCell('A1')->getCalculatedValue();
self::assertSame([['Apples'], ['Cherries']], $result);
$spreadsheet->disconnectWorksheets();
}
public static function testExtendSecondColumn(): void
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setTitle('Products');
$calculationEngine = Calculation::getInstance($spreadsheet);
$calculationEngine->setInstanceArrayReturnType(
Calculation::RETURN_ARRAY_AS_ARRAY
);
$sheet->getCell('D5')->setValue(5);
$sheet->getCell('E5')->setValue(20);
$sheet->fromArray(
[
[5, 20, 'Apples'],
[10, 20, 'Bananas'],
[5, 20, 'Cherries'],
[5, 40, 'Grapes'],
[25, 50, 'Peaches'],
[30, 60, 'Pears'],
[35, 70, 'Papayas'],
[40, 80, 'Mangos'],
[null, 20, 'Unknown'],
],
null,
'K1',
true
);
$kRows = $sheet->getHighestDataRow('K');
self::assertSame(8, $kRows);
//$lRows = $sheet->getHighestDataRow('L');
//self::assertSame(9, $lRows);
$lRows = 2;
$mRows = $sheet->getHighestDataRow('M');
self::assertSame(9, $mRows);
$sheet->getCell('A1')
->setValue(
"=FILTER(Products!M1:M$mRows,"
. "(Products!K1:K$kRows=D5)"
. "*(Products!L1:L$lRows=E5))"
);
$result = $sheet->getCell('A1')->getCalculatedValue();
self::assertSame([['Apples']], $result);
$spreadsheet->disconnectWorksheets();
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Calculation/TranslationTest.php | tests/PhpSpreadsheetTests/Calculation/TranslationTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Calculation;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PhpOffice\PhpSpreadsheet\Calculation\Functions;
use PhpOffice\PhpSpreadsheet\Settings;
use PHPUnit\Framework\TestCase;
class TranslationTest extends TestCase
{
private string $compatibilityMode;
private string $returnDate;
private string $locale;
protected function setUp(): void
{
$this->compatibilityMode = Functions::getCompatibilityMode();
$this->returnDate = Functions::getReturnDateType();
Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL);
Functions::setReturnDateType(Functions::RETURNDATE_EXCEL);
$this->locale = Settings::getLocale();
}
protected function tearDown(): void
{
Functions::setCompatibilityMode($this->compatibilityMode);
Functions::setReturnDateType($this->returnDate);
Settings::setLocale($this->locale);
}
#[\PHPUnit\Framework\Attributes\DataProvider('providerTranslations')]
public function testTranslation(string $expectedResult, string $locale, string $formula): void
{
$validLocale = Settings::setLocale($locale);
if (!$validLocale) {
self::markTestSkipped("Unable to set locale to {$locale}");
}
$translatedFormula = Calculation::getInstance()->translateFormulaToLocale($formula);
self::assertSame($expectedResult, $translatedFormula);
$restoredFormula = Calculation::getInstance()->translateFormulaToEnglish($translatedFormula);
self::assertSame(preg_replace(Calculation::CALCULATION_REGEXP_STRIP_XLFN_XLWS, '', $formula), $restoredFormula);
}
public static function providerTranslations(): array
{
return require 'tests/data/Calculation/Translations.php';
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Calculation/AssociativityTest.php | tests/PhpSpreadsheetTests/Calculation/AssociativityTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Calculation;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
class AssociativityTest extends TestCase
{
#[DataProvider('providerAssociativity')]
public function testAssociativity(mixed $expectedResult, string $formula): void
{
$result = Calculation::getInstance()->calculateFormula($formula);
if (is_float($expectedResult)) {
self::assertEqualsWithDelta($expectedResult, $result, 1E-8);
} else {
self::assertSame($expectedResult, $result);
}
}
public static function providerAssociativity(): array
{
return [
'Excel exponentiation is left-associative unlike Php and pure math' => [4096, '=4^2^3'],
'multiplication' => [24, '=4*2*3'],
'division' => [1, '=8/4/2'],
'addition' => [9, '=4+2+3'],
'subtraction' => [-1, '=4-2-3'],
'concatenation' => ['abc', '="a"&"b"&"c"'],
];
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Calculation/CalculationTest.php | tests/PhpSpreadsheetTests/Calculation/CalculationTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Calculation;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PhpOffice\PhpSpreadsheet\Calculation\Functions;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\Exception as SpreadsheetException;
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
class CalculationTest extends TestCase
{
private string $compatibilityMode;
protected function setUp(): void
{
$this->compatibilityMode = Functions::getCompatibilityMode();
Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL);
}
protected function tearDown(): void
{
Functions::setCompatibilityMode($this->compatibilityMode);
}
#[DataProvider('providerBinaryComparisonOperation')]
public function testBinaryComparisonOperation(string $formula, mixed $expectedResultExcel, mixed $expectedResultOpenOffice): void
{
Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL);
$resultExcel = Calculation::getInstance()->calculateFormula($formula);
self::assertEquals($expectedResultExcel, $resultExcel, 'should be Excel compatible');
Functions::setCompatibilityMode(Functions::COMPATIBILITY_OPENOFFICE);
$resultOpenOffice = Calculation::getInstance()->calculateFormula($formula);
self::assertEquals($expectedResultOpenOffice, $resultOpenOffice, 'should be OpenOffice compatible');
}
public static function providerBinaryComparisonOperation(): array
{
return require 'tests/data/CalculationBinaryComparisonOperation.php';
}
public function testDoesHandleXlfnFunctions(): void
{
$calculation = Calculation::getInstance();
$tree = $calculation->parseFormula('=_xlfn.ISFORMULA(A1)');
self::assertIsArray($tree);
self::assertCount(3, $tree);
/** @var mixed[] */
$function = $tree[2];
self::assertEquals('Function', $function['type']);
$tree = $calculation->parseFormula('=_xlfn.STDEV.S(A1:B2)');
self::assertIsArray($tree);
self::assertCount(5, $tree);
/** @var mixed[] */
$function = $tree[4];
self::assertEquals('Function', $function['type']);
}
public function testFormulaWithOptionalArgumentsAndRequiredCellReferenceShouldPassNullForMissingArguments(): void
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->fromArray(
[
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
]
);
$cell = $sheet->getCell('E5');
$cell->setValue('=OFFSET(D3, -1, -2, 1, 1)');
self::assertEquals(5, $cell->getCalculatedValue(), 'with all arguments');
$cell = $sheet->getCell('F6');
$cell->setValue('=OFFSET(D3, -1, -2)');
self::assertEquals(5, $cell->getCalculatedValue(), 'missing arguments should be filled with null');
$spreadsheet->disconnectWorksheets();
}
public function testCellSetAsQuotedText(): void
{
$spreadsheet = new Spreadsheet();
$workSheet = $spreadsheet->getActiveSheet();
$cell = $workSheet->getCell('A1');
$cell->setValue("=cmd|'/C calc'!A0");
$cell->getStyle()->setQuotePrefix(true);
self::assertEquals("=cmd|'/C calc'!A0", $cell->getCalculatedValue());
$cell2 = $workSheet->getCell('A2');
$cell2->setValueExplicit('ABC', DataType::TYPE_FORMULA);
self::assertEquals('ABC', $cell2->getCalculatedValue());
$cell3 = $workSheet->getCell('A3');
$cell3->setValueExplicit('=', DataType::TYPE_FORMULA);
self::assertEquals('', $cell3->getCalculatedValue());
$cell4 = $workSheet->getCell('A4');
try {
$cell4->setValueExplicit((object) null, DataType::TYPE_FORMULA);
self::fail('setValueExplicit formula with unstringable object should have thrown exception');
} catch (SpreadsheetException $e) {
self::assertStringContainsString('Unable to convert to string', $e->getMessage());
}
$cell5 = $workSheet->getCell('A5');
$cell5->setValueExplicit(null, DataType::TYPE_FORMULA);
self::assertEquals('', $cell5->getCalculatedValue());
$spreadsheet->disconnectWorksheets();
}
public function testCellWithDdeExpresion(): void
{
$spreadsheet = new Spreadsheet();
$workSheet = $spreadsheet->getActiveSheet();
$cell = $workSheet->getCell('A1');
$cell->setValue("=cmd|'/C calc'!A0");
self::assertEquals("=cmd|'/C calc'!A0", $cell->getCalculatedValue());
$spreadsheet->disconnectWorksheets();
}
public function testFormulaReferencingWorksheetWithEscapedApostrophe(): void
{
$spreadsheet = new Spreadsheet();
$workSheet = $spreadsheet->getActiveSheet();
$workSheet->setTitle("Catégorie d'absence");
$workSheet->setCellValue('A1', 'HELLO');
$workSheet->setCellValue('B1', ' ');
$workSheet->setCellValue('C1', 'WORLD');
$workSheet->setCellValue(
'A2',
"=CONCAT('Catégorie d''absence'!A1, 'Catégorie d''absence'!B1, 'Catégorie d''absence'!C1)"
);
$cellValue = $workSheet->getCell('A2')->getCalculatedValue();
self::assertSame('HELLO WORLD', $cellValue);
$spreadsheet->disconnectWorksheets();
}
public function testFormulaReferencingWorksheetWithUnescapedApostrophe(): void
{
$spreadsheet = new Spreadsheet();
$workSheet = $spreadsheet->getActiveSheet();
$workSheet->setTitle("Catégorie d'absence");
$workSheet->setCellValue('A1', 'HELLO');
$workSheet->setCellValue('B1', ' ');
$workSheet->setCellValue('C1', 'WORLD');
$workSheet->setCellValue(
'A2',
"=CONCAT('Catégorie d'absence'!A1, 'Catégorie d'absence'!B1, 'Catégorie d'absence'!C1)"
);
$cellValue = $workSheet->getCell('A2')->getCalculatedValue();
self::assertSame('HELLO WORLD', $cellValue);
$spreadsheet->disconnectWorksheets();
}
public function testCellWithFormulaTwoIndirect(): void
{
$spreadsheet = new Spreadsheet();
$workSheet = $spreadsheet->getActiveSheet();
$cell1 = $workSheet->getCell('A1');
$cell1->setValue('2');
$cell2 = $workSheet->getCell('B1');
$cell2->setValue('3');
$cell2 = $workSheet->getCell('C1');
$cell2->setValue('4');
$cell3 = $workSheet->getCell('D1');
$cell3->setValue('=SUM(INDIRECT("A"&ROW()),INDIRECT("B"&ROW()),INDIRECT("C"&ROW()))');
self::assertEquals('9', $cell3->getCalculatedValue());
$spreadsheet->disconnectWorksheets();
}
public function testCellWithStringNumeric(): void
{
$spreadsheet = new Spreadsheet();
$workSheet = $spreadsheet->getActiveSheet();
$cell1 = $workSheet->getCell('A1');
$cell1->setValue('+2.5');
$cell2 = $workSheet->getCell('B1');
$cell2->setValue('=100*A1');
self::assertSame(250.0, $cell2->getCalculatedValue());
$spreadsheet->disconnectWorksheets();
}
public function testCellWithStringFraction(): void
{
$spreadsheet = new Spreadsheet();
$workSheet = $spreadsheet->getActiveSheet();
$cell1 = $workSheet->getCell('A1');
$cell1->setValue('3/4');
$cell2 = $workSheet->getCell('B1');
$cell2->setValue('=100*A1');
self::assertSame(75.0, $cell2->getCalculatedValue());
$spreadsheet->disconnectWorksheets();
}
public function testCellWithStringPercentage(): void
{
$spreadsheet = new Spreadsheet();
$workSheet = $spreadsheet->getActiveSheet();
$cell1 = $workSheet->getCell('A1');
$cell1->setValue('2%');
$cell2 = $workSheet->getCell('B1');
$cell2->setValue('=100*A1');
self::assertSame(2.0, $cell2->getCalculatedValue());
$spreadsheet->disconnectWorksheets();
}
public function testCellWithStringCurrency(): void
{
$currencyCode = StringHelper::getCurrencyCode();
$spreadsheet = new Spreadsheet();
$workSheet = $spreadsheet->getActiveSheet();
$cell1 = $workSheet->getCell('A1');
$cell1->setValue($currencyCode . '2');
$cell2 = $workSheet->getCell('B1');
$cell2->setValue('=100*A1');
self::assertSame(200.0, $cell2->getCalculatedValue());
$spreadsheet->disconnectWorksheets();
}
public function testBranchPruningFormulaParsingSimpleCase(): void
{
$calculation = Calculation::getInstance();
$calculation->flushInstance(); // resets the ids
// Very simple formula
$formula = '=IF(A1="please +",B1)';
$tokens = $calculation->parseFormula($formula);
self::assertIsArray($tokens);
$foundEqualAssociatedToStoreKey = false;
$foundConditionalOnB1 = false;
foreach ($tokens as $token) {
/** @var mixed[] $token */
$isBinaryOperator = $token['type'] == 'Binary Operator';
$isEqual = $token['value'] == '=';
$correctStoreKey = ($token['storeKey'] ?? '') == 'storeKey-0';
$correctOnlyIf = ($token['onlyIf'] ?? '') == 'storeKey-0';
$isB1Reference = ($token['reference'] ?? '') == 'B1';
$foundEqualAssociatedToStoreKey = $foundEqualAssociatedToStoreKey
|| ($isBinaryOperator && $isEqual && $correctStoreKey);
$foundConditionalOnB1 = $foundConditionalOnB1
|| ($isB1Reference && $correctOnlyIf);
}
self::assertTrue($foundEqualAssociatedToStoreKey);
self::assertTrue($foundConditionalOnB1);
}
public function testBranchPruningFormulaParsingMultipleIfsCase(): void
{
$calculation = Calculation::getInstance();
$calculation->flushInstance(); // resets the ids
//
// Internal operation
$formula = '=IF(A1="please +",SUM(B1:B3))+IF(A2="please *",PRODUCT(C1:C3), C1)';
$tokens = $calculation->parseFormula($formula);
self::assertIsArray($tokens);
$plusGotTagged = false;
$productFunctionCorrectlyTagged = false;
foreach ($tokens as $token) {
/** @var mixed[] $token */
$isBinaryOperator = $token['type'] == 'Binary Operator';
$isPlus = $token['value'] == '+';
$anyStoreKey = isset($token['storeKey']);
$anyOnlyIf = isset($token['onlyIf']);
$anyOnlyIfNot = isset($token['onlyIfNot']);
$plusGotTagged = $plusGotTagged
|| ($isBinaryOperator && $isPlus
&& ($anyStoreKey || $anyOnlyIfNot || $anyOnlyIf));
$isFunction = $token['type'] == 'Function';
$isProductFunction = $token['value'] == 'PRODUCT(';
$correctOnlyIf = ($token['onlyIf'] ?? '') == 'storeKey-1';
$productFunctionCorrectlyTagged = $productFunctionCorrectlyTagged || ($isFunction && $isProductFunction && $correctOnlyIf);
}
self::assertFalse($plusGotTagged, 'chaining IF( should not affect the external operators');
self::assertTrue($productFunctionCorrectlyTagged, 'function nested inside if should be tagged to be processed only if parent branching requires it');
}
public function testBranchPruningFormulaParingNestedIfCase(): void
{
$calculation = Calculation::getInstance();
$calculation->flushInstance(); // resets the ids
$formula = '=IF(A1="please +",SUM(B1:B3),1+IF(NOT(A2="please *"),C2-C1,PRODUCT(C1:C3)))';
$tokens = $calculation->parseFormula($formula);
self::assertIsArray($tokens);
$plusCorrectlyTagged = false;
$productFunctionCorrectlyTagged = false;
$notFunctionCorrectlyTagged = false;
$findOneOperandCountTagged = false;
foreach ($tokens as $token) {
/** @var mixed[] $token */
$value = $token['value'];
$isPlus = $value == '+';
$isProductFunction = $value == 'PRODUCT(';
$isNotFunction = $value == 'NOT(';
$isIfOperand = $token['type'] == 'Operand Count for Function IF()';
$isOnlyIfNotDepth1 = (array_key_exists('onlyIfNot', $token) ? $token['onlyIfNot'] : null) == 'storeKey-1';
$isStoreKeyDepth1 = (array_key_exists('storeKey', $token) ? $token['storeKey'] : null) == 'storeKey-1';
$isOnlyIfNotDepth0 = (array_key_exists('onlyIfNot', $token) ? $token['onlyIfNot'] : null) == 'storeKey-0';
$plusCorrectlyTagged = $plusCorrectlyTagged || ($isPlus && $isOnlyIfNotDepth0);
$notFunctionCorrectlyTagged = $notFunctionCorrectlyTagged || ($isNotFunction && $isOnlyIfNotDepth0 && $isStoreKeyDepth1);
$productFunctionCorrectlyTagged = $productFunctionCorrectlyTagged || ($isProductFunction && $isOnlyIfNotDepth1 && !$isStoreKeyDepth1 && !$isOnlyIfNotDepth0);
$findOneOperandCountTagged = $findOneOperandCountTagged || ($isIfOperand && $isOnlyIfNotDepth0);
}
self::assertTrue($plusCorrectlyTagged);
self::assertTrue($productFunctionCorrectlyTagged);
self::assertTrue($notFunctionCorrectlyTagged);
}
public function testBranchPruningFormulaParsingNoArgumentFunctionCase(): void
{
$calculation = Calculation::getInstance();
$calculation->flushInstance(); // resets the ids
$formula = '=IF(AND(TRUE(),A1="please +"),2,3)';
// this used to raise a parser error, we keep it even though we don't
// test the output
$calculation->parseFormula($formula);
self::assertSame(1, $calculation->cyclicFormulaCount);
}
public function testBranchPruningFormulaParsingInequalitiesConditionsCase(): void
{
$calculation = Calculation::getInstance();
$calculation->flushInstance(); // resets the ids
$formula = '=IF(A1="flag",IF(A2<10, 0) + IF(A3<10000, 0))';
$tokens = $calculation->parseFormula($formula);
self::assertIsArray($tokens);
$properlyTaggedPlus = false;
foreach ($tokens as $token) {
/** @var mixed[] $token */
$isPlus = $token['value'] === '+';
$hasOnlyIf = !empty($token['onlyIf']);
$properlyTaggedPlus = $properlyTaggedPlus
|| ($isPlus && $hasOnlyIf);
}
self::assertTrue($properlyTaggedPlus);
}
/**
* @param mixed[] $dataArray
* @param string $cellCoordinates where to put the formula
* @param string[] $shouldBeSetInCacheCells coordinates of cells that must
* be set in cache
* @param string[] $shouldNotBeSetInCacheCells coordinates of cells that must
* not be set in cache because of pruning
*/
#[DataProvider('dataProviderBranchPruningFullExecution')]
public function testFullExecutionDataPruning(
mixed $expectedResult,
array $dataArray,
string $formula,
string $cellCoordinates,
array $shouldBeSetInCacheCells = [],
array $shouldNotBeSetInCacheCells = []
): void {
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->fromArray($dataArray);
$cell = $sheet->getCell($cellCoordinates);
$calculation = Calculation::getInstance($cell->getWorksheet()->getParent());
$cell->setValue($formula);
$calculated = $cell->getCalculatedValue();
self::assertEquals($expectedResult, $calculated);
// this mostly to ensure that at least some cells are cached
foreach ($shouldBeSetInCacheCells as $setCell) {
unset($inCache);
$calculation->getValueFromCache('Worksheet!' . $setCell, $inCache);
self::assertNotEmpty($inCache);
}
foreach ($shouldNotBeSetInCacheCells as $notSetCell) {
unset($inCache);
$calculation->getValueFromCache('Worksheet!' . $notSetCell, $inCache);
self::assertEmpty($inCache);
}
$calculation->disableBranchPruning();
$calculated = $cell->getCalculatedValue();
self::assertEquals($expectedResult, $calculated);
$spreadsheet->disconnectWorksheets();
}
public static function dataProviderBranchPruningFullExecution(): array
{
return require 'tests/data/Calculation/Calculation.php';
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Calculation/FunctionsTest.php | tests/PhpSpreadsheetTests/Calculation/FunctionsTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Calculation;
use PhpOffice\PhpSpreadsheet\Calculation\Functions;
use PhpOffice\PhpSpreadsheet\Calculation\Information\ExcelError;
use PhpOffice\PhpSpreadsheet\Calculation\Information\Value;
use PHPUnit\Framework\TestCase;
class FunctionsTest extends TestCase
{
private string $compatibilityMode;
private string $returnDate;
protected function setUp(): void
{
$this->compatibilityMode = Functions::getCompatibilityMode();
$this->returnDate = Functions::getReturnDateType();
Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL);
Functions::setReturnDateType(Functions::RETURNDATE_EXCEL);
}
protected function tearDown(): void
{
Functions::setCompatibilityMode($this->compatibilityMode);
Functions::setReturnDateType($this->returnDate);
}
public function testCompatibilityMode(): void
{
$result = Functions::setCompatibilityMode(Functions::COMPATIBILITY_GNUMERIC);
// Test for a true response for success
self::assertTrue($result);
// Test that mode has been changed
self::assertEquals(Functions::COMPATIBILITY_GNUMERIC, Functions::getCompatibilityMode());
}
public function testInvalidCompatibilityMode(): void
{
$result = Functions::setCompatibilityMode('INVALIDMODE');
// Test for a false response for failure
self::assertFalse($result);
// Test that mode has not been changed
self::assertEquals(Functions::COMPATIBILITY_EXCEL, Functions::getCompatibilityMode());
}
public function testReturnDateType(): void
{
$result = Functions::setReturnDateType(Functions::RETURNDATE_PHP_OBJECT);
// Test for a true response for success
self::assertTrue($result);
// Test that mode has been changed
self::assertEquals(Functions::RETURNDATE_PHP_OBJECT, Functions::getReturnDateType());
}
public function testInvalidReturnDateType(): void
{
$result = Functions::setReturnDateType('INVALIDTYPE');
// Test for a false response for failure
self::assertFalse($result);
// Test that mode has not been changed
self::assertEquals(Functions::RETURNDATE_EXCEL, Functions::getReturnDateType());
}
public function testDUMMY(): void
{
$result = Functions::DUMMY();
self::assertEquals('#Not Yet Implemented', $result);
}
#[\PHPUnit\Framework\Attributes\DataProvider('providerIfCondition')]
public function testIfCondition(string $expectedResult, string $args): void
{
$result = Functions::ifCondition($args);
self::assertEquals($expectedResult, $result);
}
public static function providerIfCondition(): array
{
return require 'tests/data/Calculation/Functions/IF_CONDITION.php';
}
public function testDeprecatedIsFormula(): void
{
$result = Value::isFormula('="STRING"');
self::assertEquals(ExcelError::REF(), $result);
}
public function testScalar(): void
{
$value = 'scalar';
$result = Functions::scalar([[$value]]);
self::assertSame($value, $result);
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Calculation/CyclicTest.php | tests/PhpSpreadsheetTests/Calculation/CyclicTest.php | <?php
declare(strict_types=1);
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();
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Calculation/CustomFunctionTest.php | tests/PhpSpreadsheetTests/Calculation/CustomFunctionTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Calculation;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PHPUnit\Framework\TestCase;
class CustomFunctionTest extends TestCase
{
public static function testCustomFunction(): void
{
$calculation = Calculation::getInstance();
$key = 'FOURTHPOWER';
$value = [
'category' => 'custom',
'functionCall' => [CustomFunction::class, 'fourthPower'],
'argumentCount' => '1',
];
self::assertTrue(Calculation::addFunction($key, $value));
self::assertFalse(Calculation::addFunction('sqrt', $value));
self::assertSame(16, $calculation->calculateFormula('=FOURTHPOWER(2)'));
self::assertSame('#VALUE!', $calculation->calculateFormula('=FOURTHPOWER("X")'));
self::assertSame('#NAME?', $calculation->calculateFormula('=FOURTHPOWE("X")'));
self::assertFalse(Calculation::removeFunction('SQRT'));
self::assertSame(2.0, $calculation->calculateFormula('=SQRT(4)'));
self::assertFalse(Calculation::removeFunction('sqrt'));
self::assertSame(4.0, $calculation->calculateFormula('=sqrt(16)'));
self::assertTrue(Calculation::removeFunction($key));
self::assertSame('#NAME?', $calculation->calculateFormula('=FOURTHPOWER(3)'));
self::assertFalse(Calculation::removeFunction('WHATEVER'));
$key = 'NATIVECOS';
$value = [
'category' => 'custom',
'functionCall' => 'cos',
'argumentCount' => '1',
];
self::assertTrue(Calculation::addFunction($key, $value));
self::assertSame(1.0, $calculation->calculateFormula('=NATIVECOS(0)'));
self::assertTrue(Calculation::removeFunction($key));
$key = 'PI';
$value = [
'category' => 'custom',
'functionCall' => 'pi',
'argumentCount' => '0',
];
self::assertFalse(Calculation::addFunction($key, $value));
}
public static function testReplaceDummyFunction(): void
{
$functions = Calculation::getFunctions();
$key = 'ASC';
$oldValue = $functions[$key] ?? null;
self::assertIsArray($oldValue);
$calculation = Calculation::getInstance();
$value = $oldValue;
$value['functionCall'] = [CustomFunction::class, 'ASC'];
self::assertTrue(Calculation::addFunction($key, $value));
self::assertSame('ABC', $calculation->calculateFormula('=ASC("ABC")'));
self::assertTrue(Calculation::removeFunction('ASC'));
self::assertTrue(Calculation::addFunction($key, $oldValue));
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Calculation/StringLengthTest.php | tests/PhpSpreadsheetTests/Calculation/StringLengthTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Calculation;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PHPUnit\Framework\TestCase;
class StringLengthTest extends TestCase
{
public function testStringLength(): void
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
// Note use Armenian character below to make sure chars, not bytes
$longstring = str_repeat('Ԁ', DataType::MAX_STRING_LENGTH - 5);
$sheet->getCell('C1')->setValue($longstring);
self::assertSame($longstring, $sheet->getCell('C1')->getValue());
$sheet->getCell('C2')->setValue($longstring . 'abcdef');
self::assertSame($longstring . 'abcde', $sheet->getCell('C2')->getValue());
$sheet->getCell('C3')->setValue('abcdef');
$sheet->getCell('C4')->setValue('=C1 & C3');
self::assertSame($longstring . 'abcde', $sheet->getCell('C4')->getCalculatedValue(), 'truncate cell concat with cell');
$sheet->getCell('C5')->setValue('=C1 & "A"');
self::assertSame($longstring . 'A', $sheet->getCell('C5')->getCalculatedValue(), 'okay cell concat with literal');
$sheet->getCell('C6')->setValue('=C1 & "ABCDEF"');
self::assertSame($longstring . 'ABCDE', $sheet->getCell('C6')->getCalculatedValue(), 'truncate cell concat with literal');
$sheet->getCell('C7')->setValue('="ABCDEF" & C1');
self::assertSame('ABCDEF' . str_repeat('Ԁ', DataType::MAX_STRING_LENGTH - 6), $sheet->getCell('C7')->getCalculatedValue(), 'truncate literal concat with cell');
$sheet->getCell('C8')->setValue('="ABCDE" & C1');
self::assertSame('ABCDE' . $longstring, $sheet->getCell('C8')->getCalculatedValue(), 'okay literal concat with cell');
$sheet->getCell('C9')->setValue('=false & true & 3');
self::assertSame('FALSETRUE3', $sheet->getCell('C9')->getCalculatedValue());
$sheet->getCell('D8')->setValue('abcde');
$sheet->getCell('D9')->setValue('=D8 & "*" & D8');
self::assertSame('abcde*abcde', $sheet->getCell('D9')->getCalculatedValue());
$sheet->getCell('E8')->setValue('"abcde"');
$sheet->getCell('E9')->setValue('=E8 & "*" & E8');
self::assertSame('"abcde"*"abcde"', $sheet->getCell('E9')->getCalculatedValue());
$sheet->getCell('F8')->setValue('"abcde"');
$sheet->getCell('F9')->setValue('=F8 & "*" & "abcde"');
self::assertSame('"abcde"*abcde', $sheet->getCell('F9')->getCalculatedValue());
$spreadsheet->disconnectWorksheets();
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Calculation/InternalFunctionsTest.php | tests/PhpSpreadsheetTests/Calculation/InternalFunctionsTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Calculation;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
class InternalFunctionsTest extends TestCase
{
/** @param mixed[] $expectedResult */
#[DataProvider('anchorArrayDataProvider')]
public function testAnchorArrayFormula(string $reference, string $range, array $expectedResult): void
{
$spreadsheet = new Spreadsheet();
Calculation::getInstance($spreadsheet)->setInstanceArrayReturnType(Calculation::RETURN_ARRAY_AS_ARRAY);
$sheet1 = $spreadsheet->getActiveSheet();
$sheet1->setTitle('SheetOne'); // no space in sheet title
$sheet2 = $spreadsheet->createSheet();
$sheet2->setTitle('Sheet Two'); // space in sheet title
$sheet1->setCellValue('C3', '=SEQUENCE(3,3,-4)');
$sheet2->setCellValue('C3', '=SEQUENCE(3,3, 9, -1)');
$sheet1->calculateArrays();
$sheet2->calculateArrays();
$sheet1->setCellValue('A8', "=ANCHORARRAY({$reference})");
$result1 = $sheet1->getCell('A8')->getCalculatedValue();
self::assertSame($expectedResult, $result1);
$attributes1 = $sheet1->getCell('A8')->getFormulaAttributes();
self::assertSame(['t' => 'array', 'ref' => $range], $attributes1);
$spreadsheet->disconnectWorksheets();
}
public static function anchorArrayDataProvider(): array
{
return [
[
'C3',
'A8:C10',
[[-4, -3, -2], [-1, 0, 1], [2, 3, 4]],
],
[
"'Sheet Two'!C3",
'A8:C10',
[[9, 8, 7], [6, 5, 4], [3, 2, 1]],
],
];
}
#[DataProvider('singleDataProvider')]
public function testSingleArrayFormula(string $reference, mixed $expectedResult): void
{
$spreadsheet = new Spreadsheet();
Calculation::getInstance($spreadsheet)->setInstanceArrayReturnType(Calculation::RETURN_ARRAY_AS_ARRAY);
$sheet1 = $spreadsheet->getActiveSheet();
$sheet1->setTitle('SheetOne'); // no space in sheet title
$sheet2 = $spreadsheet->createSheet();
$sheet2->setTitle('Sheet Two'); // space in sheet title
$sheet1->setCellValue('C3', '=SEQUENCE(3,3,-4)');
$sheet2->setCellValue('C3', '=SEQUENCE(3,3, 9, -1)');
$sheet1->setCellValue('A8', "=SINGLE({$reference})");
$sheet1->setCellValue('G3', 'three');
$sheet1->setCellValue('G4', 'four');
$sheet1->setCellValue('G5', 'five');
$sheet1->setCellValue('G7', 'seven');
$sheet1->setCellValue('G8', 'eight');
$sheet1->setCellValue('G9', 'nine');
$sheet1->calculateArrays();
$sheet2->calculateArrays();
$result1 = $sheet1->getCell('A8')->getCalculatedValue();
self::assertSame($expectedResult, $result1);
$spreadsheet->disconnectWorksheets();
}
public static function singleDataProvider(): array
{
return [
'array cell on same sheet' => [
'C3',
-4,
],
'array cell on different sheet' => [
"'Sheet Two'!C3",
9,
],
'range which includes current row' => [
'G7:G9',
'eight',
],
'range which does not include current row' => [
'G3:G5',
'#VALUE!',
],
'range which includes current row but spans columns' => [
'F7:G9',
'#VALUE!',
],
];
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Calculation/DefinedNameWithQuotePrefixedCellTest.php | tests/PhpSpreadsheetTests/Calculation/DefinedNameWithQuotePrefixedCellTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Calculation;
use PhpOffice\PhpSpreadsheet\NamedRange;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PHPUnit\Framework\TestCase;
class DefinedNameWithQuotePrefixedCellTest extends TestCase
{
public function testDefinedNameIsAlwaysEvaluated(): void
{
$spreadsheet = new Spreadsheet();
$sheet1 = $spreadsheet->getActiveSheet();
$sheet1->setTitle('Sheet1');
$sheet2 = $spreadsheet->createSheet();
$sheet2->setTitle('Sheet2');
$sheet2->getCell('A1')->setValue('July 2019');
$sheet2->getStyle('A1')
->setQuotePrefix(true);
$sheet2->getCell('A2')->setValue(3);
$spreadsheet->addNamedRange(new NamedRange('FM', $sheet2, '$A$2'));
$sheet1->getCell('A1')->setValue('=(A2+FM)');
$sheet1->getCell('A2')->setValue(38.42);
self::assertSame(41.42, $sheet1->getCell('A1')->getCalculatedValue());
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Calculation/FormulaAsStringTest.php | tests/PhpSpreadsheetTests/Calculation/FormulaAsStringTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Calculation;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
class FormulaAsStringTest extends TestCase
{
#[DataProvider('providerFunctionsAsString')]
public function testFunctionsAsString(mixed $expectedResult, string $formula): void
{
$spreadsheet = new Spreadsheet();
$calculation = Calculation::getInstance($spreadsheet);
$calculation->setInstanceArrayReturnType(
Calculation::RETURN_ARRAY_AS_VALUE
);
$workSheet = $spreadsheet->getActiveSheet();
$workSheet->setCellValue('A1', 10);
$workSheet->setCellValue('A2', 20);
$workSheet->setCellValue('A3', 30);
$workSheet->setCellValue('A4', 40);
$spreadsheet->addNamedRange(new \PhpOffice\PhpSpreadsheet\NamedRange('namedCell', $workSheet, '$A$4'));
$workSheet->setCellValue('B1', 'uPPER');
$workSheet->setCellValue('B2', '=TRUE()');
$workSheet->setCellValue('B3', '=FALSE()');
$ws2 = $spreadsheet->createSheet();
$ws2->setCellValue('A1', 100);
$ws2->setCellValue('A2', 200);
$ws2->setTitle('Sheet2');
$spreadsheet->addNamedRange(new \PhpOffice\PhpSpreadsheet\NamedRange('A2B', $ws2, '$A$2'));
$spreadsheet->setActiveSheetIndex(0);
$cell2 = $workSheet->getCell('D1');
$cell2->setValue($formula);
$result = $cell2->getCalculatedValue();
self::assertEquals($expectedResult, $result);
}
public static function providerFunctionsAsString(): array
{
return require 'tests/data/Calculation/FunctionsAsString.php';
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Calculation/DefinedNameConfusedForCellTest.php | tests/PhpSpreadsheetTests/Calculation/DefinedNameConfusedForCellTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Calculation;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\NamedRange;
use PhpOffice\PhpSpreadsheet\Shared\File;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PHPUnit\Framework\TestCase;
class DefinedNameConfusedForCellTest extends TestCase
{
public function testDefinedName(): void
{
$obj = new Spreadsheet();
$sheet0 = $obj->setActiveSheetIndex(0);
$sheet0->setCellValue('A1', 2);
$obj->addNamedRange(new NamedRange('A1A', $sheet0, '$A$1'));
$sheet0->setCellValue('B1', '=2*A1A');
$writer = IOFactory::createWriter($obj, 'Xlsx');
$filename = File::temporaryFilename();
$writer->save($filename);
unlink($filename);
self::assertSame(4, $obj->getActiveSheet()->getCell('B1')->getCalculatedValue());
$obj->disconnectWorksheets();
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Calculation/XlfnFunctionsTest.php | tests/PhpSpreadsheetTests/Calculation/XlfnFunctionsTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Calculation;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PhpOffice\PhpSpreadsheet\Shared\File;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Color;
use PhpOffice\PhpSpreadsheet\Style\Conditional;
use PhpOffice\PhpSpreadsheet\Style\Fill;
class XlfnFunctionsTest extends \PHPUnit\Framework\TestCase
{
public function testXlfn(): void
{
$formulas = [
// null indicates function not implemented in Calculation engine
['2010', 'A1', '=MODE.SNGL({5.6,4,4,3,2,4})', '=MODE.SNGL({5.6,4,4,3,2,4})', 4],
['2010', 'A2', '=MODE.SNGL({"x","y"})', '=MODE.SNGL({"x","y"})', '#N/A'],
['2013', 'A1', '=ISOWEEKNUM("2019-12-19")', '=ISOWEEKNUM("2019-12-19")', 51],
['2013', 'A2', '=SHEET("2019")', '=SHEET("2019")', null],
['2013', 'A3', '2019-01-04', '2019-01-04', null],
['2013', 'A4', '2019-07-04', '2019-07-04', null],
['2013', 'A5', '2019-12-04', '2019-12-04', null],
['2013', 'B3', 1, 1, null],
['2013', 'B4', 2, 2, null],
['2013', 'B5', -3, -3, null],
// multiple xlfn functions interleaved with non-xlfn
['2013', 'C3', '=ISOWEEKNUM(A3)+WEEKNUM(A4)+ISOWEEKNUM(A5)', '=ISOWEEKNUM(A3)+WEEKNUM(A4)+ISOWEEKNUM(A5)', 77],
['2016', 'A1', '=SWITCH(WEEKDAY("2019-12-22",1),1,"Sunday",2,"Monday","No Match")', '=SWITCH(WEEKDAY("2019-12-22",1),1,"Sunday",2,"Monday","No Match")', 'Sunday'],
['2016', 'B1', '=SWITCH(WEEKDAY("2019-12-20",1),1,"Sunday",2,"Monday","No Match")', '=SWITCH(WEEKDAY("2019-12-20",1),1,"Sunday",2,"Monday","No Match")', 'No Match'],
['2019', 'A1', '=CONCAT("The"," ","sun"," ","will"," ","come"," ","up"," ","tomorrow.")', '=CONCAT("The"," ","sun"," ","will"," ","come"," ","up"," ","tomorrow.")', 'The sun will come up tomorrow.'],
['365', 'A1', '=SORT({7;1;5})', '=SORT({7;1;5})', 1],
];
$workbook = new Spreadsheet();
$calculation = Calculation::getInstance($workbook);
$calculation->setInstanceArrayReturnType(
Calculation::RETURN_ARRAY_AS_VALUE
);
$sheet = $workbook->getActiveSheet();
$sheet->setTitle('2010');
$sheet = $workbook->createSheet();
$sheet->setTitle('2013');
$sheet = $workbook->createSheet();
$sheet->setTitle('2016');
$sheet = $workbook->createSheet();
$sheet->setTitle('2019');
$sheet = $workbook->createSheet();
$sheet->setTitle('365');
foreach ($formulas as $values) {
$sheet = $workbook->setActiveSheetIndexByName($values[0]);
$sheet->setCellValue($values[1], $values[2]);
}
$sheet = $workbook->setActiveSheetIndexByName('2013');
$sheet->getStyle('A3:A5')->getNumberFormat()->setFormatCode('yyyy-mm-dd');
$sheet->getColumnDimension('A')->setAutoSize(true);
$condition0 = new Conditional();
$condition0->setConditionType(Conditional::CONDITION_EXPRESSION);
$condition0->addCondition('ABS(B3)<2');
$condition0->getStyle()->getFill()->setFillType(Fill::FILL_SOLID);
$condition0->getStyle()->getFill()->getStartColor()->setARGB(Color::COLOR_RED);
$condition1 = new Conditional();
$condition1->setConditionType(Conditional::CONDITION_EXPRESSION);
$condition1->addCondition('ABS(B3)>2');
$condition1->getStyle()->getFill()->setFillType(Fill::FILL_SOLID);
$condition1->getStyle()->getFill()->getStartColor()->setARGB(Color::COLOR_GREEN);
$cond = [$condition0, $condition1];
$sheet->getStyle('B3:B5')->setConditionalStyles($cond);
$condition0 = new Conditional();
$condition0->setConditionType(Conditional::CONDITION_EXPRESSION);
$condition0->addCondition('ISOWEEKNUM(A3)<10');
$condition0->getStyle()->getFill()->setFillType(Fill::FILL_SOLID);
$condition0->getStyle()->getFill()->getStartColor()->setARGB(Color::COLOR_RED);
$condition1 = new Conditional();
$condition1->setConditionType(Conditional::CONDITION_EXPRESSION);
$condition1->addCondition('ISOWEEKNUM(A3)>40');
$condition1->getStyle()->getFill()->setFillType(Fill::FILL_SOLID);
$condition1->getStyle()->getFill()->getStartColor()->setARGB(Color::COLOR_GREEN);
$cond = [$condition0, $condition1];
$sheet->getStyle('A3:A5')->setConditionalStyles($cond);
$sheet->setSelectedCell('B1');
$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($workbook, 'Xlsx');
$oufil = File::temporaryFilename();
$writer->save($oufil);
$file = "zip://$oufil#xl/worksheets/sheet1.xml";
$contents = (string) file_get_contents($file);
self::assertStringContainsString('<c r="A1"><f>_xlfn.MODE.SNGL({5.6,4,4,3,2,4})</f><v>4</v></c>', $contents);
self::assertStringContainsString('<c r="A2" t="e"><f>_xlfn.MODE.SNGL({"x","y"})</f><v>#N/A</v></c>', $contents);
$file = "zip://$oufil#xl/worksheets/sheet2.xml";
$contents = (string) file_get_contents($file);
self::assertStringContainsString('<c r="A1"><f>_xlfn.ISOWEEKNUM("2019-12-19")</f><v>51</v></c>', $contents);
self::assertStringContainsString('<c r="A2"><f>_xlfn.SHEET("2019")</f></c>', $contents);
self::assertStringContainsString('<c r="C3"><f>_xlfn.ISOWEEKNUM(A3)+WEEKNUM(A4)+_xlfn.ISOWEEKNUM(A5)</f><v>77</v></c>', $contents);
self::assertStringContainsString('<conditionalFormatting sqref="B3:B5"><cfRule type="expression" dxfId="0" priority="1"><formula>ABS(B3)<2</formula></cfRule><cfRule type="expression" dxfId="1" priority="2"><formula>ABS(B3)>2</formula></cfRule></conditionalFormatting>', $contents);
self::assertStringContainsString('<conditionalFormatting sqref="A3:A5"><cfRule type="expression" dxfId="2" priority="3"><formula>_xlfn.ISOWEEKNUM(A3)<10</formula></cfRule><cfRule type="expression" dxfId="3" priority="4"><formula>_xlfn.ISOWEEKNUM(A3)>40</formula></cfRule></conditionalFormatting>', $contents);
$file = "zip://$oufil#xl/worksheets/sheet3.xml";
$contents = (string) file_get_contents($file);
self::assertStringContainsString('<c r="A1" t="str"><f>_xlfn.SWITCH(WEEKDAY("2019-12-22",1),1,"Sunday",2,"Monday","No Match")</f><v>Sunday</v></c>', $contents);
self::assertStringContainsString('<c r="B1" t="str"><f>_xlfn.SWITCH(WEEKDAY("2019-12-20",1),1,"Sunday",2,"Monday","No Match")</f><v>No Match</v></c>', $contents);
$file = "zip://$oufil#xl/worksheets/sheet4.xml";
$contents = (string) file_get_contents($file);
self::assertStringContainsString('<c r="A1" t="str"><f>_xlfn.CONCAT("The"," ","sun"," ","will"," ","come"," ","up"," ","tomorrow.")</f><v>The sun will come up tomorrow.</v></c>', $contents);
$file = "zip://$oufil#xl/worksheets/sheet5.xml";
$contents = (string) file_get_contents($file);
self::assertStringContainsString('<c r="A1"><f>_xlfn._xlws.SORT({7;1;5})</f><v>1</v></c>', $contents);
$reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader('Xlsx');
$rdobj = $reader->load($oufil);
unlink($oufil);
$calculation = Calculation::getInstance($rdobj);
$calculation->setInstanceArrayReturnType(
Calculation::RETURN_ARRAY_AS_VALUE
);
foreach ($formulas as $values) {
$sheet = $rdobj->setActiveSheetIndexByName($values[0]);
self::assertEquals($values[3], $sheet->getCell($values[1])->getValue());
if ($values[4] !== null) {
self::assertEquals($values[4], $sheet->getCell($values[1])->getCalculatedValue());
}
}
$sheet = $rdobj->setActiveSheetIndexByName('2013');
$cond = $sheet->getConditionalStyles('A3:A5');
self::assertEquals('ISOWEEKNUM(A3)<10', $cond[0]->getConditions()[0]);
self::assertEquals('ISOWEEKNUM(A3)>40', $cond[1]->getConditions()[0]);
$cond = $sheet->getConditionalStyles('B3:B5');
self::assertEquals('ABS(B3)<2', $cond[0]->getConditions()[0]);
self::assertEquals('ABS(B3)>2', $cond[1]->getConditions()[0]);
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Calculation/CalculationSettingsTest.php | tests/PhpSpreadsheetTests/Calculation/CalculationSettingsTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Calculation;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PhpOffice\PhpSpreadsheet\Calculation\Functions;
use PHPUnit\Framework\TestCase;
class CalculationSettingsTest extends TestCase
{
private string $compatibilityMode;
private string $locale;
protected function setUp(): void
{
$this->compatibilityMode = Functions::getCompatibilityMode();
$calculation = Calculation::getInstance();
$this->locale = $calculation->getLocale();
Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL);
}
protected function tearDown(): void
{
Functions::setCompatibilityMode($this->compatibilityMode);
$calculation = Calculation::getInstance();
$calculation->setLocale($this->locale);
}
#[\PHPUnit\Framework\Attributes\DataProvider('providerCanLoadAllSupportedLocales')]
public function testCanLoadAllSupportedLocales(string $locale): void
{
$calculation = Calculation::getInstance();
self::assertTrue($calculation->setLocale($locale));
}
public function testInvalidLocaleReturnsFalse(): void
{
$calculation = Calculation::getInstance();
self::assertFalse($calculation->setLocale('xx'));
}
public static function providerCanLoadAllSupportedLocales(): array
{
return [
['bg'],
['cs'],
['da'],
['de'],
['en_us'],
['es'],
['fi'],
['fr'],
['hu'],
['it'],
['nl'],
['nb'],
['pl'],
['pt'],
['pt_br'],
['ru'],
['sv'],
['tr'],
];
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Calculation/CalculationLoggingTest.php | tests/PhpSpreadsheetTests/Calculation/CalculationLoggingTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Calculation;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PHPUnit\Framework\TestCase;
class CalculationLoggingTest extends TestCase
{
public function testFormulaWithLogging(): void
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->fromArray(
[
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
]
);
$debugLog = Calculation::getInstance($spreadsheet)->getDebugLog();
$debugLog->setWriteDebugLog(true);
$cell = $sheet->getCell('E5');
$cell->setValue('=ROUND(SQRT(SUM(A1:C3)), 1)');
self::assertEquals(6.7, $cell->getCalculatedValue());
$log = $debugLog->getLog();
$entries = count($log);
self::assertGreaterThan(0, $entries);
$finalEntry = array_pop($log);
self::assertStringContainsString('Evaluation Result', $finalEntry);
}
public function testFormulaWithMultipleCellLogging(): void
{
$spreadsheet = new Spreadsheet();
$calculation = Calculation::getInstance($spreadsheet);
$calculation->setInstanceArrayReturnType(
Calculation::RETURN_ARRAY_AS_VALUE
);
$sheet = $spreadsheet->getActiveSheet();
$sheet->fromArray(
[
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
]
);
$debugLog = Calculation::getInstance($spreadsheet)->getDebugLog();
$debugLog->setWriteDebugLog(true);
$cell = $sheet->getCell('E1');
$cell->setValue('=SUM(A1:C3)');
$cell = $sheet->getCell('E3');
$cell->setValue('=SQRT(E1)');
$cell = $sheet->getCell('E5');
$cell->setValue('=ROUND(E3, 1)');
self::assertEquals(6.7, $cell->getCalculatedValue());
$log = $debugLog->getLog();
$entries = count($log);
self::assertGreaterThan(0, $entries);
$finalEntry = array_pop($log);
self::assertStringContainsString('Evaluation Result', $finalEntry);
$e1Log = array_filter($log, fn ($entry): bool => str_contains($entry, 'E1'));
$e1Entries = count($e1Log);
self::assertGreaterThan(0, $e1Entries);
$e1FinalEntry = array_pop($e1Log);
self::assertStringContainsString('Evaluation Result', $e1FinalEntry);
$e3Log = array_filter($log, fn ($entry): bool => str_contains($entry, 'E1'));
$e3Entries = count($e3Log);
self::assertGreaterThan(0, $e3Entries);
$e3FinalEntry = array_pop($e3Log);
self::assertStringContainsString('Evaluation Result', $e3FinalEntry);
}
public function testFlushLog(): void
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->fromArray(
[
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
]
);
$debugLog = Calculation::getInstance($spreadsheet)->getDebugLog();
$debugLog->setWriteDebugLog(true);
$cell = $sheet->getCell('E5');
$cell->setValue('=(1+-2)*3/4');
self::assertEquals(-0.75, $cell->getCalculatedValue());
$log = $debugLog->getLog();
$entries = count($log);
self::assertGreaterThan(0, $entries);
$debugLog->clearLog();
$log = $debugLog->getLog();
self::assertSame([], $log);
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Calculation/BinaryComparisonTest.php | tests/PhpSpreadsheetTests/Calculation/BinaryComparisonTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Calculation;
use PhpOffice\PhpSpreadsheet\Calculation\BinaryComparison;
use PhpOffice\PhpSpreadsheet\Calculation\Exception;
use PhpOffice\PhpSpreadsheet\Calculation\Functions;
use PHPUnit\Framework\TestCase;
class BinaryComparisonTest extends TestCase
{
private string $compatibilityMode;
protected function setUp(): void
{
$this->compatibilityMode = Functions::getCompatibilityMode();
Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL);
}
protected function tearDown(): void
{
Functions::setCompatibilityMode($this->compatibilityMode);
}
#[\PHPUnit\Framework\Attributes\DataProvider('providerBinaryComparison')]
public function testBinaryComparisonOperation(
mixed $operand1,
mixed $operand2,
string $operator,
bool $expectedResultExcel,
bool $expectedResultOpenOffice
): void {
Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL);
$resultExcel = BinaryComparison::compare($operand1, $operand2, $operator);
self::assertEquals($expectedResultExcel, $resultExcel, 'should be Excel compatible');
Functions::setCompatibilityMode(Functions::COMPATIBILITY_OPENOFFICE);
$resultOpenOffice = BinaryComparison::compare($operand1, $operand2, $operator);
self::assertEquals($expectedResultOpenOffice, $resultOpenOffice, 'should be OpenOffice compatible');
}
public static function providerBinaryComparison(): array
{
return require 'tests/data/Calculation/BinaryComparisonOperations.php';
}
public function testInvalidOperator(): void
{
$this->expectException(Exception::class);
$this->expectExceptionMessage('Unsupported binary comparison operator');
BinaryComparison::compare(1, 2, '!=');
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Calculation/NullEqualsZeroTest.php | tests/PhpSpreadsheetTests/Calculation/NullEqualsZeroTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Calculation;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PHPUnit\Framework\TestCase;
class NullEqualsZeroTest extends TestCase
{
public function testNullEqualsZero(): void
{
// Confirm that NULL<>0 returns false
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->fromArray([
['Item', 'QTY', 'RATE', 'RATE', 'Total'],
['Bricks', 1000, 'Each', 0.55, '=IF(B2<>0,B2*D2,"INCL.")'],
['Cement', null, null, null, '=IF(B3<>0,B3*D3,"INCL.")'],
['Labour', 10, 'Hour', 45.00, '=IF(B4<>0,B4*D4,"INCL.")'],
]);
$sheet->setCellValue('A6', 'Total');
$sheet->setCellValue('E6', '=SUM(E1:E5)');
self::assertEquals(550.00, $sheet->getCell('E2')->getCalculatedValue());
self::assertSame('INCL.', $sheet->getCell('E3')->getCalculatedValue());
self::assertEquals(450.00, $sheet->getCell('E4')->getCalculatedValue());
self::assertEquals(1000.00, $sheet->getCell('E6')->getCalculatedValue());
$sheet->setCellValue('Z1', '=Z2=0');
self::assertTrue($sheet->getCell('Z1')->getCalculatedValue());
$spreadsheet->disconnectWorksheets();
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Calculation/CalculationFunctionListTest.php | tests/PhpSpreadsheetTests/Calculation/CalculationFunctionListTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Calculation;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PhpOffice\PhpSpreadsheet\Calculation\Functions;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
class CalculationFunctionListTest extends TestCase
{
private string $compatibilityMode;
protected function setUp(): void
{
$this->compatibilityMode = Functions::getCompatibilityMode();
Functions::setCompatibilityMode(Functions::COMPATIBILITY_EXCEL);
}
protected function tearDown(): void
{
Functions::setCompatibilityMode($this->compatibilityMode);
}
/** @param array<mixed>|string $functionCall */
#[DataProvider('providerGetFunctions')]
public function testGetFunctions(array|string $functionCall): void
{
self::assertIsCallable($functionCall);
}
public static function providerGetFunctions(): array
{
$returnFunctions = [];
$functionList = Calculation::getInstance()->getFunctions();
foreach ($functionList as $functionName => $functionArray) {
$returnFunctions[$functionName]['functionCall'] = $functionArray['functionCall'];
}
return $returnFunctions;
}
public function testIsImplemented(): void
{
$calculation = Calculation::getInstance();
self::assertFalse($calculation->isImplemented('non-existing-function'));
self::assertFalse($calculation->isImplemented('AREAS'));
self::assertTrue($calculation->isImplemented('coUNt'));
self::assertTrue($calculation->isImplemented('abs'));
}
public function testUnknownFunction(): void
{
$workbook = new Spreadsheet();
$sheet = $workbook->getActiveSheet();
$sheet->setCellValue('A1', '=gzorg()');
$sheet->setCellValue('A2', '=mode.gzorg(1)');
$sheet->setCellValue('A3', '=gzorg(1,2)');
$sheet->setCellValue('A4', '=3+IF(gzorg(),1,2)');
self::assertEquals('#NAME?', $sheet->getCell('A1')->getCalculatedValue());
self::assertEquals('#NAME?', $sheet->getCell('A2')->getCalculatedValue());
self::assertEquals('#NAME?', $sheet->getCell('A3')->getCalculatedValue());
self::assertEquals('#NAME?', $sheet->getCell('A4')->getCalculatedValue());
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Calculation/DefinedNamesCalculationTest.php | tests/PhpSpreadsheetTests/Calculation/DefinedNamesCalculationTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Calculation;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
class DefinedNamesCalculationTest extends TestCase
{
#[DataProvider('namedRangeCalculationProvider1')]
public function testNamedRangeCalculations1(string $cellAddress, float $expectedValue): void
{
$inputFileType = 'Xlsx';
$inputFileName = __DIR__ . '/../../data/Calculation/DefinedNames/NamedRanges.xlsx';
$reader = IOFactory::createReader($inputFileType);
$spreadsheet = $reader->load($inputFileName);
$calculatedCellValue = $spreadsheet->getActiveSheet()->getCell($cellAddress)->getCalculatedValue();
self::assertSame($expectedValue, $calculatedCellValue, "Failed calculation for cell {$cellAddress}");
$spreadsheet->disconnectWorksheets();
}
public function testNamedRangeCalculationsIfError(): void
{
$inputFileType = 'Xlsx';
$inputFileName = __DIR__ . '/../../data/Calculation/DefinedNames/NamedRanges.xlsx';
$reader = IOFactory::createReader($inputFileType);
$spreadsheet = $reader->load($inputFileName);
$sheet = $spreadsheet->getActiveSheet();
$sheet->getCell('E1')
->setValue('=IFERROR(CHARGE_RATE, 999)');
$sheet->getCell('F1')
->setValue('=IFERROR(CHARGE_RATX, 999)');
self::assertSame(7.5, $sheet->getCell('E1')->getCalculatedValue());
self::assertSame(999, $sheet->getCell('F1')->getCalculatedValue());
$spreadsheet->disconnectWorksheets();
}
#[DataProvider('namedRangeCalculationProvider2')]
public function testNamedRangeCalculationsWithAdjustedRateValue(string $cellAddress, float $expectedValue): void
{
$inputFileType = 'Xlsx';
$inputFileName = __DIR__ . '/../../data/Calculation/DefinedNames/NamedRanges.xlsx';
$reader = IOFactory::createReader($inputFileType);
$spreadsheet = $reader->load($inputFileName);
$spreadsheet->getActiveSheet()->getCell('B1')->setValue(12.5);
$calculatedCellValue = $spreadsheet->getActiveSheet()->getCell($cellAddress)->getCalculatedValue();
self::assertSame($expectedValue, $calculatedCellValue, "Failed calculation for cell {$cellAddress}");
$spreadsheet->disconnectWorksheets();
}
#[DataProvider('namedRangeCalculationProvider1')]
public function testNamedFormulaCalculations1(string $cellAddress, float $expectedValue): void
{
$inputFileType = 'Xlsx';
$inputFileName = __DIR__ . '/../../data/Calculation/DefinedNames/NamedFormulae.xlsx';
$reader = IOFactory::createReader($inputFileType);
$spreadsheet = $reader->load($inputFileName);
$calculatedCellValue = $spreadsheet->getActiveSheet()->getCell($cellAddress)->getCalculatedValue();
self::assertSame($expectedValue, $calculatedCellValue, "Failed calculation for cell {$cellAddress}");
$spreadsheet->disconnectWorksheets();
}
#[DataProvider('namedRangeCalculationProvider2')]
public function testNamedFormulaeCalculationsWithAdjustedRateValue(string $cellAddress, float $expectedValue): void
{
$inputFileType = 'Xlsx';
$inputFileName = __DIR__ . '/../../data/Calculation/DefinedNames/NamedFormulae.xlsx';
$reader = IOFactory::createReader($inputFileType);
$spreadsheet = $reader->load($inputFileName);
$spreadsheet->getActiveSheet()->getCell('B1')->setValue(12.5);
$calculatedCellValue = $spreadsheet->getActiveSheet()->getCell($cellAddress)->getCalculatedValue();
self::assertSame($expectedValue, $calculatedCellValue, "Failed calculation for cell {$cellAddress}");
$spreadsheet->disconnectWorksheets();
}
public static function namedRangeCalculationProvider1(): array
{
return [
['C4', 56.25],
['C5', 54.375],
['C6', 48.75],
['C7', 52.5],
['C8', 41.25],
['B10', 33.75],
['C10', 253.125],
];
}
public static function namedRangeCalculationProvider2(): array
{
return [
['C4', 93.75],
['C5', 90.625],
['C6', 81.25],
['C7', 87.5],
['C8', 68.75],
['C10', 421.875],
];
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Calculation/CalculationCoverageTest.php | tests/PhpSpreadsheetTests/Calculation/CalculationCoverageTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Calculation;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PhpOffice\PhpSpreadsheet\Calculation\Exception as CalcException;
use PhpOffice\PhpSpreadsheet\Calculation\ExceptionHandler;
use PhpOffice\PhpSpreadsheet\NamedRange;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PHPUnit\Framework\TestCase;
class CalculationCoverageTest extends TestCase
{
public function testClone(): void
{
$this->expectException(CalcException::class);
$this->expectExceptionMessage('Cloning the calculation engine is not allowed!');
$calc = Calculation::getInstance();
$clone = clone $calc;
$clone->flushInstance();
}
public function testBadInstanceArray(): void
{
$spreadsheet = new Spreadsheet();
$calc = Calculation::getInstance($spreadsheet);
$type = $calc->getInstanceArrayReturnType();
self::assertFalse($calc->setInstanceArrayReturnType('bad'));
self::assertSame($type, $calc->getInstanceArrayReturnType());
$spreadsheet->disconnectWorksheets();
}
public function testCalculate(): void
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$calc = Calculation::getInstance($spreadsheet);
$sheet->getCell('A1')->setValue('=2+3');
$result = $calc->calculate($sheet->getCell('A1'));
self::assertSame(5, $result);
self::assertSame('', Calculation::boolToString(null));
$spreadsheet->disconnectWorksheets();
}
public function testCalculateBad(): void
{
$this->expectException(CalcException::class);
$this->expectExceptionMessage('Formula Error');
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$calc = Calculation::getInstance($spreadsheet);
$sheet->getCell('A1')->setValue('=SUM(');
$result = $calc->calculate($sheet->getCell('A1'));
self::assertSame(5, $result);
$spreadsheet->disconnectWorksheets();
}
public function testParse(): void
{
$calc = Calculation::getInstance();
self::assertSame([], $calc->parseFormula('2+3'), 'no leading =');
self::assertSame([], $calc->parseFormula('='), 'leading = but no other text');
}
public function testExtractNamedRange(): void
{
$spreadsheet = new Spreadsheet();
$calc = Calculation::getInstance($spreadsheet);
$sheet = $spreadsheet->getActiveSheet();
$sheet->setTitle('mysheet');
$sheet->setCellValue('A1', 1);
$sheet->setCellValue('B1', 2);
$sheet->setCellValue('A2', 3);
$sheet->setCellValue('B2', 4);
$spreadsheet->addNamedRange(
new NamedRange('Whatever', $sheet, '$A$1:$B$2')
);
$range = 'Whatever';
$result = $calc->extractNamedRange($range, $sheet);
self::assertSame('$A$1:$B$2', $range);
self::assertSame([1 => ['A' => 1, 'B' => 2], 2 => ['A' => 3, 'B' => 4]], $result);
$range = 'mysheet!Whatever';
$result = $calc->extractNamedRange($range, $sheet);
self::assertSame('$A$1:$B$2', $range);
self::assertSame([1 => ['A' => 1, 'B' => 2], 2 => ['A' => 3, 'B' => 4]], $result);
$range = 'mysheet!Whateverx';
$result = $calc->extractNamedRange($range, $sheet);
self::assertSame('Whateverx', $range);
self::assertSame('#REF!', $result);
$range = 'Why';
$result = $calc->extractNamedRange($range, $sheet);
self::assertSame('Why', $range);
self::assertSame('#REF!', $result);
$spreadsheet->addNamedRange(
new NamedRange('OneCell', $sheet, '$A$1')
);
$range = 'OneCell';
$result = $calc->extractNamedRange($range, $sheet);
self::assertSame('$A$1', $range);
self::assertSame([1 => ['A' => 1]], $result);
$spreadsheet->addNamedRange(
new NamedRange('NoSuchCell', $sheet, '$Z$1')
);
$range = 'NoSuchCell';
$result = $calc->extractNamedRange($range, $sheet);
self::assertSame('$Z$1', $range);
self::assertSame([1 => ['Z' => null]], $result);
$spreadsheet->addNamedRange(
new NamedRange('SomeCells', $sheet, '$B$1:$C$2')
);
$range = 'SomeCells';
$result = $calc->extractNamedRange($range, $sheet);
self::assertSame('$B$1:$C$2', $range);
self::assertSame([1 => ['B' => 2, 'C' => null], 2 => ['B' => 4, 'C' => null]], $result);
$spreadsheet->disconnectWorksheets();
}
protected static int $winMinPhpToSkip = 80300;
protected static int $winMaxPhpToSkip = 80499;
protected static string $winIndicator = 'WIN';
public function testExceptionHandler(): void
{
if (
strtoupper(substr(PHP_OS, 0, 3)) === self::$winIndicator
&& PHP_VERSION_ID >= self::$winMinPhpToSkip
&& PHP_VERSION_ID <= self::$winMaxPhpToSkip
) {
self::markTestSkipped('Mysterious problem on Windows with Php8.3/4 only');
}
$this->expectException(CalcException::class);
$this->expectExceptionMessage('hello');
$handler = new ExceptionHandler();
trigger_error('hello');
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Calculation/RowColumnReferenceTest.php | tests/PhpSpreadsheetTests/Calculation/RowColumnReferenceTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Calculation;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use PHPUnit\Framework\TestCase;
class RowColumnReferenceTest extends TestCase
{
protected Spreadsheet $spreadSheet;
protected function setUp(): void
{
$this->spreadSheet = new Spreadsheet();
$dataSheet = new Worksheet($this->spreadSheet, 'data sheet');
$this->spreadSheet->addSheet($dataSheet, 0);
$dataSheet->setCellValue('B1', 1.1);
$dataSheet->setCellValue('B2', 2.2);
$dataSheet->setCellValue('B3', 4.4);
$dataSheet->setCellValue('C3', 8.8);
$dataSheet->setCellValue('D3', 16.16);
$calcSheet = new Worksheet($this->spreadSheet, 'summary sheet');
$this->spreadSheet->addSheet($calcSheet, 1);
$calcSheet->setCellValue('B1', 2.2);
$calcSheet->setCellValue('B2', 4.4);
$calcSheet->setCellValue('B3', 8.8);
$calcSheet->setCellValue('C3', 16.16);
$calcSheet->setCellValue('D3', 32.32);
$this->spreadSheet->setActiveSheetIndexByName('summary sheet');
}
#[\PHPUnit\Framework\Attributes\DataProvider('providerCurrentWorksheetFormulae')]
public function testCurrentWorksheet(string $formula, float $expectedResult): void
{
$worksheet = $this->spreadSheet->getActiveSheet();
$worksheet->setCellValue('A1', $formula);
$result = $worksheet->getCell('A1')->getCalculatedValue();
self::assertEqualsWithDelta($expectedResult, $result, 1.0e-12);
}
public static function providerCurrentWorksheetFormulae(): array
{
return [
'relative range in active worksheet' => ['=SUM(B1:B3)', 15.4],
'range with absolute columns in active worksheet' => ['=SUM($B1:$B3)', 15.4],
'range with absolute rows in active worksheet' => ['=SUM(B$1:B$3)', 15.4],
'range with absolute columns and rows in active worksheet' => ['=SUM($B$1:$B$3)', 15.4],
'another relative range in active worksheet' => ['=SUM(B3:D3)', 57.28],
'relative column range in active worksheet' => ['=SUM(B:B)', 15.4],
'absolute column range in active worksheet' => ['=SUM($B:$B)', 15.4],
'relative row range in active worksheet' => ['=SUM(3:3)', 57.28],
'absolute row range in active worksheet' => ['=SUM($3:$3)', 57.28],
'relative range in specified active worksheet' => ['=SUM(\'summary sheet\'!B1:B3)', 15.4],
'range with absolute columns in specified active worksheet' => ['=SUM(\'summary sheet\'!$B1:$B3)', 15.4],
'range with absolute rows in specified active worksheet' => ['=SUM(\'summary sheet\'!B$1:B$3)', 15.4],
'range with absolute columns and rows in specified active worksheet' => ['=SUM(\'summary sheet\'!$B$1:$B$3)', 15.4],
'another relative range in specified active worksheet' => ['=SUM(\'summary sheet\'!B3:D3)', 57.28],
'relative column range in specified active worksheet' => ['=SUM(\'summary sheet\'!B:B)', 15.4],
'absolute column range in specified active worksheet' => ['=SUM(\'summary sheet\'!$B:$B)', 15.4],
'relative row range in specified active worksheet' => ['=SUM(\'summary sheet\'!3:3)', 57.28],
'absolute row range in specified active worksheet' => ['=SUM(\'summary sheet\'!$3:$3)', 57.28],
'relative range in specified other worksheet' => ['=SUM(\'data sheet\'!B1:B3)', 7.7],
'range with absolute columns in specified other worksheet' => ['=SUM(\'data sheet\'!$B1:$B3)', 7.7],
'range with absolute rows in specified other worksheet' => ['=SUM(\'data sheet\'!B$1:B$3)', 7.7],
'range with absolute columns and rows in specified other worksheet' => ['=SUM(\'data sheet\'!$B$1:$B$3)', 7.7],
'another relative range in specified other worksheet' => ['=SUM(\'data sheet\'!B3:D3)', 29.36],
'relative column range in specified other worksheet' => ['=SUM(\'data sheet\'!B:B)', 7.7],
'absolute column range in specified other worksheet' => ['=SUM(\'data sheet\'!$B:$B)', 7.7],
'relative row range in specified other worksheet' => ['=SUM(\'data sheet\'!3:3)', 29.36],
'absolute row range in specified other worksheet' => ['=SUM(\'data sheet\'!$3:$3)', 29.36],
];
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Calculation/ParseFormulaTest.php | tests/PhpSpreadsheetTests/Calculation/ParseFormulaTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Calculation;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PhpOffice\PhpSpreadsheet\Calculation\Engine\Operands\StructuredReference;
use PhpOffice\PhpSpreadsheet\NamedRange;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
class ParseFormulaTest extends TestCase
{
/** @param mixed[] $expectedStack */
#[DataProvider('providerBinaryOperations')]
public function testParseOperations(array $expectedStack, string $formula): void
{
$spreadsheet = new Spreadsheet();
$spreadsheet->addNamedRange(new NamedRange('GROUP1', $spreadsheet->getActiveSheet(), 'B2:D4'));
$spreadsheet->addNamedRange(new NamedRange('GROUP2', $spreadsheet->getActiveSheet(), 'D4:F6'));
$parser = Calculation::getInstance($spreadsheet);
$stack = $parser->parseFormula($formula);
self::assertEquals($expectedStack, $stack);
}
public static function providerBinaryOperations(): array
{
return [
'Unary negative with Value' => [
[
['type' => 'Value', 'value' => 3, 'reference' => null],
['type' => 'Unary Operator', 'value' => '~', 'reference' => null],
],
'=-3',
],
'Unary negative percentage with Value' => [
[
['type' => 'Value', 'value' => 3, 'reference' => null],
['type' => 'Unary Operator', 'value' => '%', 'reference' => null],
['type' => 'Unary Operator', 'value' => '~', 'reference' => null],
],
'=-3%',
],
'Binary minus with Values' => [
[
['type' => 'Value', 'value' => 3, 'reference' => null],
['type' => 'Value', 'value' => 4, 'reference' => null],
['type' => 'Binary Operator', 'value' => '-', 'reference' => null],
],
'=3-4',
],
'Unary negative with Cell Reference' => [
[
['type' => 'Cell Reference', 'value' => 'A1', 'reference' => 'A1'],
['type' => 'Unary Operator', 'value' => '~', 'reference' => null],
],
'=-A1',
],
'Unary negative with FQ Cell Reference' => [
[
['type' => 'Cell Reference', 'value' => "'Sheet 1'!A1", 'reference' => "'Sheet 1'!A1"],
['type' => 'Unary Operator', 'value' => '~', 'reference' => null],
],
"=-'Sheet 1'!A1",
],
'Unary negative percentage with Cell Reference' => [
[
['type' => 'Cell Reference', 'value' => 'A1', 'reference' => 'A1'],
['type' => 'Unary Operator', 'value' => '%', 'reference' => null],
['type' => 'Unary Operator', 'value' => '~', 'reference' => null],
],
'=-A1%',
],
'Unary negative with Defined Name' => [
[
['type' => 'Defined Name', 'value' => 'DEFINED_NAME', 'reference' => 'DEFINED_NAME'],
['type' => 'Unary Operator', 'value' => '~', 'reference' => null],
],
'=-DEFINED_NAME',
],
'Unary negative percentage with Defined Name' => [
[
['type' => 'Defined Name', 'value' => 'DEFINED_NAME', 'reference' => 'DEFINED_NAME'],
['type' => 'Unary Operator', 'value' => '%', 'reference' => null],
['type' => 'Unary Operator', 'value' => '~', 'reference' => null],
],
'=-DEFINED_NAME%',
],
'Integer Numbers with Operator' => [
[
['type' => 'Value', 'value' => 2, 'reference' => null],
['type' => 'Value', 'value' => 3, 'reference' => null],
['type' => 'Binary Operator', 'value' => '*', 'reference' => null],
],
'=2*3',
],
'Float Numbers with Operator' => [
[
['type' => 'Value', 'value' => 2.5, 'reference' => null],
['type' => 'Value', 'value' => 3.5, 'reference' => null],
['type' => 'Binary Operator', 'value' => '*', 'reference' => null],
],
'=2.5*3.5',
],
'Strings with Operator' => [
[
['type' => 'Value', 'value' => '"HELLO"', 'reference' => null],
['type' => 'Value', 'value' => '"WORLD"', 'reference' => null],
['type' => 'Binary Operator', 'value' => '&', 'reference' => null],
],
'="HELLO"&"WORLD"',
],
'Error' => [
[
['type' => 'Value', 'value' => '#DIV0!', 'reference' => null],
],
'=#DIV0!',
],
'Cell Range' => [
[
['type' => 'Cell Reference', 'value' => 'A1', 'reference' => 'A1'],
['type' => 'Cell Reference', 'value' => 'C3', 'reference' => 'C3'],
['type' => 'Binary Operator', 'value' => ':', 'reference' => null],
],
'=A1:C3',
],
'Chained Cell Range' => [
[
['type' => 'Cell Reference', 'value' => 'A1', 'reference' => 'A1'],
['type' => 'Cell Reference', 'value' => 'C3', 'reference' => 'C3'],
['type' => 'Binary Operator', 'value' => ':', 'reference' => null],
['type' => 'Cell Reference', 'value' => 'E5', 'reference' => 'E5'],
['type' => 'Binary Operator', 'value' => ':', 'reference' => null],
],
'=A1:C3:E5',
],
'Cell Range Intersection' => [
[
['type' => 'Cell Reference', 'value' => 'A1', 'reference' => 'A1'],
['type' => 'Cell Reference', 'value' => 'C3', 'reference' => 'C3'],
['type' => 'Binary Operator', 'value' => ':', 'reference' => null],
['type' => 'Cell Reference', 'value' => 'B2', 'reference' => 'B2'],
['type' => 'Cell Reference', 'value' => 'D4', 'reference' => 'D4'],
['type' => 'Binary Operator', 'value' => ':', 'reference' => null],
['type' => 'Binary Operator', 'value' => '∩', 'reference' => null],
],
'=A1:C3 B2:D4',
],
'Row Range' => [
[
['type' => 'Row Reference', 'value' => 'A2', 'reference' => 'A2'],
['type' => 'Row Reference', 'value' => 'XFD3', 'reference' => 'XFD3'],
['type' => 'Binary Operator', 'value' => ':', 'reference' => null],
],
'=2:3',
],
'Column Range' => [
[
['type' => 'Column Reference', 'value' => 'B1', 'reference' => 'B1'],
['type' => 'Column Reference', 'value' => 'C1048576', 'reference' => 'C1048576'],
['type' => 'Binary Operator', 'value' => ':', 'reference' => null],
],
'=B:C',
],
'Combined Cell Reference and Column Range' => [
[
['type' => 'Column Reference', 'value' => "'sheet1'!A1", 'reference' => "'sheet1'!A1"],
['type' => 'Column Reference', 'value' => "'sheet1'!A1048576", 'reference' => "'sheet1'!A1048576"],
['type' => 'Binary Operator', 'value' => ':', 'reference' => null],
['type' => 'Operand Count for Function MIN()', 'value' => 1, 'reference' => null],
['type' => 'Function', 'value' => 'MIN(', 'reference' => null],
['type' => 'Cell Reference', 'value' => "'sheet1'!A1", 'reference' => "'sheet1'!A1"],
['type' => 'Binary Operator', 'value' => '+', 'reference' => null],
],
"=MIN('sheet1'!A:A) + 'sheet1'!A1",
],
'Combined Cell Reference and Column Range Unquoted Sheet' => [
[
['type' => 'Column Reference', 'value' => 'sheet1!A1', 'reference' => 'sheet1!A1'],
['type' => 'Column Reference', 'value' => 'sheet1!A1048576', 'reference' => 'sheet1!A1048576'],
['type' => 'Binary Operator', 'value' => ':', 'reference' => null],
['type' => 'Operand Count for Function MIN()', 'value' => 1, 'reference' => null],
['type' => 'Function', 'value' => 'MIN(', 'reference' => null],
['type' => 'Cell Reference', 'value' => 'sheet1!A1', 'reference' => 'sheet1!A1'],
['type' => 'Binary Operator', 'value' => '+', 'reference' => null],
],
'=MIN(sheet1!A:A) + sheet1!A1',
],
'Combined Cell Reference and Column Range with quote' => [
[
['type' => 'Column Reference', 'value' => "'Mark's sheet1'!A1", 'reference' => "'Mark's sheet1'!A1"],
['type' => 'Column Reference', 'value' => "'Mark's sheet1'!A1048576", 'reference' => "'Mark's sheet1'!A1048576"],
['type' => 'Binary Operator', 'value' => ':', 'reference' => null],
['type' => 'Operand Count for Function MIN()', 'value' => 1, 'reference' => null],
['type' => 'Function', 'value' => 'MIN(', 'reference' => null],
['type' => 'Cell Reference', 'value' => "'Mark's sheet1'!A1", 'reference' => "'Mark's sheet1'!A1"],
['type' => 'Binary Operator', 'value' => '+', 'reference' => null],
],
"=MIN('Mark''s sheet1'!A:A) + 'Mark''s sheet1'!A1",
],
'Combined Cell Reference and Column Range with unescaped quote' => [
[
['type' => 'Column Reference', 'value' => "'Mark's sheet1'!A1", 'reference' => "'Mark's sheet1'!A1"],
['type' => 'Column Reference', 'value' => "'Mark's sheet1'!A1048576", 'reference' => "'Mark's sheet1'!A1048576"],
['type' => 'Binary Operator', 'value' => ':', 'reference' => null],
['type' => 'Operand Count for Function MIN()', 'value' => 1, 'reference' => null],
['type' => 'Function', 'value' => 'MIN(', 'reference' => null],
['type' => 'Cell Reference', 'value' => "'Mark's sheet1'!A1", 'reference' => "'Mark's sheet1'!A1"],
['type' => 'Binary Operator', 'value' => '+', 'reference' => null],
],
"=MIN('Mark's sheet1'!A:A) + 'Mark's sheet1'!A1",
],
'Combined Column Range and Cell Reference' => [
[
['type' => 'Cell Reference', 'value' => "'sheet1'!A1", 'reference' => "'sheet1'!A1"],
['type' => 'Column Reference', 'value' => "'sheet1'!A1", 'reference' => "'sheet1'!A1"],
['type' => 'Column Reference', 'value' => "'sheet1'!A1048576", 'reference' => "'sheet1'!A1048576"],
['type' => 'Binary Operator', 'value' => ':', 'reference' => null],
['type' => 'Operand Count for Function MIN()', 'value' => 1, 'reference' => null],
['type' => 'Function', 'value' => 'MIN(', 'reference' => null],
['type' => 'Binary Operator', 'value' => '+', 'reference' => null],
],
"='sheet1'!A1 + MIN('sheet1'!A:A)",
],
'Combined Column Range and Cell Reference with quote' => [
[
['type' => 'Cell Reference', 'value' => "'Mark's sheet1'!A1", 'reference' => "'Mark's sheet1'!A1"],
['type' => 'Column Reference', 'value' => "'Mark's sheet1'!A1", 'reference' => "'Mark's sheet1'!A1"],
['type' => 'Column Reference', 'value' => "'Mark's sheet1'!A1048576", 'reference' => "'Mark's sheet1'!A1048576"],
['type' => 'Binary Operator', 'value' => ':', 'reference' => null],
['type' => 'Operand Count for Function MIN()', 'value' => 1, 'reference' => null],
['type' => 'Function', 'value' => 'MIN(', 'reference' => null],
['type' => 'Binary Operator', 'value' => '+', 'reference' => null],
],
"='Mark''s sheet1'!A1 + MIN('Mark''s sheet1'!A:A)",
],
'Combined Column Range and Cell Reference with unescaped quote' => [
[
['type' => 'Cell Reference', 'value' => "'Mark's sheet1'!A1", 'reference' => "'Mark's sheet1'!A1"],
['type' => 'Column Reference', 'value' => "'Mark's sheet1'!A1", 'reference' => "'Mark's sheet1'!A1"],
['type' => 'Column Reference', 'value' => "'Mark's sheet1'!A1048576", 'reference' => "'Mark's sheet1'!A1048576"],
['type' => 'Binary Operator', 'value' => ':', 'reference' => null],
['type' => 'Operand Count for Function MIN()', 'value' => 1, 'reference' => null],
['type' => 'Function', 'value' => 'MIN(', 'reference' => null],
['type' => 'Binary Operator', 'value' => '+', 'reference' => null],
],
"='Mark's sheet1'!A1 + MIN('Mark's sheet1'!A:A)",
],
'Range with Defined Names' => [
[
['type' => 'Defined Name', 'value' => 'GROUP1', 'reference' => 'GROUP1'],
['type' => 'Defined Name', 'value' => 'D4', 'reference' => 'GROUP2'],
['type' => 'Binary Operator', 'value' => ':', 'reference' => null],
['type' => 'Defined Name', 'value' => 'F6', 'reference' => 'GROUP2'],
['type' => 'Binary Operator', 'value' => ':', 'reference' => null],
],
'=GROUP1:GROUP2',
],
'Named Range with Binary Operator' => [
[
['type' => 'Defined Name', 'value' => 'DEFINED_NAME_1', 'reference' => 'DEFINED_NAME_1'],
['type' => 'Defined Name', 'value' => 'DEFINED_NAME_2', 'reference' => 'DEFINED_NAME_2'],
['type' => 'Binary Operator', 'value' => '/', 'reference' => null],
],
'=DEFINED_NAME_1/DEFINED_NAME_2',
],
'Named Range Intersection' => [
[
['type' => 'Defined Name', 'value' => 'DEFINED_NAME_1', 'reference' => 'DEFINED_NAME_1'],
['type' => 'Defined Name', 'value' => 'DEFINED_NAME_2', 'reference' => 'DEFINED_NAME_2'],
['type' => 'Binary Operator', 'value' => '∩', 'reference' => null],
],
'=DEFINED_NAME_1 DEFINED_NAME_2',
],
'Fully Qualified Structured Reference' => [
[
['type' => 'Structured Reference', 'value' => new StructuredReference('DeptSales[@Commission Amount]'), 'reference' => null],
],
'=DeptSales[@Commission Amount]',
],
'Fully Qualified Nested Structured Reference' => [
[
['type' => 'Structured Reference', 'value' => new StructuredReference('DeptSales[[#Totals],[Sales Amount]]'), 'reference' => null],
],
'=DeptSales[[#Totals],[Sales Amount]]',
],
'Complex Range Fully Qualified Nested Structured Reference' => [
[
['type' => 'Structured Reference', 'value' => new StructuredReference('Sales_Data[[#This Row],[Q1]:[Q4]]'), 'reference' => null],
],
'=Sales_Data[[#This Row],[Q1]:[Q4]]',
],
'Complex Range Fully Qualified Nested Structured Reference 2' => [
[
['type' => 'Structured Reference', 'value' => new StructuredReference('DeptSales[[#Headers],[Region]:[Commission Amount]]'), 'reference' => null],
],
'=DeptSales[[#Headers],[Region]:[Commission Amount]]',
],
'Multi-RowGroup Fully Qualified Nested Structured Reference' => [
[
['type' => 'Structured Reference', 'value' => new StructuredReference('DeptSales[[#Headers],[#Data],[% Commission]]'), 'reference' => null],
],
'=DeptSales[[#Headers],[#Data],[% Commission]]',
],
'Unqualified Structured Reference' => [
[
['type' => 'Structured Reference', 'value' => new StructuredReference('[@Quantity]'), 'reference' => null],
],
'=[@Quantity]',
],
'Unqualified Nested Structured Reference' => [
[
['type' => 'Structured Reference', 'value' => new StructuredReference('[@[Unit Price]]'), 'reference' => null],
],
'=[@[Unit Price]]',
],
'Fully Qualified Full Table Structured Reference' => [
[
['type' => 'Structured Reference', 'value' => new StructuredReference('DeptSales[]'), 'reference' => null],
],
'=DeptSales[]',
],
'Unqualified Full Table Structured Reference' => [
[
['type' => 'Structured Reference', 'value' => new StructuredReference('[]'), 'reference' => null],
],
'=[]',
],
'Structured Reference Arithmetic' => [
[
['type' => 'Structured Reference', 'value' => new StructuredReference('[@Quantity]'), 'reference' => null],
['type' => 'Structured Reference', 'value' => new StructuredReference('[@[Unit Price]]'), 'reference' => null],
['type' => 'Binary Operator', 'value' => '*', 'reference' => null],
],
'=[@Quantity]*[@[Unit Price]]',
],
'Structured Reference Intersection' => [
[
['type' => 'Structured Reference', 'value' => new StructuredReference('DeptSales[[Sales Person]:[Sales Amount]]'), 'reference' => null],
['type' => 'Structured Reference', 'value' => new StructuredReference('DeptSales[[Region]:[% Commission]]'), 'reference' => null],
['type' => 'Binary Operator', 'value' => '∩', 'reference' => null],
],
'=DeptSales[[Sales Person]:[Sales Amount]] DeptSales[[Region]:[% Commission]]',
],
// 'Cell Range Union' => [
// [
// ['type' => 'Cell Reference', 'value' => 'A1', 'reference' => 'A1'],
// ['type' => 'Cell Reference', 'value' => 'C3', 'reference' => 'C3'],
// ['type' => 'Binary Operator', 'value' => ':', 'reference' => null],
// ['type' => 'Cell Reference', 'value' => 'B2', 'reference' => 'B2'],
// ['type' => 'Cell Reference', 'value' => 'D4', 'reference' => 'D4'],
// ['type' => 'Binary Operator', 'value' => ':', 'reference' => null],
// ['type' => 'Binary Operator', 'value' => '∪', 'reference' => null],
// ],
// '=A1:C3,B2:D4',
// ],
// 'Named Range Union' => [
// [
// ['type' => 'Defined Name', 'value' => 'DEFINED_NAME_1', 'reference' => 'DEFINED_NAME_1'],
// ['type' => 'Defined Name', 'value' => 'DEFINED_NAME_2', 'reference' => 'DEFINED_NAME_2'],
// ['type' => 'Binary Operator', 'value' => '∪', 'reference' => null],
// ],
// '=DEFINED_NAME_1,DEFINED_NAME_2',
// ],
];
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Calculation/CalculationErrorTest.php | tests/PhpSpreadsheetTests/Calculation/CalculationErrorTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Calculation;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PhpOffice\PhpSpreadsheet\Calculation\Exception as CalcException;
use PHPUnit\Framework\TestCase;
class CalculationErrorTest extends TestCase
{
public function testCalculationExceptionSuppressed(): void
{
$calculation = Calculation::getInstance();
self::assertFalse($calculation->getSuppressFormulaErrors());
$calculation->setSuppressFormulaErrors(true);
$result = $calculation->calculateFormula('=SUM(');
$calculation->setSuppressFormulaErrors(false);
self::assertFalse($result);
}
public function testCalculationException(): void
{
$calculation = Calculation::getInstance();
self::assertFalse($calculation->getSuppressFormulaErrors());
$this->expectException(CalcException::class);
$this->expectExceptionMessage("Formula Error: Expecting ')'");
$result = $calculation->calculateFormula('=SUM(');
self::assertFalse($result);
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Calculation/Functions/FormulaArguments.php | tests/PhpSpreadsheetTests/Calculation/Functions/FormulaArguments.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions;
use Exception;
use PhpOffice\PhpSpreadsheet\Cell\CellAddress;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use Stringable;
class FormulaArguments implements Stringable
{
/**
* @var mixed[]
*/
protected array $args;
public function __construct(mixed ...$args)
{
$this->args = $args;
}
public function populateWorksheet(Worksheet $worksheet): string
{
$cells = [];
$cellAddress = new CellAddress('A2');
foreach ($this->args as $value) {
if (is_array($value)) {
// We need to set a matrix in the worksheet
$worksheet->fromArray($value, null, (string) $cellAddress, true);
$from = (string) $cellAddress;
$columns = is_array($value[0]) ? count($value[0]) : count($value);
$rows = is_array($value[0]) ? count($value) : 1;
$to = $cellAddress->nextColumn($columns)->nextRow($rows);
$cells[] = "{$from}:{$to}";
$columnIncrement = $columns;
} else {
$worksheet->setCellValue($cellAddress, $value);
$cells[] = (string) $cellAddress;
$columnIncrement = 1;
}
$cellAddress = $cellAddress->nextColumn($columnIncrement);
}
return implode(',', $cells);
}
/** @param mixed[] $value */
private function matrixRows(array $value): string
{
$columns = [];
foreach ($value as $column) {
$columns[] = $this->stringify($column);
}
return implode(',', $columns);
}
/** @param mixed[] $value */
private function makeMatrix(array $value): string
{
$matrix = [];
foreach ($value as $row) {
if (is_array($row)) {
$matrix[] = $this->matrixRows($row);
} else {
$matrix[] = $this->stringify($row);
}
}
return implode(';', $matrix);
}
private function stringify(mixed $value): string
{
if (is_array($value)) {
return '{' . $this->makeMatrix($value) . '}';
} elseif (null === $value) {
return '';
} elseif (is_string($value)) {
return '"' . str_replace('"', '""', $value) . '"';
} elseif (is_bool($value)) {
return $value ? 'TRUE' : 'FALSE';
}
if (is_scalar($value) || $value instanceof Stringable) {
return (string) $value;
}
throw new Exception('Cannot convert object to string');
}
public function __toString(): string
{
$args = array_map(
self::stringify(...),
$this->args
);
return implode(',', $args);
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Calculation/Functions/LookupRef/ChooseColsTest.php | tests/PhpSpreadsheetTests/Calculation/Functions/LookupRef/ChooseColsTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\LookupRef;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PhpOffice\PhpSpreadsheet\NamedRange;
use PHPUnit\Framework\Attributes\DataProvider;
class ChooseColsTest extends AllSetupTeardown
{
#[DataProvider('providerChooseCols')]
public function testChooseCols(mixed $expectedResult, string $formula): void
{
Calculation::setArrayReturnType(
Calculation::RETURN_ARRAY_AS_ARRAY
);
$this->mightHaveException($expectedResult);
$sheet = $this->getSheet();
$sheet->fromArray(
[
['a', 'b', 'c'],
['d', 'e', 'f'],
['g', 'h', 'i'],
['j', 'k', 'l'],
['m', 'n', 'o'],
['p', 'q', 'r'],
['s', 't', 'u'],
['v', 'w', 'x'],
['y', 'z', '#'],
],
null,
'B3',
true
);
$this->getSpreadsheet()->addNamedRange(
new NamedRange(
'definedname',
$sheet,
'$B$3:$D$11'
)
);
$sheet->setCellValue('F3', $formula);
$result = $sheet->getCell('F3')->getCalculatedValue();
self::assertSame($expectedResult, $result);
}
public static function providerChooseCols(): array
{
return require 'tests/data/Calculation/LookupRef/CHOOSECOLS.php';
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Calculation/Functions/LookupRef/ColumnTest.php | tests/PhpSpreadsheetTests/Calculation/Functions/LookupRef/ColumnTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\LookupRef;
use PhpOffice\PhpSpreadsheet\Calculation\LookupRef;
use PHPUnit\Framework\Attributes\DataProvider;
class ColumnTest extends AllSetupTeardown
{
/** @param null|mixed[]|string $cellReference */
#[DataProvider('providerCOLUMN')]
public function testCOLUMN(mixed $expectedResult, null|array|string $cellReference = null): void
{
$result = LookupRef\RowColumnInformation::COLUMN($cellReference);
self::assertSame($expectedResult, $result);
}
public static function providerCOLUMN(): array
{
return require 'tests/data/Calculation/LookupRef/COLUMN.php';
}
public function testCOLUMNwithNull(): void
{
$sheet = $this->getSheet();
$sheet->getCell('D1')->setValue('=COLUMN()');
self::assertSame(4, $sheet->getCell('D1')->getCalculatedValue());
$sheet->getCell('D2')->setValue('=COLUMN(C13)');
self::assertSame(3, $sheet->getCell('D2')->getCalculatedValue());
// Sheetnames don't have to exist
$sheet->getCell('D3')->setValue('=COLUMN(Sheet17!E15)');
self::assertSame(5, $sheet->getCell('D3')->getCalculatedValue());
$sheet->getCell('D4')->setValue("=COLUMN('Worksheet #5'!X500)");
self::assertSame(24, $sheet->getCell('D4')->getCalculatedValue());
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Calculation/Functions/LookupRef/DropTest.php | tests/PhpSpreadsheetTests/Calculation/Functions/LookupRef/DropTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\LookupRef;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PhpOffice\PhpSpreadsheet\NamedRange;
use PHPUnit\Framework\Attributes\DataProvider;
class DropTest extends AllSetupTeardown
{
#[DataProvider('providerDrop')]
public function testDrop(mixed $expectedResult, string $formula): void
{
Calculation::setArrayReturnType(
Calculation::RETURN_ARRAY_AS_ARRAY
);
$this->mightHaveException($expectedResult);
$sheet = $this->getSheet();
$sheet->fromArray(
[
['a', 'b', 'c'],
['d', 'e', 'f'],
['g', 'h', 'i'],
['j', 'k', 'l'],
['m', 'n', 'o'],
['p', 'q', 'r'],
['s', 't', 'u'],
['v', 'w', 'x'],
['y', 'z', '#'],
],
null,
'B3',
true
);
$this->getSpreadsheet()->addNamedRange(
new NamedRange(
'definedname',
$sheet,
'$B$3:$D$11'
)
);
$sheet->setCellValue('F3', $formula);
$result = $sheet->getCell('F3')->getCalculatedValue();
self::assertSame($expectedResult, $result);
}
public static function providerDrop(): array
{
return require 'tests/data/Calculation/LookupRef/DROP.php';
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Calculation/Functions/LookupRef/MatrixHelperFunctionsTest.php | tests/PhpSpreadsheetTests/Calculation/Functions/LookupRef/MatrixHelperFunctionsTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\LookupRef;
use PhpOffice\PhpSpreadsheet\Calculation\LookupRef\Matrix;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
class MatrixHelperFunctionsTest extends TestCase
{
/** @param mixed[] $array */
#[DataProvider('columnVectorProvider')]
public function testIsColumnVector(bool $expectedResult, array $array): void
{
$result = Matrix::isColumnVector($array);
self::assertSame($expectedResult, $result);
}
/** @param mixed[] $array */
#[DataProvider('rowVectorProvider')]
public function testIsRowVector(bool $expectedResult, array $array): void
{
$result = Matrix::isRowVector($array);
self::assertSame($expectedResult, $result);
}
public static function columnVectorProvider(): array
{
return [
[
true,
[
[1], [2], [3],
],
],
[
false,
[1, 2, 3],
],
[
false,
[
[1, 2, 3],
[4, 5, 6],
],
],
];
}
public static function rowVectorProvider(): array
{
return [
[
false,
[
[1], [2], [3],
],
],
[
true,
[1, 2, 3],
],
[
true,
[[1, 2, 3]],
],
[
false,
[
[1, 2, 3],
[4, 5, 6],
],
],
];
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/tests/PhpSpreadsheetTests/Calculation/Functions/LookupRef/VLookupTest.php | tests/PhpSpreadsheetTests/Calculation/Functions/LookupRef/VLookupTest.php | <?php
declare(strict_types=1);
namespace PhpOffice\PhpSpreadsheetTests\Calculation\Functions\LookupRef;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PHPUnit\Framework\Attributes\DataProvider;
class VLookupTest extends AllSetupTeardown
{
#[DataProvider('providerVLOOKUP')]
public function testVLOOKUP(mixed $expectedResult, mixed $value, mixed $table, mixed $index, ?bool $lookup = null): void
{
$this->setArrayAsValue();
$sheet = $this->getSheet();
if (is_array($table)) {
$sheet->fromArray($table);
$dimension = $sheet->calculateWorksheetDimension();
} else {
$sheet->getCell('A1')->setValue($table);
$dimension = 'A1';
}
if ($lookup === null) {
$lastarg = '';
} else {
$lastarg = $lookup ? ',TRUE' : ',FALSE';
}
$sheet->getCell('Z98')->setValue($value);
if (is_array($index)) {
$sheet->fromArray($index, null, 'Z100', true);
$indexarg = 'Z100:Z' . (string) (99 + count($index));
} else {
$sheet->getCell('Z100')->setValue($index);
$indexarg = 'Z100';
}
$sheet->getCell('Z99')->setValue("=VLOOKUP(Z98,$dimension,$indexarg$lastarg)");
$result = $sheet->getCell('Z99')->getCalculatedValue();
self::assertEquals($expectedResult, $result);
}
public static function providerVLOOKUP(): array
{
return require 'tests/data/Calculation/LookupRef/VLOOKUP.php';
}
#[DataProvider('providerVLookupArray')]
public function testVLookupArray(array $expectedResult, string $values, string $database, string $index): void
{
$calculation = Calculation::getInstance();
$formula = "=VLOOKUP({$values}, {$database}, {$index}, false)";
$result = $calculation->calculateFormula($formula);
self::assertSame($expectedResult, $result);
}
public static function providerVLookupArray(): array
{
return [
'row vector' => [
[[4.19, 5.77, 4.14]],
'{"Orange", "Green", "Red"}',
'{"Red", 4.14; "Orange", 4.19; "Yellow", 5.17; "Green", 5.77; "Blue", 6.39}',
'2',
],
'issue 3561' => [
[[7, 8, 7]],
'6',
'{1,2,3,4,5;6,7,8,9,10;11,12,13,14,15}',
'{2,3,2}',
],
];
}
public function testIssue1402(): void
{
$worksheet = $this->getSheet();
$worksheet->setCellValueExplicit('A1', 1, DataType::TYPE_STRING);
$worksheet->setCellValue('B1', 'Text Nr 1');
$worksheet->setCellValue('A2', 2);
$worksheet->setCellValue('B2', 'Numeric result');
$worksheet->setCellValueExplicit('A3', 2, DataType::TYPE_STRING);
$worksheet->setCellValue('B3', 'Text Nr 2');
$worksheet->setCellValueExplicit('A4', 2, DataType::TYPE_STRING);
$worksheet->setCellValue('B4', '=VLOOKUP(A4,$A$1:$B$3,2,0)');
self::assertSame('Text Nr 2', $worksheet->getCell('B4')->getCalculatedValue());
$worksheet->setCellValue('A5', 2);
$worksheet->setCellValue('B5', '=VLOOKUP(A5,$A$1:$B$3,2,0)');
self::assertSame('Numeric result', $worksheet->getCell('B5')->getCalculatedValue());
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.