Fix phpcs

This commit is contained in:
Laurent Destailleur 2020-03-13 11:29:27 +01:00
parent d3447bb44b
commit 893ae21d3a

View File

@ -1,4 +1,5 @@
<?php <?php
/* /*
* ================================================================================ * ================================================================================
* *
@ -91,29 +92,35 @@
* \brief This file for Math evaluation * \brief This file for Math evaluation
*/ */
/** /**
* Class EvalMath * Class EvalMath
*/ */
class EvalMath class EvalMath
{ {
public $suppress_errors = false; public $suppress_errors = false;
public $last_error = null; public $last_error = null;
public $last_error_code = null; public $last_error_code = null;
public $v = array('e'=>2.71,'pi'=>3.14159); // variables (and constants) public $v = array('e' => 2.71,'pi' => 3.14159);
public $f = array(); // user-defined functions
public $vb = array('e', 'pi'); // constants // variables (and constants)
public $f = array();
// user-defined functions
public $vb = array('e','pi');
// constants
public $fb = array( // built-in functions public $fb = array( // built-in functions
'sin','sinh','arcsin','asin','arcsinh','asinh', 'sin','sinh','arcsin','asin','arcsinh','asinh','cos','cosh','arccos','acos','arccosh','acosh','tan','tanh','arctan','atan','arctanh','atanh','sqrt','abs','ln','log','intval');
'cos','cosh','arccos','acos','arccosh','acosh',
'tan','tanh','arctan','atan','arctanh','atanh',
'sqrt','abs','ln','log','intval');
/** /**
* Constructor * Constructor
*/ */
function __construct() { public function __construct()
{
// make the variables a little more accurate // make the variables a little more accurate
$this->v['pi'] = pi(); $this->v['pi'] = pi();
$this->v['e'] = exp(1); $this->v['e'] = exp(1);
@ -122,31 +129,38 @@ class EvalMath
/** /**
* Evaluate * Evaluate
* *
* @param string $expr String * @param string $expr
* String
* @return boolean|number|NULL|mixed Result * @return boolean|number|NULL|mixed Result
*/ */
function e($expr) { function e($expr)
{
return $this->evaluate($expr); return $this->evaluate($expr);
} }
/** /**
* Evaluate * Evaluate
* *
* @param string $expr String * @param string $expr
* String
* @return boolean|number|NULL|mixed Result * @return boolean|number|NULL|mixed Result
*/ */
function evaluate($expr) { function evaluate($expr)
{
$this->last_error = null; $this->last_error = null;
$this->last_error_code = null; $this->last_error_code = null;
$expr = trim($expr); $expr = trim($expr);
if (substr($expr, -1, 1) == ';') $expr = substr($expr, 0, strlen($expr)-1); // strip semicolons at the end if (substr($expr, - 1, 1) == ';')
$expr = substr($expr, 0, strlen($expr) - 1); // strip semicolons at the end
// =============== // ===============
// is it a variable assignment? // is it a variable assignment?
$matches = array();
if (preg_match('/^\s*([a-z]\w*)\s*=\s*(.+)$/', $expr, $matches)) { if (preg_match('/^\s*([a-z]\w*)\s*=\s*(.+)$/', $expr, $matches)) {
if (in_array($matches[1], $this->vb)) { // make sure we're not assigning to a constant if (in_array($matches[1], $this->vb)) { // make sure we're not assigning to a constant
return $this->trigger(1, "cannot assign to constant '$matches[1]'", $matches[1]); return $this->trigger(1, "cannot assign to constant '$matches[1]'", $matches[1]);
} }
if (($tmp = $this->pfx($this->nfx($matches[2]))) === false) return false; // get the result and make sure it's good if (($tmp = $this->pfx($this->nfx($matches[2]))) === false)
return false; // get the result and make sure it's good
$this->v[$matches[1]] = $tmp; // if so, stick it in the variable array $this->v[$matches[1]] = $tmp; // if so, stick it in the variable array
return $this->v[$matches[1]]; // and return the resulting value return $this->v[$matches[1]]; // and return the resulting value
// =============== // ===============
@ -157,7 +171,8 @@ class EvalMath
return $this->trigger(2, "cannot redefine built-in function '$matches[1]()'", $matches[1]); return $this->trigger(2, "cannot redefine built-in function '$matches[1]()'", $matches[1]);
} }
$args = explode(",", preg_replace("/\s+/", "", $matches[2])); // get the arguments $args = explode(",", preg_replace("/\s+/", "", $matches[2])); // get the arguments
if (($stack = $this->nfx($matches[3])) === false) return false; // see if it can be converted to postfix if (($stack = $this->nfx($matches[3])) === false)
return false; // see if it can be converted to postfix
$nbstack = count($stack); $nbstack = count($stack);
for ($i = 0; $i < $nbstack; $i ++) { // freeze the state of the non-argument variables for ($i = 0; $i < $nbstack; $i ++) { // freeze the state of the non-argument variables
$token = $stack[$i]; $token = $stack[$i];
@ -182,7 +197,8 @@ class EvalMath
* *
* @return string Output * @return string Output
*/ */
function vars() { function vars()
{
$output = $this->v; $output = $this->v;
unset($output['pi']); unset($output['pi']);
unset($output['e']); unset($output['e']);
@ -194,24 +210,25 @@ class EvalMath
* *
* @return string Output * @return string Output
*/ */
function funcs() { function funcs()
{
$output = array(); $output = array();
foreach ($this->f as $fnn => $dat) foreach ($this->f as $fnn => $dat)
$output[] = $fnn . '(' . implode(',', $dat['args']) . ')'; $output[] = $fnn . '(' . implode(',', $dat['args']) . ')';
return $output; return $output;
} }
// ===================== HERE BE INTERNAL METHODS ====================\\ // ===================== HERE BE INTERNAL METHODS ====================\\
/** /**
* Convert infix to postfix notation * Convert infix to postfix notation
* *
* @param string $expr Expression * @param string $expr
* Expression
* @return string Output * @return string Output
*/ */
function nfx($expr) { function nfx($expr)
{
$index = 0; $index = 0;
$stack = new EvalMathStack(); $stack = new EvalMathStack();
$output = array(); // postfix form of expression, to be passed to pfx() $output = array(); // postfix form of expression, to be passed to pfx()
@ -224,6 +241,7 @@ class EvalMath
$expecting_op = false; // we use this in syntax-checking the expression $expecting_op = false; // we use this in syntax-checking the expression
// and determining when a - is a negation // and determining when a - is a negation
$matches = array();
if (preg_match("/[^\w\s+*^\/()\.,-]/", $expr, $matches)) { // make sure the characters are all good if (preg_match("/[^\w\s+*^\/()\.,-]/", $expr, $matches)) { // make sure the characters are all good
return $this->trigger(4, "illegal character '{$matches[0]}'", $matches[0]); return $this->trigger(4, "illegal character '{$matches[0]}'", $matches[0]);
} }
@ -231,6 +249,7 @@ class EvalMath
while (1) { // 1 Infinite Loop ;) while (1) { // 1 Infinite Loop ;)
$op = substr($expr, $index, 1); // get the first character at the current index $op = substr($expr, $index, 1); // get the first character at the current index
// find out if we're currently at the beginning of a number/variable/function/parenthesis/operand // find out if we're currently at the beginning of a number/variable/function/parenthesis/operand
$match = array();
$ex = preg_match('/^([a-z]\w*\(?|\d+(?:\.\d*)?|\.\d+|\()/', substr($expr, $index), $match); $ex = preg_match('/^([a-z]\w*\(?|\d+(?:\.\d*)?|\.\d+|\()/', substr($expr, $index), $match);
// =============== // ===============
if ($op == '-' and ! $expecting_op) { // is it a negation instead of a minus? if ($op == '-' and ! $expecting_op) { // is it a negation instead of a minus?
@ -241,7 +260,8 @@ class EvalMath
// =============== // ===============
} elseif ((in_array($op, $ops) or $ex) and $expecting_op) { // are we putting an operator on the stack? } elseif ((in_array($op, $ops) or $ex) and $expecting_op) { // are we putting an operator on the stack?
if ($ex) { // are we expecting an operator but have a number/variable/function/opening parethesis? if ($ex) { // are we expecting an operator but have a number/variable/function/opening parethesis?
$op = '*'; $index--; // it's an implicit multiplication $op = '*';
$index --; // it's an implicit multiplication
} }
// heart of the algorithm: // heart of the algorithm:
while ($stack->count > 0 and ($o2 = $stack->last()) and in_array($o2, $ops) and ($ops_r[$op] ? $ops_p[$op] < $ops_p[$o2] : $ops_p[$op] <= $ops_p[$o2])) { while ($stack->count > 0 and ($o2 = $stack->last()) and in_array($o2, $ops) and ($ops_r[$op] ? $ops_p[$op] < $ops_p[$o2] : $ops_p[$op] <= $ops_p[$o2])) {
@ -254,8 +274,10 @@ class EvalMath
// =============== // ===============
} elseif ($op == ')' and $expecting_op) { // ready to close a parenthesis? } elseif ($op == ')' and $expecting_op) { // ready to close a parenthesis?
while (($o2 = $stack->pop()) != '(') { // pop off the stack back to the last ( while (($o2 = $stack->pop()) != '(') { // pop off the stack back to the last (
if (is_null($o2)) return $this->trigger(5, "unexpected ')'", ")"); if (is_null($o2))
else $output[] = $o2; return $this->trigger(5, "unexpected ')'", ")");
else
$output[] = $o2;
} }
if (preg_match("/^([a-z]\w*)\($/", $stack->last(2), $matches)) { // did we just close a function? if (preg_match("/^([a-z]\w*)\($/", $stack->last(2), $matches)) { // did we just close a function?
$fnn = $matches[1]; // get the function name $fnn = $matches[1]; // get the function name
@ -275,8 +297,10 @@ class EvalMath
// =============== // ===============
} elseif ($op == ',' and $expecting_op) { // did we just finish a function argument? } elseif ($op == ',' and $expecting_op) { // did we just finish a function argument?
while (($o2 = $stack->pop()) != '(') { while (($o2 = $stack->pop()) != '(') {
if (is_null($o2)) return $this->trigger(5, "unexpected ','", ","); // oops, never had a ( if (is_null($o2))
else $output[] = $o2; // pop the argument expression stuff and push onto the output return $this->trigger(5, "unexpected ','", ","); // oops, never had a (
else
$output[] = $o2; // pop the argument expression stuff and push onto the output
} }
// make sure there was a function // make sure there was a function
if (! preg_match("/^([a-z]\w*)\($/", $stack->last(2), $matches)) if (! preg_match("/^([a-z]\w*)\($/", $stack->last(2), $matches))
@ -326,46 +350,57 @@ class EvalMath
while (substr($expr, $index, 1) == ' ') { // step the index past whitespace (pretty much turns whitespace while (substr($expr, $index, 1) == ' ') { // step the index past whitespace (pretty much turns whitespace
$index ++; // into implicit multiplication if no operator is there) $index ++; // into implicit multiplication if no operator is there)
} }
} }
while (! is_null($op = $stack->pop())) { // pop everything off the stack and push onto output while (! is_null($op = $stack->pop())) { // pop everything off the stack and push onto output
if ($op == '(') return $this->trigger(11, "expecting ')'", ")"); // if there are (s on the stack, ()s were unbalanced if ($op == '(')
return $this->trigger(11, "expecting ')'", ")"); // if there are (s on the stack, ()s were unbalanced
$output[] = $op; $output[] = $op;
} }
return $output; return $output;
} }
/** /**
* evaluate postfix notation * evaluate postfix notation
* *
* @param string $tokens Expression * @param string $tokens
* @param array $vars Array * Expression
* @param array $vars
* Array
* @return string Output * @return string Output
*/ */
function pfx($tokens, $vars = array()) { function pfx($tokens, $vars = array())
{
if ($tokens == false) return false; if ($tokens == false)
return false;
$stack = new EvalMathStack(); $stack = new EvalMathStack();
foreach ($tokens as $token) { // nice and easy foreach ($tokens as $token) { // nice and easy
// if the token is a binary operator, pop two values off the stack, do the operation, and push the result back on // if the token is a binary operator, pop two values off the stack, do the operation, and push the result back on
$matches = array();
if (in_array($token, array('+','-','*','/','^'))) { if (in_array($token, array('+','-','*','/','^'))) {
if (is_null($op2 = $stack->pop())) return $this->trigger(12, "internal error"); if (is_null($op2 = $stack->pop()))
if (is_null($op1 = $stack->pop())) return $this->trigger(13, "internal error"); return $this->trigger(12, "internal error");
if (is_null($op1 = $stack->pop()))
return $this->trigger(13, "internal error");
switch ($token) { switch ($token) {
case '+': case '+':
$stack->push($op1+$op2); break; $stack->push($op1 + $op2);
break;
case '-': case '-':
$stack->push($op1-$op2); break; $stack->push($op1 - $op2);
break;
case '*': case '*':
$stack->push($op1*$op2); break; $stack->push($op1 * $op2);
break;
case '/': case '/':
if ($op2 == 0) return $this->trigger(14, "division by zero"); if ($op2 == 0)
$stack->push($op1/$op2); break; return $this->trigger(14, "division by zero");
$stack->push($op1 / $op2);
break;
case '^': case '^':
$stack->push(pow($op1, $op2)); break; $stack->push(pow($op1, $op2));
break;
} }
// if the token is a unary operator, pop one value off the stack, do the operation, and push it back on // if the token is a unary operator, pop one value off the stack, do the operation, and push it back on
} elseif ($token == "_") { } elseif ($token == "_") {
@ -374,15 +409,18 @@ class EvalMath
} elseif (preg_match("/^([a-z]\w*)\($/", $token, $matches)) { // it's a function! } elseif (preg_match("/^([a-z]\w*)\($/", $token, $matches)) { // it's a function!
$fnn = $matches[1]; $fnn = $matches[1];
if (in_array($fnn, $this->fb)) { // built-in function: if (in_array($fnn, $this->fb)) { // built-in function:
if (is_null($op1 = $stack->pop())) return $this->trigger(15, "internal error"); if (is_null($op1 = $stack->pop()))
return $this->trigger(15, "internal error");
$fnn = preg_replace("/^arc/", "a", $fnn); // for the 'arc' trig synonyms $fnn = preg_replace("/^arc/", "a", $fnn); // for the 'arc' trig synonyms
if ($fnn == 'ln') $fnn = 'log'; if ($fnn == 'ln')
$fnn = 'log';
eval('$stack->push(' . $fnn . '($op1));'); // perfectly safe eval() eval('$stack->push(' . $fnn . '($op1));'); // perfectly safe eval()
} elseif (array_key_exists($fnn, $this->f)) { // user function } elseif (array_key_exists($fnn, $this->f)) { // user function
// get args // get args
$args = array(); $args = array();
for ($i = count($this->f[$fnn]['args']) - 1; $i >= 0; $i --) { for ($i = count($this->f[$fnn]['args']) - 1; $i >= 0; $i --) {
if (is_null($args[$this->f[$fnn]['args'][$i]] = $stack->pop())) return $this->trigger(16, "internal error"); if (is_null($args[$this->f[$fnn]['args'][$i]] = $stack->pop()))
return $this->trigger(16, "internal error");
} }
$stack->push($this->pfx($this->f[$fnn]['func'], $args)); // yay... recursion!!!! $stack->push($this->pfx($this->f[$fnn]['func'], $args)); // yay... recursion!!!!
} }
@ -400,22 +438,28 @@ class EvalMath
} }
} }
// when we're out of tokens, the stack should have a single element, the final result // when we're out of tokens, the stack should have a single element, the final result
if ($stack->count != 1) return $this->trigger(18, "internal error"); if ($stack->count != 1)
return $this->trigger(18, "internal error");
return $stack->pop(); return $stack->pop();
} }
/** /**
* trigger an error, but nicely, if need be * trigger an error, but nicely, if need be
* *
* @param string $code Code * @param string $code
* @param string $msg Msg * Code
* @param string|null $info sting * @param string $msg
* Msg
* @param string|null $info
* sting
* @return boolean False * @return boolean False
*/ */
function trigger($code, $msg, $info = null) { function trigger($code, $msg, $info = null)
{
$this->last_error = $msg; $this->last_error = $msg;
$this->last_error_code = array($code,$info); $this->last_error_code = array($code,$info);
if (!$this->suppress_errors) trigger_error($msg, E_USER_WARNING); if (! $this->suppress_errors)
trigger_error($msg, E_USER_WARNING);
return false; return false;
} }
} }
@ -425,16 +469,20 @@ class EvalMath
*/ */
class EvalMathStack class EvalMathStack
{ {
var $stack = array(); var $stack = array();
var $count = 0; var $count = 0;
/** /**
* push * push
* *
* @param string $val Val * @param string $val
* Val
* @return void * @return void
*/ */
function push($val) { function push($val)
{
$this->stack[$this->count] = $val; $this->stack[$this->count] = $val;
$this->count ++; $this->count ++;
} }
@ -444,7 +492,8 @@ class EvalMathStack
* *
* @return mixed Stack * @return mixed Stack
*/ */
function pop() { function pop()
{
if ($this->count > 0) { if ($this->count > 0) {
$this->count --; $this->count --;
return $this->stack[$this->count]; return $this->stack[$this->count];
@ -455,10 +504,12 @@ class EvalMathStack
/** /**
* last * last
* *
* @param int $n N * @param int $n
* N
* @return mixed Stack * @return mixed Stack
*/ */
function last($n=1) { function last($n = 1)
{
if (isset($this->stack[$this->count - $n])) { if (isset($this->stack[$this->count - $n])) {
return $this->stack[$this->count - $n]; return $this->stack[$this->count - $n];
} }