Skip to content

Commit

Permalink
Adding varExists method and support for undefined var handler in getV…
Browse files Browse the repository at this point in the history
…ar (#96)

* Added varExists method

* getVar now respects VarNotFoundHandler setting

* Use local version of PHP-CS-Fixer

Instead of hard coded version from github actions

* Fixing actions

* Fixing actions

* Dropping testing for 7.3, as it is no longer supported
  • Loading branch information
phpfui authored Mar 21, 2022
1 parent 6ebe484 commit a0ff7a7
Show file tree
Hide file tree
Showing 9 changed files with 79 additions and 51 deletions.
8 changes: 4 additions & 4 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ jobs:
strategy:
fail-fast: false
matrix:
php: [8.1, 8.0, 7.4, 7.3]
php: [8.1, 8.0, 7.4]
dependency-version: [prefer-lowest, prefer-stable]
os: [ubuntu-latest, windows-latest]

Expand All @@ -34,7 +34,7 @@ jobs:
run: vendor/bin/phpunit

- name: PHP CS Fixer
uses: StephaneBour/[email protected]
if: matrix.os != 'windows-latest'
with:
dir: './src'
run: |
vendor/bin/php-cs-fixer fix --dry-run -v ./src
vendor/bin/php-cs-fixer fix --dry-run -v ./tests
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,5 @@ vendor/
composer.lock
.phpunit.result.cache
.vscode
.php-cs-fixer.cache

3 changes: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,8 @@
"php": ">=7.3"
},
"require-dev": {
"phpunit/phpunit": ">=9.0"
"phpunit/phpunit": ">=9.0",
"friendsofphp/php-cs-fixer": "^3.8"
},
"autoload": {
"psr-4": {
Expand Down
3 changes: 1 addition & 2 deletions src/NXP/Classes/CustomFunction.php
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
<?php


namespace NXP\Classes;

use NXP\Exception\IncorrectNumberOfFunctionParametersException;
Expand Down Expand Up @@ -49,7 +48,7 @@ public function __construct(string $name, callable $function, ?int $places = nul
*
* @throws IncorrectNumberOfFunctionParametersException
*/
public function execute(array &$stack) : Token
public function execute(array &$stack): Token
{
if (count($stack) < $this->places) {
throw new IncorrectNumberOfFunctionParametersException($this->name);
Expand Down
3 changes: 1 addition & 2 deletions src/NXP/Classes/Operator.php
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
<?php


namespace NXP\Classes;

use NXP\Exception\IncorrectExpressionException;
Expand Down Expand Up @@ -55,7 +54,7 @@ public function __construct(string $operator, bool $isRightAssoc, int $priority,
*
* @throws IncorrectExpressionException
*/
public function execute(array &$stack) : Token
public function execute(array &$stack): Token
{
if (count($stack) < $this->places) {
throw new IncorrectExpressionException();
Expand Down
1 change: 0 additions & 1 deletion src/NXP/Classes/Token.php
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
<?php


namespace NXP\Classes;

class Token
Expand Down
20 changes: 10 additions & 10 deletions src/NXP/Classes/Tokenizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ public function __construct(string $input, array $operators)
$this->operators = $operators;
}

public function tokenize() : self
public function tokenize(): self
{
foreach (str_split($this->input, 1) as $ch) {
switch (true) {
Expand Down Expand Up @@ -184,48 +184,48 @@ public function tokenize() : self
return $this;
}

private function isNumber(string $ch) : bool
private function isNumber(string $ch): bool
{
return $ch >= '0' && $ch <= '9';
}

private function isAlpha(string $ch) : bool
private function isAlpha(string $ch): bool
{
return $ch >= 'a' && $ch <= 'z' || $ch >= 'A' && $ch <= 'Z' || $ch == '_';
}

private function emptyNumberBufferAsLiteral() : void
private function emptyNumberBufferAsLiteral(): void
{
if (strlen($this->numberBuffer)) {
$this->tokens[] = new Token(Token::Literal, $this->numberBuffer);
$this->numberBuffer = '';
}
}

private function isDot(string $ch) : bool
private function isDot(string $ch): bool
{
return $ch == '.';
}

private function isLP(string $ch) : bool
private function isLP(string $ch): bool
{
return $ch == '(';
}

private function isRP(string $ch) : bool
private function isRP(string $ch): bool
{
return $ch == ')';
}

private function emptyStrBufferAsVariable() : void
private function emptyStrBufferAsVariable(): void
{
if ($this->stringBuffer != '') {
$this->tokens[] = new Token(Token::Variable, $this->stringBuffer);
$this->stringBuffer = '';
}
}

private function isComma(string $ch) : bool
private function isComma(string $ch): bool
{
return $ch == ',';
}
Expand All @@ -235,7 +235,7 @@ private function isComma(string $ch) : bool
* @throws IncorrectBracketsException
* @throws UnknownOperatorException
*/
public function buildReversePolishNotation() : array
public function buildReversePolishNotation(): array
{
$tokens = [];
/** @var SplStack<Token> $stack */
Expand Down
45 changes: 29 additions & 16 deletions src/NXP/MathExecutor.php
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ public function __construct()
* Set default operands and functions
* @throws ReflectionException
*/
protected function addDefaults() : void
protected function addDefaults(): void
{
foreach ($this->defaultOperators() as $name => $operator) {
[$callable, $priority, $isRightAssoc] = $operator;
Expand All @@ -82,7 +82,7 @@ protected function addDefaults() : void
*
* @return array<string, array{callable, int, bool}>
*/
protected function defaultOperators() : array
protected function defaultOperators(): array
{
return [
'+' => [
Expand Down Expand Up @@ -210,7 +210,7 @@ function ($a, $b) {
* @param Operator $operator
* @return MathExecutor
*/
public function addOperator(Operator $operator) : self
public function addOperator(Operator $operator): self
{
$this->operators[$operator->operator] = $operator;
return $this;
Expand All @@ -222,7 +222,7 @@ public function addOperator(Operator $operator) : self
*
* @return array<callable>
*/
protected function defaultFunctions() : array
protected function defaultFunctions(): array
{
return [
'abs' => function ($arg) {
Expand Down Expand Up @@ -459,7 +459,7 @@ public function execute(string $expression, bool $cache = true)
* @return MathExecutor
* @throws ReflectionException
*/
public function addFunction(string $name, ?callable $function = null, ?int $places = null) : self
public function addFunction(string $name, ?callable $function = null, ?int $places = null): self
{
$this->functions[$name] = new CustomFunction($name, $function, $places);
return $this;
Expand All @@ -470,7 +470,7 @@ public function addFunction(string $name, ?callable $function = null, ?int $plac
*
* @return array<string, float>
*/
protected function defaultVars() : array
protected function defaultVars(): array
{
return [
'pi' => 3.14159265359,
Expand All @@ -483,7 +483,7 @@ protected function defaultVars() : array
*
* @return array<string, float|string>
*/
public function getVars() : array
public function getVars(): array
{
return $this->variables;
}
Expand All @@ -493,11 +493,14 @@ public function getVars() : array
*
* @param string $variable
* @return integer|float
* @throws UnknownVariableException
* @throws UnknownVariableException if VarNotFoundHandler is not set
*/
public function getVar(string $variable)
{
if (!array_key_exists($variable, $this->variables)) {
if ($this->onVarNotFound) {
return call_user_func($this->onVarNotFound, $variable);
}
throw new UnknownVariableException("Variable ({$variable}) not set");
}
return $this->variables[$variable];
Expand All @@ -510,7 +513,7 @@ public function getVar(string $variable)
* @param int|float $value
* @return MathExecutor
*/
public function setVar(string $variable, $value) : self
public function setVar(string $variable, $value): self
{
if (!is_scalar($value) && $value !== null) {
$type = gettype($value);
Expand All @@ -521,6 +524,16 @@ public function setVar(string $variable, $value) : self
return $this;
}

/**
* Test to see if a variable exists
*
* @param string $variable
*/
public function varExists(string $variable): bool
{
return array_key_exists($variable, $this->variables);
}

/**
* Add variables to executor
*
Expand All @@ -529,7 +542,7 @@ public function setVar(string $variable, $value) : self
* @return MathExecutor
* @throws \Exception
*/
public function setVars(array $variables, bool $clear = true) : self
public function setVars(array $variables, bool $clear = true): self
{
if ($clear) {
$this->removeVars();
Expand Down Expand Up @@ -560,7 +573,7 @@ public function setVarNotFoundHandler(callable $handler): self
* @param string $variable
* @return MathExecutor
*/
public function removeVar(string $variable) : self
public function removeVar(string $variable): self
{
unset($this->variables[$variable]);
return $this;
Expand All @@ -570,7 +583,7 @@ public function removeVar(string $variable) : self
* Remove all variables and the variable not found handler
* @return MathExecutor
*/
public function removeVars() : self
public function removeVars(): self
{
$this->variables = [];
$this->onVarNotFound = null;
Expand All @@ -593,7 +606,7 @@ public function getOperators()
* @return array<string, CustomFunction> containing callback and places indexed by
* function name
*/
public function getFunctions() : array
public function getFunctions(): array
{
return $this->functions;
}
Expand All @@ -603,7 +616,7 @@ public function getFunctions() : array
*
* @return MathExecutor
*/
public function setDivisionByZeroIsZero() : self
public function setDivisionByZeroIsZero(): self
{
$this->addOperator(new Operator("/", false, 180, function ($a, $b) {
if ($b == 0) {
Expand All @@ -618,15 +631,15 @@ public function setDivisionByZeroIsZero() : self
* Get cache array with tokens
* @return array<string, Token[]>
*/
public function getCache() : array
public function getCache(): array
{
return $this->cache;
}

/**
* Clear token's cache
*/
public function clearCache() : void
public function clearCache(): void
{
$this->cache = [];
}
Expand Down
45 changes: 30 additions & 15 deletions tests/MathTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -58,17 +58,17 @@ public function providerExpressions()
['(4*2) - 5'],
['4*-5'],
['4 * -5'],
['+5'],
['+(3+2)'],
['+(+3+2)'],
['+(-3+2)'],
['-5'],
['-(-5)'],
['-(+5)'],
['+(-5)'],
['+(+5)'],
['-(3+2)'],
['-(-3+-2)'],
['+5'],
['+(3+2)'],
['+(+3+2)'],
['+(-3+2)'],
['-5'],
['-(-5)'],
['-(+5)'],
['+(-5)'],
['+(+5)'],
['-(3+2)'],
['-(-3+-2)'],

['abs(1.5)'],
['acos(0.15)'],
Expand Down Expand Up @@ -499,6 +499,15 @@ function ($varName) {
}
);
$this->assertEquals(15, $calculator->execute('5 * undefined'));
$this->assertEquals(3, $calculator->getVar('undefined'));
$this->assertNull($calculator->getVar('Lucy'));
}

public function testGetVarException()
{
$calculator = new MathExecutor();
$this->expectException(UnknownVariableException::class);
$this->assertNull($calculator->getVar('Lucy'));
}

public function testMinusZero()
Expand Down Expand Up @@ -580,6 +589,15 @@ public function testSetVarsDoesNotAcceptResource()
$calculator->setVar('resource', tmpfile());
}

public function testVarExists()
{
$calculator = new MathExecutor();
$varName = 'Eythel';
$calculator->setVar($varName, 1);
$this->assertTrue($calculator->varExists($varName));
$this->assertFalse($calculator->varExists('Lucy'));
}

/**
* @dataProvider providerExpressionValues
*/
Expand Down Expand Up @@ -662,8 +680,5 @@ public function testCache()

$this->assertEquals(2048, $calculator->execute('2 ^ 11', false));
$this->assertEquals(0, count($calculator->getCache()));


}

}
}

0 comments on commit a0ff7a7

Please sign in to comment.