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,34 +129,41 @@ 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
//=============== // ===============
// is it a function assignment? // is it a function assignment?
} elseif (preg_match('/^\s*([a-z]\w*)\s*\(\s*([a-z]\w*(?:\s*,\s*[a-z]\w*)*)\s*\)\s*=\s*(.+)$/', $expr, $matches)) { } elseif (preg_match('/^\s*([a-z]\w*)\s*\(\s*([a-z]\w*(?:\s*,\s*[a-z]\w*)*)\s*\)\s*=\s*(.+)$/', $expr, $matches)) {
$fnn = $matches[1]; // get the function name $fnn = $matches[1]; // get the function name
@ -157,11 +171,12 @@ 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];
if (preg_match('/^[a-z]\w*$/', $token) and !in_array($token, $args)) { if (preg_match('/^[a-z]\w*$/', $token) and ! in_array($token, $args)) {
if (array_key_exists($token, $this->v)) { if (array_key_exists($token, $this->v)) {
$stack[$i] = $this->v[$token]; $stack[$i] = $this->v[$token];
} else { } else {
@ -169,9 +184,9 @@ class EvalMath
} }
} }
} }
$this->f[$fnn] = array('args'=>$args, 'func'=>$stack); $this->f[$fnn] = array('args' => $args,'func' => $stack);
return true; return true;
//=============== // ===============
} else { } else {
return $this->pfx($this->nfx($expr)); // straight up evaluation, woo return $this->pfx($this->nfx($expr)); // straight up evaluation, woo
} }
@ -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,104 +210,112 @@ 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()
$expr = trim(strtolower($expr)); $expr = trim(strtolower($expr));
$ops = array('+', '-', '*', '/', '^', '_'); $ops = array('+','-','*','/','^','_');
$ops_r = array('+'=>0,'-'=>0,'*'=>0,'/'=>0,'^'=>1); // right-associative operator? $ops_r = array('+' => 0,'-' => 0,'*' => 0,'/' => 0,'^' => 1); // right-associative operator?
$ops_p = array('+'=>0,'-'=>0,'*'=>1,'/'=>1,'_'=>1,'^'=>2); // operator precedence $ops_p = array('+' => 0,'-' => 0,'*' => 1,'/' => 1,'_' => 1,'^' => 2); // operator precedence
$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]);
} }
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?
$stack->push('_'); // put a negation on the stack $stack->push('_'); // put a negation on the stack
$index++; $index ++;
} elseif ($op == '_') { // we have to explicitly deny this, because it's legal on the stack } elseif ($op == '_') { // we have to explicitly deny this, because it's legal on the stack
return $this->trigger(4, "illegal character '_'", "_"); // but not in the input expression return $this->trigger(4, "illegal character '_'", "_"); // but not in the input expression
//=============== // ===============
} 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])) {
$output[] = $stack->pop(); // pop stuff off the stack into the output $output[] = $stack->pop(); // pop stuff off the stack into the output
} }
// many thanks: http://en.wikipedia.org/wiki/Reverse_Polish_notation#The_algorithm_in_detail // many thanks: http://en.wikipedia.org/wiki/Reverse_Polish_notation#The_algorithm_in_detail
$stack->push($op); // finally put OUR operator onto the stack $stack->push($op); // finally put OUR operator onto the stack
$index++; $index ++;
$expecting_op = false; $expecting_op = false;
//=============== // ===============
} 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
$arg_count = $stack->pop(); // see how many arguments there were (cleverly stored on the stack, thank you) $arg_count = $stack->pop(); // see how many arguments there were (cleverly stored on the stack, thank you)
$output[] = $stack->pop(); // pop the function and push onto the output $output[] = $stack->pop(); // pop the function and push onto the output
if (in_array($fnn, $this->fb)) { // check the argument count if (in_array($fnn, $this->fb)) { // check the argument count
if($arg_count > 1) if ($arg_count > 1)
return $this->trigger(6, "wrong number of arguments ($arg_count given, 1 expected)", array($arg_count, 1)); return $this->trigger(6, "wrong number of arguments ($arg_count given, 1 expected)", array($arg_count,1));
} elseif (array_key_exists($fnn, $this->f)) { } elseif (array_key_exists($fnn, $this->f)) {
if ($arg_count != count($this->f[$fnn]['args'])) if ($arg_count != count($this->f[$fnn]['args']))
return $this->trigger(6, "wrong number of arguments ($arg_count given, " . count($this->f[$fnn]['args']) . " expected)", array($arg_count, count($this->f[$fnn]['args']))); return $this->trigger(6, "wrong number of arguments ($arg_count given, " . count($this->f[$fnn]['args']) . " expected)", array($arg_count,count($this->f[$fnn]['args'])));
} else { // did we somehow push a non-function on the stack? this should never happen } else { // did we somehow push a non-function on the stack? this should never happen
return $this->trigger(7, "internal error"); return $this->trigger(7, "internal error");
} }
} }
$index++; $index ++;
//=============== // ===============
} 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))
return $this->trigger(5, "unexpected ','", ","); return $this->trigger(5, "unexpected ','", ",");
$stack->push($stack->pop()+1); // increment the argument count $stack->push($stack->pop() + 1); // increment the argument count
$stack->push('('); // put the ( back on, we'll need to pop back to it again $stack->push('('); // put the ( back on, we'll need to pop back to it again
$index++; $index ++;
$expecting_op = false; $expecting_op = false;
//=============== // ===============
} elseif ($op == '(' and !$expecting_op) { } elseif ($op == '(' and ! $expecting_op) {
$stack->push('('); // that was easy $stack->push('('); // that was easy
$index++; $index ++;
$allow_neg = true; $allow_neg = true;
//=============== // ===============
} elseif ($ex and !$expecting_op) { // do we now have a function/variable/number? } elseif ($ex and ! $expecting_op) { // do we now have a function/variable/number?
$expecting_op = true; $expecting_op = true;
$val = $match[1]; $val = $match[1];
if (preg_match("/^([a-z]\w*)\($/", $val, $matches)) { // may be func, or variable w/ implicit multiplication against parentheses... if (preg_match("/^([a-z]\w*)\($/", $val, $matches)) { // may be func, or variable w/ implicit multiplication against parentheses...
@ -308,10 +332,10 @@ class EvalMath
$output[] = $val; $output[] = $val;
} }
$index += strlen($val); $index += strlen($val);
//=============== // ===============
} elseif ($op == ')') { // miscellaneous error checking } elseif ($op == ')') { // miscellaneous error checking
return $this->trigger(5, "unexpected ')'", ")"); return $this->trigger(5, "unexpected ')'", ")");
} elseif (in_array($op, $ops) and !$expecting_op) { } elseif (in_array($op, $ops) and ! $expecting_op) {
return $this->trigger(8, "unexpected operator '$op'", $op); return $this->trigger(8, "unexpected operator '$op'", $op);
} else { // I don't even want to know what you did to get here } else { // I don't even want to know what you did to get here
return $this->trigger(9, "an unexpected error occured"); return $this->trigger(9, "an unexpected error occured");
@ -324,65 +348,79 @@ 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
if (in_array($token, array('+', '-', '*', '/', '^'))) { $matches = array();
if (is_null($op2 = $stack->pop())) return $this->trigger(12, "internal error"); if (in_array($token, array('+','-','*','/','^'))) {
if (is_null($op1 = $stack->pop())) return $this->trigger(13, "internal error"); if (is_null($op2 = $stack->pop()))
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 == "_") {
$stack->push(-1*$stack->pop()); $stack->push(- 1 * $stack->pop());
// if the token is a function, pop arguments off the stack, hand them to the function, and push the result back on // if the token is a function, pop arguments off the stack, hand them to the function, and push the result back on
} 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,18 +469,22 @@ 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,9 +492,10 @@ 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];
} }
return null; return null;
@ -455,12 +504,14 @@ 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])) { {
return $this->stack[$this->count-$n]; if (isset($this->stack[$this->count - $n])) {
return $this->stack[$this->count - $n];
} }
return; return;
} }