Files
PhpSpreadsheet/tests/PhpSpreadsheetTests/Calculation/CustomFunctionTest.php
T
oleibman 53bce34456 Add Ability to Add Custom Functions to Calculation
For an overview of why this is desired (and ways that people have coped with its absence), see issue #2900 and issue #4048; also PR #4043 which will be superseded by this PR.

The list of Excel functions is moved from Calculation/Calculation to its own member. I believe that it is done in a way that will not cause big complications to two experiments from @MarkBaker (PR #2714 and PR #2734). I believe it is also done in such a way that further refactoring of Calculation can follow this model.

Custom functions can be added or removed from the function list. You cannot add a function if it already exists in the list, and you cannot remove a non-custom function from the list. They will, of course, not be understood by Excel if written to a spreadsheet; the use case is mainly using the Calculation engine outside of spreadsheet context.
2025-03-02 13:56:34 -08:00

36 lines
1.4 KiB
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';
// I have no idea why Phpstan needs this
/** @var array<string, array> */
$value = [
'category' => 'custom',
'functionCall' => [CustomFunction::class, 'fourthPower'],
'argumentCount' => '1',
];
self::assertTrue(Calculation::addFunction($key, $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'));
}
}