repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6 values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1 value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
mossadal/math-parser | src/MathParser/Extensions/Complex.php | Complex.artanh | public static function artanh($z) {
if (!($z instanceof Complex)) $z = static::parse($z);
return static::div(static::log(static::div(static::add(1,$z), static::sub(1,$z))),2);
} | php | public static function artanh($z) {
if (!($z instanceof Complex)) $z = static::parse($z);
return static::div(static::log(static::div(static::add(1,$z), static::sub(1,$z))),2);
} | [
"public",
"static",
"function",
"artanh",
"(",
"$",
"z",
")",
"{",
"if",
"(",
"!",
"(",
"$",
"z",
"instanceof",
"Complex",
")",
")",
"$",
"z",
"=",
"static",
"::",
"parse",
"(",
"$",
"z",
")",
";",
"return",
"static",
"::",
"div",
"(",
"static",
"::",
"log",
"(",
"static",
"::",
"div",
"(",
"static",
"::",
"add",
"(",
"1",
",",
"$",
"z",
")",
",",
"static",
"::",
"sub",
"(",
"1",
",",
"$",
"z",
")",
")",
")",
",",
"2",
")",
";",
"}"
] | complex inverse hyperbolic tangent function
Complex::artanh($z) computes and returns the principal branch of artanh($z)
@param mixed $z (Complex, or parsable to Complex)
@retval Complex | [
"complex",
"inverse",
"hyperbolic",
"tangent",
"function"
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Extensions/Complex.php#L630-L634 |
mossadal/math-parser | src/MathParser/Extensions/Complex.php | Complex.sqrt | public static function sqrt($z)
{
if (!($z instanceof Complex)) $z = static::parse($z);
$r = sqrt($z->abs());
$theta = $z->arg()/2;
return new Complex($r*cos($theta), $r*sin($theta));
} | php | public static function sqrt($z)
{
if (!($z instanceof Complex)) $z = static::parse($z);
$r = sqrt($z->abs());
$theta = $z->arg()/2;
return new Complex($r*cos($theta), $r*sin($theta));
} | [
"public",
"static",
"function",
"sqrt",
"(",
"$",
"z",
")",
"{",
"if",
"(",
"!",
"(",
"$",
"z",
"instanceof",
"Complex",
")",
")",
"$",
"z",
"=",
"static",
"::",
"parse",
"(",
"$",
"z",
")",
";",
"$",
"r",
"=",
"sqrt",
"(",
"$",
"z",
"->",
"abs",
"(",
")",
")",
";",
"$",
"theta",
"=",
"$",
"z",
"->",
"arg",
"(",
")",
"/",
"2",
";",
"return",
"new",
"Complex",
"(",
"$",
"r",
"*",
"cos",
"(",
"$",
"theta",
")",
",",
"$",
"r",
"*",
"sin",
"(",
"$",
"theta",
")",
")",
";",
"}"
] | complex square root function
Complex::sqrt($z) computes and returns the principal branch of sqrt($z)
@param mixed $z (Complex, or parsable to Complex)
@retval Complex | [
"complex",
"square",
"root",
"function"
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Extensions/Complex.php#L645-L653 |
mossadal/math-parser | src/MathParser/Interpreting/ComplexEvaluator.php | ComplexEvaluator.setVariables | public function setVariables($variables)
{
$this->variables = [];
foreach ($variables as $var => $value) {
$this->variables[$var] = Complex::parse($value);
}
} | php | public function setVariables($variables)
{
$this->variables = [];
foreach ($variables as $var => $value) {
$this->variables[$var] = Complex::parse($value);
}
} | [
"public",
"function",
"setVariables",
"(",
"$",
"variables",
")",
"{",
"$",
"this",
"->",
"variables",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"variables",
"as",
"$",
"var",
"=>",
"$",
"value",
")",
"{",
"$",
"this",
"->",
"variables",
"[",
"$",
"var",
"]",
"=",
"Complex",
"::",
"parse",
"(",
"$",
"value",
")",
";",
"}",
"}"
] | Update the variables used for evaluating
@retval void
@param array $variables Key/value pair holding current variable values | [
"Update",
"the",
"variables",
"used",
"for",
"evaluating"
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Interpreting/ComplexEvaluator.php#L75-L81 |
mossadal/math-parser | src/MathParser/Interpreting/ComplexEvaluator.php | ComplexEvaluator.visitExpressionNode | public function visitExpressionNode(ExpressionNode $node)
{
$operator = $node->getOperator();
$a = $node->getLeft()->accept($this);
if ($node->getRight()) {
$b = $node->getRight()->accept($this);
} else {
$b = null;
}
// Perform the right operation based on the operator
switch ($operator) {
case '+':
return Complex::add($a, $b);
case '-':
if ($b === null) {
return Complex::mul($a, -1);
}
return Complex::sub($a, $b);
case '*':
return Complex::mul($a, $b);
case '/':
return Complex::div($a, $b);
case '^':
// This needs to be improved.
return Complex::pow($a, $b);
default:
throw new UnknownOperatorException($operator);
}
} | php | public function visitExpressionNode(ExpressionNode $node)
{
$operator = $node->getOperator();
$a = $node->getLeft()->accept($this);
if ($node->getRight()) {
$b = $node->getRight()->accept($this);
} else {
$b = null;
}
// Perform the right operation based on the operator
switch ($operator) {
case '+':
return Complex::add($a, $b);
case '-':
if ($b === null) {
return Complex::mul($a, -1);
}
return Complex::sub($a, $b);
case '*':
return Complex::mul($a, $b);
case '/':
return Complex::div($a, $b);
case '^':
// This needs to be improved.
return Complex::pow($a, $b);
default:
throw new UnknownOperatorException($operator);
}
} | [
"public",
"function",
"visitExpressionNode",
"(",
"ExpressionNode",
"$",
"node",
")",
"{",
"$",
"operator",
"=",
"$",
"node",
"->",
"getOperator",
"(",
")",
";",
"$",
"a",
"=",
"$",
"node",
"->",
"getLeft",
"(",
")",
"->",
"accept",
"(",
"$",
"this",
")",
";",
"if",
"(",
"$",
"node",
"->",
"getRight",
"(",
")",
")",
"{",
"$",
"b",
"=",
"$",
"node",
"->",
"getRight",
"(",
")",
"->",
"accept",
"(",
"$",
"this",
")",
";",
"}",
"else",
"{",
"$",
"b",
"=",
"null",
";",
"}",
"// Perform the right operation based on the operator",
"switch",
"(",
"$",
"operator",
")",
"{",
"case",
"'+'",
":",
"return",
"Complex",
"::",
"add",
"(",
"$",
"a",
",",
"$",
"b",
")",
";",
"case",
"'-'",
":",
"if",
"(",
"$",
"b",
"===",
"null",
")",
"{",
"return",
"Complex",
"::",
"mul",
"(",
"$",
"a",
",",
"-",
"1",
")",
";",
"}",
"return",
"Complex",
"::",
"sub",
"(",
"$",
"a",
",",
"$",
"b",
")",
";",
"case",
"'*'",
":",
"return",
"Complex",
"::",
"mul",
"(",
"$",
"a",
",",
"$",
"b",
")",
";",
"case",
"'/'",
":",
"return",
"Complex",
"::",
"div",
"(",
"$",
"a",
",",
"$",
"b",
")",
";",
"case",
"'^'",
":",
"// This needs to be improved.",
"return",
"Complex",
"::",
"pow",
"(",
"$",
"a",
",",
"$",
"b",
")",
";",
"default",
":",
"throw",
"new",
"UnknownOperatorException",
"(",
"$",
"operator",
")",
";",
"}",
"}"
] | Evaluate an ExpressionNode
Computes the value of an ExpressionNode `x op y`
where `op` is one of `+`, `-`, `*`, `/` or `^`
`+`, `-`, `*`, `/` or `^`
@retval float
@param ExpressionNode $node AST to be evaluated
@throws UnknownOperatorException if the operator is something other than | [
"Evaluate",
"an",
"ExpressionNode"
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Interpreting/ComplexEvaluator.php#L94-L126 |
mossadal/math-parser | src/MathParser/Interpreting/ComplexEvaluator.php | ComplexEvaluator.visitVariableNode | public function visitVariableNode(VariableNode $node)
{
$name = $node->getName();
if (array_key_exists($name, $this->variables)) {
return $this->variables[$name];
}
throw new UnknownVariableException($name);
} | php | public function visitVariableNode(VariableNode $node)
{
$name = $node->getName();
if (array_key_exists($name, $this->variables)) {
return $this->variables[$name];
}
throw new UnknownVariableException($name);
} | [
"public",
"function",
"visitVariableNode",
"(",
"VariableNode",
"$",
"node",
")",
"{",
"$",
"name",
"=",
"$",
"node",
"->",
"getName",
"(",
")",
";",
"if",
"(",
"array_key_exists",
"(",
"$",
"name",
",",
"$",
"this",
"->",
"variables",
")",
")",
"{",
"return",
"$",
"this",
"->",
"variables",
"[",
"$",
"name",
"]",
";",
"}",
"throw",
"new",
"UnknownVariableException",
"(",
"$",
"name",
")",
";",
"}"
] | Evaluate a VariableNode
Returns the current value of a VariableNode, as defined
either by the constructor or set using the `Evaluator::setVariables()` method.
VariableNode is *not* set.
@retval float
@see Evaluator::setVariables() to define the variables
@param VariableNode $node AST to be evaluated
@throws UnknownVariableException if the variable respresented by the | [
"Evaluate",
"a",
"VariableNode"
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Interpreting/ComplexEvaluator.php#L164-L173 |
mossadal/math-parser | src/MathParser/Interpreting/ComplexEvaluator.php | ComplexEvaluator.visitFunctionNode | public function visitFunctionNode(FunctionNode $node)
{
$z = $node->getOperand()->accept($this);
$a = $z->r();
$b = $z->i();
switch ($node->getName()) {
// Trigonometric functions
case 'sin':
return Complex::sin($z);
case 'cos':
return Complex::cos($z);
case 'tan':
return Complex::tan($z);
case 'cot':
return Complex::cot($z);
// Inverse trigonometric functions
case 'arcsin':
return Complex::arcsin($z);
case 'arccos':
return Complex::arccos($z);
case 'arctan':
return Complex::arctan($z);
case 'arccot':
return Complex::arccot($z);
case 'sinh':
return Complex::sinh($z);
case 'cosh':
return Complex::cosh($z);
case 'tanh':
return Complex::tanh($z);
case 'coth':
return Complex::div(1, Complex::tanh($z));
case 'arsinh':
return Complex::arsinh($z);
case 'arcosh':
return Complex::arcosh($z);
case 'artanh':
return Complex::artanh($z);
case 'arcoth':
return Complex::div(1, Complex::artanh($z));
case 'exp':
return Complex::exp($z);
case 'ln':
if ($z->i() != 0 || $z->r() <= 0) {
throw new \UnexpectedValueException("Expecting positive real number (ln)");
}
return Complex::log($z);
case 'log':
return Complex::log($z);
case 'lg':
return Complex::div(Complex::log($z), M_LN10);
case 'sqrt':
return Complex::sqrt($z);
case 'abs':
return new Complex($z->abs(), 0);
case 'arg':
return new Complex($z->arg(), 0);
case 're':
return new Complex($z->r(), 0);
case 'im':
return new Complex($z->i(), 0);
case 'conj':
return new Complex($z->r(), -$z->i());
default:
throw new UnknownFunctionException($node->getName());
}
return new FunctionNode($node->getName(), $inner);
} | php | public function visitFunctionNode(FunctionNode $node)
{
$z = $node->getOperand()->accept($this);
$a = $z->r();
$b = $z->i();
switch ($node->getName()) {
// Trigonometric functions
case 'sin':
return Complex::sin($z);
case 'cos':
return Complex::cos($z);
case 'tan':
return Complex::tan($z);
case 'cot':
return Complex::cot($z);
// Inverse trigonometric functions
case 'arcsin':
return Complex::arcsin($z);
case 'arccos':
return Complex::arccos($z);
case 'arctan':
return Complex::arctan($z);
case 'arccot':
return Complex::arccot($z);
case 'sinh':
return Complex::sinh($z);
case 'cosh':
return Complex::cosh($z);
case 'tanh':
return Complex::tanh($z);
case 'coth':
return Complex::div(1, Complex::tanh($z));
case 'arsinh':
return Complex::arsinh($z);
case 'arcosh':
return Complex::arcosh($z);
case 'artanh':
return Complex::artanh($z);
case 'arcoth':
return Complex::div(1, Complex::artanh($z));
case 'exp':
return Complex::exp($z);
case 'ln':
if ($z->i() != 0 || $z->r() <= 0) {
throw new \UnexpectedValueException("Expecting positive real number (ln)");
}
return Complex::log($z);
case 'log':
return Complex::log($z);
case 'lg':
return Complex::div(Complex::log($z), M_LN10);
case 'sqrt':
return Complex::sqrt($z);
case 'abs':
return new Complex($z->abs(), 0);
case 'arg':
return new Complex($z->arg(), 0);
case 're':
return new Complex($z->r(), 0);
case 'im':
return new Complex($z->i(), 0);
case 'conj':
return new Complex($z->r(), -$z->i());
default:
throw new UnknownFunctionException($node->getName());
}
return new FunctionNode($node->getName(), $inner);
} | [
"public",
"function",
"visitFunctionNode",
"(",
"FunctionNode",
"$",
"node",
")",
"{",
"$",
"z",
"=",
"$",
"node",
"->",
"getOperand",
"(",
")",
"->",
"accept",
"(",
"$",
"this",
")",
";",
"$",
"a",
"=",
"$",
"z",
"->",
"r",
"(",
")",
";",
"$",
"b",
"=",
"$",
"z",
"->",
"i",
"(",
")",
";",
"switch",
"(",
"$",
"node",
"->",
"getName",
"(",
")",
")",
"{",
"// Trigonometric functions",
"case",
"'sin'",
":",
"return",
"Complex",
"::",
"sin",
"(",
"$",
"z",
")",
";",
"case",
"'cos'",
":",
"return",
"Complex",
"::",
"cos",
"(",
"$",
"z",
")",
";",
"case",
"'tan'",
":",
"return",
"Complex",
"::",
"tan",
"(",
"$",
"z",
")",
";",
"case",
"'cot'",
":",
"return",
"Complex",
"::",
"cot",
"(",
"$",
"z",
")",
";",
"// Inverse trigonometric functions",
"case",
"'arcsin'",
":",
"return",
"Complex",
"::",
"arcsin",
"(",
"$",
"z",
")",
";",
"case",
"'arccos'",
":",
"return",
"Complex",
"::",
"arccos",
"(",
"$",
"z",
")",
";",
"case",
"'arctan'",
":",
"return",
"Complex",
"::",
"arctan",
"(",
"$",
"z",
")",
";",
"case",
"'arccot'",
":",
"return",
"Complex",
"::",
"arccot",
"(",
"$",
"z",
")",
";",
"case",
"'sinh'",
":",
"return",
"Complex",
"::",
"sinh",
"(",
"$",
"z",
")",
";",
"case",
"'cosh'",
":",
"return",
"Complex",
"::",
"cosh",
"(",
"$",
"z",
")",
";",
"case",
"'tanh'",
":",
"return",
"Complex",
"::",
"tanh",
"(",
"$",
"z",
")",
";",
"case",
"'coth'",
":",
"return",
"Complex",
"::",
"div",
"(",
"1",
",",
"Complex",
"::",
"tanh",
"(",
"$",
"z",
")",
")",
";",
"case",
"'arsinh'",
":",
"return",
"Complex",
"::",
"arsinh",
"(",
"$",
"z",
")",
";",
"case",
"'arcosh'",
":",
"return",
"Complex",
"::",
"arcosh",
"(",
"$",
"z",
")",
";",
"case",
"'artanh'",
":",
"return",
"Complex",
"::",
"artanh",
"(",
"$",
"z",
")",
";",
"case",
"'arcoth'",
":",
"return",
"Complex",
"::",
"div",
"(",
"1",
",",
"Complex",
"::",
"artanh",
"(",
"$",
"z",
")",
")",
";",
"case",
"'exp'",
":",
"return",
"Complex",
"::",
"exp",
"(",
"$",
"z",
")",
";",
"case",
"'ln'",
":",
"if",
"(",
"$",
"z",
"->",
"i",
"(",
")",
"!=",
"0",
"||",
"$",
"z",
"->",
"r",
"(",
")",
"<=",
"0",
")",
"{",
"throw",
"new",
"\\",
"UnexpectedValueException",
"(",
"\"Expecting positive real number (ln)\"",
")",
";",
"}",
"return",
"Complex",
"::",
"log",
"(",
"$",
"z",
")",
";",
"case",
"'log'",
":",
"return",
"Complex",
"::",
"log",
"(",
"$",
"z",
")",
";",
"case",
"'lg'",
":",
"return",
"Complex",
"::",
"div",
"(",
"Complex",
"::",
"log",
"(",
"$",
"z",
")",
",",
"M_LN10",
")",
";",
"case",
"'sqrt'",
":",
"return",
"Complex",
"::",
"sqrt",
"(",
"$",
"z",
")",
";",
"case",
"'abs'",
":",
"return",
"new",
"Complex",
"(",
"$",
"z",
"->",
"abs",
"(",
")",
",",
"0",
")",
";",
"case",
"'arg'",
":",
"return",
"new",
"Complex",
"(",
"$",
"z",
"->",
"arg",
"(",
")",
",",
"0",
")",
";",
"case",
"'re'",
":",
"return",
"new",
"Complex",
"(",
"$",
"z",
"->",
"r",
"(",
")",
",",
"0",
")",
";",
"case",
"'im'",
":",
"return",
"new",
"Complex",
"(",
"$",
"z",
"->",
"i",
"(",
")",
",",
"0",
")",
";",
"case",
"'conj'",
":",
"return",
"new",
"Complex",
"(",
"$",
"z",
"->",
"r",
"(",
")",
",",
"-",
"$",
"z",
"->",
"i",
"(",
")",
")",
";",
"default",
":",
"throw",
"new",
"UnknownFunctionException",
"(",
"$",
"node",
"->",
"getName",
"(",
")",
")",
";",
"}",
"return",
"new",
"FunctionNode",
"(",
"$",
"node",
"->",
"getName",
"(",
")",
",",
"$",
"inner",
")",
";",
"}"
] | Evaluate a FunctionNode
Computes the value of a FunctionNode `f(x)`, where f is
an elementary function recognized by StdMathLexer and StdMathParser.
FunctionNode is *not* recognized.
@retval float
@see \MathParser\Lexer\StdMathLexer StdMathLexer
@see \MathParser\StdMathParser StdMathParser
@param FunctionNode $node AST to be evaluated
@throws UnknownFunctionException if the function respresented by the | [
"Evaluate",
"a",
"FunctionNode"
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Interpreting/ComplexEvaluator.php#L189-L285 |
mossadal/math-parser | src/MathParser/Interpreting/ComplexEvaluator.php | ComplexEvaluator.visitConstantNode | public function visitConstantNode(ConstantNode $node)
{
switch ($node->getName()) {
case 'pi':
return new Complex(M_PI, 0);
case 'e':
return new Complex(M_E, 0);
case 'i':
return new Complex(0, 1);
default:
throw new UnknownConstantException($node->getName());
}
} | php | public function visitConstantNode(ConstantNode $node)
{
switch ($node->getName()) {
case 'pi':
return new Complex(M_PI, 0);
case 'e':
return new Complex(M_E, 0);
case 'i':
return new Complex(0, 1);
default:
throw new UnknownConstantException($node->getName());
}
} | [
"public",
"function",
"visitConstantNode",
"(",
"ConstantNode",
"$",
"node",
")",
"{",
"switch",
"(",
"$",
"node",
"->",
"getName",
"(",
")",
")",
"{",
"case",
"'pi'",
":",
"return",
"new",
"Complex",
"(",
"M_PI",
",",
"0",
")",
";",
"case",
"'e'",
":",
"return",
"new",
"Complex",
"(",
"M_E",
",",
"0",
")",
";",
"case",
"'i'",
":",
"return",
"new",
"Complex",
"(",
"0",
",",
"1",
")",
";",
"default",
":",
"throw",
"new",
"UnknownConstantException",
"(",
"$",
"node",
"->",
"getName",
"(",
")",
")",
";",
"}",
"}"
] | Evaluate a ConstantNode
Returns the value of a ConstantNode recognized by StdMathLexer and StdMathParser.
ConstantNode is *not* recognized.
@retval float
@see \MathParser\Lexer\StdMathLexer StdMathLexer
@see \MathParser\StdMathParser StdMathParser
@param ConstantNode $node AST to be evaluated
@throws UnknownConstantException if the variable respresented by the | [
"Evaluate",
"a",
"ConstantNode"
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Interpreting/ComplexEvaluator.php#L300-L312 |
mossadal/math-parser | src/MathParser/Parsing/Nodes/Factories/NodeFactory.php | NodeFactory.simplify | public function simplify(ExpressionNode $node)
{
switch($node->getOperator()) {
case '+': return $this->addition($node->getLeft(), $node->getRight());
case '-': return $this->subtraction($node->getLeft(), $node->getRight());
case '*': return $this->multiplication($node->getLeft(), $node->getRight());
case '/': return $this->division($node->getLeft(), $node->getRight());
case '^': return $this->exponentiation($node->getLeft(), $node->getRight());
}
} | php | public function simplify(ExpressionNode $node)
{
switch($node->getOperator()) {
case '+': return $this->addition($node->getLeft(), $node->getRight());
case '-': return $this->subtraction($node->getLeft(), $node->getRight());
case '*': return $this->multiplication($node->getLeft(), $node->getRight());
case '/': return $this->division($node->getLeft(), $node->getRight());
case '^': return $this->exponentiation($node->getLeft(), $node->getRight());
}
} | [
"public",
"function",
"simplify",
"(",
"ExpressionNode",
"$",
"node",
")",
"{",
"switch",
"(",
"$",
"node",
"->",
"getOperator",
"(",
")",
")",
"{",
"case",
"'+'",
":",
"return",
"$",
"this",
"->",
"addition",
"(",
"$",
"node",
"->",
"getLeft",
"(",
")",
",",
"$",
"node",
"->",
"getRight",
"(",
")",
")",
";",
"case",
"'-'",
":",
"return",
"$",
"this",
"->",
"subtraction",
"(",
"$",
"node",
"->",
"getLeft",
"(",
")",
",",
"$",
"node",
"->",
"getRight",
"(",
")",
")",
";",
"case",
"'*'",
":",
"return",
"$",
"this",
"->",
"multiplication",
"(",
"$",
"node",
"->",
"getLeft",
"(",
")",
",",
"$",
"node",
"->",
"getRight",
"(",
")",
")",
";",
"case",
"'/'",
":",
"return",
"$",
"this",
"->",
"division",
"(",
"$",
"node",
"->",
"getLeft",
"(",
")",
",",
"$",
"node",
"->",
"getRight",
"(",
")",
")",
";",
"case",
"'^'",
":",
"return",
"$",
"this",
"->",
"exponentiation",
"(",
"$",
"node",
"->",
"getLeft",
"(",
")",
",",
"$",
"node",
"->",
"getRight",
"(",
")",
")",
";",
"}",
"}"
] | Simplify the given ExpressionNode, using the appropriate factory.
@param ExpressionNode $node
@retval Node Simplified version of the input | [
"Simplify",
"the",
"given",
"ExpressionNode",
"using",
"the",
"appropriate",
"factory",
"."
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Parsing/Nodes/Factories/NodeFactory.php#L173-L182 |
mossadal/math-parser | src/MathParser/Parsing/Nodes/ExpressionNode.php | ExpressionNode.lowerPrecedenceThan | public function lowerPrecedenceThan($other)
{
if (!($other instanceof ExpressionNode)) return false;
if ($this->getPrecedence() < $other->getPrecedence()) return true;
if ($this->getPrecedence() > $other->getPrecedence()) return false;
if ($this->associativity == self::LEFT_ASSOC) return true;
return false;
} | php | public function lowerPrecedenceThan($other)
{
if (!($other instanceof ExpressionNode)) return false;
if ($this->getPrecedence() < $other->getPrecedence()) return true;
if ($this->getPrecedence() > $other->getPrecedence()) return false;
if ($this->associativity == self::LEFT_ASSOC) return true;
return false;
} | [
"public",
"function",
"lowerPrecedenceThan",
"(",
"$",
"other",
")",
"{",
"if",
"(",
"!",
"(",
"$",
"other",
"instanceof",
"ExpressionNode",
")",
")",
"return",
"false",
";",
"if",
"(",
"$",
"this",
"->",
"getPrecedence",
"(",
")",
"<",
"$",
"other",
"->",
"getPrecedence",
"(",
")",
")",
"return",
"true",
";",
"if",
"(",
"$",
"this",
"->",
"getPrecedence",
"(",
")",
">",
"$",
"other",
"->",
"getPrecedence",
"(",
")",
")",
"return",
"false",
";",
"if",
"(",
"$",
"this",
"->",
"associativity",
"==",
"self",
"::",
"LEFT_ASSOC",
")",
"return",
"true",
";",
"return",
"false",
";",
"}"
] | Returns true if the current Node has lower precedence than the one
we compare with.
In case of a tie, we also consider the associativity.
(Left associative operators are lower precedence in this context.)
@param Node $other Node to compare to.
@retval boolean | [
"Returns",
"true",
"if",
"the",
"current",
"Node",
"has",
"lower",
"precedence",
"than",
"the",
"one",
"we",
"compare",
"with",
"."
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Parsing/Nodes/ExpressionNode.php#L203-L214 |
mossadal/math-parser | src/MathParser/Parsing/Nodes/ExpressionNode.php | ExpressionNode.compareTo | public function compareTo($other)
{
if ($other === null) {
return false;
}
if (!($other instanceof ExpressionNode)) {
return false;
}
if ($this->getOperator() != $other->getOperator()) return false;
$thisLeft = $this->getLeft();
$otherLeft = $other->getLeft();
$thisRight = $this->getRight();
$otherRight = $other->getRight();
if ($thisLeft === null) {
return $otherLeft === null && $thisRight->compareTo($otherRight);
}
if ($thisRight === null) {
return $otherRight=== null && $thisLeft->compareTo($otherLeft);
}
return $thisLeft->compareTo($otherLeft) && $thisRight->compareTo($otherRight);
} | php | public function compareTo($other)
{
if ($other === null) {
return false;
}
if (!($other instanceof ExpressionNode)) {
return false;
}
if ($this->getOperator() != $other->getOperator()) return false;
$thisLeft = $this->getLeft();
$otherLeft = $other->getLeft();
$thisRight = $this->getRight();
$otherRight = $other->getRight();
if ($thisLeft === null) {
return $otherLeft === null && $thisRight->compareTo($otherRight);
}
if ($thisRight === null) {
return $otherRight=== null && $thisLeft->compareTo($otherLeft);
}
return $thisLeft->compareTo($otherLeft) && $thisRight->compareTo($otherRight);
} | [
"public",
"function",
"compareTo",
"(",
"$",
"other",
")",
"{",
"if",
"(",
"$",
"other",
"===",
"null",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"!",
"(",
"$",
"other",
"instanceof",
"ExpressionNode",
")",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"getOperator",
"(",
")",
"!=",
"$",
"other",
"->",
"getOperator",
"(",
")",
")",
"return",
"false",
";",
"$",
"thisLeft",
"=",
"$",
"this",
"->",
"getLeft",
"(",
")",
";",
"$",
"otherLeft",
"=",
"$",
"other",
"->",
"getLeft",
"(",
")",
";",
"$",
"thisRight",
"=",
"$",
"this",
"->",
"getRight",
"(",
")",
";",
"$",
"otherRight",
"=",
"$",
"other",
"->",
"getRight",
"(",
")",
";",
"if",
"(",
"$",
"thisLeft",
"===",
"null",
")",
"{",
"return",
"$",
"otherLeft",
"===",
"null",
"&&",
"$",
"thisRight",
"->",
"compareTo",
"(",
"$",
"otherRight",
")",
";",
"}",
"if",
"(",
"$",
"thisRight",
"===",
"null",
")",
"{",
"return",
"$",
"otherRight",
"===",
"null",
"&&",
"$",
"thisLeft",
"->",
"compareTo",
"(",
"$",
"otherLeft",
")",
";",
"}",
"return",
"$",
"thisLeft",
"->",
"compareTo",
"(",
"$",
"otherLeft",
")",
"&&",
"$",
"thisRight",
"->",
"compareTo",
"(",
"$",
"otherRight",
")",
";",
"}"
] | Implementing the compareTo abstract method. | [
"Implementing",
"the",
"compareTo",
"abstract",
"method",
"."
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Parsing/Nodes/ExpressionNode.php#L227-L252 |
mossadal/math-parser | src/MathParser/Parsing/Nodes/SubExpressionNode.php | SubExpressionNode.compareTo | public function compareTo($other)
{
if ($other === null) {
return false;
}
if (!($other instanceof SubExpressionNode)) {
return false;
}
return $this->getValue() == $other->getValue();
} | php | public function compareTo($other)
{
if ($other === null) {
return false;
}
if (!($other instanceof SubExpressionNode)) {
return false;
}
return $this->getValue() == $other->getValue();
} | [
"public",
"function",
"compareTo",
"(",
"$",
"other",
")",
"{",
"if",
"(",
"$",
"other",
"===",
"null",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"!",
"(",
"$",
"other",
"instanceof",
"SubExpressionNode",
")",
")",
"{",
"return",
"false",
";",
"}",
"return",
"$",
"this",
"->",
"getValue",
"(",
")",
"==",
"$",
"other",
"->",
"getValue",
"(",
")",
";",
"}"
] | Implementing the compareTo abstract method. | [
"Implementing",
"the",
"compareTo",
"abstract",
"method",
"."
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Parsing/Nodes/SubExpressionNode.php#L53-L63 |
mossadal/math-parser | src/MathParser/Parsing/Nodes/RationalNode.php | RationalNode.compareTo | public function compareTo($other)
{
if ($other === null) {
return false;
}
if ($other instanceof IntegerNode) {
return $this->getDenominator() == 1 && $this->getNumerator() == $other->getValue();
}
if (!($other instanceof RationalNode)) {
return false;
}
return $this->getNumerator() == $other->getNumerator() && $this->getDenominator() == $other->getDenominator();
} | php | public function compareTo($other)
{
if ($other === null) {
return false;
}
if ($other instanceof IntegerNode) {
return $this->getDenominator() == 1 && $this->getNumerator() == $other->getValue();
}
if (!($other instanceof RationalNode)) {
return false;
}
return $this->getNumerator() == $other->getNumerator() && $this->getDenominator() == $other->getDenominator();
} | [
"public",
"function",
"compareTo",
"(",
"$",
"other",
")",
"{",
"if",
"(",
"$",
"other",
"===",
"null",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"$",
"other",
"instanceof",
"IntegerNode",
")",
"{",
"return",
"$",
"this",
"->",
"getDenominator",
"(",
")",
"==",
"1",
"&&",
"$",
"this",
"->",
"getNumerator",
"(",
")",
"==",
"$",
"other",
"->",
"getValue",
"(",
")",
";",
"}",
"if",
"(",
"!",
"(",
"$",
"other",
"instanceof",
"RationalNode",
")",
")",
"{",
"return",
"false",
";",
"}",
"return",
"$",
"this",
"->",
"getNumerator",
"(",
")",
"==",
"$",
"other",
"->",
"getNumerator",
"(",
")",
"&&",
"$",
"this",
"->",
"getDenominator",
"(",
")",
"==",
"$",
"other",
"->",
"getDenominator",
"(",
")",
";",
"}"
] | Implementing the compareTo abstract method. | [
"Implementing",
"the",
"compareTo",
"abstract",
"method",
"."
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Parsing/Nodes/RationalNode.php#L80-L93 |
mossadal/math-parser | src/MathParser/Parsing/Nodes/PostfixOperatorNode.php | PostfixOperatorNode.compareTo | public function compareTo($other)
{
if ($other === null) {
return false;
}
if (!($other instanceof PostfixOperatorNode)) {
return false;
}
return $this->getOperator() == $other->getOperator();
} | php | public function compareTo($other)
{
if ($other === null) {
return false;
}
if (!($other instanceof PostfixOperatorNode)) {
return false;
}
return $this->getOperator() == $other->getOperator();
} | [
"public",
"function",
"compareTo",
"(",
"$",
"other",
")",
"{",
"if",
"(",
"$",
"other",
"===",
"null",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"!",
"(",
"$",
"other",
"instanceof",
"PostfixOperatorNode",
")",
")",
"{",
"return",
"false",
";",
"}",
"return",
"$",
"this",
"->",
"getOperator",
"(",
")",
"==",
"$",
"other",
"->",
"getOperator",
"(",
")",
";",
"}"
] | Implementing the compareTo abstract method. | [
"Implementing",
"the",
"compareTo",
"abstract",
"method",
"."
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Parsing/Nodes/PostfixOperatorNode.php#L46-L56 |
mossadal/math-parser | src/MathParser/Extensions/Math.php | Math.gcd | public static function gcd($a, $b)
{
$sign = 1;
if ($a < 0) $sign = -$sign;
if ($b < 0) $sign = -$sign;
while ($b != 0)
{
$m = $a % $b;
$a = $b;
$b = $m;
}
return $sign*abs($a);
} | php | public static function gcd($a, $b)
{
$sign = 1;
if ($a < 0) $sign = -$sign;
if ($b < 0) $sign = -$sign;
while ($b != 0)
{
$m = $a % $b;
$a = $b;
$b = $m;
}
return $sign*abs($a);
} | [
"public",
"static",
"function",
"gcd",
"(",
"$",
"a",
",",
"$",
"b",
")",
"{",
"$",
"sign",
"=",
"1",
";",
"if",
"(",
"$",
"a",
"<",
"0",
")",
"$",
"sign",
"=",
"-",
"$",
"sign",
";",
"if",
"(",
"$",
"b",
"<",
"0",
")",
"$",
"sign",
"=",
"-",
"$",
"sign",
";",
"while",
"(",
"$",
"b",
"!=",
"0",
")",
"{",
"$",
"m",
"=",
"$",
"a",
"%",
"$",
"b",
";",
"$",
"a",
"=",
"$",
"b",
";",
"$",
"b",
"=",
"$",
"m",
";",
"}",
"return",
"$",
"sign",
"*",
"abs",
"(",
"$",
"a",
")",
";",
"}"
] | Compute greates common denominator, using the Euclidean algorithm
Compute and return gcd($a, $b)
@param int $a
@param int $b
@retval int | [
"Compute",
"greates",
"common",
"denominator",
"using",
"the",
"Euclidean",
"algorithm"
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Extensions/Math.php#L21-L34 |
mossadal/math-parser | src/MathParser/Extensions/Math.php | Math.logGamma | public static function logGamma($a) {
if($a < 0)
throw new \InvalidArgumentException("Log gamma calls should be >0.");
if ($a >= 171) // Lanczos approximation w/ the given coefficients is accurate to 15 digits for 0 <= real(z) <= 171
return self::logStirlingApproximation($a);
else
return log(self::lanczosApproximation($a));
} | php | public static function logGamma($a) {
if($a < 0)
throw new \InvalidArgumentException("Log gamma calls should be >0.");
if ($a >= 171) // Lanczos approximation w/ the given coefficients is accurate to 15 digits for 0 <= real(z) <= 171
return self::logStirlingApproximation($a);
else
return log(self::lanczosApproximation($a));
} | [
"public",
"static",
"function",
"logGamma",
"(",
"$",
"a",
")",
"{",
"if",
"(",
"$",
"a",
"<",
"0",
")",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"\"Log gamma calls should be >0.\"",
")",
";",
"if",
"(",
"$",
"a",
">=",
"171",
")",
"// Lanczos approximation w/ the given coefficients is accurate to 15 digits for 0 <= real(z) <= 171",
"return",
"self",
"::",
"logStirlingApproximation",
"(",
"$",
"a",
")",
";",
"else",
"return",
"log",
"(",
"self",
"::",
"lanczosApproximation",
"(",
"$",
"a",
")",
")",
";",
"}"
] | Compute log(Gamma($a)) where $a is a positive real number
For large values of $a ($a > 171), use Stirling asympotic expansion,
otherwise use the Lanczos approximation
@param float $a
@throws InvalidArgumentException if $a < 0
@retval float | [
"Compute",
"log",
"(",
"Gamma",
"(",
"$a",
"))",
"where",
"$a",
"is",
"a",
"positive",
"real",
"number"
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Extensions/Math.php#L47-L55 |
mossadal/math-parser | src/MathParser/Extensions/Math.php | Math.logStirlingApproximation | private static function logStirlingApproximation($x) {
$t = 0.5*log(2*pi()) - 0.5*log($x) + $x*(log($x))-$x;
$x2 = $x * $x;
$x3 = $x2 * $x;
$x4 = $x3 * $x;
$err_term = log(1 + (1.0/(12*$x)) + (1.0/(288*$x2)) - (139.0/(51840*$x3))
- (571.0/(2488320*$x4)));
$res = $t + $err_term;
return $res;
} | php | private static function logStirlingApproximation($x) {
$t = 0.5*log(2*pi()) - 0.5*log($x) + $x*(log($x))-$x;
$x2 = $x * $x;
$x3 = $x2 * $x;
$x4 = $x3 * $x;
$err_term = log(1 + (1.0/(12*$x)) + (1.0/(288*$x2)) - (139.0/(51840*$x3))
- (571.0/(2488320*$x4)));
$res = $t + $err_term;
return $res;
} | [
"private",
"static",
"function",
"logStirlingApproximation",
"(",
"$",
"x",
")",
"{",
"$",
"t",
"=",
"0.5",
"*",
"log",
"(",
"2",
"*",
"pi",
"(",
")",
")",
"-",
"0.5",
"*",
"log",
"(",
"$",
"x",
")",
"+",
"$",
"x",
"*",
"(",
"log",
"(",
"$",
"x",
")",
")",
"-",
"$",
"x",
";",
"$",
"x2",
"=",
"$",
"x",
"*",
"$",
"x",
";",
"$",
"x3",
"=",
"$",
"x2",
"*",
"$",
"x",
";",
"$",
"x4",
"=",
"$",
"x3",
"*",
"$",
"x",
";",
"$",
"err_term",
"=",
"log",
"(",
"1",
"+",
"(",
"1.0",
"/",
"(",
"12",
"*",
"$",
"x",
")",
")",
"+",
"(",
"1.0",
"/",
"(",
"288",
"*",
"$",
"x2",
")",
")",
"-",
"(",
"139.0",
"/",
"(",
"51840",
"*",
"$",
"x3",
")",
")",
"-",
"(",
"571.0",
"/",
"(",
"2488320",
"*",
"$",
"x4",
")",
")",
")",
";",
"$",
"res",
"=",
"$",
"t",
"+",
"$",
"err_term",
";",
"return",
"$",
"res",
";",
"}"
] | Compute log(Gamma($x)) using Stirling asympotic expansion
@param float $x
@retval float | [
"Compute",
"log",
"(",
"Gamma",
"(",
"$x",
"))",
"using",
"Stirling",
"asympotic",
"expansion"
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Extensions/Math.php#L63-L75 |
mossadal/math-parser | src/MathParser/Extensions/Math.php | Math.Factorial | public static function Factorial($num) {
if ($num < 0) throw new \InvalidArgumentException("Fatorial calls should be >0.");
$rval=1;
for ($i = 1; $i <= $num; $i++)
$rval = $rval * $i;
return $rval;
} | php | public static function Factorial($num) {
if ($num < 0) throw new \InvalidArgumentException("Fatorial calls should be >0.");
$rval=1;
for ($i = 1; $i <= $num; $i++)
$rval = $rval * $i;
return $rval;
} | [
"public",
"static",
"function",
"Factorial",
"(",
"$",
"num",
")",
"{",
"if",
"(",
"$",
"num",
"<",
"0",
")",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"\"Fatorial calls should be >0.\"",
")",
";",
"$",
"rval",
"=",
"1",
";",
"for",
"(",
"$",
"i",
"=",
"1",
";",
"$",
"i",
"<=",
"$",
"num",
";",
"$",
"i",
"++",
")",
"$",
"rval",
"=",
"$",
"rval",
"*",
"$",
"i",
";",
"return",
"$",
"rval",
";",
"}"
] | Compute factorial n! for an integer $n using iteration
@param int $num
@retval int | [
"Compute",
"factorial",
"n!",
"for",
"an",
"integer",
"$n",
"using",
"iteration"
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Extensions/Math.php#L83-L90 |
mossadal/math-parser | src/MathParser/Extensions/Math.php | Math.SemiFactorial | public static function SemiFactorial($num) {
if ($num < 0) throw new \InvalidArgumentException("Semifactorial calls should be >0.");
$rval=1;
while ($num >= 2) {
$rval =$rval * $num;
$num = $num-2;
}
return $rval;
} | php | public static function SemiFactorial($num) {
if ($num < 0) throw new \InvalidArgumentException("Semifactorial calls should be >0.");
$rval=1;
while ($num >= 2) {
$rval =$rval * $num;
$num = $num-2;
}
return $rval;
} | [
"public",
"static",
"function",
"SemiFactorial",
"(",
"$",
"num",
")",
"{",
"if",
"(",
"$",
"num",
"<",
"0",
")",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"\"Semifactorial calls should be >0.\"",
")",
";",
"$",
"rval",
"=",
"1",
";",
"while",
"(",
"$",
"num",
">=",
"2",
")",
"{",
"$",
"rval",
"=",
"$",
"rval",
"*",
"$",
"num",
";",
"$",
"num",
"=",
"$",
"num",
"-",
"2",
";",
"}",
"return",
"$",
"rval",
";",
"}"
] | Compute semi-factorial n!! for an integer $n using iteration
@param int $num
@retval int | [
"Compute",
"semi",
"-",
"factorial",
"n!!",
"for",
"an",
"integer",
"$n",
"using",
"iteration"
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Extensions/Math.php#L98-L107 |
mossadal/math-parser | src/MathParser/Extensions/Math.php | Math.lanczosApproximation | private static function lanczosApproximation($x) {
$g = 7;
$p = array(0.99999999999980993, 676.5203681218851, -1259.1392167224028,
771.32342877765313, -176.61502916214059, 12.507343278686905,
-0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7);
if (abs($x - floor($x)) < 1e-16)
{
// if we're real close to an integer, let's just compute the factorial integerly.
if ($x >= 1)
return self::Factorial($x - 1);
else
return INF;
}
else
{
$x -= 1;
$y = $p[0];
for ($i=1; $i < $g+2; $i++)
{
$y = $y + $p[$i]/($x + $i);
}
$t = $x + $g + 0.5;
$res_fr = sqrt(2*pi()) * exp((($x+0.5)*log($t))-$t)*$y;
return $res_fr;
}
} | php | private static function lanczosApproximation($x) {
$g = 7;
$p = array(0.99999999999980993, 676.5203681218851, -1259.1392167224028,
771.32342877765313, -176.61502916214059, 12.507343278686905,
-0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7);
if (abs($x - floor($x)) < 1e-16)
{
// if we're real close to an integer, let's just compute the factorial integerly.
if ($x >= 1)
return self::Factorial($x - 1);
else
return INF;
}
else
{
$x -= 1;
$y = $p[0];
for ($i=1; $i < $g+2; $i++)
{
$y = $y + $p[$i]/($x + $i);
}
$t = $x + $g + 0.5;
$res_fr = sqrt(2*pi()) * exp((($x+0.5)*log($t))-$t)*$y;
return $res_fr;
}
} | [
"private",
"static",
"function",
"lanczosApproximation",
"(",
"$",
"x",
")",
"{",
"$",
"g",
"=",
"7",
";",
"$",
"p",
"=",
"array",
"(",
"0.99999999999980993",
",",
"676.5203681218851",
",",
"-",
"1259.1392167224028",
",",
"771.32342877765313",
",",
"-",
"176.61502916214059",
",",
"12.507343278686905",
",",
"-",
"0.13857109526572012",
",",
"9.9843695780195716e-6",
",",
"1.5056327351493116e-7",
")",
";",
"if",
"(",
"abs",
"(",
"$",
"x",
"-",
"floor",
"(",
"$",
"x",
")",
")",
"<",
"1e-16",
")",
"{",
"// if we're real close to an integer, let's just compute the factorial integerly.",
"if",
"(",
"$",
"x",
">=",
"1",
")",
"return",
"self",
"::",
"Factorial",
"(",
"$",
"x",
"-",
"1",
")",
";",
"else",
"return",
"INF",
";",
"}",
"else",
"{",
"$",
"x",
"-=",
"1",
";",
"$",
"y",
"=",
"$",
"p",
"[",
"0",
"]",
";",
"for",
"(",
"$",
"i",
"=",
"1",
";",
"$",
"i",
"<",
"$",
"g",
"+",
"2",
";",
"$",
"i",
"++",
")",
"{",
"$",
"y",
"=",
"$",
"y",
"+",
"$",
"p",
"[",
"$",
"i",
"]",
"/",
"(",
"$",
"x",
"+",
"$",
"i",
")",
";",
"}",
"$",
"t",
"=",
"$",
"x",
"+",
"$",
"g",
"+",
"0.5",
";",
"$",
"res_fr",
"=",
"sqrt",
"(",
"2",
"*",
"pi",
"(",
")",
")",
"*",
"exp",
"(",
"(",
"(",
"$",
"x",
"+",
"0.5",
")",
"*",
"log",
"(",
"$",
"t",
")",
")",
"-",
"$",
"t",
")",
"*",
"$",
"y",
";",
"return",
"$",
"res_fr",
";",
"}",
"}"
] | Compute log(Gamma($x)) using Lanczos approximation
@param float $x
@retval float | [
"Compute",
"log",
"(",
"Gamma",
"(",
"$x",
"))",
"using",
"Lanczos",
"approximation"
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Extensions/Math.php#L115-L147 |
mossadal/math-parser | src/MathParser/Interpreting/RationalEvaluator.php | RationalEvaluator.setVariables | public function setVariables($variables)
{
$this->variables = [];
foreach ($variables as $var => $value) {
if ($value instanceof RationalNode) {
$this->variables[$var] = $value;
} elseif ($this->isInteger($value)) {
$this->variables[$var] = new RationalNode(intval($value), 1);
} else {
$this->variables[$var] = $this->parseRational($value);
}
}
} | php | public function setVariables($variables)
{
$this->variables = [];
foreach ($variables as $var => $value) {
if ($value instanceof RationalNode) {
$this->variables[$var] = $value;
} elseif ($this->isInteger($value)) {
$this->variables[$var] = new RationalNode(intval($value), 1);
} else {
$this->variables[$var] = $this->parseRational($value);
}
}
} | [
"public",
"function",
"setVariables",
"(",
"$",
"variables",
")",
"{",
"$",
"this",
"->",
"variables",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"variables",
"as",
"$",
"var",
"=>",
"$",
"value",
")",
"{",
"if",
"(",
"$",
"value",
"instanceof",
"RationalNode",
")",
"{",
"$",
"this",
"->",
"variables",
"[",
"$",
"var",
"]",
"=",
"$",
"value",
";",
"}",
"elseif",
"(",
"$",
"this",
"->",
"isInteger",
"(",
"$",
"value",
")",
")",
"{",
"$",
"this",
"->",
"variables",
"[",
"$",
"var",
"]",
"=",
"new",
"RationalNode",
"(",
"intval",
"(",
"$",
"value",
")",
",",
"1",
")",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"variables",
"[",
"$",
"var",
"]",
"=",
"$",
"this",
"->",
"parseRational",
"(",
"$",
"value",
")",
";",
"}",
"}",
"}"
] | Update the variables used for evaluating
@retval void
@param array $variables Key/value pair holding current variable values | [
"Update",
"the",
"variables",
"used",
"for",
"evaluating"
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Interpreting/RationalEvaluator.php#L109-L121 |
mossadal/math-parser | src/MathParser/Interpreting/RationalEvaluator.php | RationalEvaluator.visitExpressionNode | public function visitExpressionNode(ExpressionNode $node)
{
$operator = $node->getOperator();
$a = $node->getLeft()->accept($this);
if ($node->getRight()) {
$b = $node->getRight()->accept($this);
} else {
$b = null;
}
// Perform the right operation based on the operator
switch ($operator) {
case '+':
$p = $a->getNumerator() * $b->getDenominator() + $a->getDenominator() * $b->getNumerator();
$q = $a->getDenominator() * $b->getDenominator();
return new RationalNode($p, $q);
case '-':
if ($b === null) {
return new RationalNode(-$a->getNumerator(), $a->getDenominator());
}
$p = $a->getNumerator() * $b->getDenominator() - $a->getDenominator() * $b->getNumerator();
$q = $a->getDenominator() * $b->getDenominator();
return new RationalNode($p, $q);
case '*':
$p = $a->getNumerator() * $b->getNumerator();
$q = $a->getDenominator() * $b->getDenominator();
return new RationalNode($p, $q);
case '/':
if ($b->getNumerator() == 0) {
throw new DivisionByZeroException();
}
$p = $a->getNumerator() * $b->getDenominator();
$q = $a->getDenominator() * $b->getNumerator();
return new RationalNode($p, $q);
case '^':
return $this->rpow($a, $b);
default:
throw new UnknownOperatorException($operator);
}
} | php | public function visitExpressionNode(ExpressionNode $node)
{
$operator = $node->getOperator();
$a = $node->getLeft()->accept($this);
if ($node->getRight()) {
$b = $node->getRight()->accept($this);
} else {
$b = null;
}
// Perform the right operation based on the operator
switch ($operator) {
case '+':
$p = $a->getNumerator() * $b->getDenominator() + $a->getDenominator() * $b->getNumerator();
$q = $a->getDenominator() * $b->getDenominator();
return new RationalNode($p, $q);
case '-':
if ($b === null) {
return new RationalNode(-$a->getNumerator(), $a->getDenominator());
}
$p = $a->getNumerator() * $b->getDenominator() - $a->getDenominator() * $b->getNumerator();
$q = $a->getDenominator() * $b->getDenominator();
return new RationalNode($p, $q);
case '*':
$p = $a->getNumerator() * $b->getNumerator();
$q = $a->getDenominator() * $b->getDenominator();
return new RationalNode($p, $q);
case '/':
if ($b->getNumerator() == 0) {
throw new DivisionByZeroException();
}
$p = $a->getNumerator() * $b->getDenominator();
$q = $a->getDenominator() * $b->getNumerator();
return new RationalNode($p, $q);
case '^':
return $this->rpow($a, $b);
default:
throw new UnknownOperatorException($operator);
}
} | [
"public",
"function",
"visitExpressionNode",
"(",
"ExpressionNode",
"$",
"node",
")",
"{",
"$",
"operator",
"=",
"$",
"node",
"->",
"getOperator",
"(",
")",
";",
"$",
"a",
"=",
"$",
"node",
"->",
"getLeft",
"(",
")",
"->",
"accept",
"(",
"$",
"this",
")",
";",
"if",
"(",
"$",
"node",
"->",
"getRight",
"(",
")",
")",
"{",
"$",
"b",
"=",
"$",
"node",
"->",
"getRight",
"(",
")",
"->",
"accept",
"(",
"$",
"this",
")",
";",
"}",
"else",
"{",
"$",
"b",
"=",
"null",
";",
"}",
"// Perform the right operation based on the operator",
"switch",
"(",
"$",
"operator",
")",
"{",
"case",
"'+'",
":",
"$",
"p",
"=",
"$",
"a",
"->",
"getNumerator",
"(",
")",
"*",
"$",
"b",
"->",
"getDenominator",
"(",
")",
"+",
"$",
"a",
"->",
"getDenominator",
"(",
")",
"*",
"$",
"b",
"->",
"getNumerator",
"(",
")",
";",
"$",
"q",
"=",
"$",
"a",
"->",
"getDenominator",
"(",
")",
"*",
"$",
"b",
"->",
"getDenominator",
"(",
")",
";",
"return",
"new",
"RationalNode",
"(",
"$",
"p",
",",
"$",
"q",
")",
";",
"case",
"'-'",
":",
"if",
"(",
"$",
"b",
"===",
"null",
")",
"{",
"return",
"new",
"RationalNode",
"(",
"-",
"$",
"a",
"->",
"getNumerator",
"(",
")",
",",
"$",
"a",
"->",
"getDenominator",
"(",
")",
")",
";",
"}",
"$",
"p",
"=",
"$",
"a",
"->",
"getNumerator",
"(",
")",
"*",
"$",
"b",
"->",
"getDenominator",
"(",
")",
"-",
"$",
"a",
"->",
"getDenominator",
"(",
")",
"*",
"$",
"b",
"->",
"getNumerator",
"(",
")",
";",
"$",
"q",
"=",
"$",
"a",
"->",
"getDenominator",
"(",
")",
"*",
"$",
"b",
"->",
"getDenominator",
"(",
")",
";",
"return",
"new",
"RationalNode",
"(",
"$",
"p",
",",
"$",
"q",
")",
";",
"case",
"'*'",
":",
"$",
"p",
"=",
"$",
"a",
"->",
"getNumerator",
"(",
")",
"*",
"$",
"b",
"->",
"getNumerator",
"(",
")",
";",
"$",
"q",
"=",
"$",
"a",
"->",
"getDenominator",
"(",
")",
"*",
"$",
"b",
"->",
"getDenominator",
"(",
")",
";",
"return",
"new",
"RationalNode",
"(",
"$",
"p",
",",
"$",
"q",
")",
";",
"case",
"'/'",
":",
"if",
"(",
"$",
"b",
"->",
"getNumerator",
"(",
")",
"==",
"0",
")",
"{",
"throw",
"new",
"DivisionByZeroException",
"(",
")",
";",
"}",
"$",
"p",
"=",
"$",
"a",
"->",
"getNumerator",
"(",
")",
"*",
"$",
"b",
"->",
"getDenominator",
"(",
")",
";",
"$",
"q",
"=",
"$",
"a",
"->",
"getDenominator",
"(",
")",
"*",
"$",
"b",
"->",
"getNumerator",
"(",
")",
";",
"return",
"new",
"RationalNode",
"(",
"$",
"p",
",",
"$",
"q",
")",
";",
"case",
"'^'",
":",
"return",
"$",
"this",
"->",
"rpow",
"(",
"$",
"a",
",",
"$",
"b",
")",
";",
"default",
":",
"throw",
"new",
"UnknownOperatorException",
"(",
"$",
"operator",
")",
";",
"}",
"}"
] | Evaluate an ExpressionNode
Computes the value of an ExpressionNode `x op y`
where `op` is one of `+`, `-`, `*`, `/` or `^`
`+`, `-`, `*`, `/` or `^`
@retval float
@param ExpressionNode $node AST to be evaluated
@throws UnknownOperatorException if the operator is something other than | [
"Evaluate",
"an",
"ExpressionNode"
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Interpreting/RationalEvaluator.php#L134-L180 |
mossadal/math-parser | src/MathParser/Interpreting/RationalEvaluator.php | RationalEvaluator.visitFunctionNode | public function visitFunctionNode(FunctionNode $node)
{
$inner = $node->getOperand()->accept($this);
switch ($node->getName()) {
// Trigonometric functions
case 'sin':
case 'cos':
case 'tan':
case 'cot':
case 'arcsin':
case 'arccos':
case 'arctan':
case 'arccot':
case 'exp':
case 'log':
case 'ln':
case 'lg':
case 'sinh':
case 'cosh':
case 'tanh':
case 'coth':
case 'arsinh':
case 'arcosh':
case 'artanh':
case 'arcoth':
throw new \UnexpectedValueException("Expecting rational expression");
case 'abs':
return new RationalNode(abs($inner->getNumerator()), $inner->getDenominator());
case 'sgn':
if ($inner->getNumerator() >= 0) {
return new RationalNode(1, 0);
} else {
return new RationalNode(-1, 0);
}
// Powers
case 'sqrt':
return $this->rpow($inner, new RationalNode(1, 2));
case '!':
if ($inner->getDenominator() == 1 && $inner->getNumerator() >= 0) {
return new RationalNode(Math::Factorial($inner->getNumerator()), 1);
}
throw new \UnexpectedValueException("Expecting positive integer (factorial)");
case '!!':
if ($inner->getDenominator() == 1 && $inner->getNumerator() >= 0) {
return new RationalNode(Math::SemiFactorial($inner->getNumerator()), 1);
}
throw new \UnexpectedValueException("Expecting positive integer (factorial)");
default:
throw new UnknownFunctionException($node->getName());
}
} | php | public function visitFunctionNode(FunctionNode $node)
{
$inner = $node->getOperand()->accept($this);
switch ($node->getName()) {
// Trigonometric functions
case 'sin':
case 'cos':
case 'tan':
case 'cot':
case 'arcsin':
case 'arccos':
case 'arctan':
case 'arccot':
case 'exp':
case 'log':
case 'ln':
case 'lg':
case 'sinh':
case 'cosh':
case 'tanh':
case 'coth':
case 'arsinh':
case 'arcosh':
case 'artanh':
case 'arcoth':
throw new \UnexpectedValueException("Expecting rational expression");
case 'abs':
return new RationalNode(abs($inner->getNumerator()), $inner->getDenominator());
case 'sgn':
if ($inner->getNumerator() >= 0) {
return new RationalNode(1, 0);
} else {
return new RationalNode(-1, 0);
}
// Powers
case 'sqrt':
return $this->rpow($inner, new RationalNode(1, 2));
case '!':
if ($inner->getDenominator() == 1 && $inner->getNumerator() >= 0) {
return new RationalNode(Math::Factorial($inner->getNumerator()), 1);
}
throw new \UnexpectedValueException("Expecting positive integer (factorial)");
case '!!':
if ($inner->getDenominator() == 1 && $inner->getNumerator() >= 0) {
return new RationalNode(Math::SemiFactorial($inner->getNumerator()), 1);
}
throw new \UnexpectedValueException("Expecting positive integer (factorial)");
default:
throw new UnknownFunctionException($node->getName());
}
} | [
"public",
"function",
"visitFunctionNode",
"(",
"FunctionNode",
"$",
"node",
")",
"{",
"$",
"inner",
"=",
"$",
"node",
"->",
"getOperand",
"(",
")",
"->",
"accept",
"(",
"$",
"this",
")",
";",
"switch",
"(",
"$",
"node",
"->",
"getName",
"(",
")",
")",
"{",
"// Trigonometric functions",
"case",
"'sin'",
":",
"case",
"'cos'",
":",
"case",
"'tan'",
":",
"case",
"'cot'",
":",
"case",
"'arcsin'",
":",
"case",
"'arccos'",
":",
"case",
"'arctan'",
":",
"case",
"'arccot'",
":",
"case",
"'exp'",
":",
"case",
"'log'",
":",
"case",
"'ln'",
":",
"case",
"'lg'",
":",
"case",
"'sinh'",
":",
"case",
"'cosh'",
":",
"case",
"'tanh'",
":",
"case",
"'coth'",
":",
"case",
"'arsinh'",
":",
"case",
"'arcosh'",
":",
"case",
"'artanh'",
":",
"case",
"'arcoth'",
":",
"throw",
"new",
"\\",
"UnexpectedValueException",
"(",
"\"Expecting rational expression\"",
")",
";",
"case",
"'abs'",
":",
"return",
"new",
"RationalNode",
"(",
"abs",
"(",
"$",
"inner",
"->",
"getNumerator",
"(",
")",
")",
",",
"$",
"inner",
"->",
"getDenominator",
"(",
")",
")",
";",
"case",
"'sgn'",
":",
"if",
"(",
"$",
"inner",
"->",
"getNumerator",
"(",
")",
">=",
"0",
")",
"{",
"return",
"new",
"RationalNode",
"(",
"1",
",",
"0",
")",
";",
"}",
"else",
"{",
"return",
"new",
"RationalNode",
"(",
"-",
"1",
",",
"0",
")",
";",
"}",
"// Powers",
"case",
"'sqrt'",
":",
"return",
"$",
"this",
"->",
"rpow",
"(",
"$",
"inner",
",",
"new",
"RationalNode",
"(",
"1",
",",
"2",
")",
")",
";",
"case",
"'!'",
":",
"if",
"(",
"$",
"inner",
"->",
"getDenominator",
"(",
")",
"==",
"1",
"&&",
"$",
"inner",
"->",
"getNumerator",
"(",
")",
">=",
"0",
")",
"{",
"return",
"new",
"RationalNode",
"(",
"Math",
"::",
"Factorial",
"(",
"$",
"inner",
"->",
"getNumerator",
"(",
")",
")",
",",
"1",
")",
";",
"}",
"throw",
"new",
"\\",
"UnexpectedValueException",
"(",
"\"Expecting positive integer (factorial)\"",
")",
";",
"case",
"'!!'",
":",
"if",
"(",
"$",
"inner",
"->",
"getDenominator",
"(",
")",
"==",
"1",
"&&",
"$",
"inner",
"->",
"getNumerator",
"(",
")",
">=",
"0",
")",
"{",
"return",
"new",
"RationalNode",
"(",
"Math",
"::",
"SemiFactorial",
"(",
"$",
"inner",
"->",
"getNumerator",
"(",
")",
")",
",",
"1",
")",
";",
"}",
"throw",
"new",
"\\",
"UnexpectedValueException",
"(",
"\"Expecting positive integer (factorial)\"",
")",
";",
"default",
":",
"throw",
"new",
"UnknownFunctionException",
"(",
"$",
"node",
"->",
"getName",
"(",
")",
")",
";",
"}",
"}"
] | Evaluate a FunctionNode
Computes the value of a FunctionNode `f(x)`, where f is
an elementary function recognized by StdMathLexer and StdMathParser.
FunctionNode is *not* recognized.
@retval float
@see \MathParser\Lexer\StdMathLexer StdMathLexer
@see \MathParser\StdMathParser StdMathParser
@param FunctionNode $node AST to be evaluated
@throws UnknownFunctionException if the function respresented by the | [
"Evaluate",
"a",
"FunctionNode"
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Interpreting/RationalEvaluator.php#L243-L302 |
mossadal/math-parser | src/MathParser/Interpreting/RationalEvaluator.php | RationalEvaluator.ifactor | public static function ifactor($n)
{
// max_n = 2^31-1 = 2147483647
$d = 2;
$factors = [];
$dmax = floor(sqrt($n));
self::$sieve = array_pad(self::$sieve, $dmax, 1);
do {
$r = false;
while ($n % $d == 0) {
if (array_key_exists($d, $factors)) {
$factors[$d]++;
} else {
$factors[$d] = 1;
}
$n /= $d;
$r = true;
}
if ($r) {
$dmax = floor(sqrt($n));
}
if ($n > 1) {
for ($i = $d; $i <= $dmax; $i += $d) {
self::$sieve[$i] = 0;
}
do {
$d++;
} while ($d < $dmax && self::$sieve[$d] != 1);
if ($d > $dmax) {
if (array_key_exists($n, $factors)) {
$factors[$n]++;
} else {
$factors[$n] = 1;
}
}
}
} while ($n > 1 && $d <= $dmax);
return $factors;
} | php | public static function ifactor($n)
{
// max_n = 2^31-1 = 2147483647
$d = 2;
$factors = [];
$dmax = floor(sqrt($n));
self::$sieve = array_pad(self::$sieve, $dmax, 1);
do {
$r = false;
while ($n % $d == 0) {
if (array_key_exists($d, $factors)) {
$factors[$d]++;
} else {
$factors[$d] = 1;
}
$n /= $d;
$r = true;
}
if ($r) {
$dmax = floor(sqrt($n));
}
if ($n > 1) {
for ($i = $d; $i <= $dmax; $i += $d) {
self::$sieve[$i] = 0;
}
do {
$d++;
} while ($d < $dmax && self::$sieve[$d] != 1);
if ($d > $dmax) {
if (array_key_exists($n, $factors)) {
$factors[$n]++;
} else {
$factors[$n] = 1;
}
}
}
} while ($n > 1 && $d <= $dmax);
return $factors;
} | [
"public",
"static",
"function",
"ifactor",
"(",
"$",
"n",
")",
"{",
"// max_n = 2^31-1 = 2147483647",
"$",
"d",
"=",
"2",
";",
"$",
"factors",
"=",
"[",
"]",
";",
"$",
"dmax",
"=",
"floor",
"(",
"sqrt",
"(",
"$",
"n",
")",
")",
";",
"self",
"::",
"$",
"sieve",
"=",
"array_pad",
"(",
"self",
"::",
"$",
"sieve",
",",
"$",
"dmax",
",",
"1",
")",
";",
"do",
"{",
"$",
"r",
"=",
"false",
";",
"while",
"(",
"$",
"n",
"%",
"$",
"d",
"==",
"0",
")",
"{",
"if",
"(",
"array_key_exists",
"(",
"$",
"d",
",",
"$",
"factors",
")",
")",
"{",
"$",
"factors",
"[",
"$",
"d",
"]",
"++",
";",
"}",
"else",
"{",
"$",
"factors",
"[",
"$",
"d",
"]",
"=",
"1",
";",
"}",
"$",
"n",
"/=",
"$",
"d",
";",
"$",
"r",
"=",
"true",
";",
"}",
"if",
"(",
"$",
"r",
")",
"{",
"$",
"dmax",
"=",
"floor",
"(",
"sqrt",
"(",
"$",
"n",
")",
")",
";",
"}",
"if",
"(",
"$",
"n",
">",
"1",
")",
"{",
"for",
"(",
"$",
"i",
"=",
"$",
"d",
";",
"$",
"i",
"<=",
"$",
"dmax",
";",
"$",
"i",
"+=",
"$",
"d",
")",
"{",
"self",
"::",
"$",
"sieve",
"[",
"$",
"i",
"]",
"=",
"0",
";",
"}",
"do",
"{",
"$",
"d",
"++",
";",
"}",
"while",
"(",
"$",
"d",
"<",
"$",
"dmax",
"&&",
"self",
"::",
"$",
"sieve",
"[",
"$",
"d",
"]",
"!=",
"1",
")",
";",
"if",
"(",
"$",
"d",
">",
"$",
"dmax",
")",
"{",
"if",
"(",
"array_key_exists",
"(",
"$",
"n",
",",
"$",
"factors",
")",
")",
"{",
"$",
"factors",
"[",
"$",
"n",
"]",
"++",
";",
"}",
"else",
"{",
"$",
"factors",
"[",
"$",
"n",
"]",
"=",
"1",
";",
"}",
"}",
"}",
"}",
"while",
"(",
"$",
"n",
">",
"1",
"&&",
"$",
"d",
"<=",
"$",
"dmax",
")",
";",
"return",
"$",
"factors",
";",
"}"
] | Integer factorization
Computes an integer factorization of $n using
trial division and a cached sieve of computed primes
@param type var Description | [
"Integer",
"factorization"
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Interpreting/RationalEvaluator.php#L347-L391 |
mossadal/math-parser | src/MathParser/Interpreting/RationalEvaluator.php | RationalEvaluator.powerFreeFactorization | public static function powerFreeFactorization($n, $d)
{
$factors = self::ifactor($n);
$square = 1;
$nonSquare = 1;
foreach ($factors as $prime => $exponent) {
$remainder = $exponent % $d;
if ($remainder != 0) {
$reducedExponent = ($exponent - $remainder) / $d;
$nonSquare *= $prime;
} else {
$reducedExponent = $exponent / $d;
}
$square *= pow($prime, $reducedExponent);
}
return ['square' => $square, 'nonSquare' => $nonSquare];
} | php | public static function powerFreeFactorization($n, $d)
{
$factors = self::ifactor($n);
$square = 1;
$nonSquare = 1;
foreach ($factors as $prime => $exponent) {
$remainder = $exponent % $d;
if ($remainder != 0) {
$reducedExponent = ($exponent - $remainder) / $d;
$nonSquare *= $prime;
} else {
$reducedExponent = $exponent / $d;
}
$square *= pow($prime, $reducedExponent);
}
return ['square' => $square, 'nonSquare' => $nonSquare];
} | [
"public",
"static",
"function",
"powerFreeFactorization",
"(",
"$",
"n",
",",
"$",
"d",
")",
"{",
"$",
"factors",
"=",
"self",
"::",
"ifactor",
"(",
"$",
"n",
")",
";",
"$",
"square",
"=",
"1",
";",
"$",
"nonSquare",
"=",
"1",
";",
"foreach",
"(",
"$",
"factors",
"as",
"$",
"prime",
"=>",
"$",
"exponent",
")",
"{",
"$",
"remainder",
"=",
"$",
"exponent",
"%",
"$",
"d",
";",
"if",
"(",
"$",
"remainder",
"!=",
"0",
")",
"{",
"$",
"reducedExponent",
"=",
"(",
"$",
"exponent",
"-",
"$",
"remainder",
")",
"/",
"$",
"d",
";",
"$",
"nonSquare",
"*=",
"$",
"prime",
";",
"}",
"else",
"{",
"$",
"reducedExponent",
"=",
"$",
"exponent",
"/",
"$",
"d",
";",
"}",
"$",
"square",
"*=",
"pow",
"(",
"$",
"prime",
",",
"$",
"reducedExponent",
")",
";",
"}",
"return",
"[",
"'square'",
"=>",
"$",
"square",
",",
"'nonSquare'",
"=>",
"$",
"nonSquare",
"]",
";",
"}"
] | Compute a power free integer factorization: n = pq^d,
where p is d-power free.
The function returns an array:
[
'square' => q,
'nonSquare' => p
]
@param int $n input | [
"Compute",
"a",
"power",
"free",
"integer",
"factorization",
":",
"n",
"=",
"pq^d",
"where",
"p",
"is",
"d",
"-",
"power",
"free",
"."
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Interpreting/RationalEvaluator.php#L405-L425 |
mossadal/math-parser | src/MathParser/Parsing/Nodes/Factories/DivisionNodeFactory.php | DivisionNodeFactory.makeNode | public function makeNode($leftOperand, $rightOperand)
{
$leftOperand = $this->sanitize($leftOperand);
$rightOperand = $this->sanitize($rightOperand);
// Return rational number?
// if ($leftOperand instanceof NumberNode && $rightOperand instanceof NumberNode)
// return new NumberNode($leftOperand->getValue() / $rightOperand->getValue());
$node = $this->numericFactors($leftOperand, $rightOperand);
if ($node) return $node;
if ($leftOperand->compareTo($rightOperand)) {
return new IntegerNode(1);
}
return new ExpressionNode($leftOperand, '/', $rightOperand);
} | php | public function makeNode($leftOperand, $rightOperand)
{
$leftOperand = $this->sanitize($leftOperand);
$rightOperand = $this->sanitize($rightOperand);
// Return rational number?
// if ($leftOperand instanceof NumberNode && $rightOperand instanceof NumberNode)
// return new NumberNode($leftOperand->getValue() / $rightOperand->getValue());
$node = $this->numericFactors($leftOperand, $rightOperand);
if ($node) return $node;
if ($leftOperand->compareTo($rightOperand)) {
return new IntegerNode(1);
}
return new ExpressionNode($leftOperand, '/', $rightOperand);
} | [
"public",
"function",
"makeNode",
"(",
"$",
"leftOperand",
",",
"$",
"rightOperand",
")",
"{",
"$",
"leftOperand",
"=",
"$",
"this",
"->",
"sanitize",
"(",
"$",
"leftOperand",
")",
";",
"$",
"rightOperand",
"=",
"$",
"this",
"->",
"sanitize",
"(",
"$",
"rightOperand",
")",
";",
"// Return rational number?",
"// if ($leftOperand instanceof NumberNode && $rightOperand instanceof NumberNode)",
"// return new NumberNode($leftOperand->getValue() / $rightOperand->getValue());",
"$",
"node",
"=",
"$",
"this",
"->",
"numericFactors",
"(",
"$",
"leftOperand",
",",
"$",
"rightOperand",
")",
";",
"if",
"(",
"$",
"node",
")",
"return",
"$",
"node",
";",
"if",
"(",
"$",
"leftOperand",
"->",
"compareTo",
"(",
"$",
"rightOperand",
")",
")",
"{",
"return",
"new",
"IntegerNode",
"(",
"1",
")",
";",
"}",
"return",
"new",
"ExpressionNode",
"(",
"$",
"leftOperand",
",",
"'/'",
",",
"$",
"rightOperand",
")",
";",
"}"
] | Create a Node representing '$leftOperand/$rightOperand'
Using some simplification rules, create a NumberNode or ExpressionNode
giving an AST correctly representing '$leftOperand/$rightOperand'.
### Simplification rules:
- To simplify the use of the function, convert integer params to NumberNodes
- If $leftOperand is a NumberNode representing 0, return 0
- If $rightOperand is a NumberNode representing 1, return $leftOperand
- If $leftOperand and $rightOperand are equal, return '1'
@param Node|int $leftOperand Numerator
@param Node|int $rightOperand Denominator
@retval Node | [
"Create",
"a",
"Node",
"representing",
"$leftOperand",
"/",
"$rightOperand"
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Parsing/Nodes/Factories/DivisionNodeFactory.php#L54-L71 |
mossadal/math-parser | src/MathParser/Parsing/Nodes/Factories/DivisionNodeFactory.php | DivisionNodeFactory.numericFactors | protected function numericFactors($leftOperand, $rightOperand)
{
if ($this->isNumeric($rightOperand) && $rightOperand->getValue() == 0) {
throw new DivisionByZeroException();
}
if ($this->isNumeric($rightOperand) && $rightOperand->getValue() == 1)
{
return $leftOperand;
}
if ($this->isNumeric($leftOperand) && $leftOperand->getValue() == 0)
{
return new IntegerNode(0);
}
if (!$this->isNumeric($leftOperand) || !$this->isNumeric($rightOperand)) {
return null;
}
$type = $this->resultingType($leftOperand, $rightOperand);
switch($type) {
case Node::NumericFloat:
return new NumberNode($leftOperand->getValue() / $rightOperand->getValue());
case Node::NumericRational:
case Node::NumericInteger:
$p = $leftOperand->getNumerator() * $rightOperand->getDenominator();
$q = $leftOperand->getDenominator() * $rightOperand->getNumerator();
return new RationalNode($p, $q);
}
return null;
} | php | protected function numericFactors($leftOperand, $rightOperand)
{
if ($this->isNumeric($rightOperand) && $rightOperand->getValue() == 0) {
throw new DivisionByZeroException();
}
if ($this->isNumeric($rightOperand) && $rightOperand->getValue() == 1)
{
return $leftOperand;
}
if ($this->isNumeric($leftOperand) && $leftOperand->getValue() == 0)
{
return new IntegerNode(0);
}
if (!$this->isNumeric($leftOperand) || !$this->isNumeric($rightOperand)) {
return null;
}
$type = $this->resultingType($leftOperand, $rightOperand);
switch($type) {
case Node::NumericFloat:
return new NumberNode($leftOperand->getValue() / $rightOperand->getValue());
case Node::NumericRational:
case Node::NumericInteger:
$p = $leftOperand->getNumerator() * $rightOperand->getDenominator();
$q = $leftOperand->getDenominator() * $rightOperand->getNumerator();
return new RationalNode($p, $q);
}
return null;
} | [
"protected",
"function",
"numericFactors",
"(",
"$",
"leftOperand",
",",
"$",
"rightOperand",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"isNumeric",
"(",
"$",
"rightOperand",
")",
"&&",
"$",
"rightOperand",
"->",
"getValue",
"(",
")",
"==",
"0",
")",
"{",
"throw",
"new",
"DivisionByZeroException",
"(",
")",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"isNumeric",
"(",
"$",
"rightOperand",
")",
"&&",
"$",
"rightOperand",
"->",
"getValue",
"(",
")",
"==",
"1",
")",
"{",
"return",
"$",
"leftOperand",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"isNumeric",
"(",
"$",
"leftOperand",
")",
"&&",
"$",
"leftOperand",
"->",
"getValue",
"(",
")",
"==",
"0",
")",
"{",
"return",
"new",
"IntegerNode",
"(",
"0",
")",
";",
"}",
"if",
"(",
"!",
"$",
"this",
"->",
"isNumeric",
"(",
"$",
"leftOperand",
")",
"||",
"!",
"$",
"this",
"->",
"isNumeric",
"(",
"$",
"rightOperand",
")",
")",
"{",
"return",
"null",
";",
"}",
"$",
"type",
"=",
"$",
"this",
"->",
"resultingType",
"(",
"$",
"leftOperand",
",",
"$",
"rightOperand",
")",
";",
"switch",
"(",
"$",
"type",
")",
"{",
"case",
"Node",
"::",
"NumericFloat",
":",
"return",
"new",
"NumberNode",
"(",
"$",
"leftOperand",
"->",
"getValue",
"(",
")",
"/",
"$",
"rightOperand",
"->",
"getValue",
"(",
")",
")",
";",
"case",
"Node",
"::",
"NumericRational",
":",
"case",
"Node",
"::",
"NumericInteger",
":",
"$",
"p",
"=",
"$",
"leftOperand",
"->",
"getNumerator",
"(",
")",
"*",
"$",
"rightOperand",
"->",
"getDenominator",
"(",
")",
";",
"$",
"q",
"=",
"$",
"leftOperand",
"->",
"getDenominator",
"(",
")",
"*",
"$",
"rightOperand",
"->",
"getNumerator",
"(",
")",
";",
"return",
"new",
"RationalNode",
"(",
"$",
"p",
",",
"$",
"q",
")",
";",
"}",
"return",
"null",
";",
"}"
] | Simplify division nodes when factors are numeric
@param Node $leftOperand
@param Node $rightOperand
@retval Node|null | [
"Simplify",
"division",
"nodes",
"when",
"factors",
"are",
"numeric"
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Parsing/Nodes/Factories/DivisionNodeFactory.php#L78-L109 |
mossadal/math-parser | src/MathParser/Parsing/Nodes/Traits/Sanitize.php | Sanitize.sanitize | protected function sanitize($operand)
{
if (is_int($operand)) return new IntegerNode($operand);
if (is_float($operand)) return new NumberNode($operand);
return $operand;
} | php | protected function sanitize($operand)
{
if (is_int($operand)) return new IntegerNode($operand);
if (is_float($operand)) return new NumberNode($operand);
return $operand;
} | [
"protected",
"function",
"sanitize",
"(",
"$",
"operand",
")",
"{",
"if",
"(",
"is_int",
"(",
"$",
"operand",
")",
")",
"return",
"new",
"IntegerNode",
"(",
"$",
"operand",
")",
";",
"if",
"(",
"is_float",
"(",
"$",
"operand",
")",
")",
"return",
"new",
"NumberNode",
"(",
"$",
"operand",
")",
";",
"return",
"$",
"operand",
";",
"}"
] | Convert ints and floats to NumberNodes
@param Node|int|float $operand
@retval Node | [
"Convert",
"ints",
"and",
"floats",
"to",
"NumberNodes"
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Parsing/Nodes/Traits/Sanitize.php#L33-L39 |
mossadal/math-parser | src/MathParser/Interpreting/Differentiator.php | Differentiator.visitExpressionNode | public function visitExpressionNode(ExpressionNode $node)
{
$operator = $node->getOperator();
$leftValue = $node->getLeft()->accept($this);
if ($node->getRight()) {
$rightValue = $node->getRight()->accept($this);
} else {
$rightValue = null;
}
// Perform the right operation based on the operator
switch ($operator) {
case '+':
return $this->nodeFactory->addition($leftValue, $rightValue);
case '-':
return $this->nodeFactory->subtraction($leftValue, $rightValue);
// Product rule (fg)' = fg' + f'g
case '*':
return $this->nodeFactory->addition(
$this->nodeFactory->multiplication($node->getLeft(), $rightValue),
$this->nodeFactory->multiplication($leftValue, $node->getRight())
);
// Quotient rule (f/g)' = (f'g - fg')/g^2
case '/':
$term1 = $this->nodeFactory->multiplication($leftValue, $node->getRight());
$term2 = $this->nodeFactory->multiplication($node->getLeft(), $rightValue);
$numerator = $this->nodeFactory->subtraction($term1, $term2);
$denominator = $this->nodeFactory->exponentiation($node->getRight(), new IntegerNode(2));
return $this->nodeFactory->division($numerator, $denominator);
// f^g = exp(g log(f)), so (f^g)' = f^g (g'log(f) + g/f)
case '^':
$base = $node->getLeft();
$exponent = $node->getRight();
if ($exponent instanceof IntegerNode || $exponent instanceof NumberNode) {
$power = $exponent->getValue();
$fpow = $this->nodeFactory->exponentiation($base, $power - 1);
return $this->nodeFactory->multiplication($power, $this->nodeFactory->multiplication($fpow, $leftValue));
} elseif ($exponent instanceof RationalNode) {
$newPower = new RationalNode($exponent->getNumerator() - $exponent->getDenominator(), $exponent->getDenominator());
$fpow = $this->nodeFactory->exponentiation($base, $newPower);
return $this->nodeFactory->multiplication($exponent, $this->nodeFactory->multiplication($fpow, $leftValue));
} elseif ($base instanceof ConstantNode && $base->getName() == 'e') {
return $this->nodeFactory->multiplication($rightValue, $node);
} else {
$term1 = $this->nodeFactory->multiplication($rightValue, new FunctionNode('ln', $base));
$term2 = $this->nodeFactory->division(
$this->nodeFactory->multiplication($exponent, $base->accept($this)),
$base);
$factor2 = $this->nodeFactory->addition($term1, $term2);
return $this->nodeFactory->multiplication($node, $factor2);
}
default:
throw new UnknownOperatorException($operator);
}
} | php | public function visitExpressionNode(ExpressionNode $node)
{
$operator = $node->getOperator();
$leftValue = $node->getLeft()->accept($this);
if ($node->getRight()) {
$rightValue = $node->getRight()->accept($this);
} else {
$rightValue = null;
}
// Perform the right operation based on the operator
switch ($operator) {
case '+':
return $this->nodeFactory->addition($leftValue, $rightValue);
case '-':
return $this->nodeFactory->subtraction($leftValue, $rightValue);
// Product rule (fg)' = fg' + f'g
case '*':
return $this->nodeFactory->addition(
$this->nodeFactory->multiplication($node->getLeft(), $rightValue),
$this->nodeFactory->multiplication($leftValue, $node->getRight())
);
// Quotient rule (f/g)' = (f'g - fg')/g^2
case '/':
$term1 = $this->nodeFactory->multiplication($leftValue, $node->getRight());
$term2 = $this->nodeFactory->multiplication($node->getLeft(), $rightValue);
$numerator = $this->nodeFactory->subtraction($term1, $term2);
$denominator = $this->nodeFactory->exponentiation($node->getRight(), new IntegerNode(2));
return $this->nodeFactory->division($numerator, $denominator);
// f^g = exp(g log(f)), so (f^g)' = f^g (g'log(f) + g/f)
case '^':
$base = $node->getLeft();
$exponent = $node->getRight();
if ($exponent instanceof IntegerNode || $exponent instanceof NumberNode) {
$power = $exponent->getValue();
$fpow = $this->nodeFactory->exponentiation($base, $power - 1);
return $this->nodeFactory->multiplication($power, $this->nodeFactory->multiplication($fpow, $leftValue));
} elseif ($exponent instanceof RationalNode) {
$newPower = new RationalNode($exponent->getNumerator() - $exponent->getDenominator(), $exponent->getDenominator());
$fpow = $this->nodeFactory->exponentiation($base, $newPower);
return $this->nodeFactory->multiplication($exponent, $this->nodeFactory->multiplication($fpow, $leftValue));
} elseif ($base instanceof ConstantNode && $base->getName() == 'e') {
return $this->nodeFactory->multiplication($rightValue, $node);
} else {
$term1 = $this->nodeFactory->multiplication($rightValue, new FunctionNode('ln', $base));
$term2 = $this->nodeFactory->division(
$this->nodeFactory->multiplication($exponent, $base->accept($this)),
$base);
$factor2 = $this->nodeFactory->addition($term1, $term2);
return $this->nodeFactory->multiplication($node, $factor2);
}
default:
throw new UnknownOperatorException($operator);
}
} | [
"public",
"function",
"visitExpressionNode",
"(",
"ExpressionNode",
"$",
"node",
")",
"{",
"$",
"operator",
"=",
"$",
"node",
"->",
"getOperator",
"(",
")",
";",
"$",
"leftValue",
"=",
"$",
"node",
"->",
"getLeft",
"(",
")",
"->",
"accept",
"(",
"$",
"this",
")",
";",
"if",
"(",
"$",
"node",
"->",
"getRight",
"(",
")",
")",
"{",
"$",
"rightValue",
"=",
"$",
"node",
"->",
"getRight",
"(",
")",
"->",
"accept",
"(",
"$",
"this",
")",
";",
"}",
"else",
"{",
"$",
"rightValue",
"=",
"null",
";",
"}",
"// Perform the right operation based on the operator",
"switch",
"(",
"$",
"operator",
")",
"{",
"case",
"'+'",
":",
"return",
"$",
"this",
"->",
"nodeFactory",
"->",
"addition",
"(",
"$",
"leftValue",
",",
"$",
"rightValue",
")",
";",
"case",
"'-'",
":",
"return",
"$",
"this",
"->",
"nodeFactory",
"->",
"subtraction",
"(",
"$",
"leftValue",
",",
"$",
"rightValue",
")",
";",
"// Product rule (fg)' = fg' + f'g",
"case",
"'*'",
":",
"return",
"$",
"this",
"->",
"nodeFactory",
"->",
"addition",
"(",
"$",
"this",
"->",
"nodeFactory",
"->",
"multiplication",
"(",
"$",
"node",
"->",
"getLeft",
"(",
")",
",",
"$",
"rightValue",
")",
",",
"$",
"this",
"->",
"nodeFactory",
"->",
"multiplication",
"(",
"$",
"leftValue",
",",
"$",
"node",
"->",
"getRight",
"(",
")",
")",
")",
";",
"// Quotient rule (f/g)' = (f'g - fg')/g^2",
"case",
"'/'",
":",
"$",
"term1",
"=",
"$",
"this",
"->",
"nodeFactory",
"->",
"multiplication",
"(",
"$",
"leftValue",
",",
"$",
"node",
"->",
"getRight",
"(",
")",
")",
";",
"$",
"term2",
"=",
"$",
"this",
"->",
"nodeFactory",
"->",
"multiplication",
"(",
"$",
"node",
"->",
"getLeft",
"(",
")",
",",
"$",
"rightValue",
")",
";",
"$",
"numerator",
"=",
"$",
"this",
"->",
"nodeFactory",
"->",
"subtraction",
"(",
"$",
"term1",
",",
"$",
"term2",
")",
";",
"$",
"denominator",
"=",
"$",
"this",
"->",
"nodeFactory",
"->",
"exponentiation",
"(",
"$",
"node",
"->",
"getRight",
"(",
")",
",",
"new",
"IntegerNode",
"(",
"2",
")",
")",
";",
"return",
"$",
"this",
"->",
"nodeFactory",
"->",
"division",
"(",
"$",
"numerator",
",",
"$",
"denominator",
")",
";",
"// f^g = exp(g log(f)), so (f^g)' = f^g (g'log(f) + g/f)",
"case",
"'^'",
":",
"$",
"base",
"=",
"$",
"node",
"->",
"getLeft",
"(",
")",
";",
"$",
"exponent",
"=",
"$",
"node",
"->",
"getRight",
"(",
")",
";",
"if",
"(",
"$",
"exponent",
"instanceof",
"IntegerNode",
"||",
"$",
"exponent",
"instanceof",
"NumberNode",
")",
"{",
"$",
"power",
"=",
"$",
"exponent",
"->",
"getValue",
"(",
")",
";",
"$",
"fpow",
"=",
"$",
"this",
"->",
"nodeFactory",
"->",
"exponentiation",
"(",
"$",
"base",
",",
"$",
"power",
"-",
"1",
")",
";",
"return",
"$",
"this",
"->",
"nodeFactory",
"->",
"multiplication",
"(",
"$",
"power",
",",
"$",
"this",
"->",
"nodeFactory",
"->",
"multiplication",
"(",
"$",
"fpow",
",",
"$",
"leftValue",
")",
")",
";",
"}",
"elseif",
"(",
"$",
"exponent",
"instanceof",
"RationalNode",
")",
"{",
"$",
"newPower",
"=",
"new",
"RationalNode",
"(",
"$",
"exponent",
"->",
"getNumerator",
"(",
")",
"-",
"$",
"exponent",
"->",
"getDenominator",
"(",
")",
",",
"$",
"exponent",
"->",
"getDenominator",
"(",
")",
")",
";",
"$",
"fpow",
"=",
"$",
"this",
"->",
"nodeFactory",
"->",
"exponentiation",
"(",
"$",
"base",
",",
"$",
"newPower",
")",
";",
"return",
"$",
"this",
"->",
"nodeFactory",
"->",
"multiplication",
"(",
"$",
"exponent",
",",
"$",
"this",
"->",
"nodeFactory",
"->",
"multiplication",
"(",
"$",
"fpow",
",",
"$",
"leftValue",
")",
")",
";",
"}",
"elseif",
"(",
"$",
"base",
"instanceof",
"ConstantNode",
"&&",
"$",
"base",
"->",
"getName",
"(",
")",
"==",
"'e'",
")",
"{",
"return",
"$",
"this",
"->",
"nodeFactory",
"->",
"multiplication",
"(",
"$",
"rightValue",
",",
"$",
"node",
")",
";",
"}",
"else",
"{",
"$",
"term1",
"=",
"$",
"this",
"->",
"nodeFactory",
"->",
"multiplication",
"(",
"$",
"rightValue",
",",
"new",
"FunctionNode",
"(",
"'ln'",
",",
"$",
"base",
")",
")",
";",
"$",
"term2",
"=",
"$",
"this",
"->",
"nodeFactory",
"->",
"division",
"(",
"$",
"this",
"->",
"nodeFactory",
"->",
"multiplication",
"(",
"$",
"exponent",
",",
"$",
"base",
"->",
"accept",
"(",
"$",
"this",
")",
")",
",",
"$",
"base",
")",
";",
"$",
"factor2",
"=",
"$",
"this",
"->",
"nodeFactory",
"->",
"addition",
"(",
"$",
"term1",
",",
"$",
"term2",
")",
";",
"return",
"$",
"this",
"->",
"nodeFactory",
"->",
"multiplication",
"(",
"$",
"node",
",",
"$",
"factor2",
")",
";",
"}",
"default",
":",
"throw",
"new",
"UnknownOperatorException",
"(",
"$",
"operator",
")",
";",
"}",
"}"
] | Differentiate an ExpressionNode
Using the usual rules for differentiating, create an ExpressionNode
giving an AST correctly representing the derivative `(x op y)'`
where `op` is one of `+`, `-`, `*`, `/` or `^`
### Differentiation rules:
- \\( (f+g)' = f' + g' \\)
- \\( (f-g) ' = f' - g' \\)
- \\( (-f)' = -f' \\)
- \\( (f*g)' = f'g + f g' \\)
- \\( (f/g)' = (f' g - f g')/g^2 \\)
- \\( (f^g)' = f^g (g' \\log(f) + gf'/f) \\) with a simpler expression when g is a NumberNode
`+`, `-`, `*`, `/` or `^`
@retval Node
@param ExpressionNode $node AST to be differentiated
@throws UnknownOperatorException if the operator is something other than | [
"Differentiate",
"an",
"ExpressionNode"
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Interpreting/Differentiator.php#L101-L166 |
mossadal/math-parser | src/MathParser/Interpreting/Differentiator.php | Differentiator.visitFunctionNode | public function visitFunctionNode(FunctionNode $node)
{
$inner = $node->getOperand()->accept($this);
$arg = $node->getOperand();
switch ($node->getName()) {
case 'sin':
$df = new FunctionNode('cos', $arg);
break;
case 'cos':
$sin = new FunctionNode('sin', $arg);
$df = $this->nodeFactory->unaryMinus($sin);
break;
case 'tan':
$tansquare = $this->nodeFactory->exponentiation($node, 2);
$df = $this->nodeFactory->addition(1, $tansquare);
break;
case 'cot':
$cotsquare = $this->nodeFactory->exponentiation($node, 2);
$df = $this->nodeFactory->subtraction($this->nodeFactory->unaryMinus(1), $cotsquare);
break;
case 'arcsin':
$denom = new FunctionNode('sqrt',
$this->nodeFactory->subtraction(1, $this->nodeFactory->exponentiation($arg, 2)));
return $this->nodeFactory->division($inner, $denom);
case 'arccos':
$denom = new FunctionNode('sqrt',
$this->nodeFactory->subtraction(1, $this->nodeFactory->exponentiation($arg, 2)));
return $this->nodeFactory->division($this->nodeFactory->unaryMinus($inner), $denom);
case 'arctan':
$denom = $this->nodeFactory->addition(1, $this->nodeFactory->exponentiation($arg, 2));
return $this->nodeFactory->division($inner, $denom);
case 'arccot':
$denom = $this->nodeFactory->addition(1, $this->nodeFactory->exponentiation($arg, 2));
$df = $this->nodeFactory->unaryMinus($this->nodeFactory->division(1, $denom));
break;
case 'exp':
$df = new FunctionNode('exp', $arg);
break;
case 'ln':
case 'log':
return $this->nodeFactory->division($inner, $arg);
case 'lg':
$denominator = $this->nodeFactory->multiplication(new FunctionNode('ln', new IntegerNode(10)), $arg);
return $this->nodeFactory->division($inner, $denominator);
case 'sqrt':
$denom = $this->nodeFactory->multiplication(2, $node);
return $this->nodeFactory->division($inner, $denom);
case 'sinh':
$df = new FunctionNode('cosh', $arg);
break;
case 'cosh':
$df = new FunctionNode('sinh', $arg);
break;
case 'tanh':
$tanhsquare = $this->nodeFactory->exponentiation(new FunctionNode('tanh', $arg), 2);
$df = $this->nodeFactory->subtraction(1, $tanhsquare);
break;
case 'coth':
$cothsquare = $this->nodeFactory->exponentiation(new FunctionNode('coth', $arg), 2);
$df = $this->nodeFactory->subtraction(1, $cothsquare);
break;
case 'arsinh':
$temp = $this->nodeFactory->addition($this->nodeFactory->exponentiation($arg, 2), 1);
return $this->nodeFactory->division($inner, new FunctionNode('sqrt', $temp));
case 'arcosh':
$temp = $this->nodeFactory->subtraction($this->nodeFactory->exponentiation($arg, 2), 1);
return $this->nodeFactory->division($inner, new FunctionNode('sqrt', $temp));
case 'artanh':
case 'arcoth':
$denominator = $this->nodeFactory->subtraction(1, $this->nodeFactory->exponentiation($arg, 2));
return $this->nodeFactory->division($inner, $denominator);
case 'abs':
$df = new FunctionNode('sgn', $arg);
break;
default:
throw new UnknownFunctionException($node->getName());
}
return $this->nodeFactory->multiplication($inner, $df);
} | php | public function visitFunctionNode(FunctionNode $node)
{
$inner = $node->getOperand()->accept($this);
$arg = $node->getOperand();
switch ($node->getName()) {
case 'sin':
$df = new FunctionNode('cos', $arg);
break;
case 'cos':
$sin = new FunctionNode('sin', $arg);
$df = $this->nodeFactory->unaryMinus($sin);
break;
case 'tan':
$tansquare = $this->nodeFactory->exponentiation($node, 2);
$df = $this->nodeFactory->addition(1, $tansquare);
break;
case 'cot':
$cotsquare = $this->nodeFactory->exponentiation($node, 2);
$df = $this->nodeFactory->subtraction($this->nodeFactory->unaryMinus(1), $cotsquare);
break;
case 'arcsin':
$denom = new FunctionNode('sqrt',
$this->nodeFactory->subtraction(1, $this->nodeFactory->exponentiation($arg, 2)));
return $this->nodeFactory->division($inner, $denom);
case 'arccos':
$denom = new FunctionNode('sqrt',
$this->nodeFactory->subtraction(1, $this->nodeFactory->exponentiation($arg, 2)));
return $this->nodeFactory->division($this->nodeFactory->unaryMinus($inner), $denom);
case 'arctan':
$denom = $this->nodeFactory->addition(1, $this->nodeFactory->exponentiation($arg, 2));
return $this->nodeFactory->division($inner, $denom);
case 'arccot':
$denom = $this->nodeFactory->addition(1, $this->nodeFactory->exponentiation($arg, 2));
$df = $this->nodeFactory->unaryMinus($this->nodeFactory->division(1, $denom));
break;
case 'exp':
$df = new FunctionNode('exp', $arg);
break;
case 'ln':
case 'log':
return $this->nodeFactory->division($inner, $arg);
case 'lg':
$denominator = $this->nodeFactory->multiplication(new FunctionNode('ln', new IntegerNode(10)), $arg);
return $this->nodeFactory->division($inner, $denominator);
case 'sqrt':
$denom = $this->nodeFactory->multiplication(2, $node);
return $this->nodeFactory->division($inner, $denom);
case 'sinh':
$df = new FunctionNode('cosh', $arg);
break;
case 'cosh':
$df = new FunctionNode('sinh', $arg);
break;
case 'tanh':
$tanhsquare = $this->nodeFactory->exponentiation(new FunctionNode('tanh', $arg), 2);
$df = $this->nodeFactory->subtraction(1, $tanhsquare);
break;
case 'coth':
$cothsquare = $this->nodeFactory->exponentiation(new FunctionNode('coth', $arg), 2);
$df = $this->nodeFactory->subtraction(1, $cothsquare);
break;
case 'arsinh':
$temp = $this->nodeFactory->addition($this->nodeFactory->exponentiation($arg, 2), 1);
return $this->nodeFactory->division($inner, new FunctionNode('sqrt', $temp));
case 'arcosh':
$temp = $this->nodeFactory->subtraction($this->nodeFactory->exponentiation($arg, 2), 1);
return $this->nodeFactory->division($inner, new FunctionNode('sqrt', $temp));
case 'artanh':
case 'arcoth':
$denominator = $this->nodeFactory->subtraction(1, $this->nodeFactory->exponentiation($arg, 2));
return $this->nodeFactory->division($inner, $denominator);
case 'abs':
$df = new FunctionNode('sgn', $arg);
break;
default:
throw new UnknownFunctionException($node->getName());
}
return $this->nodeFactory->multiplication($inner, $df);
} | [
"public",
"function",
"visitFunctionNode",
"(",
"FunctionNode",
"$",
"node",
")",
"{",
"$",
"inner",
"=",
"$",
"node",
"->",
"getOperand",
"(",
")",
"->",
"accept",
"(",
"$",
"this",
")",
";",
"$",
"arg",
"=",
"$",
"node",
"->",
"getOperand",
"(",
")",
";",
"switch",
"(",
"$",
"node",
"->",
"getName",
"(",
")",
")",
"{",
"case",
"'sin'",
":",
"$",
"df",
"=",
"new",
"FunctionNode",
"(",
"'cos'",
",",
"$",
"arg",
")",
";",
"break",
";",
"case",
"'cos'",
":",
"$",
"sin",
"=",
"new",
"FunctionNode",
"(",
"'sin'",
",",
"$",
"arg",
")",
";",
"$",
"df",
"=",
"$",
"this",
"->",
"nodeFactory",
"->",
"unaryMinus",
"(",
"$",
"sin",
")",
";",
"break",
";",
"case",
"'tan'",
":",
"$",
"tansquare",
"=",
"$",
"this",
"->",
"nodeFactory",
"->",
"exponentiation",
"(",
"$",
"node",
",",
"2",
")",
";",
"$",
"df",
"=",
"$",
"this",
"->",
"nodeFactory",
"->",
"addition",
"(",
"1",
",",
"$",
"tansquare",
")",
";",
"break",
";",
"case",
"'cot'",
":",
"$",
"cotsquare",
"=",
"$",
"this",
"->",
"nodeFactory",
"->",
"exponentiation",
"(",
"$",
"node",
",",
"2",
")",
";",
"$",
"df",
"=",
"$",
"this",
"->",
"nodeFactory",
"->",
"subtraction",
"(",
"$",
"this",
"->",
"nodeFactory",
"->",
"unaryMinus",
"(",
"1",
")",
",",
"$",
"cotsquare",
")",
";",
"break",
";",
"case",
"'arcsin'",
":",
"$",
"denom",
"=",
"new",
"FunctionNode",
"(",
"'sqrt'",
",",
"$",
"this",
"->",
"nodeFactory",
"->",
"subtraction",
"(",
"1",
",",
"$",
"this",
"->",
"nodeFactory",
"->",
"exponentiation",
"(",
"$",
"arg",
",",
"2",
")",
")",
")",
";",
"return",
"$",
"this",
"->",
"nodeFactory",
"->",
"division",
"(",
"$",
"inner",
",",
"$",
"denom",
")",
";",
"case",
"'arccos'",
":",
"$",
"denom",
"=",
"new",
"FunctionNode",
"(",
"'sqrt'",
",",
"$",
"this",
"->",
"nodeFactory",
"->",
"subtraction",
"(",
"1",
",",
"$",
"this",
"->",
"nodeFactory",
"->",
"exponentiation",
"(",
"$",
"arg",
",",
"2",
")",
")",
")",
";",
"return",
"$",
"this",
"->",
"nodeFactory",
"->",
"division",
"(",
"$",
"this",
"->",
"nodeFactory",
"->",
"unaryMinus",
"(",
"$",
"inner",
")",
",",
"$",
"denom",
")",
";",
"case",
"'arctan'",
":",
"$",
"denom",
"=",
"$",
"this",
"->",
"nodeFactory",
"->",
"addition",
"(",
"1",
",",
"$",
"this",
"->",
"nodeFactory",
"->",
"exponentiation",
"(",
"$",
"arg",
",",
"2",
")",
")",
";",
"return",
"$",
"this",
"->",
"nodeFactory",
"->",
"division",
"(",
"$",
"inner",
",",
"$",
"denom",
")",
";",
"case",
"'arccot'",
":",
"$",
"denom",
"=",
"$",
"this",
"->",
"nodeFactory",
"->",
"addition",
"(",
"1",
",",
"$",
"this",
"->",
"nodeFactory",
"->",
"exponentiation",
"(",
"$",
"arg",
",",
"2",
")",
")",
";",
"$",
"df",
"=",
"$",
"this",
"->",
"nodeFactory",
"->",
"unaryMinus",
"(",
"$",
"this",
"->",
"nodeFactory",
"->",
"division",
"(",
"1",
",",
"$",
"denom",
")",
")",
";",
"break",
";",
"case",
"'exp'",
":",
"$",
"df",
"=",
"new",
"FunctionNode",
"(",
"'exp'",
",",
"$",
"arg",
")",
";",
"break",
";",
"case",
"'ln'",
":",
"case",
"'log'",
":",
"return",
"$",
"this",
"->",
"nodeFactory",
"->",
"division",
"(",
"$",
"inner",
",",
"$",
"arg",
")",
";",
"case",
"'lg'",
":",
"$",
"denominator",
"=",
"$",
"this",
"->",
"nodeFactory",
"->",
"multiplication",
"(",
"new",
"FunctionNode",
"(",
"'ln'",
",",
"new",
"IntegerNode",
"(",
"10",
")",
")",
",",
"$",
"arg",
")",
";",
"return",
"$",
"this",
"->",
"nodeFactory",
"->",
"division",
"(",
"$",
"inner",
",",
"$",
"denominator",
")",
";",
"case",
"'sqrt'",
":",
"$",
"denom",
"=",
"$",
"this",
"->",
"nodeFactory",
"->",
"multiplication",
"(",
"2",
",",
"$",
"node",
")",
";",
"return",
"$",
"this",
"->",
"nodeFactory",
"->",
"division",
"(",
"$",
"inner",
",",
"$",
"denom",
")",
";",
"case",
"'sinh'",
":",
"$",
"df",
"=",
"new",
"FunctionNode",
"(",
"'cosh'",
",",
"$",
"arg",
")",
";",
"break",
";",
"case",
"'cosh'",
":",
"$",
"df",
"=",
"new",
"FunctionNode",
"(",
"'sinh'",
",",
"$",
"arg",
")",
";",
"break",
";",
"case",
"'tanh'",
":",
"$",
"tanhsquare",
"=",
"$",
"this",
"->",
"nodeFactory",
"->",
"exponentiation",
"(",
"new",
"FunctionNode",
"(",
"'tanh'",
",",
"$",
"arg",
")",
",",
"2",
")",
";",
"$",
"df",
"=",
"$",
"this",
"->",
"nodeFactory",
"->",
"subtraction",
"(",
"1",
",",
"$",
"tanhsquare",
")",
";",
"break",
";",
"case",
"'coth'",
":",
"$",
"cothsquare",
"=",
"$",
"this",
"->",
"nodeFactory",
"->",
"exponentiation",
"(",
"new",
"FunctionNode",
"(",
"'coth'",
",",
"$",
"arg",
")",
",",
"2",
")",
";",
"$",
"df",
"=",
"$",
"this",
"->",
"nodeFactory",
"->",
"subtraction",
"(",
"1",
",",
"$",
"cothsquare",
")",
";",
"break",
";",
"case",
"'arsinh'",
":",
"$",
"temp",
"=",
"$",
"this",
"->",
"nodeFactory",
"->",
"addition",
"(",
"$",
"this",
"->",
"nodeFactory",
"->",
"exponentiation",
"(",
"$",
"arg",
",",
"2",
")",
",",
"1",
")",
";",
"return",
"$",
"this",
"->",
"nodeFactory",
"->",
"division",
"(",
"$",
"inner",
",",
"new",
"FunctionNode",
"(",
"'sqrt'",
",",
"$",
"temp",
")",
")",
";",
"case",
"'arcosh'",
":",
"$",
"temp",
"=",
"$",
"this",
"->",
"nodeFactory",
"->",
"subtraction",
"(",
"$",
"this",
"->",
"nodeFactory",
"->",
"exponentiation",
"(",
"$",
"arg",
",",
"2",
")",
",",
"1",
")",
";",
"return",
"$",
"this",
"->",
"nodeFactory",
"->",
"division",
"(",
"$",
"inner",
",",
"new",
"FunctionNode",
"(",
"'sqrt'",
",",
"$",
"temp",
")",
")",
";",
"case",
"'artanh'",
":",
"case",
"'arcoth'",
":",
"$",
"denominator",
"=",
"$",
"this",
"->",
"nodeFactory",
"->",
"subtraction",
"(",
"1",
",",
"$",
"this",
"->",
"nodeFactory",
"->",
"exponentiation",
"(",
"$",
"arg",
",",
"2",
")",
")",
";",
"return",
"$",
"this",
"->",
"nodeFactory",
"->",
"division",
"(",
"$",
"inner",
",",
"$",
"denominator",
")",
";",
"case",
"'abs'",
":",
"$",
"df",
"=",
"new",
"FunctionNode",
"(",
"'sgn'",
",",
"$",
"arg",
")",
";",
"break",
";",
"default",
":",
"throw",
"new",
"UnknownFunctionException",
"(",
"$",
"node",
"->",
"getName",
"(",
")",
")",
";",
"}",
"return",
"$",
"this",
"->",
"nodeFactory",
"->",
"multiplication",
"(",
"$",
"inner",
",",
"$",
"df",
")",
";",
"}"
] | Differentiate a FunctionNode
Create an ExpressionNode giving an AST correctly representing the
derivative `f'` where `f` is an elementary function.
### Differentiation rules:
\\( \\sin(f(x))' = f'(x) \\cos(f(x)) \\)
\\( \\cos(f(x))' = -f'(x) \\sin(f(x)) \\)
\\( \\tan(f(x))' = f'(x) (1 + \\tan(f(x))^2 \\)
\\( \\operatorname{cot}(f(x))' = f'(x) (-1 - \\operatorname{cot}(f(x))^2 \\)
\\( \\arcsin(f(x))' = f'(x) / \\sqrt{1-f(x)^2} \\)
\\( \\arccos(f(x))' = -f'(x) / \\sqrt{1-f(x)^2} \\)
\\( \\arctan(f(x))' = f'(x) / (1+f(x)^2) \\)
\\( \\operatorname{arccot}(f(x))' = -f'(x) / (1+f(x)^2) \\)
\\( \\exp(f(x))' = f'(x) \\exp(f(x)) \\)
\\( \\log(f(x))' = f'(x) / f(x) \\)
\\( \\ln(f(x))' = f'(x) / (\\log(10) * f(x)) \\)
\\( \\sqrt{f(x)}' = f'(x) / (2 \\sqrt{f(x)} \\)
\\( \\sinh(f(x))' = f'(x) \\cosh(f(x)) \\)
\\( \\cosh(f(x))' = f'(x) \\sinh(f(x)) \\)
\\( \\tanh(f(x))' = f'(x) (1-\\tanh(f(x))^2) \\)
\\( \\operatorname{coth}(f(x))' = f'(x) (1-\\operatorname{coth}(f(x))^2) \\)
\\( \\operatorname{arsinh}(f(x))' = f'(x) / \\sqrt{f(x)^2+1} \\)
\\( \\operatorname{arcosh}(f(x))' = f'(x) / \\sqrt{f(x)^2-1} \\)
\\( \\operatorname{artanh}(f(x))' = f'(x) (1-f(x)^2) \\)
\\( \\operatorname{arcoth}(f(x))' = f'(x) (1-f(x)^2) \\)
one of the above
@retval Node
@param FunctionNode $node AST to be differentiated
@throws UnknownFunctionException if the function name doesn't match | [
"Differentiate",
"a",
"FunctionNode"
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Interpreting/Differentiator.php#L244-L347 |
mossadal/math-parser | src/MathParser/Parsing/Nodes/NumberNode.php | NumberNode.compareTo | public function compareTo($other)
{
if ($other === null) {
return false;
}
if (!($other instanceof NumberNode)) {
return false;
}
return $this->getValue() == $other->getValue();
} | php | public function compareTo($other)
{
if ($other === null) {
return false;
}
if (!($other instanceof NumberNode)) {
return false;
}
return $this->getValue() == $other->getValue();
} | [
"public",
"function",
"compareTo",
"(",
"$",
"other",
")",
"{",
"if",
"(",
"$",
"other",
"===",
"null",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"!",
"(",
"$",
"other",
"instanceof",
"NumberNode",
")",
")",
"{",
"return",
"false",
";",
"}",
"return",
"$",
"this",
"->",
"getValue",
"(",
")",
"==",
"$",
"other",
"->",
"getValue",
"(",
")",
";",
"}"
] | Implementing the compareTo abstract method. | [
"Implementing",
"the",
"compareTo",
"abstract",
"method",
"."
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Parsing/Nodes/NumberNode.php#L46-L56 |
mossadal/math-parser | src/MathParser/Interpreting/TreePrinter.php | TreePrinter.visitExpressionNode | public function visitExpressionNode(ExpressionNode $node)
{
$leftValue = $node->getLeft()->accept($this);
$operator = $node->getOperator();
// The operator and the right side are optional, remember?
if (!$operator)
return "$leftValue";
$right = $node->getRight();
if ($right) {
$rightValue = $node->getRight()->accept($this);
return "($operator, $leftValue, $rightValue)";
} else {
return "($operator, $leftValue)";
}
} | php | public function visitExpressionNode(ExpressionNode $node)
{
$leftValue = $node->getLeft()->accept($this);
$operator = $node->getOperator();
// The operator and the right side are optional, remember?
if (!$operator)
return "$leftValue";
$right = $node->getRight();
if ($right) {
$rightValue = $node->getRight()->accept($this);
return "($operator, $leftValue, $rightValue)";
} else {
return "($operator, $leftValue)";
}
} | [
"public",
"function",
"visitExpressionNode",
"(",
"ExpressionNode",
"$",
"node",
")",
"{",
"$",
"leftValue",
"=",
"$",
"node",
"->",
"getLeft",
"(",
")",
"->",
"accept",
"(",
"$",
"this",
")",
";",
"$",
"operator",
"=",
"$",
"node",
"->",
"getOperator",
"(",
")",
";",
"// The operator and the right side are optional, remember?",
"if",
"(",
"!",
"$",
"operator",
")",
"return",
"\"$leftValue\"",
";",
"$",
"right",
"=",
"$",
"node",
"->",
"getRight",
"(",
")",
";",
"if",
"(",
"$",
"right",
")",
"{",
"$",
"rightValue",
"=",
"$",
"node",
"->",
"getRight",
"(",
")",
"->",
"accept",
"(",
"$",
"this",
")",
";",
"return",
"\"($operator, $leftValue, $rightValue)\"",
";",
"}",
"else",
"{",
"return",
"\"($operator, $leftValue)\"",
";",
"}",
"}"
] | Print an ExpressionNode.
@param ExpressionNode $node | [
"Print",
"an",
"ExpressionNode",
"."
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Interpreting/TreePrinter.php#L43-L61 |
mossadal/math-parser | src/MathParser/Interpreting/TreePrinter.php | TreePrinter.visitFunctionNode | public function visitFunctionNode(FunctionNode $node)
{
$functionName = $node->getName();
$operand = $node->getOperand()->accept($this);
return "$functionName($operand)";
} | php | public function visitFunctionNode(FunctionNode $node)
{
$functionName = $node->getName();
$operand = $node->getOperand()->accept($this);
return "$functionName($operand)";
} | [
"public",
"function",
"visitFunctionNode",
"(",
"FunctionNode",
"$",
"node",
")",
"{",
"$",
"functionName",
"=",
"$",
"node",
"->",
"getName",
"(",
")",
";",
"$",
"operand",
"=",
"$",
"node",
"->",
"getOperand",
"(",
")",
"->",
"accept",
"(",
"$",
"this",
")",
";",
"return",
"\"$functionName($operand)\"",
";",
"}"
] | Print a FunctionNode.
@param FunctionNode $node | [
"Print",
"a",
"FunctionNode",
"."
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Interpreting/TreePrinter.php#L100-L106 |
mossadal/math-parser | src/MathParser/Parsing/Parser.php | Parser.parse | public function parse(array $tokens)
{
// Filter away any whitespace
$tokens = $this->filterTokens($tokens);
// Insert missing implicit multiplication tokens
if (static::allowImplicitMultiplication()) {
$tokens = $this->parseImplicitMultiplication($tokens);
}
$this->tokens = $tokens;
// Perform the actual parsing
return $this->shuntingYard($tokens);
} | php | public function parse(array $tokens)
{
// Filter away any whitespace
$tokens = $this->filterTokens($tokens);
// Insert missing implicit multiplication tokens
if (static::allowImplicitMultiplication()) {
$tokens = $this->parseImplicitMultiplication($tokens);
}
$this->tokens = $tokens;
// Perform the actual parsing
return $this->shuntingYard($tokens);
} | [
"public",
"function",
"parse",
"(",
"array",
"$",
"tokens",
")",
"{",
"// Filter away any whitespace",
"$",
"tokens",
"=",
"$",
"this",
"->",
"filterTokens",
"(",
"$",
"tokens",
")",
";",
"// Insert missing implicit multiplication tokens",
"if",
"(",
"static",
"::",
"allowImplicitMultiplication",
"(",
")",
")",
"{",
"$",
"tokens",
"=",
"$",
"this",
"->",
"parseImplicitMultiplication",
"(",
"$",
"tokens",
")",
";",
"}",
"$",
"this",
"->",
"tokens",
"=",
"$",
"tokens",
";",
"// Perform the actual parsing",
"return",
"$",
"this",
"->",
"shuntingYard",
"(",
"$",
"tokens",
")",
";",
"}"
] | Parse list of tokens
@param array $tokens Array (Token[]) of input tokens.
@retval Node AST representing the parsed expression. | [
"Parse",
"list",
"of",
"tokens"
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Parsing/Parser.php#L111-L125 |
mossadal/math-parser | src/MathParser/Parsing/Parser.php | Parser.shuntingYard | private function shuntingYard(array $tokens)
{
// Clear the oepratorStack
$this->operatorStack = new Stack();
// Clear the operandStack.
$this->operandStack = new Stack();
// Remember the last token handled, this is done to recognize unary operators.
$lastNode = null;
// Loop over the tokens
for ($index = 0; $index < count($tokens); $index++)
{
$token = $tokens[$index];
// echo "current token $token\n";
// echo("operands:" . $this->operandStack . "\n");
// echo("operators: " . $this->operatorStack . "\n\n");
if ($this->rationalFactory) {
$node = Node::rationalFactory($token);
} else {
$node = Node::factory($token);
}
// Handle closing parentheses
if ($token->getType() == TokenType::CloseParenthesis) {
$this->handleSubExpression();
}
// Push terminal tokens on the operandStack
elseif ($node->isTerminal()) {
$this->operandStack->push($node);
// Push function applications or open parentheses `(` onto the operatorStack
} elseif ($node instanceof FunctionNode) {
$this->operatorStack->push($node);
} elseif ($node instanceof SubExpressionNode) {
$this->operatorStack->push($node);
// Handle the remaining operators.
} elseif ($node instanceof PostfixOperatorNode) {
$op = $this->operandStack->pop();
if ($op == NULL) throw new SyntaxErrorException();
$this->operandStack->push(new FunctionNode($node->getOperator(), $op));
} elseif ($node instanceof ExpressionNode) {
// Check for unary minus and unary plus.
$unary = $this->isUnary($node, $lastNode);
if ($unary) {
switch($token->getType()) {
// Unary +, just ignore it
case TokenType::AdditionOperator:
$node = null;
break;
// Unary -, replace the token.
case TokenType::SubtractionOperator:
$node->setOperator('~');
break;
}
} else {
// Pop operators with higher priority
while ($node->lowerPrecedenceThan($this->operatorStack->peek())) {
$popped = $this->operatorStack->pop();
$popped = $this->handleExpression($popped);
$this->operandStack->push($popped);
}
}
if ($node) $this->operatorStack->push($node);
}
// Remember the current token (if it hasn't been nulled, for example being a unary +)
if ($node) $lastNode = $node;
}
// Pop remaining operators
while (!$this->operatorStack->isEmpty()) {
$node = $this->operatorStack->pop();
$node = $this->handleExpression($node);
$this->operandStack->push($node);
}
// Stack should be empty here
if ($this->operandStack->count() > 1) {
throw new SyntaxErrorException();
}
return $this->operandStack->pop();
} | php | private function shuntingYard(array $tokens)
{
// Clear the oepratorStack
$this->operatorStack = new Stack();
// Clear the operandStack.
$this->operandStack = new Stack();
// Remember the last token handled, this is done to recognize unary operators.
$lastNode = null;
// Loop over the tokens
for ($index = 0; $index < count($tokens); $index++)
{
$token = $tokens[$index];
// echo "current token $token\n";
// echo("operands:" . $this->operandStack . "\n");
// echo("operators: " . $this->operatorStack . "\n\n");
if ($this->rationalFactory) {
$node = Node::rationalFactory($token);
} else {
$node = Node::factory($token);
}
// Handle closing parentheses
if ($token->getType() == TokenType::CloseParenthesis) {
$this->handleSubExpression();
}
// Push terminal tokens on the operandStack
elseif ($node->isTerminal()) {
$this->operandStack->push($node);
// Push function applications or open parentheses `(` onto the operatorStack
} elseif ($node instanceof FunctionNode) {
$this->operatorStack->push($node);
} elseif ($node instanceof SubExpressionNode) {
$this->operatorStack->push($node);
// Handle the remaining operators.
} elseif ($node instanceof PostfixOperatorNode) {
$op = $this->operandStack->pop();
if ($op == NULL) throw new SyntaxErrorException();
$this->operandStack->push(new FunctionNode($node->getOperator(), $op));
} elseif ($node instanceof ExpressionNode) {
// Check for unary minus and unary plus.
$unary = $this->isUnary($node, $lastNode);
if ($unary) {
switch($token->getType()) {
// Unary +, just ignore it
case TokenType::AdditionOperator:
$node = null;
break;
// Unary -, replace the token.
case TokenType::SubtractionOperator:
$node->setOperator('~');
break;
}
} else {
// Pop operators with higher priority
while ($node->lowerPrecedenceThan($this->operatorStack->peek())) {
$popped = $this->operatorStack->pop();
$popped = $this->handleExpression($popped);
$this->operandStack->push($popped);
}
}
if ($node) $this->operatorStack->push($node);
}
// Remember the current token (if it hasn't been nulled, for example being a unary +)
if ($node) $lastNode = $node;
}
// Pop remaining operators
while (!$this->operatorStack->isEmpty()) {
$node = $this->operatorStack->pop();
$node = $this->handleExpression($node);
$this->operandStack->push($node);
}
// Stack should be empty here
if ($this->operandStack->count() > 1) {
throw new SyntaxErrorException();
}
return $this->operandStack->pop();
} | [
"private",
"function",
"shuntingYard",
"(",
"array",
"$",
"tokens",
")",
"{",
"// Clear the oepratorStack",
"$",
"this",
"->",
"operatorStack",
"=",
"new",
"Stack",
"(",
")",
";",
"// Clear the operandStack.",
"$",
"this",
"->",
"operandStack",
"=",
"new",
"Stack",
"(",
")",
";",
"// Remember the last token handled, this is done to recognize unary operators.",
"$",
"lastNode",
"=",
"null",
";",
"// Loop over the tokens",
"for",
"(",
"$",
"index",
"=",
"0",
";",
"$",
"index",
"<",
"count",
"(",
"$",
"tokens",
")",
";",
"$",
"index",
"++",
")",
"{",
"$",
"token",
"=",
"$",
"tokens",
"[",
"$",
"index",
"]",
";",
"// echo \"current token $token\\n\";",
"// echo(\"operands:\" . $this->operandStack . \"\\n\");",
"// echo(\"operators: \" . $this->operatorStack . \"\\n\\n\");",
"if",
"(",
"$",
"this",
"->",
"rationalFactory",
")",
"{",
"$",
"node",
"=",
"Node",
"::",
"rationalFactory",
"(",
"$",
"token",
")",
";",
"}",
"else",
"{",
"$",
"node",
"=",
"Node",
"::",
"factory",
"(",
"$",
"token",
")",
";",
"}",
"// Handle closing parentheses",
"if",
"(",
"$",
"token",
"->",
"getType",
"(",
")",
"==",
"TokenType",
"::",
"CloseParenthesis",
")",
"{",
"$",
"this",
"->",
"handleSubExpression",
"(",
")",
";",
"}",
"// Push terminal tokens on the operandStack",
"elseif",
"(",
"$",
"node",
"->",
"isTerminal",
"(",
")",
")",
"{",
"$",
"this",
"->",
"operandStack",
"->",
"push",
"(",
"$",
"node",
")",
";",
"// Push function applications or open parentheses `(` onto the operatorStack",
"}",
"elseif",
"(",
"$",
"node",
"instanceof",
"FunctionNode",
")",
"{",
"$",
"this",
"->",
"operatorStack",
"->",
"push",
"(",
"$",
"node",
")",
";",
"}",
"elseif",
"(",
"$",
"node",
"instanceof",
"SubExpressionNode",
")",
"{",
"$",
"this",
"->",
"operatorStack",
"->",
"push",
"(",
"$",
"node",
")",
";",
"// Handle the remaining operators.",
"}",
"elseif",
"(",
"$",
"node",
"instanceof",
"PostfixOperatorNode",
")",
"{",
"$",
"op",
"=",
"$",
"this",
"->",
"operandStack",
"->",
"pop",
"(",
")",
";",
"if",
"(",
"$",
"op",
"==",
"NULL",
")",
"throw",
"new",
"SyntaxErrorException",
"(",
")",
";",
"$",
"this",
"->",
"operandStack",
"->",
"push",
"(",
"new",
"FunctionNode",
"(",
"$",
"node",
"->",
"getOperator",
"(",
")",
",",
"$",
"op",
")",
")",
";",
"}",
"elseif",
"(",
"$",
"node",
"instanceof",
"ExpressionNode",
")",
"{",
"// Check for unary minus and unary plus.",
"$",
"unary",
"=",
"$",
"this",
"->",
"isUnary",
"(",
"$",
"node",
",",
"$",
"lastNode",
")",
";",
"if",
"(",
"$",
"unary",
")",
"{",
"switch",
"(",
"$",
"token",
"->",
"getType",
"(",
")",
")",
"{",
"// Unary +, just ignore it",
"case",
"TokenType",
"::",
"AdditionOperator",
":",
"$",
"node",
"=",
"null",
";",
"break",
";",
"// Unary -, replace the token.",
"case",
"TokenType",
"::",
"SubtractionOperator",
":",
"$",
"node",
"->",
"setOperator",
"(",
"'~'",
")",
";",
"break",
";",
"}",
"}",
"else",
"{",
"// Pop operators with higher priority",
"while",
"(",
"$",
"node",
"->",
"lowerPrecedenceThan",
"(",
"$",
"this",
"->",
"operatorStack",
"->",
"peek",
"(",
")",
")",
")",
"{",
"$",
"popped",
"=",
"$",
"this",
"->",
"operatorStack",
"->",
"pop",
"(",
")",
";",
"$",
"popped",
"=",
"$",
"this",
"->",
"handleExpression",
"(",
"$",
"popped",
")",
";",
"$",
"this",
"->",
"operandStack",
"->",
"push",
"(",
"$",
"popped",
")",
";",
"}",
"}",
"if",
"(",
"$",
"node",
")",
"$",
"this",
"->",
"operatorStack",
"->",
"push",
"(",
"$",
"node",
")",
";",
"}",
"// Remember the current token (if it hasn't been nulled, for example being a unary +)",
"if",
"(",
"$",
"node",
")",
"$",
"lastNode",
"=",
"$",
"node",
";",
"}",
"// Pop remaining operators",
"while",
"(",
"!",
"$",
"this",
"->",
"operatorStack",
"->",
"isEmpty",
"(",
")",
")",
"{",
"$",
"node",
"=",
"$",
"this",
"->",
"operatorStack",
"->",
"pop",
"(",
")",
";",
"$",
"node",
"=",
"$",
"this",
"->",
"handleExpression",
"(",
"$",
"node",
")",
";",
"$",
"this",
"->",
"operandStack",
"->",
"push",
"(",
"$",
"node",
")",
";",
"}",
"// Stack should be empty here",
"if",
"(",
"$",
"this",
"->",
"operandStack",
"->",
"count",
"(",
")",
">",
"1",
")",
"{",
"throw",
"new",
"SyntaxErrorException",
"(",
")",
";",
"}",
"return",
"$",
"this",
"->",
"operandStack",
"->",
"pop",
"(",
")",
";",
"}"
] | Implementation of the shunting yard parsing algorithm
@param array $tokens Token[] array of tokens to process
@retval Node AST of the parsed expression
@throws SyntaxErrorException
@throws ParenthesisMismatchException | [
"Implementation",
"of",
"the",
"shunting",
"yard",
"parsing",
"algorithm"
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Parsing/Parser.php#L135-L231 |
mossadal/math-parser | src/MathParser/Parsing/Parser.php | Parser.handleExpression | protected function handleExpression($node)
{
if ($node instanceof FunctionNode) throw new ParenthesisMismatchException($node->getOperator());
if ($node instanceof SubExpressionNode) throw new ParenthesisMismatchException($node->getOperator());
if (!$this->simplifyingParser) return $this->naiveHandleExpression($node);
if ($node->getOperator() == '~') {
$left = $this->operandStack->pop();
if ($left === null) {
throw new SyntaxErrorException();
}
if ($left instanceof NumberNode) {
return new NumberNode(-$left->getValue());
}
if ($left instanceof IntegerNode) {
return new IntegerNode(-$left->getValue());
}
if ($left instanceof RationalNode) {
return new RationalNode(-$left->getNumerator(), $left->getDenominator());
}
$node->setOperator('-');
$node->setLeft($left);
return $this->nodeFactory->simplify($node);
}
$right = $this->operandStack->pop();
$left = $this->operandStack->pop();
if ($right === null || $left === null) {
throw new SyntaxErrorException();
}
$node->setLeft($left);
$node->setRight($right);
return $this->nodeFactory->simplify($node);
} | php | protected function handleExpression($node)
{
if ($node instanceof FunctionNode) throw new ParenthesisMismatchException($node->getOperator());
if ($node instanceof SubExpressionNode) throw new ParenthesisMismatchException($node->getOperator());
if (!$this->simplifyingParser) return $this->naiveHandleExpression($node);
if ($node->getOperator() == '~') {
$left = $this->operandStack->pop();
if ($left === null) {
throw new SyntaxErrorException();
}
if ($left instanceof NumberNode) {
return new NumberNode(-$left->getValue());
}
if ($left instanceof IntegerNode) {
return new IntegerNode(-$left->getValue());
}
if ($left instanceof RationalNode) {
return new RationalNode(-$left->getNumerator(), $left->getDenominator());
}
$node->setOperator('-');
$node->setLeft($left);
return $this->nodeFactory->simplify($node);
}
$right = $this->operandStack->pop();
$left = $this->operandStack->pop();
if ($right === null || $left === null) {
throw new SyntaxErrorException();
}
$node->setLeft($left);
$node->setRight($right);
return $this->nodeFactory->simplify($node);
} | [
"protected",
"function",
"handleExpression",
"(",
"$",
"node",
")",
"{",
"if",
"(",
"$",
"node",
"instanceof",
"FunctionNode",
")",
"throw",
"new",
"ParenthesisMismatchException",
"(",
"$",
"node",
"->",
"getOperator",
"(",
")",
")",
";",
"if",
"(",
"$",
"node",
"instanceof",
"SubExpressionNode",
")",
"throw",
"new",
"ParenthesisMismatchException",
"(",
"$",
"node",
"->",
"getOperator",
"(",
")",
")",
";",
"if",
"(",
"!",
"$",
"this",
"->",
"simplifyingParser",
")",
"return",
"$",
"this",
"->",
"naiveHandleExpression",
"(",
"$",
"node",
")",
";",
"if",
"(",
"$",
"node",
"->",
"getOperator",
"(",
")",
"==",
"'~'",
")",
"{",
"$",
"left",
"=",
"$",
"this",
"->",
"operandStack",
"->",
"pop",
"(",
")",
";",
"if",
"(",
"$",
"left",
"===",
"null",
")",
"{",
"throw",
"new",
"SyntaxErrorException",
"(",
")",
";",
"}",
"if",
"(",
"$",
"left",
"instanceof",
"NumberNode",
")",
"{",
"return",
"new",
"NumberNode",
"(",
"-",
"$",
"left",
"->",
"getValue",
"(",
")",
")",
";",
"}",
"if",
"(",
"$",
"left",
"instanceof",
"IntegerNode",
")",
"{",
"return",
"new",
"IntegerNode",
"(",
"-",
"$",
"left",
"->",
"getValue",
"(",
")",
")",
";",
"}",
"if",
"(",
"$",
"left",
"instanceof",
"RationalNode",
")",
"{",
"return",
"new",
"RationalNode",
"(",
"-",
"$",
"left",
"->",
"getNumerator",
"(",
")",
",",
"$",
"left",
"->",
"getDenominator",
"(",
")",
")",
";",
"}",
"$",
"node",
"->",
"setOperator",
"(",
"'-'",
")",
";",
"$",
"node",
"->",
"setLeft",
"(",
"$",
"left",
")",
";",
"return",
"$",
"this",
"->",
"nodeFactory",
"->",
"simplify",
"(",
"$",
"node",
")",
";",
"}",
"$",
"right",
"=",
"$",
"this",
"->",
"operandStack",
"->",
"pop",
"(",
")",
";",
"$",
"left",
"=",
"$",
"this",
"->",
"operandStack",
"->",
"pop",
"(",
")",
";",
"if",
"(",
"$",
"right",
"===",
"null",
"||",
"$",
"left",
"===",
"null",
")",
"{",
"throw",
"new",
"SyntaxErrorException",
"(",
")",
";",
"}",
"$",
"node",
"->",
"setLeft",
"(",
"$",
"left",
")",
";",
"$",
"node",
"->",
"setRight",
"(",
"$",
"right",
")",
";",
"return",
"$",
"this",
"->",
"nodeFactory",
"->",
"simplify",
"(",
"$",
"node",
")",
";",
"}"
] | Populate node with operands.
@param Node $node
@retval Node
@throws SyntaxErrorException | [
"Populate",
"node",
"with",
"operands",
"."
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Parsing/Parser.php#L241-L283 |
mossadal/math-parser | src/MathParser/Parsing/Parser.php | Parser.naiveHandleExpression | protected function naiveHandleExpression($node)
{
if ($node->getOperator() == '~') {
$left = $this->operandStack->pop();
if ($left === null) {
throw new SyntaxErrorException();
}
$node->setOperator('-');
$node->setLeft($left);
return $node;
}
$right = $this->operandStack->pop();
$left = $this->operandStack->pop();
if ($right === null || $left === null) {
throw new SyntaxErrorException();
}
$node->setLeft($left);
$node->setRight($right);
return $node;
} | php | protected function naiveHandleExpression($node)
{
if ($node->getOperator() == '~') {
$left = $this->operandStack->pop();
if ($left === null) {
throw new SyntaxErrorException();
}
$node->setOperator('-');
$node->setLeft($left);
return $node;
}
$right = $this->operandStack->pop();
$left = $this->operandStack->pop();
if ($right === null || $left === null) {
throw new SyntaxErrorException();
}
$node->setLeft($left);
$node->setRight($right);
return $node;
} | [
"protected",
"function",
"naiveHandleExpression",
"(",
"$",
"node",
")",
"{",
"if",
"(",
"$",
"node",
"->",
"getOperator",
"(",
")",
"==",
"'~'",
")",
"{",
"$",
"left",
"=",
"$",
"this",
"->",
"operandStack",
"->",
"pop",
"(",
")",
";",
"if",
"(",
"$",
"left",
"===",
"null",
")",
"{",
"throw",
"new",
"SyntaxErrorException",
"(",
")",
";",
"}",
"$",
"node",
"->",
"setOperator",
"(",
"'-'",
")",
";",
"$",
"node",
"->",
"setLeft",
"(",
"$",
"left",
")",
";",
"return",
"$",
"node",
";",
"}",
"$",
"right",
"=",
"$",
"this",
"->",
"operandStack",
"->",
"pop",
"(",
")",
";",
"$",
"left",
"=",
"$",
"this",
"->",
"operandStack",
"->",
"pop",
"(",
")",
";",
"if",
"(",
"$",
"right",
"===",
"null",
"||",
"$",
"left",
"===",
"null",
")",
"{",
"throw",
"new",
"SyntaxErrorException",
"(",
")",
";",
"}",
"$",
"node",
"->",
"setLeft",
"(",
"$",
"left",
")",
";",
"$",
"node",
"->",
"setRight",
"(",
"$",
"right",
")",
";",
"return",
"$",
"node",
";",
"}"
] | Populate node with operands, without any simplification.
@param Node $node
@retval Node
@throws SyntaxErrorException | [
"Populate",
"node",
"with",
"operands",
"without",
"any",
"simplification",
"."
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Parsing/Parser.php#L292-L317 |
mossadal/math-parser | src/MathParser/Parsing/Parser.php | Parser.filterTokens | protected function filterTokens(array $tokens)
{
$filteredTokens = array_filter($tokens, function (Token $t) {
return $t->getType() !== TokenType::Whitespace;
});
// Return the array values only, because array_filter preserves the keys
return array_values($filteredTokens);
} | php | protected function filterTokens(array $tokens)
{
$filteredTokens = array_filter($tokens, function (Token $t) {
return $t->getType() !== TokenType::Whitespace;
});
// Return the array values only, because array_filter preserves the keys
return array_values($filteredTokens);
} | [
"protected",
"function",
"filterTokens",
"(",
"array",
"$",
"tokens",
")",
"{",
"$",
"filteredTokens",
"=",
"array_filter",
"(",
"$",
"tokens",
",",
"function",
"(",
"Token",
"$",
"t",
")",
"{",
"return",
"$",
"t",
"->",
"getType",
"(",
")",
"!==",
"TokenType",
"::",
"Whitespace",
";",
"}",
")",
";",
"// Return the array values only, because array_filter preserves the keys",
"return",
"array_values",
"(",
"$",
"filteredTokens",
")",
";",
"}"
] | Remove Whitespace from the token list.
@param array $tokens Input list of tokens
@retval Token[] | [
"Remove",
"Whitespace",
"from",
"the",
"token",
"list",
"."
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Parsing/Parser.php#L325-L333 |
mossadal/math-parser | src/MathParser/Parsing/Parser.php | Parser.parseImplicitMultiplication | protected function parseImplicitMultiplication(array $tokens)
{
$result = [];
$lastToken = null;
foreach ($tokens as $token) {
if (Token::canFactorsInImplicitMultiplication($lastToken, $token)) {
$result[] = new Token('*', TokenType::MultiplicationOperator);
}
$lastToken = $token;
$result[] = $token;
}
return $result;
} | php | protected function parseImplicitMultiplication(array $tokens)
{
$result = [];
$lastToken = null;
foreach ($tokens as $token) {
if (Token::canFactorsInImplicitMultiplication($lastToken, $token)) {
$result[] = new Token('*', TokenType::MultiplicationOperator);
}
$lastToken = $token;
$result[] = $token;
}
return $result;
} | [
"protected",
"function",
"parseImplicitMultiplication",
"(",
"array",
"$",
"tokens",
")",
"{",
"$",
"result",
"=",
"[",
"]",
";",
"$",
"lastToken",
"=",
"null",
";",
"foreach",
"(",
"$",
"tokens",
"as",
"$",
"token",
")",
"{",
"if",
"(",
"Token",
"::",
"canFactorsInImplicitMultiplication",
"(",
"$",
"lastToken",
",",
"$",
"token",
")",
")",
"{",
"$",
"result",
"[",
"]",
"=",
"new",
"Token",
"(",
"'*'",
",",
"TokenType",
"::",
"MultiplicationOperator",
")",
";",
"}",
"$",
"lastToken",
"=",
"$",
"token",
";",
"$",
"result",
"[",
"]",
"=",
"$",
"token",
";",
"}",
"return",
"$",
"result",
";",
"}"
] | Insert multiplication tokens where needed (taking care of implicit mulitplication).
@param array $tokens Input list of tokens (Token[])
@retval Token[] | [
"Insert",
"multiplication",
"tokens",
"where",
"needed",
"(",
"taking",
"care",
"of",
"implicit",
"mulitplication",
")",
"."
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Parsing/Parser.php#L341-L353 |
mossadal/math-parser | src/MathParser/Parsing/Parser.php | Parser.isUnary | protected function isUnary($node, $lastNode)
{
if (!($node->canBeUnary())) return false;
// Unary if it is the first token
if ($this->operatorStack->isEmpty() && $this->operandStack->isEmpty()) return true;
// or if the previous token was '('
if ($lastNode instanceof SubExpressionNode) return true;
// or last node was already a unary minus
if ($lastNode instanceof ExpressionNode && $lastNode->getOperator() == '~') return true;
return false;
} | php | protected function isUnary($node, $lastNode)
{
if (!($node->canBeUnary())) return false;
// Unary if it is the first token
if ($this->operatorStack->isEmpty() && $this->operandStack->isEmpty()) return true;
// or if the previous token was '('
if ($lastNode instanceof SubExpressionNode) return true;
// or last node was already a unary minus
if ($lastNode instanceof ExpressionNode && $lastNode->getOperator() == '~') return true;
return false;
} | [
"protected",
"function",
"isUnary",
"(",
"$",
"node",
",",
"$",
"lastNode",
")",
"{",
"if",
"(",
"!",
"(",
"$",
"node",
"->",
"canBeUnary",
"(",
")",
")",
")",
"return",
"false",
";",
"// Unary if it is the first token",
"if",
"(",
"$",
"this",
"->",
"operatorStack",
"->",
"isEmpty",
"(",
")",
"&&",
"$",
"this",
"->",
"operandStack",
"->",
"isEmpty",
"(",
")",
")",
"return",
"true",
";",
"// or if the previous token was '('",
"if",
"(",
"$",
"lastNode",
"instanceof",
"SubExpressionNode",
")",
"return",
"true",
";",
"// or last node was already a unary minus",
"if",
"(",
"$",
"lastNode",
"instanceof",
"ExpressionNode",
"&&",
"$",
"lastNode",
"->",
"getOperator",
"(",
")",
"==",
"'~'",
")",
"return",
"true",
";",
"return",
"false",
";",
"}"
] | Determine if $node is in fact a unary operator.
If $node can be a unary operator (i.e. is a '+' or '-' node),
**and** this is the first node we parse or the previous node
was a SubExpressionNode, i.e. an opening parenthesis, or the
previous node was already a unary minus, this means that the
current node is in fact a unary '+' or '-' and we return true,
otherwise we return false.
@param Node $node Current node
@param Node|null $lastNode Previous node handled by the Parser
@retval boolean | [
"Determine",
"if",
"$node",
"is",
"in",
"fact",
"a",
"unary",
"operator",
"."
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Parsing/Parser.php#L396-L408 |
mossadal/math-parser | src/MathParser/Parsing/Parser.php | Parser.handleSubExpression | protected function handleSubExpression()
{
// Flag, checking for mismatching parentheses
$clean = false;
// Pop operators off the operatorStack until its empty, or
// we find an opening parenthesis, building subexpressions
// on the operandStack as we go.
while ($popped = $this->operatorStack->pop()) {
// ok, we have our matching opening parenthesis
if ($popped instanceof SubExpressionNode) {
$clean = true;
break;
}
$node = $this->handleExpression($popped);
$this->operandStack->push($node);
}
// Throw an error if the parenthesis couldn't be matched
if (!$clean) {
throw new ParenthesisMismatchException();
}
// Check to see if the parenthesis pair was in fact part
// of a function application. If so, create the corresponding
// FunctionNode and push it onto the operandStack.
$previous = $this->operatorStack->peek();
if ($previous instanceof FunctionNode) {
$node = $this->operatorStack->pop();
$operand = $this->operandStack->pop();
$node->setOperand($operand);
$this->operandStack->push($node);
}
} | php | protected function handleSubExpression()
{
// Flag, checking for mismatching parentheses
$clean = false;
// Pop operators off the operatorStack until its empty, or
// we find an opening parenthesis, building subexpressions
// on the operandStack as we go.
while ($popped = $this->operatorStack->pop()) {
// ok, we have our matching opening parenthesis
if ($popped instanceof SubExpressionNode) {
$clean = true;
break;
}
$node = $this->handleExpression($popped);
$this->operandStack->push($node);
}
// Throw an error if the parenthesis couldn't be matched
if (!$clean) {
throw new ParenthesisMismatchException();
}
// Check to see if the parenthesis pair was in fact part
// of a function application. If so, create the corresponding
// FunctionNode and push it onto the operandStack.
$previous = $this->operatorStack->peek();
if ($previous instanceof FunctionNode) {
$node = $this->operatorStack->pop();
$operand = $this->operandStack->pop();
$node->setOperand($operand);
$this->operandStack->push($node);
}
} | [
"protected",
"function",
"handleSubExpression",
"(",
")",
"{",
"// Flag, checking for mismatching parentheses",
"$",
"clean",
"=",
"false",
";",
"// Pop operators off the operatorStack until its empty, or",
"// we find an opening parenthesis, building subexpressions",
"// on the operandStack as we go.",
"while",
"(",
"$",
"popped",
"=",
"$",
"this",
"->",
"operatorStack",
"->",
"pop",
"(",
")",
")",
"{",
"// ok, we have our matching opening parenthesis",
"if",
"(",
"$",
"popped",
"instanceof",
"SubExpressionNode",
")",
"{",
"$",
"clean",
"=",
"true",
";",
"break",
";",
"}",
"$",
"node",
"=",
"$",
"this",
"->",
"handleExpression",
"(",
"$",
"popped",
")",
";",
"$",
"this",
"->",
"operandStack",
"->",
"push",
"(",
"$",
"node",
")",
";",
"}",
"// Throw an error if the parenthesis couldn't be matched",
"if",
"(",
"!",
"$",
"clean",
")",
"{",
"throw",
"new",
"ParenthesisMismatchException",
"(",
")",
";",
"}",
"// Check to see if the parenthesis pair was in fact part",
"// of a function application. If so, create the corresponding",
"// FunctionNode and push it onto the operandStack.",
"$",
"previous",
"=",
"$",
"this",
"->",
"operatorStack",
"->",
"peek",
"(",
")",
";",
"if",
"(",
"$",
"previous",
"instanceof",
"FunctionNode",
")",
"{",
"$",
"node",
"=",
"$",
"this",
"->",
"operatorStack",
"->",
"pop",
"(",
")",
";",
"$",
"operand",
"=",
"$",
"this",
"->",
"operandStack",
"->",
"pop",
"(",
")",
";",
"$",
"node",
"->",
"setOperand",
"(",
"$",
"operand",
")",
";",
"$",
"this",
"->",
"operandStack",
"->",
"push",
"(",
"$",
"node",
")",
";",
"}",
"}"
] | Handle a closing parenthesis, popping operators off the
operator stack until we find a matching opening parenthesis.
@throws ParenthesisMismatchException | [
"Handle",
"a",
"closing",
"parenthesis",
"popping",
"operators",
"off",
"the",
"operator",
"stack",
"until",
"we",
"find",
"a",
"matching",
"opening",
"parenthesis",
"."
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Parsing/Parser.php#L415-L452 |
mossadal/math-parser | src/MathParser/Parsing/Nodes/Factories/ExponentiationNodeFactory.php | ExponentiationNodeFactory.makeNode | public function makeNode($leftOperand, $rightOperand)
{
$leftOperand = $this->sanitize($leftOperand);
$rightOperand = $this->sanitize($rightOperand);
// Simplification if the exponent is a number.
if ($this->isNumeric($rightOperand)) {
$node = $this->numericExponent($leftOperand, $rightOperand);
if ($node) return $node;
}
$node = $this->doubleExponentiation($leftOperand, $rightOperand);
if ($node) return $node;
return new ExpressionNode($leftOperand, '^', $rightOperand);
} | php | public function makeNode($leftOperand, $rightOperand)
{
$leftOperand = $this->sanitize($leftOperand);
$rightOperand = $this->sanitize($rightOperand);
// Simplification if the exponent is a number.
if ($this->isNumeric($rightOperand)) {
$node = $this->numericExponent($leftOperand, $rightOperand);
if ($node) return $node;
}
$node = $this->doubleExponentiation($leftOperand, $rightOperand);
if ($node) return $node;
return new ExpressionNode($leftOperand, '^', $rightOperand);
} | [
"public",
"function",
"makeNode",
"(",
"$",
"leftOperand",
",",
"$",
"rightOperand",
")",
"{",
"$",
"leftOperand",
"=",
"$",
"this",
"->",
"sanitize",
"(",
"$",
"leftOperand",
")",
";",
"$",
"rightOperand",
"=",
"$",
"this",
"->",
"sanitize",
"(",
"$",
"rightOperand",
")",
";",
"// Simplification if the exponent is a number.",
"if",
"(",
"$",
"this",
"->",
"isNumeric",
"(",
"$",
"rightOperand",
")",
")",
"{",
"$",
"node",
"=",
"$",
"this",
"->",
"numericExponent",
"(",
"$",
"leftOperand",
",",
"$",
"rightOperand",
")",
";",
"if",
"(",
"$",
"node",
")",
"return",
"$",
"node",
";",
"}",
"$",
"node",
"=",
"$",
"this",
"->",
"doubleExponentiation",
"(",
"$",
"leftOperand",
",",
"$",
"rightOperand",
")",
";",
"if",
"(",
"$",
"node",
")",
"return",
"$",
"node",
";",
"return",
"new",
"ExpressionNode",
"(",
"$",
"leftOperand",
",",
"'^'",
",",
"$",
"rightOperand",
")",
";",
"}"
] | Create a Node representing '$leftOperand^$rightOperand'
Using some simplification rules, create a NumberNode or ExpressionNode
giving an AST correctly representing '$leftOperand^$rightOperand'.
### Simplification rules:
- To simplify the use of the function, convert integer params to NumberNodes
- If $leftOperand and $rightOperand are both NumberNodes, return a single NumberNode containing x^y
- If $rightOperand is a NumberNode representing 0, return '1'
- If $rightOperand is a NumberNode representing 1, return $leftOperand
- If $leftOperand is already a power x=a^b and $rightOperand is a NumberNode, return a^(b*y)
@param Node|int $leftOperand Minuend
@param Node|int $rightOperand Subtrahend
@retval Node | [
"Create",
"a",
"Node",
"representing",
"$leftOperand^$rightOperand"
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Parsing/Nodes/Factories/ExponentiationNodeFactory.php#L54-L69 |
mossadal/math-parser | src/MathParser/Parsing/Nodes/Factories/ExponentiationNodeFactory.php | ExponentiationNodeFactory.numericExponent | private function numericExponent($leftOperand, $rightOperand)
{
// 0^0 throws an exception
if ($this->isNumeric($leftOperand) && $this->isNumeric($rightOperand)) {
if ($leftOperand->getValue() == 0 && $rightOperand->getValue() == 0)
throw new DivisionByZeroException();
}
// x^0 = 1
if ($rightOperand->getValue() == 0) return new IntegerNode(1);
// x^1 = x
if ($rightOperand->getValue() == 1) return $leftOperand;
if (!$this->isNumeric($leftOperand) || !$this->isNumeric($rightOperand)) {
return null;
}
$type = $this->resultingType($leftOperand, $rightOperand);
// Compute x^y if both are numbers.
switch($type) {
case Node::NumericFloat:
return new NumberNode(pow($leftOperand->getValue(), $rightOperand->getValue()));
case Node::NumericInteger:
if ($rightOperand->getValue() > 0)
{
return new IntegerNode(pow($leftOperand->getValue(), $rightOperand->getValue()));
}
}
// No simplification found
return null;
} | php | private function numericExponent($leftOperand, $rightOperand)
{
// 0^0 throws an exception
if ($this->isNumeric($leftOperand) && $this->isNumeric($rightOperand)) {
if ($leftOperand->getValue() == 0 && $rightOperand->getValue() == 0)
throw new DivisionByZeroException();
}
// x^0 = 1
if ($rightOperand->getValue() == 0) return new IntegerNode(1);
// x^1 = x
if ($rightOperand->getValue() == 1) return $leftOperand;
if (!$this->isNumeric($leftOperand) || !$this->isNumeric($rightOperand)) {
return null;
}
$type = $this->resultingType($leftOperand, $rightOperand);
// Compute x^y if both are numbers.
switch($type) {
case Node::NumericFloat:
return new NumberNode(pow($leftOperand->getValue(), $rightOperand->getValue()));
case Node::NumericInteger:
if ($rightOperand->getValue() > 0)
{
return new IntegerNode(pow($leftOperand->getValue(), $rightOperand->getValue()));
}
}
// No simplification found
return null;
} | [
"private",
"function",
"numericExponent",
"(",
"$",
"leftOperand",
",",
"$",
"rightOperand",
")",
"{",
"// 0^0 throws an exception",
"if",
"(",
"$",
"this",
"->",
"isNumeric",
"(",
"$",
"leftOperand",
")",
"&&",
"$",
"this",
"->",
"isNumeric",
"(",
"$",
"rightOperand",
")",
")",
"{",
"if",
"(",
"$",
"leftOperand",
"->",
"getValue",
"(",
")",
"==",
"0",
"&&",
"$",
"rightOperand",
"->",
"getValue",
"(",
")",
"==",
"0",
")",
"throw",
"new",
"DivisionByZeroException",
"(",
")",
";",
"}",
"// x^0 = 1",
"if",
"(",
"$",
"rightOperand",
"->",
"getValue",
"(",
")",
"==",
"0",
")",
"return",
"new",
"IntegerNode",
"(",
"1",
")",
";",
"// x^1 = x",
"if",
"(",
"$",
"rightOperand",
"->",
"getValue",
"(",
")",
"==",
"1",
")",
"return",
"$",
"leftOperand",
";",
"if",
"(",
"!",
"$",
"this",
"->",
"isNumeric",
"(",
"$",
"leftOperand",
")",
"||",
"!",
"$",
"this",
"->",
"isNumeric",
"(",
"$",
"rightOperand",
")",
")",
"{",
"return",
"null",
";",
"}",
"$",
"type",
"=",
"$",
"this",
"->",
"resultingType",
"(",
"$",
"leftOperand",
",",
"$",
"rightOperand",
")",
";",
"// Compute x^y if both are numbers.",
"switch",
"(",
"$",
"type",
")",
"{",
"case",
"Node",
"::",
"NumericFloat",
":",
"return",
"new",
"NumberNode",
"(",
"pow",
"(",
"$",
"leftOperand",
"->",
"getValue",
"(",
")",
",",
"$",
"rightOperand",
"->",
"getValue",
"(",
")",
")",
")",
";",
"case",
"Node",
"::",
"NumericInteger",
":",
"if",
"(",
"$",
"rightOperand",
"->",
"getValue",
"(",
")",
">",
"0",
")",
"{",
"return",
"new",
"IntegerNode",
"(",
"pow",
"(",
"$",
"leftOperand",
"->",
"getValue",
"(",
")",
",",
"$",
"rightOperand",
"->",
"getValue",
"(",
")",
")",
")",
";",
"}",
"}",
"// No simplification found",
"return",
"null",
";",
"}"
] | Simplify an expression x^y, when y is numeric.
@param Node $leftOperand
@param Node $rightOperand
@retval Node|null | [
"Simplify",
"an",
"expression",
"x^y",
"when",
"y",
"is",
"numeric",
"."
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Parsing/Nodes/Factories/ExponentiationNodeFactory.php#L77-L109 |
mossadal/math-parser | src/MathParser/Parsing/Nodes/Factories/ExponentiationNodeFactory.php | ExponentiationNodeFactory.doubleExponentiation | private function doubleExponentiation($leftOperand, $rightOperand)
{
// (x^a)^b -> x^(ab) for a, b numbers
if ($leftOperand instanceof ExpressionNode && $leftOperand->getOperator() == '^') {
$factory = new MultiplicationNodeFactory();
$power = $factory->makeNode($leftOperand->getRight(), $rightOperand);
$base = $leftOperand->getLeft();
return self::makeNode($base, $power);
}
// No simplification found
return null;
} | php | private function doubleExponentiation($leftOperand, $rightOperand)
{
// (x^a)^b -> x^(ab) for a, b numbers
if ($leftOperand instanceof ExpressionNode && $leftOperand->getOperator() == '^') {
$factory = new MultiplicationNodeFactory();
$power = $factory->makeNode($leftOperand->getRight(), $rightOperand);
$base = $leftOperand->getLeft();
return self::makeNode($base, $power);
}
// No simplification found
return null;
} | [
"private",
"function",
"doubleExponentiation",
"(",
"$",
"leftOperand",
",",
"$",
"rightOperand",
")",
"{",
"// (x^a)^b -> x^(ab) for a, b numbers",
"if",
"(",
"$",
"leftOperand",
"instanceof",
"ExpressionNode",
"&&",
"$",
"leftOperand",
"->",
"getOperator",
"(",
")",
"==",
"'^'",
")",
"{",
"$",
"factory",
"=",
"new",
"MultiplicationNodeFactory",
"(",
")",
";",
"$",
"power",
"=",
"$",
"factory",
"->",
"makeNode",
"(",
"$",
"leftOperand",
"->",
"getRight",
"(",
")",
",",
"$",
"rightOperand",
")",
";",
"$",
"base",
"=",
"$",
"leftOperand",
"->",
"getLeft",
"(",
")",
";",
"return",
"self",
"::",
"makeNode",
"(",
"$",
"base",
",",
"$",
"power",
")",
";",
"}",
"// No simplification found",
"return",
"null",
";",
"}"
] | Simplify (x^a)^b when a and b are both numeric.
@param Node $leftOperand
@param Node $rightOperand
@retval Node|null | [
"Simplify",
"(",
"x^a",
")",
"^b",
"when",
"a",
"and",
"b",
"are",
"both",
"numeric",
"."
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Parsing/Nodes/Factories/ExponentiationNodeFactory.php#L116-L130 |
mossadal/math-parser | src/MathParser/Parsing/Nodes/Node.php | Node.rationalFactory | public static function rationalFactory(Token $token)
{
switch ($token->getType()) {
case TokenType::PosInt:
case TokenType::Integer:
$x = intval($token->getValue());
return new IntegerNode($x);
case TokenType::RealNumber:
$x = floatval(str_replace(',', '.', $token->getValue()));
return new NumberNode($x);
case TokenType::Identifier:
return new VariableNode($token->getValue());
case TokenType::Constant:
return new ConstantNode($token->getValue());
case TokenType::FunctionName:
return new FunctionNode($token->getValue(), null);
case TokenType::OpenParenthesis:
return new SubExpressionNode($token->getValue());
case TokenType::AdditionOperator:
case TokenType::SubtractionOperator:
case TokenType::MultiplicationOperator:
case TokenType::DivisionOperator:
case TokenType::ExponentiationOperator:
return new ExpressionNode(null, $token->getValue(), null);
case TokenType::FactorialOperator:
return new PostfixOperatorNode($token->getValue(), null);
default:
// echo "Node factory returning null on $token\n";
return null;
}
} | php | public static function rationalFactory(Token $token)
{
switch ($token->getType()) {
case TokenType::PosInt:
case TokenType::Integer:
$x = intval($token->getValue());
return new IntegerNode($x);
case TokenType::RealNumber:
$x = floatval(str_replace(',', '.', $token->getValue()));
return new NumberNode($x);
case TokenType::Identifier:
return new VariableNode($token->getValue());
case TokenType::Constant:
return new ConstantNode($token->getValue());
case TokenType::FunctionName:
return new FunctionNode($token->getValue(), null);
case TokenType::OpenParenthesis:
return new SubExpressionNode($token->getValue());
case TokenType::AdditionOperator:
case TokenType::SubtractionOperator:
case TokenType::MultiplicationOperator:
case TokenType::DivisionOperator:
case TokenType::ExponentiationOperator:
return new ExpressionNode(null, $token->getValue(), null);
case TokenType::FactorialOperator:
return new PostfixOperatorNode($token->getValue(), null);
default:
// echo "Node factory returning null on $token\n";
return null;
}
} | [
"public",
"static",
"function",
"rationalFactory",
"(",
"Token",
"$",
"token",
")",
"{",
"switch",
"(",
"$",
"token",
"->",
"getType",
"(",
")",
")",
"{",
"case",
"TokenType",
"::",
"PosInt",
":",
"case",
"TokenType",
"::",
"Integer",
":",
"$",
"x",
"=",
"intval",
"(",
"$",
"token",
"->",
"getValue",
"(",
")",
")",
";",
"return",
"new",
"IntegerNode",
"(",
"$",
"x",
")",
";",
"case",
"TokenType",
"::",
"RealNumber",
":",
"$",
"x",
"=",
"floatval",
"(",
"str_replace",
"(",
"','",
",",
"'.'",
",",
"$",
"token",
"->",
"getValue",
"(",
")",
")",
")",
";",
"return",
"new",
"NumberNode",
"(",
"$",
"x",
")",
";",
"case",
"TokenType",
"::",
"Identifier",
":",
"return",
"new",
"VariableNode",
"(",
"$",
"token",
"->",
"getValue",
"(",
")",
")",
";",
"case",
"TokenType",
"::",
"Constant",
":",
"return",
"new",
"ConstantNode",
"(",
"$",
"token",
"->",
"getValue",
"(",
")",
")",
";",
"case",
"TokenType",
"::",
"FunctionName",
":",
"return",
"new",
"FunctionNode",
"(",
"$",
"token",
"->",
"getValue",
"(",
")",
",",
"null",
")",
";",
"case",
"TokenType",
"::",
"OpenParenthesis",
":",
"return",
"new",
"SubExpressionNode",
"(",
"$",
"token",
"->",
"getValue",
"(",
")",
")",
";",
"case",
"TokenType",
"::",
"AdditionOperator",
":",
"case",
"TokenType",
"::",
"SubtractionOperator",
":",
"case",
"TokenType",
"::",
"MultiplicationOperator",
":",
"case",
"TokenType",
"::",
"DivisionOperator",
":",
"case",
"TokenType",
"::",
"ExponentiationOperator",
":",
"return",
"new",
"ExpressionNode",
"(",
"null",
",",
"$",
"token",
"->",
"getValue",
"(",
")",
",",
"null",
")",
";",
"case",
"TokenType",
"::",
"FactorialOperator",
":",
"return",
"new",
"PostfixOperatorNode",
"(",
"$",
"token",
"->",
"getValue",
"(",
")",
",",
"null",
")",
";",
"default",
":",
"// echo \"Node factory returning null on $token\\n\";",
"return",
"null",
";",
"}",
"}"
] | Node factory, creating an appropriate Node from a Token.
Based on the provided Token, returns a TerminalNode if the
token type is PosInt, Integer, RealNumber, Identifier or Constant
otherwise returns null.
@retval Node|null
@param Token $token Provided token | [
"Node",
"factory",
"creating",
"an",
"appropriate",
"Node",
"from",
"a",
"Token",
"."
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Parsing/Nodes/Node.php#L44-L80 |
mossadal/math-parser | src/MathParser/Parsing/Nodes/Node.php | Node.complexity | public function complexity()
{
if ($this instanceof IntegerNode || $this instanceof VariableNode || $this instanceof ConstantNode) {
return 1;
} elseif ($this instanceof RationalNode || $this instanceof NumberNode) {
return 2;
} elseif ($this instanceof FunctionNode) {
return 5 + $this->getOperand()->complexity();
} elseif ($this instanceof ExpressionNode) {
$operator = $this->getOperator();
$left = $this->getLeft();
$right = $this->getRight();
switch ($operator) {
case '+':
case '-':
case '*':
return 1 + $left->complexity() + (($right === null) ? 0 : $right->complexity());
case '/':
return 3 + $left->complexity() + (($right === null) ? 0 : $right->complexity());
case '^':
return 8 + $left->complexity() + (($right === null) ? 0 : $right->complexity());
}
}
// This shouldn't happen under normal circumstances
return 1000;
} | php | public function complexity()
{
if ($this instanceof IntegerNode || $this instanceof VariableNode || $this instanceof ConstantNode) {
return 1;
} elseif ($this instanceof RationalNode || $this instanceof NumberNode) {
return 2;
} elseif ($this instanceof FunctionNode) {
return 5 + $this->getOperand()->complexity();
} elseif ($this instanceof ExpressionNode) {
$operator = $this->getOperator();
$left = $this->getLeft();
$right = $this->getRight();
switch ($operator) {
case '+':
case '-':
case '*':
return 1 + $left->complexity() + (($right === null) ? 0 : $right->complexity());
case '/':
return 3 + $left->complexity() + (($right === null) ? 0 : $right->complexity());
case '^':
return 8 + $left->complexity() + (($right === null) ? 0 : $right->complexity());
}
}
// This shouldn't happen under normal circumstances
return 1000;
} | [
"public",
"function",
"complexity",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"instanceof",
"IntegerNode",
"||",
"$",
"this",
"instanceof",
"VariableNode",
"||",
"$",
"this",
"instanceof",
"ConstantNode",
")",
"{",
"return",
"1",
";",
"}",
"elseif",
"(",
"$",
"this",
"instanceof",
"RationalNode",
"||",
"$",
"this",
"instanceof",
"NumberNode",
")",
"{",
"return",
"2",
";",
"}",
"elseif",
"(",
"$",
"this",
"instanceof",
"FunctionNode",
")",
"{",
"return",
"5",
"+",
"$",
"this",
"->",
"getOperand",
"(",
")",
"->",
"complexity",
"(",
")",
";",
"}",
"elseif",
"(",
"$",
"this",
"instanceof",
"ExpressionNode",
")",
"{",
"$",
"operator",
"=",
"$",
"this",
"->",
"getOperator",
"(",
")",
";",
"$",
"left",
"=",
"$",
"this",
"->",
"getLeft",
"(",
")",
";",
"$",
"right",
"=",
"$",
"this",
"->",
"getRight",
"(",
")",
";",
"switch",
"(",
"$",
"operator",
")",
"{",
"case",
"'+'",
":",
"case",
"'-'",
":",
"case",
"'*'",
":",
"return",
"1",
"+",
"$",
"left",
"->",
"complexity",
"(",
")",
"+",
"(",
"(",
"$",
"right",
"===",
"null",
")",
"?",
"0",
":",
"$",
"right",
"->",
"complexity",
"(",
")",
")",
";",
"case",
"'/'",
":",
"return",
"3",
"+",
"$",
"left",
"->",
"complexity",
"(",
")",
"+",
"(",
"(",
"$",
"right",
"===",
"null",
")",
"?",
"0",
":",
"$",
"right",
"->",
"complexity",
"(",
")",
")",
";",
"case",
"'^'",
":",
"return",
"8",
"+",
"$",
"left",
"->",
"complexity",
"(",
")",
"+",
"(",
"(",
"$",
"right",
"===",
"null",
")",
"?",
"0",
":",
"$",
"right",
"->",
"complexity",
"(",
")",
")",
";",
"}",
"}",
"// This shouldn't happen under normal circumstances",
"return",
"1000",
";",
"}"
] | Rough estimate of the complexity of the AST.
Gives a rough measure of the complexity of an AST. This can
be useful to choose between different simplification rules
or how to print a tree ("e^{...}" or ("\exp(...)") for example.
More precisely, the complexity is computed as the sum of
the complexity of all nodes of the AST, and
NumberNodes, VariableNodes and ConstantNodes have complexity 1,
FunctionNodes have complexity 5 (plus the complexity of its operand),
ExpressionNodes have complexity 1 (for `+`, `-`, `*`), 2 (for `/`),
or 8 (for `^`) | [
"Rough",
"estimate",
"of",
"the",
"complexity",
"of",
"the",
"AST",
"."
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Parsing/Nodes/Node.php#L177-L205 |
mossadal/math-parser | src/MathParser/Parsing/Nodes/Node.php | Node.isTerminal | public function isTerminal()
{
if ($this instanceof NumberNode) {
return true;
}
if ($this instanceof IntegerNode) {
return true;
}
if ($this instanceof RationalNode) {
return true;
}
if ($this instanceof VariableNode) {
return true;
}
if ($this instanceof ConstantNode) {
return true;
}
return false;
} | php | public function isTerminal()
{
if ($this instanceof NumberNode) {
return true;
}
if ($this instanceof IntegerNode) {
return true;
}
if ($this instanceof RationalNode) {
return true;
}
if ($this instanceof VariableNode) {
return true;
}
if ($this instanceof ConstantNode) {
return true;
}
return false;
} | [
"public",
"function",
"isTerminal",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"instanceof",
"NumberNode",
")",
"{",
"return",
"true",
";",
"}",
"if",
"(",
"$",
"this",
"instanceof",
"IntegerNode",
")",
"{",
"return",
"true",
";",
"}",
"if",
"(",
"$",
"this",
"instanceof",
"RationalNode",
")",
"{",
"return",
"true",
";",
"}",
"if",
"(",
"$",
"this",
"instanceof",
"VariableNode",
")",
"{",
"return",
"true",
";",
"}",
"if",
"(",
"$",
"this",
"instanceof",
"ConstantNode",
")",
"{",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}"
] | Returns true if the node is a terminal node, i.e.
a NumerNode, VariableNode or ConstantNode.
@retval boolean | [
"Returns",
"true",
"if",
"the",
"node",
"is",
"a",
"terminal",
"node",
"i",
".",
"e",
".",
"a",
"NumerNode",
"VariableNode",
"or",
"ConstantNode",
"."
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Parsing/Nodes/Node.php#L214-L237 |
mossadal/math-parser | src/MathParser/Lexing/TokenDefinition.php | TokenDefinition.match | public function match($input)
{
// Match the input with the regex pattern, storing any match found into the $matches variable,
// along with the index of the string at which it was matched.
$result = preg_match($this->pattern, $input, $matches, PREG_OFFSET_CAPTURE);
// preg_match returns false if an error occured
if ($result === false)
throw new \Exception(preg_last_error());
// 0 means no match was found
if ($result === 0)
return null;
return $this->getTokenFromMatch($matches[0]);
} | php | public function match($input)
{
// Match the input with the regex pattern, storing any match found into the $matches variable,
// along with the index of the string at which it was matched.
$result = preg_match($this->pattern, $input, $matches, PREG_OFFSET_CAPTURE);
// preg_match returns false if an error occured
if ($result === false)
throw new \Exception(preg_last_error());
// 0 means no match was found
if ($result === 0)
return null;
return $this->getTokenFromMatch($matches[0]);
} | [
"public",
"function",
"match",
"(",
"$",
"input",
")",
"{",
"// Match the input with the regex pattern, storing any match found into the $matches variable,",
"// along with the index of the string at which it was matched.",
"$",
"result",
"=",
"preg_match",
"(",
"$",
"this",
"->",
"pattern",
",",
"$",
"input",
",",
"$",
"matches",
",",
"PREG_OFFSET_CAPTURE",
")",
";",
"// preg_match returns false if an error occured",
"if",
"(",
"$",
"result",
"===",
"false",
")",
"throw",
"new",
"\\",
"Exception",
"(",
"preg_last_error",
"(",
")",
")",
";",
"// 0 means no match was found",
"if",
"(",
"$",
"result",
"===",
"0",
")",
"return",
"null",
";",
"return",
"$",
"this",
"->",
"getTokenFromMatch",
"(",
"$",
"matches",
"[",
"0",
"]",
")",
";",
"}"
] | Try to match the given input to the current TokenDefinition.
@param string $input Input string
@retval Token|null Token matching the regular expression defining the TokenDefinition | [
"Try",
"to",
"match",
"the",
"given",
"input",
"to",
"the",
"current",
"TokenDefinition",
"."
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Lexing/TokenDefinition.php#L60-L75 |
mossadal/math-parser | src/MathParser/Lexing/TokenDefinition.php | TokenDefinition.getTokenFromMatch | private function getTokenFromMatch($match)
{
$value = $match[0];
$offset = $match[1];
// If we don't match at the beginning of the string, it fails.
if ($offset !== 0)
return null;
if ($this->value) $value = $this->value;
return new Token($value, $this->tokenType, $match[0]);
} | php | private function getTokenFromMatch($match)
{
$value = $match[0];
$offset = $match[1];
// If we don't match at the beginning of the string, it fails.
if ($offset !== 0)
return null;
if ($this->value) $value = $this->value;
return new Token($value, $this->tokenType, $match[0]);
} | [
"private",
"function",
"getTokenFromMatch",
"(",
"$",
"match",
")",
"{",
"$",
"value",
"=",
"$",
"match",
"[",
"0",
"]",
";",
"$",
"offset",
"=",
"$",
"match",
"[",
"1",
"]",
";",
"// If we don't match at the beginning of the string, it fails.",
"if",
"(",
"$",
"offset",
"!==",
"0",
")",
"return",
"null",
";",
"if",
"(",
"$",
"this",
"->",
"value",
")",
"$",
"value",
"=",
"$",
"this",
"->",
"value",
";",
"return",
"new",
"Token",
"(",
"$",
"value",
",",
"$",
"this",
"->",
"tokenType",
",",
"$",
"match",
"[",
"0",
"]",
")",
";",
"}"
] | Convert matching string to an actual Token.
@param string $match Matching text.
@retval Token Corresponding token. | [
"Convert",
"matching",
"string",
"to",
"an",
"actual",
"Token",
"."
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Lexing/TokenDefinition.php#L83-L95 |
mossadal/math-parser | src/MathParser/Parsing/Nodes/FunctionNode.php | FunctionNode.compareTo | public function compareTo($other)
{
if ($other === null) {
return false;
}
if (!($other instanceof FunctionNode)) {
return false;
}
$thisOperand = $this->getOperand();
$otherOperand = $other->getOperand();
return $this->getName() == $other->getName() && $thisOperand->compareTo($otherOperand);
} | php | public function compareTo($other)
{
if ($other === null) {
return false;
}
if (!($other instanceof FunctionNode)) {
return false;
}
$thisOperand = $this->getOperand();
$otherOperand = $other->getOperand();
return $this->getName() == $other->getName() && $thisOperand->compareTo($otherOperand);
} | [
"public",
"function",
"compareTo",
"(",
"$",
"other",
")",
"{",
"if",
"(",
"$",
"other",
"===",
"null",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"!",
"(",
"$",
"other",
"instanceof",
"FunctionNode",
")",
")",
"{",
"return",
"false",
";",
"}",
"$",
"thisOperand",
"=",
"$",
"this",
"->",
"getOperand",
"(",
")",
";",
"$",
"otherOperand",
"=",
"$",
"other",
"->",
"getOperand",
"(",
")",
";",
"return",
"$",
"this",
"->",
"getName",
"(",
")",
"==",
"$",
"other",
"->",
"getName",
"(",
")",
"&&",
"$",
"thisOperand",
"->",
"compareTo",
"(",
"$",
"otherOperand",
")",
";",
"}"
] | Implementing the compareTo abstract method. | [
"Implementing",
"the",
"compareTo",
"abstract",
"method",
"."
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Parsing/Nodes/FunctionNode.php#L73-L86 |
mossadal/math-parser | src/MathParser/Interpreting/Evaluator.php | Evaluator.visitExpressionNode | public function visitExpressionNode(ExpressionNode $node)
{
$operator = $node->getOperator();
$leftValue = $node->getLeft()->accept($this);
if ($node->getRight()) {
$rightValue = $node->getRight()->accept($this);
} else {
$rightValue = null;
}
// Perform the right operation based on the operator
switch ($operator) {
case '+':
return $leftValue + $rightValue;
case '-':
return $rightValue === null ? -$leftValue : $leftValue - $rightValue;
case '*':
return $rightValue * $leftValue;
case '/':
if ($rightValue == 0) {
throw new DivisionByZeroException();
}
return $leftValue / $rightValue;
case '^':
// Check for base equal to M_E, to take care of PHP's strange
// implementation of pow, where pow(M_E, x) is not necessarily
// equal to exp(x).
if ($leftValue == M_E) {
return exp($rightValue);
} else {
return pow($leftValue, $rightValue);
}
default:
throw new UnknownOperatorException($operator);
}
} | php | public function visitExpressionNode(ExpressionNode $node)
{
$operator = $node->getOperator();
$leftValue = $node->getLeft()->accept($this);
if ($node->getRight()) {
$rightValue = $node->getRight()->accept($this);
} else {
$rightValue = null;
}
// Perform the right operation based on the operator
switch ($operator) {
case '+':
return $leftValue + $rightValue;
case '-':
return $rightValue === null ? -$leftValue : $leftValue - $rightValue;
case '*':
return $rightValue * $leftValue;
case '/':
if ($rightValue == 0) {
throw new DivisionByZeroException();
}
return $leftValue / $rightValue;
case '^':
// Check for base equal to M_E, to take care of PHP's strange
// implementation of pow, where pow(M_E, x) is not necessarily
// equal to exp(x).
if ($leftValue == M_E) {
return exp($rightValue);
} else {
return pow($leftValue, $rightValue);
}
default:
throw new UnknownOperatorException($operator);
}
} | [
"public",
"function",
"visitExpressionNode",
"(",
"ExpressionNode",
"$",
"node",
")",
"{",
"$",
"operator",
"=",
"$",
"node",
"->",
"getOperator",
"(",
")",
";",
"$",
"leftValue",
"=",
"$",
"node",
"->",
"getLeft",
"(",
")",
"->",
"accept",
"(",
"$",
"this",
")",
";",
"if",
"(",
"$",
"node",
"->",
"getRight",
"(",
")",
")",
"{",
"$",
"rightValue",
"=",
"$",
"node",
"->",
"getRight",
"(",
")",
"->",
"accept",
"(",
"$",
"this",
")",
";",
"}",
"else",
"{",
"$",
"rightValue",
"=",
"null",
";",
"}",
"// Perform the right operation based on the operator",
"switch",
"(",
"$",
"operator",
")",
"{",
"case",
"'+'",
":",
"return",
"$",
"leftValue",
"+",
"$",
"rightValue",
";",
"case",
"'-'",
":",
"return",
"$",
"rightValue",
"===",
"null",
"?",
"-",
"$",
"leftValue",
":",
"$",
"leftValue",
"-",
"$",
"rightValue",
";",
"case",
"'*'",
":",
"return",
"$",
"rightValue",
"*",
"$",
"leftValue",
";",
"case",
"'/'",
":",
"if",
"(",
"$",
"rightValue",
"==",
"0",
")",
"{",
"throw",
"new",
"DivisionByZeroException",
"(",
")",
";",
"}",
"return",
"$",
"leftValue",
"/",
"$",
"rightValue",
";",
"case",
"'^'",
":",
"// Check for base equal to M_E, to take care of PHP's strange",
"// implementation of pow, where pow(M_E, x) is not necessarily",
"// equal to exp(x).",
"if",
"(",
"$",
"leftValue",
"==",
"M_E",
")",
"{",
"return",
"exp",
"(",
"$",
"rightValue",
")",
";",
"}",
"else",
"{",
"return",
"pow",
"(",
"$",
"leftValue",
",",
"$",
"rightValue",
")",
";",
"}",
"default",
":",
"throw",
"new",
"UnknownOperatorException",
"(",
"$",
"operator",
")",
";",
"}",
"}"
] | Evaluate an ExpressionNode
Computes the value of an ExpressionNode `x op y`
where `op` is one of `+`, `-`, `*`, `/` or `^`
`+`, `-`, `*`, `/` or `^`
@retval float
@param ExpressionNode $node AST to be evaluated
@throws UnknownOperatorException if the operator is something other than | [
"Evaluate",
"an",
"ExpressionNode"
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Interpreting/Evaluator.php#L91-L130 |
mossadal/math-parser | src/MathParser/Interpreting/Evaluator.php | Evaluator.visitFunctionNode | public function visitFunctionNode(FunctionNode $node)
{
$inner = $node->getOperand()->accept($this);
switch ($node->getName()) {
// Trigonometric functions
case 'sin':
return sin($inner);
case 'cos':
return cos($inner);
case 'tan':
return tan($inner);
case 'cot':
$tan_inner = tan($inner);
if ($tan_inner == 0) {
return NAN;
}
return 1 / $tan_inner;
// Trigonometric functions, argument in degrees
case 'sind':
return sin(deg2rad($inner));
case 'cosd':
return cos(deg2rad($inner));
case 'tand':
return tan(deg2rad($inner));
case 'cotd':
$tan_inner = tan(deg2rad($inner));
if ($tan_inner == 0) {
return NAN;
}
return 1 / $tan_inner;
// Inverse trigonometric functions
case 'arcsin':
return asin($inner);
case 'arccos':
return acos($inner);
case 'arctan':
return atan($inner);
case 'arccot':
return pi() / 2 - atan($inner);
// Exponentials and logarithms
case 'exp':
return exp($inner);
case 'log':
case 'ln':
return log($inner);
case 'lg':
return log10($inner);
// Powers
case 'sqrt':
return sqrt($inner);
// Hyperbolic functions
case 'sinh':
return sinh($inner);
case 'cosh':
return cosh($inner);
case 'tanh':
return tanh($inner);
case 'coth':
$tanh_inner = tanh($inner);
if ($tanh_inner == 0) {
return NAN;
}
return 1 / $tanh_inner;
// Inverse hyperbolic functions
case 'arsinh':
return asinh($inner);
case 'arcosh':
return acosh($inner);
case 'artanh':
return atanh($inner);
case 'arcoth':
return atanh(1 / $inner);
case 'abs':
return abs($inner);
case 'sgn':
return $inner >= 0 ? 1 : -1;
case '!':
$logGamma = Math::logGamma(1 + $inner);
return exp($logGamma);
case '!!':
if (round($inner) != $inner) {
throw new \UnexpectedValueException("Expecting positive integer (semifactorial)");
}
return Math::SemiFactorial($inner);
// Rounding functions
case 'round':
return round($inner);
case 'floor':
return floor($inner);
case 'ceil':
return ceil($inner);
default:
throw new UnknownFunctionException($node->getName());
}
} | php | public function visitFunctionNode(FunctionNode $node)
{
$inner = $node->getOperand()->accept($this);
switch ($node->getName()) {
// Trigonometric functions
case 'sin':
return sin($inner);
case 'cos':
return cos($inner);
case 'tan':
return tan($inner);
case 'cot':
$tan_inner = tan($inner);
if ($tan_inner == 0) {
return NAN;
}
return 1 / $tan_inner;
// Trigonometric functions, argument in degrees
case 'sind':
return sin(deg2rad($inner));
case 'cosd':
return cos(deg2rad($inner));
case 'tand':
return tan(deg2rad($inner));
case 'cotd':
$tan_inner = tan(deg2rad($inner));
if ($tan_inner == 0) {
return NAN;
}
return 1 / $tan_inner;
// Inverse trigonometric functions
case 'arcsin':
return asin($inner);
case 'arccos':
return acos($inner);
case 'arctan':
return atan($inner);
case 'arccot':
return pi() / 2 - atan($inner);
// Exponentials and logarithms
case 'exp':
return exp($inner);
case 'log':
case 'ln':
return log($inner);
case 'lg':
return log10($inner);
// Powers
case 'sqrt':
return sqrt($inner);
// Hyperbolic functions
case 'sinh':
return sinh($inner);
case 'cosh':
return cosh($inner);
case 'tanh':
return tanh($inner);
case 'coth':
$tanh_inner = tanh($inner);
if ($tanh_inner == 0) {
return NAN;
}
return 1 / $tanh_inner;
// Inverse hyperbolic functions
case 'arsinh':
return asinh($inner);
case 'arcosh':
return acosh($inner);
case 'artanh':
return atanh($inner);
case 'arcoth':
return atanh(1 / $inner);
case 'abs':
return abs($inner);
case 'sgn':
return $inner >= 0 ? 1 : -1;
case '!':
$logGamma = Math::logGamma(1 + $inner);
return exp($logGamma);
case '!!':
if (round($inner) != $inner) {
throw new \UnexpectedValueException("Expecting positive integer (semifactorial)");
}
return Math::SemiFactorial($inner);
// Rounding functions
case 'round':
return round($inner);
case 'floor':
return floor($inner);
case 'ceil':
return ceil($inner);
default:
throw new UnknownFunctionException($node->getName());
}
} | [
"public",
"function",
"visitFunctionNode",
"(",
"FunctionNode",
"$",
"node",
")",
"{",
"$",
"inner",
"=",
"$",
"node",
"->",
"getOperand",
"(",
")",
"->",
"accept",
"(",
"$",
"this",
")",
";",
"switch",
"(",
"$",
"node",
"->",
"getName",
"(",
")",
")",
"{",
"// Trigonometric functions",
"case",
"'sin'",
":",
"return",
"sin",
"(",
"$",
"inner",
")",
";",
"case",
"'cos'",
":",
"return",
"cos",
"(",
"$",
"inner",
")",
";",
"case",
"'tan'",
":",
"return",
"tan",
"(",
"$",
"inner",
")",
";",
"case",
"'cot'",
":",
"$",
"tan_inner",
"=",
"tan",
"(",
"$",
"inner",
")",
";",
"if",
"(",
"$",
"tan_inner",
"==",
"0",
")",
"{",
"return",
"NAN",
";",
"}",
"return",
"1",
"/",
"$",
"tan_inner",
";",
"// Trigonometric functions, argument in degrees",
"case",
"'sind'",
":",
"return",
"sin",
"(",
"deg2rad",
"(",
"$",
"inner",
")",
")",
";",
"case",
"'cosd'",
":",
"return",
"cos",
"(",
"deg2rad",
"(",
"$",
"inner",
")",
")",
";",
"case",
"'tand'",
":",
"return",
"tan",
"(",
"deg2rad",
"(",
"$",
"inner",
")",
")",
";",
"case",
"'cotd'",
":",
"$",
"tan_inner",
"=",
"tan",
"(",
"deg2rad",
"(",
"$",
"inner",
")",
")",
";",
"if",
"(",
"$",
"tan_inner",
"==",
"0",
")",
"{",
"return",
"NAN",
";",
"}",
"return",
"1",
"/",
"$",
"tan_inner",
";",
"// Inverse trigonometric functions",
"case",
"'arcsin'",
":",
"return",
"asin",
"(",
"$",
"inner",
")",
";",
"case",
"'arccos'",
":",
"return",
"acos",
"(",
"$",
"inner",
")",
";",
"case",
"'arctan'",
":",
"return",
"atan",
"(",
"$",
"inner",
")",
";",
"case",
"'arccot'",
":",
"return",
"pi",
"(",
")",
"/",
"2",
"-",
"atan",
"(",
"$",
"inner",
")",
";",
"// Exponentials and logarithms",
"case",
"'exp'",
":",
"return",
"exp",
"(",
"$",
"inner",
")",
";",
"case",
"'log'",
":",
"case",
"'ln'",
":",
"return",
"log",
"(",
"$",
"inner",
")",
";",
"case",
"'lg'",
":",
"return",
"log10",
"(",
"$",
"inner",
")",
";",
"// Powers",
"case",
"'sqrt'",
":",
"return",
"sqrt",
"(",
"$",
"inner",
")",
";",
"// Hyperbolic functions",
"case",
"'sinh'",
":",
"return",
"sinh",
"(",
"$",
"inner",
")",
";",
"case",
"'cosh'",
":",
"return",
"cosh",
"(",
"$",
"inner",
")",
";",
"case",
"'tanh'",
":",
"return",
"tanh",
"(",
"$",
"inner",
")",
";",
"case",
"'coth'",
":",
"$",
"tanh_inner",
"=",
"tanh",
"(",
"$",
"inner",
")",
";",
"if",
"(",
"$",
"tanh_inner",
"==",
"0",
")",
"{",
"return",
"NAN",
";",
"}",
"return",
"1",
"/",
"$",
"tanh_inner",
";",
"// Inverse hyperbolic functions",
"case",
"'arsinh'",
":",
"return",
"asinh",
"(",
"$",
"inner",
")",
";",
"case",
"'arcosh'",
":",
"return",
"acosh",
"(",
"$",
"inner",
")",
";",
"case",
"'artanh'",
":",
"return",
"atanh",
"(",
"$",
"inner",
")",
";",
"case",
"'arcoth'",
":",
"return",
"atanh",
"(",
"1",
"/",
"$",
"inner",
")",
";",
"case",
"'abs'",
":",
"return",
"abs",
"(",
"$",
"inner",
")",
";",
"case",
"'sgn'",
":",
"return",
"$",
"inner",
">=",
"0",
"?",
"1",
":",
"-",
"1",
";",
"case",
"'!'",
":",
"$",
"logGamma",
"=",
"Math",
"::",
"logGamma",
"(",
"1",
"+",
"$",
"inner",
")",
";",
"return",
"exp",
"(",
"$",
"logGamma",
")",
";",
"case",
"'!!'",
":",
"if",
"(",
"round",
"(",
"$",
"inner",
")",
"!=",
"$",
"inner",
")",
"{",
"throw",
"new",
"\\",
"UnexpectedValueException",
"(",
"\"Expecting positive integer (semifactorial)\"",
")",
";",
"}",
"return",
"Math",
"::",
"SemiFactorial",
"(",
"$",
"inner",
")",
";",
"// Rounding functions",
"case",
"'round'",
":",
"return",
"round",
"(",
"$",
"inner",
")",
";",
"case",
"'floor'",
":",
"return",
"floor",
"(",
"$",
"inner",
")",
";",
"case",
"'ceil'",
":",
"return",
"ceil",
"(",
"$",
"inner",
")",
";",
"default",
":",
"throw",
"new",
"UnknownFunctionException",
"(",
"$",
"node",
"->",
"getName",
"(",
")",
")",
";",
"}",
"}"
] | Evaluate a FunctionNode
Computes the value of a FunctionNode `f(x)`, where f is
an elementary function recognized by StdMathLexer and StdMathParser.
FunctionNode is *not* recognized.
@retval float
@see \MathParser\Lexer\StdMathLexer StdMathLexer
@see \MathParser\StdMathParser StdMathParser
@param FunctionNode $node AST to be evaluated
@throws UnknownFunctionException if the function respresented by the | [
"Evaluate",
"a",
"FunctionNode"
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Interpreting/Evaluator.php#L193-L324 |
mossadal/math-parser | src/MathParser/Interpreting/Evaluator.php | Evaluator.visitConstantNode | public function visitConstantNode(ConstantNode $node)
{
switch ($node->getName()) {
case 'pi':
return M_PI;
case 'e':
return exp(1);
case 'NAN':
return NAN;
case 'INF':
return INF;
default:
throw new UnknownConstantException($node->getName());
}
} | php | public function visitConstantNode(ConstantNode $node)
{
switch ($node->getName()) {
case 'pi':
return M_PI;
case 'e':
return exp(1);
case 'NAN':
return NAN;
case 'INF':
return INF;
default:
throw new UnknownConstantException($node->getName());
}
} | [
"public",
"function",
"visitConstantNode",
"(",
"ConstantNode",
"$",
"node",
")",
"{",
"switch",
"(",
"$",
"node",
"->",
"getName",
"(",
")",
")",
"{",
"case",
"'pi'",
":",
"return",
"M_PI",
";",
"case",
"'e'",
":",
"return",
"exp",
"(",
"1",
")",
";",
"case",
"'NAN'",
":",
"return",
"NAN",
";",
"case",
"'INF'",
":",
"return",
"INF",
";",
"default",
":",
"throw",
"new",
"UnknownConstantException",
"(",
"$",
"node",
"->",
"getName",
"(",
")",
")",
";",
"}",
"}"
] | Evaluate a ConstantNode
Returns the value of a ConstantNode recognized by StdMathLexer and StdMathParser.
ConstantNode is *not* recognized.
@retval float
@see \MathParser\Lexer\StdMathLexer StdMathLexer
@see \MathParser\StdMathParser StdMathParser
@param ConstantNode $node AST to be evaluated
@throws UnknownConstantException if the variable respresented by the | [
"Evaluate",
"a",
"ConstantNode"
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Interpreting/Evaluator.php#L339-L353 |
mossadal/math-parser | src/MathParser/RationalMathParser.php | RationalMathParser.parse | public function parse($text)
{
$this->tokens = $this->lexer->tokenize($text);
$this->tree = $this->parser->parse($this->tokens);
return $this->tree;
} | php | public function parse($text)
{
$this->tokens = $this->lexer->tokenize($text);
$this->tree = $this->parser->parse($this->tokens);
return $this->tree;
} | [
"public",
"function",
"parse",
"(",
"$",
"text",
")",
"{",
"$",
"this",
"->",
"tokens",
"=",
"$",
"this",
"->",
"lexer",
"->",
"tokenize",
"(",
"$",
"text",
")",
";",
"$",
"this",
"->",
"tree",
"=",
"$",
"this",
"->",
"parser",
"->",
"parse",
"(",
"$",
"this",
"->",
"tokens",
")",
";",
"return",
"$",
"this",
"->",
"tree",
";",
"}"
] | Parse the given mathematical expression into an abstract syntax tree.
@param string $text Input
@retval Node | [
"Parse",
"the",
"given",
"mathematical",
"expression",
"into",
"an",
"abstract",
"syntax",
"tree",
"."
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/RationalMathParser.php#L53-L59 |
mossadal/math-parser | src/MathParser/Parsing/Nodes/Factories/SubtractionNodeFactory.php | SubtractionNodeFactory.makeNode | public function makeNode($leftOperand, $rightOperand)
{
if ($rightOperand === null) return $this->createUnaryMinusNode($leftOperand);
$leftOperand = $this->sanitize($leftOperand);
$rightOperand = $this->sanitize($rightOperand);
$node = $this->numericTerms($leftOperand, $rightOperand);
if ($node) return $node;
if ($leftOperand->compareTo($rightOperand)) {
return new IntegerNode(0);
}
return new ExpressionNode($leftOperand, '-', $rightOperand);
} | php | public function makeNode($leftOperand, $rightOperand)
{
if ($rightOperand === null) return $this->createUnaryMinusNode($leftOperand);
$leftOperand = $this->sanitize($leftOperand);
$rightOperand = $this->sanitize($rightOperand);
$node = $this->numericTerms($leftOperand, $rightOperand);
if ($node) return $node;
if ($leftOperand->compareTo($rightOperand)) {
return new IntegerNode(0);
}
return new ExpressionNode($leftOperand, '-', $rightOperand);
} | [
"public",
"function",
"makeNode",
"(",
"$",
"leftOperand",
",",
"$",
"rightOperand",
")",
"{",
"if",
"(",
"$",
"rightOperand",
"===",
"null",
")",
"return",
"$",
"this",
"->",
"createUnaryMinusNode",
"(",
"$",
"leftOperand",
")",
";",
"$",
"leftOperand",
"=",
"$",
"this",
"->",
"sanitize",
"(",
"$",
"leftOperand",
")",
";",
"$",
"rightOperand",
"=",
"$",
"this",
"->",
"sanitize",
"(",
"$",
"rightOperand",
")",
";",
"$",
"node",
"=",
"$",
"this",
"->",
"numericTerms",
"(",
"$",
"leftOperand",
",",
"$",
"rightOperand",
")",
";",
"if",
"(",
"$",
"node",
")",
"return",
"$",
"node",
";",
"if",
"(",
"$",
"leftOperand",
"->",
"compareTo",
"(",
"$",
"rightOperand",
")",
")",
"{",
"return",
"new",
"IntegerNode",
"(",
"0",
")",
";",
"}",
"return",
"new",
"ExpressionNode",
"(",
"$",
"leftOperand",
",",
"'-'",
",",
"$",
"rightOperand",
")",
";",
"}"
] | Create a Node representing 'leftOperand - rightOperand'
Using some simplification rules, create a NumberNode or ExpressionNode
giving an AST correctly representing 'rightOperand - leftOperand'.
### Simplification rules:
- To simplify the use of the function, convert integer params to NumberNodes
- If $rightOperand is null, return a unary minus node '-x' instead
- If $leftOperand and $rightOperand are both NumberNodes, return a single NumberNode containing their difference
- If $rightOperand is a NumberNode representing 0, return $leftOperand unchanged
- If $leftOperand and $rightOperand are equal, return '0'
@param Node|int|float $leftOperand Minuend
@param Node|int|float $rightOperand Subtrahend
@retval Node | [
"Create",
"a",
"Node",
"representing",
"leftOperand",
"-",
"rightOperand"
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Parsing/Nodes/Factories/SubtractionNodeFactory.php#L52-L67 |
mossadal/math-parser | src/MathParser/Parsing/Nodes/Factories/SubtractionNodeFactory.php | SubtractionNodeFactory.createUnaryMinusNode | public function createUnaryMinusNode($operand)
{
$operand = $this->sanitize($operand);
if ($operand instanceof NumberNode) {
return new NumberNode(-$operand->getValue());
}
if ($operand instanceof IntegerNode) {
return new IntegerNode(-$operand->getValue());
}
if ($operand instanceof RationalNode) {
return new RationalNode(-$operand->getNumerator(), $operand->getDenominator());
}
// --x => x
if ($operand instanceof ExpressionNode && $operand->getOperator() == '-' && $operand->getRight() === null) {
return $operand->getLeft();
}
return new ExpressionNode($operand, '-', null);
} | php | public function createUnaryMinusNode($operand)
{
$operand = $this->sanitize($operand);
if ($operand instanceof NumberNode) {
return new NumberNode(-$operand->getValue());
}
if ($operand instanceof IntegerNode) {
return new IntegerNode(-$operand->getValue());
}
if ($operand instanceof RationalNode) {
return new RationalNode(-$operand->getNumerator(), $operand->getDenominator());
}
// --x => x
if ($operand instanceof ExpressionNode && $operand->getOperator() == '-' && $operand->getRight() === null) {
return $operand->getLeft();
}
return new ExpressionNode($operand, '-', null);
} | [
"public",
"function",
"createUnaryMinusNode",
"(",
"$",
"operand",
")",
"{",
"$",
"operand",
"=",
"$",
"this",
"->",
"sanitize",
"(",
"$",
"operand",
")",
";",
"if",
"(",
"$",
"operand",
"instanceof",
"NumberNode",
")",
"{",
"return",
"new",
"NumberNode",
"(",
"-",
"$",
"operand",
"->",
"getValue",
"(",
")",
")",
";",
"}",
"if",
"(",
"$",
"operand",
"instanceof",
"IntegerNode",
")",
"{",
"return",
"new",
"IntegerNode",
"(",
"-",
"$",
"operand",
"->",
"getValue",
"(",
")",
")",
";",
"}",
"if",
"(",
"$",
"operand",
"instanceof",
"RationalNode",
")",
"{",
"return",
"new",
"RationalNode",
"(",
"-",
"$",
"operand",
"->",
"getNumerator",
"(",
")",
",",
"$",
"operand",
"->",
"getDenominator",
"(",
")",
")",
";",
"}",
"// --x => x",
"if",
"(",
"$",
"operand",
"instanceof",
"ExpressionNode",
"&&",
"$",
"operand",
"->",
"getOperator",
"(",
")",
"==",
"'-'",
"&&",
"$",
"operand",
"->",
"getRight",
"(",
")",
"===",
"null",
")",
"{",
"return",
"$",
"operand",
"->",
"getLeft",
"(",
")",
";",
"}",
"return",
"new",
"ExpressionNode",
"(",
"$",
"operand",
",",
"'-'",
",",
"null",
")",
";",
"}"
] | Create a Node representing '-$operand'
Using some simplification rules, create a NumberNode or ExpressionNode
giving an AST correctly representing '-$operand'.
### Simplification rules:
- To simplify the use of the function, convert integer params to NumberNodes
- If $operand is a NumberNodes, return a single NumberNode containing its negative
- If $operand already is a unary minus, 'x=-y', return y
@param Node|int $operand Operand
@retval Node | [
"Create",
"a",
"Node",
"representing",
"-",
"$operand"
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Parsing/Nodes/Factories/SubtractionNodeFactory.php#L115-L133 |
mossadal/math-parser | src/MathParser/Parsing/Nodes/VariableNode.php | VariableNode.compareTo | public function compareTo($other)
{
if ($other === null) {
return false;
}
if (!($other instanceof VariableNode)) {
return false;
}
return $this->getName() == $other->getName();
} | php | public function compareTo($other)
{
if ($other === null) {
return false;
}
if (!($other instanceof VariableNode)) {
return false;
}
return $this->getName() == $other->getName();
} | [
"public",
"function",
"compareTo",
"(",
"$",
"other",
")",
"{",
"if",
"(",
"$",
"other",
"===",
"null",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"!",
"(",
"$",
"other",
"instanceof",
"VariableNode",
")",
")",
"{",
"return",
"false",
";",
"}",
"return",
"$",
"this",
"->",
"getName",
"(",
")",
"==",
"$",
"other",
"->",
"getName",
"(",
")",
";",
"}"
] | Implementing the compareTo abstract method. | [
"Implementing",
"the",
"compareTo",
"abstract",
"method",
"."
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Parsing/Nodes/VariableNode.php#L46-L56 |
mossadal/math-parser | src/MathParser/Parsing/Nodes/IntegerNode.php | IntegerNode.compareTo | public function compareTo($other)
{
if ($other === null) {
return false;
}
if ($other instanceof RationalNode) {
return $other->getDenominator() == 1 && $this->getValue() == $other->getNumerator();
}
if (!($other instanceof IntegerNode)) {
return false;
}
return $this->getValue() == $other->getValue();
} | php | public function compareTo($other)
{
if ($other === null) {
return false;
}
if ($other instanceof RationalNode) {
return $other->getDenominator() == 1 && $this->getValue() == $other->getNumerator();
}
if (!($other instanceof IntegerNode)) {
return false;
}
return $this->getValue() == $other->getValue();
} | [
"public",
"function",
"compareTo",
"(",
"$",
"other",
")",
"{",
"if",
"(",
"$",
"other",
"===",
"null",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"$",
"other",
"instanceof",
"RationalNode",
")",
"{",
"return",
"$",
"other",
"->",
"getDenominator",
"(",
")",
"==",
"1",
"&&",
"$",
"this",
"->",
"getValue",
"(",
")",
"==",
"$",
"other",
"->",
"getNumerator",
"(",
")",
";",
"}",
"if",
"(",
"!",
"(",
"$",
"other",
"instanceof",
"IntegerNode",
")",
")",
"{",
"return",
"false",
";",
"}",
"return",
"$",
"this",
"->",
"getValue",
"(",
")",
"==",
"$",
"other",
"->",
"getValue",
"(",
")",
";",
"}"
] | Implementing the compareTo abstract method. | [
"Implementing",
"the",
"compareTo",
"abstract",
"method",
"."
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Parsing/Nodes/IntegerNode.php#L58-L71 |
mossadal/math-parser | src/MathParser/Interpreting/LaTeXPrinter.php | LaTeXPrinter.visitExpressionNode | public function visitExpressionNode(ExpressionNode $node)
{
$operator = $node->getOperator();
$left = $node->getLeft();
$right = $node->getRight();
switch ($operator) {
case '+':
$leftValue = $left->accept($this);
$rightValue = $this->parenthesize($right, $node);
return "$leftValue+$rightValue";
case '-':
if ($right) {
// Binary minus
$leftValue = $left->accept($this);
$rightValue = $this->parenthesize($right, $node);
return "$leftValue-$rightValue";
} else {
// Unary minus
$leftValue = $this->parenthesize($left, $node);
return "-$leftValue";
}
case '*':
$operator = '';
if ($this->MultiplicationNeedsCdot($left, $right)) {
$operator = '\cdot ';
}
$leftValue = $this->parenthesize($left, $node);
$rightValue = $this->parenthesize($right, $node);
return "$leftValue$operator$rightValue";
case '/':
if ($this->solidus) {
$leftValue = $this->parenthesize($left, $node);
$rightValue = $this->parenthesize($right, $node);
return "$leftValue$operator$rightValue";
}
return '\frac{' . $left->accept($this) . '}{' . $right->accept($this) . '}';
case '^':
$leftValue = $this->parenthesize($left, $node, '', true);
// Typeset exponents with solidus
$this->solidus = true;
$result = $leftValue . '^' . $this->bracesNeeded($right);
$this->solidus = false;
return $result;
}
} | php | public function visitExpressionNode(ExpressionNode $node)
{
$operator = $node->getOperator();
$left = $node->getLeft();
$right = $node->getRight();
switch ($operator) {
case '+':
$leftValue = $left->accept($this);
$rightValue = $this->parenthesize($right, $node);
return "$leftValue+$rightValue";
case '-':
if ($right) {
// Binary minus
$leftValue = $left->accept($this);
$rightValue = $this->parenthesize($right, $node);
return "$leftValue-$rightValue";
} else {
// Unary minus
$leftValue = $this->parenthesize($left, $node);
return "-$leftValue";
}
case '*':
$operator = '';
if ($this->MultiplicationNeedsCdot($left, $right)) {
$operator = '\cdot ';
}
$leftValue = $this->parenthesize($left, $node);
$rightValue = $this->parenthesize($right, $node);
return "$leftValue$operator$rightValue";
case '/':
if ($this->solidus) {
$leftValue = $this->parenthesize($left, $node);
$rightValue = $this->parenthesize($right, $node);
return "$leftValue$operator$rightValue";
}
return '\frac{' . $left->accept($this) . '}{' . $right->accept($this) . '}';
case '^':
$leftValue = $this->parenthesize($left, $node, '', true);
// Typeset exponents with solidus
$this->solidus = true;
$result = $leftValue . '^' . $this->bracesNeeded($right);
$this->solidus = false;
return $result;
}
} | [
"public",
"function",
"visitExpressionNode",
"(",
"ExpressionNode",
"$",
"node",
")",
"{",
"$",
"operator",
"=",
"$",
"node",
"->",
"getOperator",
"(",
")",
";",
"$",
"left",
"=",
"$",
"node",
"->",
"getLeft",
"(",
")",
";",
"$",
"right",
"=",
"$",
"node",
"->",
"getRight",
"(",
")",
";",
"switch",
"(",
"$",
"operator",
")",
"{",
"case",
"'+'",
":",
"$",
"leftValue",
"=",
"$",
"left",
"->",
"accept",
"(",
"$",
"this",
")",
";",
"$",
"rightValue",
"=",
"$",
"this",
"->",
"parenthesize",
"(",
"$",
"right",
",",
"$",
"node",
")",
";",
"return",
"\"$leftValue+$rightValue\"",
";",
"case",
"'-'",
":",
"if",
"(",
"$",
"right",
")",
"{",
"// Binary minus",
"$",
"leftValue",
"=",
"$",
"left",
"->",
"accept",
"(",
"$",
"this",
")",
";",
"$",
"rightValue",
"=",
"$",
"this",
"->",
"parenthesize",
"(",
"$",
"right",
",",
"$",
"node",
")",
";",
"return",
"\"$leftValue-$rightValue\"",
";",
"}",
"else",
"{",
"// Unary minus",
"$",
"leftValue",
"=",
"$",
"this",
"->",
"parenthesize",
"(",
"$",
"left",
",",
"$",
"node",
")",
";",
"return",
"\"-$leftValue\"",
";",
"}",
"case",
"'*'",
":",
"$",
"operator",
"=",
"''",
";",
"if",
"(",
"$",
"this",
"->",
"MultiplicationNeedsCdot",
"(",
"$",
"left",
",",
"$",
"right",
")",
")",
"{",
"$",
"operator",
"=",
"'\\cdot '",
";",
"}",
"$",
"leftValue",
"=",
"$",
"this",
"->",
"parenthesize",
"(",
"$",
"left",
",",
"$",
"node",
")",
";",
"$",
"rightValue",
"=",
"$",
"this",
"->",
"parenthesize",
"(",
"$",
"right",
",",
"$",
"node",
")",
";",
"return",
"\"$leftValue$operator$rightValue\"",
";",
"case",
"'/'",
":",
"if",
"(",
"$",
"this",
"->",
"solidus",
")",
"{",
"$",
"leftValue",
"=",
"$",
"this",
"->",
"parenthesize",
"(",
"$",
"left",
",",
"$",
"node",
")",
";",
"$",
"rightValue",
"=",
"$",
"this",
"->",
"parenthesize",
"(",
"$",
"right",
",",
"$",
"node",
")",
";",
"return",
"\"$leftValue$operator$rightValue\"",
";",
"}",
"return",
"'\\frac{'",
".",
"$",
"left",
"->",
"accept",
"(",
"$",
"this",
")",
".",
"'}{'",
".",
"$",
"right",
"->",
"accept",
"(",
"$",
"this",
")",
".",
"'}'",
";",
"case",
"'^'",
":",
"$",
"leftValue",
"=",
"$",
"this",
"->",
"parenthesize",
"(",
"$",
"left",
",",
"$",
"node",
",",
"''",
",",
"true",
")",
";",
"// Typeset exponents with solidus",
"$",
"this",
"->",
"solidus",
"=",
"true",
";",
"$",
"result",
"=",
"$",
"leftValue",
".",
"'^'",
".",
"$",
"this",
"->",
"bracesNeeded",
"(",
"$",
"right",
")",
";",
"$",
"this",
"->",
"solidus",
"=",
"false",
";",
"return",
"$",
"result",
";",
"}",
"}"
] | Generate LaTeX code for an ExpressionNode
Create a string giving LaTeX code for an ExpressionNode `(x op y)`
where `op` is one of `+`, `-`, `*`, `/` or `^`
### Typesetting rules:
- Adds parentheses around each operand, if needed. (I.e. if their precedence
lower than that of the current Node.) For example, the AST `(^ (+ 1 2) 3)`
generates `(1+2)^3` but `(+ (^ 1 2) 3)` generates `1^2+3` as expected.
- Multiplications are typeset implicitly `(* x y)` returns `xy` or using
`\cdot` if the first factor is a FunctionNode or the (left operand) in the
second factor is a NumberNode, so `(* x 2)` return `x \cdot 2` and `(* (sin x) x)`
return `\sin x \cdot x` (but `(* x (sin x))` returns `x\sin x`)
- Divisions are typeset using `\frac`
- Exponentiation adds braces around the power when needed.
@retval string
@param ExpressionNode $node AST to be typeset | [
"Generate",
"LaTeX",
"code",
"for",
"an",
"ExpressionNode"
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Interpreting/LaTeXPrinter.php#L86-L146 |
mossadal/math-parser | src/MathParser/Interpreting/LaTeXPrinter.php | LaTeXPrinter.MultiplicationNeedsCdot | private function MultiplicationNeedsCdot($left, $right)
{
if ($left instanceof FunctionNode) {
return true;
}
if ($this->isNumeric($right)) {
return true;
}
if ($right instanceof ExpressionNode && $this->isNumeric($right->getLeft())) {
return true;
}
return false;
} | php | private function MultiplicationNeedsCdot($left, $right)
{
if ($left instanceof FunctionNode) {
return true;
}
if ($this->isNumeric($right)) {
return true;
}
if ($right instanceof ExpressionNode && $this->isNumeric($right->getLeft())) {
return true;
}
return false;
} | [
"private",
"function",
"MultiplicationNeedsCdot",
"(",
"$",
"left",
",",
"$",
"right",
")",
"{",
"if",
"(",
"$",
"left",
"instanceof",
"FunctionNode",
")",
"{",
"return",
"true",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"isNumeric",
"(",
"$",
"right",
")",
")",
"{",
"return",
"true",
";",
"}",
"if",
"(",
"$",
"right",
"instanceof",
"ExpressionNode",
"&&",
"$",
"this",
"->",
"isNumeric",
"(",
"$",
"right",
"->",
"getLeft",
"(",
")",
")",
")",
"{",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}"
] | Check if a multiplication needs an inserted \cdot or if
it can be safely written with implicit multiplication.
@retval bool
@param $left AST of first factor
@param $right AST of second factor | [
"Check",
"if",
"a",
"multiplication",
"needs",
"an",
"inserted",
"\\",
"cdot",
"or",
"if",
"it",
"can",
"be",
"safely",
"written",
"with",
"implicit",
"multiplication",
"."
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Interpreting/LaTeXPrinter.php#L156-L171 |
mossadal/math-parser | src/MathParser/Interpreting/LaTeXPrinter.php | LaTeXPrinter.visitFactorialNode | private function visitFactorialNode(FunctionNode $node)
{
$functionName = $node->getName();
$op = $node->getOperand();
$operand = $op->accept($this);
// Add parentheses most of the time.
if ($this->isNumeric($op)) {
if ($op->getValue() < 0) {
$operand = "($operand)";
}
} elseif ($op instanceof VariableNode || $op instanceof ConstantNode) {
// Do nothing
} else {
$operand = "($operand)";
}
return "$operand$functionName";
} | php | private function visitFactorialNode(FunctionNode $node)
{
$functionName = $node->getName();
$op = $node->getOperand();
$operand = $op->accept($this);
// Add parentheses most of the time.
if ($this->isNumeric($op)) {
if ($op->getValue() < 0) {
$operand = "($operand)";
}
} elseif ($op instanceof VariableNode || $op instanceof ConstantNode) {
// Do nothing
} else {
$operand = "($operand)";
}
return "$operand$functionName";
} | [
"private",
"function",
"visitFactorialNode",
"(",
"FunctionNode",
"$",
"node",
")",
"{",
"$",
"functionName",
"=",
"$",
"node",
"->",
"getName",
"(",
")",
";",
"$",
"op",
"=",
"$",
"node",
"->",
"getOperand",
"(",
")",
";",
"$",
"operand",
"=",
"$",
"op",
"->",
"accept",
"(",
"$",
"this",
")",
";",
"// Add parentheses most of the time.",
"if",
"(",
"$",
"this",
"->",
"isNumeric",
"(",
"$",
"op",
")",
")",
"{",
"if",
"(",
"$",
"op",
"->",
"getValue",
"(",
")",
"<",
"0",
")",
"{",
"$",
"operand",
"=",
"\"($operand)\"",
";",
"}",
"}",
"elseif",
"(",
"$",
"op",
"instanceof",
"VariableNode",
"||",
"$",
"op",
"instanceof",
"ConstantNode",
")",
"{",
"// Do nothing",
"}",
"else",
"{",
"$",
"operand",
"=",
"\"($operand)\"",
";",
"}",
"return",
"\"$operand$functionName\"",
";",
"}"
] | Generate LaTeX code for factorials
@retval string
@param FunctionNode $node AST to be typeset | [
"Generate",
"LaTeX",
"code",
"for",
"factorials"
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Interpreting/LaTeXPrinter.php#L232-L250 |
mossadal/math-parser | src/MathParser/Interpreting/LaTeXPrinter.php | LaTeXPrinter.visitFunctionNode | public function visitFunctionNode(FunctionNode $node)
{
$functionName = $node->getName();
$operand = $node->getOperand()->accept($this);
switch ($functionName) {
case 'sqrt':
return "\\$functionName{" . $node->getOperand()->accept($this) . '}';
case 'exp':
$operand = $node->getOperand();
if ($operand->complexity() < 10) {
$this->solidus = true;
$result = 'e^' . $this->bracesNeeded($operand);
$this->solidus = false;
return $result;
}
// Operand is complex, typset using \exp instead
return '\exp(' . $operand->accept($this) . ')';
case 'ln':
case 'log':
case 'sin':
case 'cos':
case 'tan':
case 'arcsin':
case 'arccos':
case 'arctan':
break;
case 'abs':
$operand = $node->getOperand();
return '\lvert ' . $operand->accept($this) . '\rvert ';
case '!':
case '!!':
return $this->visitFactorialNode($node);
default:
$functionName = 'operatorname{' . $functionName . '}';
}
return "\\$functionName($operand)";
} | php | public function visitFunctionNode(FunctionNode $node)
{
$functionName = $node->getName();
$operand = $node->getOperand()->accept($this);
switch ($functionName) {
case 'sqrt':
return "\\$functionName{" . $node->getOperand()->accept($this) . '}';
case 'exp':
$operand = $node->getOperand();
if ($operand->complexity() < 10) {
$this->solidus = true;
$result = 'e^' . $this->bracesNeeded($operand);
$this->solidus = false;
return $result;
}
// Operand is complex, typset using \exp instead
return '\exp(' . $operand->accept($this) . ')';
case 'ln':
case 'log':
case 'sin':
case 'cos':
case 'tan':
case 'arcsin':
case 'arccos':
case 'arctan':
break;
case 'abs':
$operand = $node->getOperand();
return '\lvert ' . $operand->accept($this) . '\rvert ';
case '!':
case '!!':
return $this->visitFactorialNode($node);
default:
$functionName = 'operatorname{' . $functionName . '}';
}
return "\\$functionName($operand)";
} | [
"public",
"function",
"visitFunctionNode",
"(",
"FunctionNode",
"$",
"node",
")",
"{",
"$",
"functionName",
"=",
"$",
"node",
"->",
"getName",
"(",
")",
";",
"$",
"operand",
"=",
"$",
"node",
"->",
"getOperand",
"(",
")",
"->",
"accept",
"(",
"$",
"this",
")",
";",
"switch",
"(",
"$",
"functionName",
")",
"{",
"case",
"'sqrt'",
":",
"return",
"\"\\\\$functionName{\"",
".",
"$",
"node",
"->",
"getOperand",
"(",
")",
"->",
"accept",
"(",
"$",
"this",
")",
".",
"'}'",
";",
"case",
"'exp'",
":",
"$",
"operand",
"=",
"$",
"node",
"->",
"getOperand",
"(",
")",
";",
"if",
"(",
"$",
"operand",
"->",
"complexity",
"(",
")",
"<",
"10",
")",
"{",
"$",
"this",
"->",
"solidus",
"=",
"true",
";",
"$",
"result",
"=",
"'e^'",
".",
"$",
"this",
"->",
"bracesNeeded",
"(",
"$",
"operand",
")",
";",
"$",
"this",
"->",
"solidus",
"=",
"false",
";",
"return",
"$",
"result",
";",
"}",
"// Operand is complex, typset using \\exp instead",
"return",
"'\\exp('",
".",
"$",
"operand",
"->",
"accept",
"(",
"$",
"this",
")",
".",
"')'",
";",
"case",
"'ln'",
":",
"case",
"'log'",
":",
"case",
"'sin'",
":",
"case",
"'cos'",
":",
"case",
"'tan'",
":",
"case",
"'arcsin'",
":",
"case",
"'arccos'",
":",
"case",
"'arctan'",
":",
"break",
";",
"case",
"'abs'",
":",
"$",
"operand",
"=",
"$",
"node",
"->",
"getOperand",
"(",
")",
";",
"return",
"'\\lvert '",
".",
"$",
"operand",
"->",
"accept",
"(",
"$",
"this",
")",
".",
"'\\rvert '",
";",
"case",
"'!'",
":",
"case",
"'!!'",
":",
"return",
"$",
"this",
"->",
"visitFactorialNode",
"(",
"$",
"node",
")",
";",
"default",
":",
"$",
"functionName",
"=",
"'operatorname{'",
".",
"$",
"functionName",
".",
"'}'",
";",
"}",
"return",
"\"\\\\$functionName($operand)\"",
";",
"}"
] | Generate LaTeX code for a FunctionNode
Create a string giving LaTeX code for a functionNode.
### Typesetting rules:
- `sqrt(op)` is typeset as `\sqrt{op}
- `exp(op)` is either typeset as `e^{op}`, if `op` is a simple
expression or as `\exp(op)` for more complicated operands.
@retval string
@param FunctionNode $node AST to be typeset | [
"Generate",
"LaTeX",
"code",
"for",
"a",
"FunctionNode"
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Interpreting/LaTeXPrinter.php#L267-L314 |
mossadal/math-parser | src/MathParser/Interpreting/LaTeXPrinter.php | LaTeXPrinter.parenthesize | public function parenthesize(Node $node, ExpressionNode $cutoff, $prepend = '', $conservative = false)
{
$text = $node->accept($this);
if ($node instanceof ExpressionNode) {
// Second term is a unary minus
if ($node->getOperator() == '-' && $node->getRight() == null) {
return "($text)";
}
if ($cutoff->getOperator() == '-' && $node->lowerPrecedenceThan($cutoff)) {
return "($text)";
}
if ($node->strictlyLowerPrecedenceThan($cutoff)) {
return "($text)";
}
if ($conservative) {
// Add parentheses more liberally for / and ^ operators,
// so that e.g. x/(y*z) is printed correctly
if ($cutoff->getOperator() == '/' && $node->lowerPrecedenceThan($cutoff)) {
return "($text)";
}
if ($cutoff->getOperator() == '^' && $node->getOperator() == '^') {
return '{' . $text . '}';
}
}
}
if ($this->isNumeric($node) && $node->getValue() < 0) {
return "($text)";
}
return "$prepend$text";
} | php | public function parenthesize(Node $node, ExpressionNode $cutoff, $prepend = '', $conservative = false)
{
$text = $node->accept($this);
if ($node instanceof ExpressionNode) {
// Second term is a unary minus
if ($node->getOperator() == '-' && $node->getRight() == null) {
return "($text)";
}
if ($cutoff->getOperator() == '-' && $node->lowerPrecedenceThan($cutoff)) {
return "($text)";
}
if ($node->strictlyLowerPrecedenceThan($cutoff)) {
return "($text)";
}
if ($conservative) {
// Add parentheses more liberally for / and ^ operators,
// so that e.g. x/(y*z) is printed correctly
if ($cutoff->getOperator() == '/' && $node->lowerPrecedenceThan($cutoff)) {
return "($text)";
}
if ($cutoff->getOperator() == '^' && $node->getOperator() == '^') {
return '{' . $text . '}';
}
}
}
if ($this->isNumeric($node) && $node->getValue() < 0) {
return "($text)";
}
return "$prepend$text";
} | [
"public",
"function",
"parenthesize",
"(",
"Node",
"$",
"node",
",",
"ExpressionNode",
"$",
"cutoff",
",",
"$",
"prepend",
"=",
"''",
",",
"$",
"conservative",
"=",
"false",
")",
"{",
"$",
"text",
"=",
"$",
"node",
"->",
"accept",
"(",
"$",
"this",
")",
";",
"if",
"(",
"$",
"node",
"instanceof",
"ExpressionNode",
")",
"{",
"// Second term is a unary minus",
"if",
"(",
"$",
"node",
"->",
"getOperator",
"(",
")",
"==",
"'-'",
"&&",
"$",
"node",
"->",
"getRight",
"(",
")",
"==",
"null",
")",
"{",
"return",
"\"($text)\"",
";",
"}",
"if",
"(",
"$",
"cutoff",
"->",
"getOperator",
"(",
")",
"==",
"'-'",
"&&",
"$",
"node",
"->",
"lowerPrecedenceThan",
"(",
"$",
"cutoff",
")",
")",
"{",
"return",
"\"($text)\"",
";",
"}",
"if",
"(",
"$",
"node",
"->",
"strictlyLowerPrecedenceThan",
"(",
"$",
"cutoff",
")",
")",
"{",
"return",
"\"($text)\"",
";",
"}",
"if",
"(",
"$",
"conservative",
")",
"{",
"// Add parentheses more liberally for / and ^ operators,",
"// so that e.g. x/(y*z) is printed correctly",
"if",
"(",
"$",
"cutoff",
"->",
"getOperator",
"(",
")",
"==",
"'/'",
"&&",
"$",
"node",
"->",
"lowerPrecedenceThan",
"(",
"$",
"cutoff",
")",
")",
"{",
"return",
"\"($text)\"",
";",
"}",
"if",
"(",
"$",
"cutoff",
"->",
"getOperator",
"(",
")",
"==",
"'^'",
"&&",
"$",
"node",
"->",
"getOperator",
"(",
")",
"==",
"'^'",
")",
"{",
"return",
"'{'",
".",
"$",
"text",
".",
"'}'",
";",
"}",
"}",
"}",
"if",
"(",
"$",
"this",
"->",
"isNumeric",
"(",
"$",
"node",
")",
"&&",
"$",
"node",
"->",
"getValue",
"(",
")",
"<",
"0",
")",
"{",
"return",
"\"($text)\"",
";",
"}",
"return",
"\"$prepend$text\"",
";",
"}"
] | Add parentheses to the LaTeX representation of $node if needed.
node. Operands with a lower precedence have parentheses
added.
be added at the beginning of the returned string.
@retval string
@param Node $node The AST to typeset
@param ExpressionNode $cutoff A token representing the precedence of the parent
@param bool $addSpace Flag determining whether an additional space should | [
"Add",
"parentheses",
"to",
"the",
"LaTeX",
"representation",
"of",
"$node",
"if",
"needed",
"."
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Interpreting/LaTeXPrinter.php#L355-L389 |
mossadal/math-parser | src/MathParser/Interpreting/LaTeXPrinter.php | LaTeXPrinter.bracesNeeded | public function bracesNeeded(Node $node)
{
if ($node instanceof VariableNode || $node instanceof ConstantNode) {
return $node->accept($this);
} elseif ($node instanceof IntegerNode && $node->getValue() >= 0 && $node->getValue() <= 9) {
return $node->accept($this);
} else {
return '{' . $node->accept($this) . '}';
}
} | php | public function bracesNeeded(Node $node)
{
if ($node instanceof VariableNode || $node instanceof ConstantNode) {
return $node->accept($this);
} elseif ($node instanceof IntegerNode && $node->getValue() >= 0 && $node->getValue() <= 9) {
return $node->accept($this);
} else {
return '{' . $node->accept($this) . '}';
}
} | [
"public",
"function",
"bracesNeeded",
"(",
"Node",
"$",
"node",
")",
"{",
"if",
"(",
"$",
"node",
"instanceof",
"VariableNode",
"||",
"$",
"node",
"instanceof",
"ConstantNode",
")",
"{",
"return",
"$",
"node",
"->",
"accept",
"(",
"$",
"this",
")",
";",
"}",
"elseif",
"(",
"$",
"node",
"instanceof",
"IntegerNode",
"&&",
"$",
"node",
"->",
"getValue",
"(",
")",
">=",
"0",
"&&",
"$",
"node",
"->",
"getValue",
"(",
")",
"<=",
"9",
")",
"{",
"return",
"$",
"node",
"->",
"accept",
"(",
"$",
"this",
")",
";",
"}",
"else",
"{",
"return",
"'{'",
".",
"$",
"node",
"->",
"accept",
"(",
"$",
"this",
")",
".",
"'}'",
";",
"}",
"}"
] | Add curly braces around the LaTex representation of $node if needed.
Nodes representing a single ConstantNode, VariableNode or NumberNodes (0--9)
are returned as-is. Other Nodes get curly braces around their LaTeX code.
@retval string
@param Node $node AST to parse | [
"Add",
"curly",
"braces",
"around",
"the",
"LaTex",
"representation",
"of",
"$node",
"if",
"needed",
"."
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Interpreting/LaTeXPrinter.php#L400-L409 |
mossadal/math-parser | src/MathParser/Interpreting/ASCIIPrinter.php | ASCIIPrinter.visitExpressionNode | public function visitExpressionNode(ExpressionNode $node)
{
$operator = $node->getOperator();
$left = $node->getLeft();
$right = $node->getRight();
switch ($operator) {
case '+':
$leftValue = $left->accept($this);
$rightValue = $this->parenthesize($right, $node);
return "$leftValue+$rightValue";
case '-':
if ($right) {
// Binary minus
$leftValue = $left->accept($this);
$rightValue = $this->parenthesize($right, $node);
return "$leftValue-$rightValue";
} else {
// Unary minus
$leftValue = $this->parenthesize($left, $node);
return "-$leftValue";
}
case '*':
case '/':
$leftValue = $this->parenthesize($left, $node, '', false);
$rightValue = $this->parenthesize($right, $node, '', true);
return "$leftValue$operator$rightValue";
case '^':
$leftValue = $this->parenthesize($left, $node, '', true);
$rightValue = $this->parenthesize($right, $node, '', false);
return "$leftValue$operator$rightValue";
}
} | php | public function visitExpressionNode(ExpressionNode $node)
{
$operator = $node->getOperator();
$left = $node->getLeft();
$right = $node->getRight();
switch ($operator) {
case '+':
$leftValue = $left->accept($this);
$rightValue = $this->parenthesize($right, $node);
return "$leftValue+$rightValue";
case '-':
if ($right) {
// Binary minus
$leftValue = $left->accept($this);
$rightValue = $this->parenthesize($right, $node);
return "$leftValue-$rightValue";
} else {
// Unary minus
$leftValue = $this->parenthesize($left, $node);
return "-$leftValue";
}
case '*':
case '/':
$leftValue = $this->parenthesize($left, $node, '', false);
$rightValue = $this->parenthesize($right, $node, '', true);
return "$leftValue$operator$rightValue";
case '^':
$leftValue = $this->parenthesize($left, $node, '', true);
$rightValue = $this->parenthesize($right, $node, '', false);
return "$leftValue$operator$rightValue";
}
} | [
"public",
"function",
"visitExpressionNode",
"(",
"ExpressionNode",
"$",
"node",
")",
"{",
"$",
"operator",
"=",
"$",
"node",
"->",
"getOperator",
"(",
")",
";",
"$",
"left",
"=",
"$",
"node",
"->",
"getLeft",
"(",
")",
";",
"$",
"right",
"=",
"$",
"node",
"->",
"getRight",
"(",
")",
";",
"switch",
"(",
"$",
"operator",
")",
"{",
"case",
"'+'",
":",
"$",
"leftValue",
"=",
"$",
"left",
"->",
"accept",
"(",
"$",
"this",
")",
";",
"$",
"rightValue",
"=",
"$",
"this",
"->",
"parenthesize",
"(",
"$",
"right",
",",
"$",
"node",
")",
";",
"return",
"\"$leftValue+$rightValue\"",
";",
"case",
"'-'",
":",
"if",
"(",
"$",
"right",
")",
"{",
"// Binary minus",
"$",
"leftValue",
"=",
"$",
"left",
"->",
"accept",
"(",
"$",
"this",
")",
";",
"$",
"rightValue",
"=",
"$",
"this",
"->",
"parenthesize",
"(",
"$",
"right",
",",
"$",
"node",
")",
";",
"return",
"\"$leftValue-$rightValue\"",
";",
"}",
"else",
"{",
"// Unary minus",
"$",
"leftValue",
"=",
"$",
"this",
"->",
"parenthesize",
"(",
"$",
"left",
",",
"$",
"node",
")",
";",
"return",
"\"-$leftValue\"",
";",
"}",
"case",
"'*'",
":",
"case",
"'/'",
":",
"$",
"leftValue",
"=",
"$",
"this",
"->",
"parenthesize",
"(",
"$",
"left",
",",
"$",
"node",
",",
"''",
",",
"false",
")",
";",
"$",
"rightValue",
"=",
"$",
"this",
"->",
"parenthesize",
"(",
"$",
"right",
",",
"$",
"node",
",",
"''",
",",
"true",
")",
";",
"return",
"\"$leftValue$operator$rightValue\"",
";",
"case",
"'^'",
":",
"$",
"leftValue",
"=",
"$",
"this",
"->",
"parenthesize",
"(",
"$",
"left",
",",
"$",
"node",
",",
"''",
",",
"true",
")",
";",
"$",
"rightValue",
"=",
"$",
"this",
"->",
"parenthesize",
"(",
"$",
"right",
",",
"$",
"node",
",",
"''",
",",
"false",
")",
";",
"return",
"\"$leftValue$operator$rightValue\"",
";",
"}",
"}"
] | Generate ASCII output code for an ExpressionNode
Create a string giving ASCII output representing an ExpressionNode `(x op y)`
where `op` is one of `+`, `-`, `*`, `/` or `^`
@retval string
@param ExpressionNode $node AST to be typeset | [
"Generate",
"ASCII",
"output",
"code",
"for",
"an",
"ExpressionNode"
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Interpreting/ASCIIPrinter.php#L69-L112 |
mossadal/math-parser | src/MathParser/Lexing/Token.php | Token.canFactorsInImplicitMultiplication | public static function canFactorsInImplicitMultiplication($token1, $token2)
{
if ($token1 === null || $token2 === null) return false;
$check1 = (
$token1->type == TokenType::PosInt ||
$token1->type == TokenType::Integer ||
$token1->type == TokenType::RealNumber ||
$token1->type == TokenType::Constant ||
$token1->type == TokenType::Identifier ||
$token1->type == TokenType::FunctionName ||
$token1->type == TokenType::CloseParenthesis ||
$token1->type == TokenType::FactorialOperator ||
$token1->type == TokenType::SemiFactorialOperator
);
if (!$check1) return false;
$check2 = (
$token2->type == TokenType::PosInt ||
$token2->type == TokenType::Integer ||
$token2->type == TokenType::RealNumber ||
$token2->type == TokenType::Constant ||
$token2->type == TokenType::Identifier ||
$token2->type == TokenType::FunctionName ||
$token2->type == TokenType::OpenParenthesis
);
if (!$check2) return false;
if ($token1->type == TokenType::FunctionName && $token2->type == TokenType::OpenParenthesis)
return false;
return true;
} | php | public static function canFactorsInImplicitMultiplication($token1, $token2)
{
if ($token1 === null || $token2 === null) return false;
$check1 = (
$token1->type == TokenType::PosInt ||
$token1->type == TokenType::Integer ||
$token1->type == TokenType::RealNumber ||
$token1->type == TokenType::Constant ||
$token1->type == TokenType::Identifier ||
$token1->type == TokenType::FunctionName ||
$token1->type == TokenType::CloseParenthesis ||
$token1->type == TokenType::FactorialOperator ||
$token1->type == TokenType::SemiFactorialOperator
);
if (!$check1) return false;
$check2 = (
$token2->type == TokenType::PosInt ||
$token2->type == TokenType::Integer ||
$token2->type == TokenType::RealNumber ||
$token2->type == TokenType::Constant ||
$token2->type == TokenType::Identifier ||
$token2->type == TokenType::FunctionName ||
$token2->type == TokenType::OpenParenthesis
);
if (!$check2) return false;
if ($token1->type == TokenType::FunctionName && $token2->type == TokenType::OpenParenthesis)
return false;
return true;
} | [
"public",
"static",
"function",
"canFactorsInImplicitMultiplication",
"(",
"$",
"token1",
",",
"$",
"token2",
")",
"{",
"if",
"(",
"$",
"token1",
"===",
"null",
"||",
"$",
"token2",
"===",
"null",
")",
"return",
"false",
";",
"$",
"check1",
"=",
"(",
"$",
"token1",
"->",
"type",
"==",
"TokenType",
"::",
"PosInt",
"||",
"$",
"token1",
"->",
"type",
"==",
"TokenType",
"::",
"Integer",
"||",
"$",
"token1",
"->",
"type",
"==",
"TokenType",
"::",
"RealNumber",
"||",
"$",
"token1",
"->",
"type",
"==",
"TokenType",
"::",
"Constant",
"||",
"$",
"token1",
"->",
"type",
"==",
"TokenType",
"::",
"Identifier",
"||",
"$",
"token1",
"->",
"type",
"==",
"TokenType",
"::",
"FunctionName",
"||",
"$",
"token1",
"->",
"type",
"==",
"TokenType",
"::",
"CloseParenthesis",
"||",
"$",
"token1",
"->",
"type",
"==",
"TokenType",
"::",
"FactorialOperator",
"||",
"$",
"token1",
"->",
"type",
"==",
"TokenType",
"::",
"SemiFactorialOperator",
")",
";",
"if",
"(",
"!",
"$",
"check1",
")",
"return",
"false",
";",
"$",
"check2",
"=",
"(",
"$",
"token2",
"->",
"type",
"==",
"TokenType",
"::",
"PosInt",
"||",
"$",
"token2",
"->",
"type",
"==",
"TokenType",
"::",
"Integer",
"||",
"$",
"token2",
"->",
"type",
"==",
"TokenType",
"::",
"RealNumber",
"||",
"$",
"token2",
"->",
"type",
"==",
"TokenType",
"::",
"Constant",
"||",
"$",
"token2",
"->",
"type",
"==",
"TokenType",
"::",
"Identifier",
"||",
"$",
"token2",
"->",
"type",
"==",
"TokenType",
"::",
"FunctionName",
"||",
"$",
"token2",
"->",
"type",
"==",
"TokenType",
"::",
"OpenParenthesis",
")",
";",
"if",
"(",
"!",
"$",
"check2",
")",
"return",
"false",
";",
"if",
"(",
"$",
"token1",
"->",
"type",
"==",
"TokenType",
"::",
"FunctionName",
"&&",
"$",
"token2",
"->",
"type",
"==",
"TokenType",
"::",
"OpenParenthesis",
")",
"return",
"false",
";",
"return",
"true",
";",
"}"
] | Helper function, determining whether a pair of tokens
can form an implicit multiplication.
Mathematical shorthand writing often leaves out explicit multiplication
symbols, writing "2x" instead of "2*x" or "2 \cdot x". The parser
accepts implicit multiplication if the first token is a nullary operator
or a a closing parenthesis, and the second token is a nullary operator
or an opening parenthesis. (Unless the first token is a a function name,
and the second is an opening parentheis.)
@retval boolean | [
"Helper",
"function",
"determining",
"whether",
"a",
"pair",
"of",
"tokens",
"can",
"form",
"an",
"implicit",
"multiplication",
"."
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Lexing/Token.php#L119-L153 |
mossadal/math-parser | src/MathParser/Extensions/Rational.php | Rational.normalize | private function normalize()
{
$gcd = Math::gcd($this->p, $this->q);
if ($gcd == 0) throw new DivisionByZeroException();
$this->p = $this->p/$gcd;
$this->q = $this->q/$gcd;
if ($this->q < 0) {
$this->p = -$this->p;
$this->q = -$this->q;
}
} | php | private function normalize()
{
$gcd = Math::gcd($this->p, $this->q);
if ($gcd == 0) throw new DivisionByZeroException();
$this->p = $this->p/$gcd;
$this->q = $this->q/$gcd;
if ($this->q < 0) {
$this->p = -$this->p;
$this->q = -$this->q;
}
} | [
"private",
"function",
"normalize",
"(",
")",
"{",
"$",
"gcd",
"=",
"Math",
"::",
"gcd",
"(",
"$",
"this",
"->",
"p",
",",
"$",
"this",
"->",
"q",
")",
";",
"if",
"(",
"$",
"gcd",
"==",
"0",
")",
"throw",
"new",
"DivisionByZeroException",
"(",
")",
";",
"$",
"this",
"->",
"p",
"=",
"$",
"this",
"->",
"p",
"/",
"$",
"gcd",
";",
"$",
"this",
"->",
"q",
"=",
"$",
"this",
"->",
"q",
"/",
"$",
"gcd",
";",
"if",
"(",
"$",
"this",
"->",
"q",
"<",
"0",
")",
"{",
"$",
"this",
"->",
"p",
"=",
"-",
"$",
"this",
"->",
"p",
";",
"$",
"this",
"->",
"q",
"=",
"-",
"$",
"this",
"->",
"q",
";",
"}",
"}"
] | Normalize, i.e. make sure the denominator is positive and that
the numerator and denominator have no common factors | [
"Normalize",
"i",
".",
"e",
".",
"make",
"sure",
"the",
"denominator",
"is",
"positive",
"and",
"that",
"the",
"numerator",
"and",
"denominator",
"have",
"no",
"common",
"factors"
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Extensions/Rational.php#L61-L74 |
mossadal/math-parser | src/MathParser/Extensions/Rational.php | Rational.add | public static function add($x, $y)
{
$X = static::parse($x);
$Y = static::parse($y);
$resp = $X->p * $Y->q + $X->q * $Y->p;
$resq = $X->q * $Y->q;
return new Rational($resp, $resq);
} | php | public static function add($x, $y)
{
$X = static::parse($x);
$Y = static::parse($y);
$resp = $X->p * $Y->q + $X->q * $Y->p;
$resq = $X->q * $Y->q;
return new Rational($resp, $resq);
} | [
"public",
"static",
"function",
"add",
"(",
"$",
"x",
",",
"$",
"y",
")",
"{",
"$",
"X",
"=",
"static",
"::",
"parse",
"(",
"$",
"x",
")",
";",
"$",
"Y",
"=",
"static",
"::",
"parse",
"(",
"$",
"y",
")",
";",
"$",
"resp",
"=",
"$",
"X",
"->",
"p",
"*",
"$",
"Y",
"->",
"q",
"+",
"$",
"X",
"->",
"q",
"*",
"$",
"Y",
"->",
"p",
";",
"$",
"resq",
"=",
"$",
"X",
"->",
"q",
"*",
"$",
"Y",
"->",
"q",
";",
"return",
"new",
"Rational",
"(",
"$",
"resp",
",",
"$",
"resq",
")",
";",
"}"
] | add two rational numbers
Rational::add($x, $y) computes and returns $x+$y
@param mixed $x (Rational, or parsable to Rational)
@param mixed $y (Rational, or parsable to Rational)
@retval Rational | [
"add",
"two",
"rational",
"numbers"
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Extensions/Rational.php#L86-L95 |
mossadal/math-parser | src/MathParser/Extensions/Rational.php | Rational.div | public static function div($x, $y)
{
$X = static::parse($x);
$Y = static::parse($y);
if ($Y->p == 0) throw new DivisionByZeroException();
$resp = $X->p * $Y->q;
$resq = $X->q * $Y->p;
return new Rational($resp, $resq);
} | php | public static function div($x, $y)
{
$X = static::parse($x);
$Y = static::parse($y);
if ($Y->p == 0) throw new DivisionByZeroException();
$resp = $X->p * $Y->q;
$resq = $X->q * $Y->p;
return new Rational($resp, $resq);
} | [
"public",
"static",
"function",
"div",
"(",
"$",
"x",
",",
"$",
"y",
")",
"{",
"$",
"X",
"=",
"static",
"::",
"parse",
"(",
"$",
"x",
")",
";",
"$",
"Y",
"=",
"static",
"::",
"parse",
"(",
"$",
"y",
")",
";",
"if",
"(",
"$",
"Y",
"->",
"p",
"==",
"0",
")",
"throw",
"new",
"DivisionByZeroException",
"(",
")",
";",
"$",
"resp",
"=",
"$",
"X",
"->",
"p",
"*",
"$",
"Y",
"->",
"q",
";",
"$",
"resq",
"=",
"$",
"X",
"->",
"q",
"*",
"$",
"Y",
"->",
"p",
";",
"return",
"new",
"Rational",
"(",
"$",
"resp",
",",
"$",
"resq",
")",
";",
"}"
] | add two rational numbers
Rational::div($x, $y) computes and returns $x/$y
@param mixed $x (Rational, or parsable to Rational)
@param mixed $y (Rational, or parsable to Rational)
@retval Rational | [
"add",
"two",
"rational",
"numbers"
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Extensions/Rational.php#L149-L160 |
mossadal/math-parser | src/MathParser/Extensions/Rational.php | Rational.signed | public function signed()
{
if ($this->q == 1) {
return sprintf("%+d", $this->p);
}
return sprintf("%+d/%d", $this->p, $this->q);
} | php | public function signed()
{
if ($this->q == 1) {
return sprintf("%+d", $this->p);
}
return sprintf("%+d/%d", $this->p, $this->q);
} | [
"public",
"function",
"signed",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"q",
"==",
"1",
")",
"{",
"return",
"sprintf",
"(",
"\"%+d\"",
",",
"$",
"this",
"->",
"p",
")",
";",
"}",
"return",
"sprintf",
"(",
"\"%+d/%d\"",
",",
"$",
"this",
"->",
"p",
",",
"$",
"this",
"->",
"q",
")",
";",
"}"
] | convert rational number to string, adding a '+' if the number is positive
@retval string | [
"convert",
"rational",
"number",
"to",
"string",
"adding",
"a",
"+",
"if",
"the",
"number",
"is",
"positive"
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Extensions/Rational.php#L167-L175 |
mossadal/math-parser | src/MathParser/Extensions/Rational.php | Rational.is_nan | public function is_nan()
{
if ($this->q == 0) return true;
return is_nan($this->p) || is_nan($this->q);
} | php | public function is_nan()
{
if ($this->q == 0) return true;
return is_nan($this->p) || is_nan($this->q);
} | [
"public",
"function",
"is_nan",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"q",
"==",
"0",
")",
"return",
"true",
";",
"return",
"is_nan",
"(",
"$",
"this",
"->",
"p",
")",
"||",
"is_nan",
"(",
"$",
"this",
"->",
"q",
")",
";",
"}"
] | test if the rational number is NAN
@retval bool | [
"test",
"if",
"the",
"rational",
"number",
"is",
"NAN"
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Extensions/Rational.php#L202-L206 |
mossadal/math-parser | src/MathParser/Extensions/Rational.php | Rational.parse | public static function parse($value, $normalize=true)
{
if ($value === '') return null;
if ($value === 'NAN') return new Rational(NAN, 1);
if ($value === 'INF') return new Rational(INF, 1);
if ($value === '-INF') return new Rational(-INF, 1);
$data = $value;
$numbers = explode('/', $data);
if (count($numbers) == 1) {
$p = static::isSignedInteger($numbers[0]) ? intval($numbers[0]) : NAN;
$q = 1;
}
elseif (count($numbers) != 2) {
$p = NAN;
$q = NAN;
}
else {
$p = static::isSignedInteger($numbers[0]) ? intval($numbers[0]) : NAN;
$q = static::isInteger($numbers[1]) ? intval($numbers[1]) : NAN;
}
if (is_nan($p) || is_nan($q)) throw new SyntaxErrorException();
return new Rational($p, $q, $normalize);
} | php | public static function parse($value, $normalize=true)
{
if ($value === '') return null;
if ($value === 'NAN') return new Rational(NAN, 1);
if ($value === 'INF') return new Rational(INF, 1);
if ($value === '-INF') return new Rational(-INF, 1);
$data = $value;
$numbers = explode('/', $data);
if (count($numbers) == 1) {
$p = static::isSignedInteger($numbers[0]) ? intval($numbers[0]) : NAN;
$q = 1;
}
elseif (count($numbers) != 2) {
$p = NAN;
$q = NAN;
}
else {
$p = static::isSignedInteger($numbers[0]) ? intval($numbers[0]) : NAN;
$q = static::isInteger($numbers[1]) ? intval($numbers[1]) : NAN;
}
if (is_nan($p) || is_nan($q)) throw new SyntaxErrorException();
return new Rational($p, $q, $normalize);
} | [
"public",
"static",
"function",
"parse",
"(",
"$",
"value",
",",
"$",
"normalize",
"=",
"true",
")",
"{",
"if",
"(",
"$",
"value",
"===",
"''",
")",
"return",
"null",
";",
"if",
"(",
"$",
"value",
"===",
"'NAN'",
")",
"return",
"new",
"Rational",
"(",
"NAN",
",",
"1",
")",
";",
"if",
"(",
"$",
"value",
"===",
"'INF'",
")",
"return",
"new",
"Rational",
"(",
"INF",
",",
"1",
")",
";",
"if",
"(",
"$",
"value",
"===",
"'-INF'",
")",
"return",
"new",
"Rational",
"(",
"-",
"INF",
",",
"1",
")",
";",
"$",
"data",
"=",
"$",
"value",
";",
"$",
"numbers",
"=",
"explode",
"(",
"'/'",
",",
"$",
"data",
")",
";",
"if",
"(",
"count",
"(",
"$",
"numbers",
")",
"==",
"1",
")",
"{",
"$",
"p",
"=",
"static",
"::",
"isSignedInteger",
"(",
"$",
"numbers",
"[",
"0",
"]",
")",
"?",
"intval",
"(",
"$",
"numbers",
"[",
"0",
"]",
")",
":",
"NAN",
";",
"$",
"q",
"=",
"1",
";",
"}",
"elseif",
"(",
"count",
"(",
"$",
"numbers",
")",
"!=",
"2",
")",
"{",
"$",
"p",
"=",
"NAN",
";",
"$",
"q",
"=",
"NAN",
";",
"}",
"else",
"{",
"$",
"p",
"=",
"static",
"::",
"isSignedInteger",
"(",
"$",
"numbers",
"[",
"0",
"]",
")",
"?",
"intval",
"(",
"$",
"numbers",
"[",
"0",
"]",
")",
":",
"NAN",
";",
"$",
"q",
"=",
"static",
"::",
"isInteger",
"(",
"$",
"numbers",
"[",
"1",
"]",
")",
"?",
"intval",
"(",
"$",
"numbers",
"[",
"1",
"]",
")",
":",
"NAN",
";",
"}",
"if",
"(",
"is_nan",
"(",
"$",
"p",
")",
"||",
"is_nan",
"(",
"$",
"q",
")",
")",
"throw",
"new",
"SyntaxErrorException",
"(",
")",
";",
"return",
"new",
"Rational",
"(",
"$",
"p",
",",
"$",
"q",
",",
"$",
"normalize",
")",
";",
"}"
] | Convert $value to Rational
@param $value mixed
@throws SyntaxErrorException
@retval Rational | [
"Convert",
"$value",
"to",
"Rational"
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Extensions/Rational.php#L215-L242 |
mossadal/math-parser | src/MathParser/Extensions/Rational.php | Rational.fromFloat | public static function fromFloat($float, $tolerance=1e-7)
{
if (is_string($float) && preg_match('~^\-?\d+([,|.]\d+)?$~', $float)) {
$float = floatval(str_replace(',','.',$float));
}
if ($float == 0.0) {
return new Rational(0,1);
}
$negative = ($float < 0);
if ($negative) {
$float = abs($float);
}
$num1 = 1;
$num2 = 0;
$den1 = 0;
$den2 = 1;
$oneOver = 1 / $float;
do {
$oneOver = 1 / $oneOver;
$floor = floor($oneOver);
$aux = $num1;
$num1 = $floor * $num1 + $num2;
$num2 = $aux;
$aux = $den1;
$den1 = $floor * $den1 + $den2;
$den2 = $aux;
$oneOver = $oneOver - $floor;
} while (abs($float - $num1 / $den1) > $float * $tolerance);
if ($negative) {
$num1 *= -1;
}
return new Rational(intval($num1), intval($den1));
} | php | public static function fromFloat($float, $tolerance=1e-7)
{
if (is_string($float) && preg_match('~^\-?\d+([,|.]\d+)?$~', $float)) {
$float = floatval(str_replace(',','.',$float));
}
if ($float == 0.0) {
return new Rational(0,1);
}
$negative = ($float < 0);
if ($negative) {
$float = abs($float);
}
$num1 = 1;
$num2 = 0;
$den1 = 0;
$den2 = 1;
$oneOver = 1 / $float;
do {
$oneOver = 1 / $oneOver;
$floor = floor($oneOver);
$aux = $num1;
$num1 = $floor * $num1 + $num2;
$num2 = $aux;
$aux = $den1;
$den1 = $floor * $den1 + $den2;
$den2 = $aux;
$oneOver = $oneOver - $floor;
} while (abs($float - $num1 / $den1) > $float * $tolerance);
if ($negative) {
$num1 *= -1;
}
return new Rational(intval($num1), intval($den1));
} | [
"public",
"static",
"function",
"fromFloat",
"(",
"$",
"float",
",",
"$",
"tolerance",
"=",
"1e-7",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"float",
")",
"&&",
"preg_match",
"(",
"'~^\\-?\\d+([,|.]\\d+)?$~'",
",",
"$",
"float",
")",
")",
"{",
"$",
"float",
"=",
"floatval",
"(",
"str_replace",
"(",
"','",
",",
"'.'",
",",
"$",
"float",
")",
")",
";",
"}",
"if",
"(",
"$",
"float",
"==",
"0.0",
")",
"{",
"return",
"new",
"Rational",
"(",
"0",
",",
"1",
")",
";",
"}",
"$",
"negative",
"=",
"(",
"$",
"float",
"<",
"0",
")",
";",
"if",
"(",
"$",
"negative",
")",
"{",
"$",
"float",
"=",
"abs",
"(",
"$",
"float",
")",
";",
"}",
"$",
"num1",
"=",
"1",
";",
"$",
"num2",
"=",
"0",
";",
"$",
"den1",
"=",
"0",
";",
"$",
"den2",
"=",
"1",
";",
"$",
"oneOver",
"=",
"1",
"/",
"$",
"float",
";",
"do",
"{",
"$",
"oneOver",
"=",
"1",
"/",
"$",
"oneOver",
";",
"$",
"floor",
"=",
"floor",
"(",
"$",
"oneOver",
")",
";",
"$",
"aux",
"=",
"$",
"num1",
";",
"$",
"num1",
"=",
"$",
"floor",
"*",
"$",
"num1",
"+",
"$",
"num2",
";",
"$",
"num2",
"=",
"$",
"aux",
";",
"$",
"aux",
"=",
"$",
"den1",
";",
"$",
"den1",
"=",
"$",
"floor",
"*",
"$",
"den1",
"+",
"$",
"den2",
";",
"$",
"den2",
"=",
"$",
"aux",
";",
"$",
"oneOver",
"=",
"$",
"oneOver",
"-",
"$",
"floor",
";",
"}",
"while",
"(",
"abs",
"(",
"$",
"float",
"-",
"$",
"num1",
"/",
"$",
"den1",
")",
">",
"$",
"float",
"*",
"$",
"tolerance",
")",
";",
"if",
"(",
"$",
"negative",
")",
"{",
"$",
"num1",
"*=",
"-",
"1",
";",
"}",
"return",
"new",
"Rational",
"(",
"intval",
"(",
"$",
"num1",
")",
",",
"intval",
"(",
"$",
"den1",
")",
")",
";",
"}"
] | convert float to Rational
Convert float to a continued fraction, with prescribed accuracy
@param string|float $float
@param float $tolerance
@retval Rational | [
"convert",
"float",
"to",
"Rational"
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Extensions/Rational.php#L253-L287 |
mossadal/math-parser | src/MathParser/Parsing/Nodes/ConstantNode.php | ConstantNode.compareTo | public function compareTo($other)
{
if ($other === null) {
return false;
}
if (!($other instanceof ConstantNode)) {
return false;
}
return $this->getName() == $other->getName();
} | php | public function compareTo($other)
{
if ($other === null) {
return false;
}
if (!($other instanceof ConstantNode)) {
return false;
}
return $this->getName() == $other->getName();
} | [
"public",
"function",
"compareTo",
"(",
"$",
"other",
")",
"{",
"if",
"(",
"$",
"other",
"===",
"null",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"!",
"(",
"$",
"other",
"instanceof",
"ConstantNode",
")",
")",
"{",
"return",
"false",
";",
"}",
"return",
"$",
"this",
"->",
"getName",
"(",
")",
"==",
"$",
"other",
"->",
"getName",
"(",
")",
";",
"}"
] | Implementing the compareTo abstract method. | [
"Implementing",
"the",
"compareTo",
"abstract",
"method",
"."
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Parsing/Nodes/ConstantNode.php#L61-L71 |
mossadal/math-parser | src/MathParser/Parsing/Nodes/Factories/AdditionNodeFactory.php | AdditionNodeFactory.makeNode | public function makeNode($leftOperand, $rightOperand)
{
$leftOperand = $this->sanitize($leftOperand);
$rightOperand = $this->sanitize($rightOperand);
$node = $this->numericTerms($leftOperand, $rightOperand);
if ($node) return $node;
return new ExpressionNode($leftOperand, '+', $rightOperand);
} | php | public function makeNode($leftOperand, $rightOperand)
{
$leftOperand = $this->sanitize($leftOperand);
$rightOperand = $this->sanitize($rightOperand);
$node = $this->numericTerms($leftOperand, $rightOperand);
if ($node) return $node;
return new ExpressionNode($leftOperand, '+', $rightOperand);
} | [
"public",
"function",
"makeNode",
"(",
"$",
"leftOperand",
",",
"$",
"rightOperand",
")",
"{",
"$",
"leftOperand",
"=",
"$",
"this",
"->",
"sanitize",
"(",
"$",
"leftOperand",
")",
";",
"$",
"rightOperand",
"=",
"$",
"this",
"->",
"sanitize",
"(",
"$",
"rightOperand",
")",
";",
"$",
"node",
"=",
"$",
"this",
"->",
"numericTerms",
"(",
"$",
"leftOperand",
",",
"$",
"rightOperand",
")",
";",
"if",
"(",
"$",
"node",
")",
"return",
"$",
"node",
";",
"return",
"new",
"ExpressionNode",
"(",
"$",
"leftOperand",
",",
"'+'",
",",
"$",
"rightOperand",
")",
";",
"}"
] | Create a Node representing 'leftOperand + rightOperand'
Using some simplification rules, create a NumberNode or ExpressionNode
giving an AST correctly representing 'leftOperand + rightOperand'.
### Simplification rules:
- To simplify the use of the function, convert integer or float params to NumberNodes
- If $leftOperand and $rightOperand are both NumberNodes, return a single NumberNode containing their sum
- If $leftOperand or $rightOperand are NumberNodes representing 0, return the other term unchanged
@param Node|int $leftOperand First term
@param Node|int $rightOperand Second term
@retval Node | [
"Create",
"a",
"Node",
"representing",
"leftOperand",
"+",
"rightOperand"
] | train | https://github.com/mossadal/math-parser/blob/1ef8217fe48c8a02fdf4ca6da4fa0561732981fb/src/MathParser/Parsing/Nodes/Factories/AdditionNodeFactory.php#L50-L59 |
TheDMSGroup/mautic-contact-client | Model/Attribution.php | Attribution.applyAttribution | public function applyAttribution()
{
$update = false;
$originalAttribution = $this->contact->getFieldValue('attribution');
$originalAttribution = !empty($originalAttribution) ? $originalAttribution : 0;
$attributionChange = 0;
if ($this->payloadModel) {
$jsonHelper = new JSONHelper();
$attributionSettings = $jsonHelper->decodeObject(
$this->contactClient->getAttributionSettings(),
'AttributionSettings'
);
if (
$attributionSettings
&& isset($attributionSettings->mode)
&& is_object($attributionSettings->mode)
&& !empty($attributionSettings->mode->key)
&& method_exists($this->payloadModel, 'getAggregateActualResponses')
) {
// Dynamic mode.
$key = $attributionSettings->mode->key;
// Attempt to get this field value from the response operations.
$responseFieldValue = $this->payloadModel->getAggregateActualResponses($key);
if (!empty($responseFieldValue) && is_numeric($responseFieldValue)) {
// We have a value, apply sign.
$sign = isset($attributionSettings->mode->sign) ? $attributionSettings->mode->sign : '+';
if ('+' == $sign) {
$attributionChange = abs($responseFieldValue);
} elseif ('-' == $sign) {
$attributionChange = abs($responseFieldValue) * -1;
} else {
$attributionChange = $responseFieldValue;
}
// Apply maths.
$math = isset($attributionSettings->mode->math) ? $attributionSettings->mode->math : null;
if ('/100' == $math) {
$attributionChange = $attributionChange / 100;
} elseif ('*100' == $math) {
$attributionChange = $attributionChange * 100;
}
$update = true;
}
}
}
// If we were not able to apply a dynamic cost/attribution, then fall back to the default (if set).
if (!$update) {
$attributionDefault = $this->contactClient->getAttributionDefault();
if (!empty($attributionDefault) && is_numeric($attributionDefault)) {
$attributionChange = $attributionDefault;
$update = true;
}
}
if ($update && $attributionChange) {
$this->attributionChange = $attributionChange;
$this->contact->addUpdatedField(
'attribution',
$originalAttribution + $attributionChange,
$originalAttribution
);
// Unsure if we should keep this next line for BC.
$this->contact->addUpdatedField('attribution_date', (new \DateTime())->format('Y-m-d H:i:s'));
}
return $update;
} | php | public function applyAttribution()
{
$update = false;
$originalAttribution = $this->contact->getFieldValue('attribution');
$originalAttribution = !empty($originalAttribution) ? $originalAttribution : 0;
$attributionChange = 0;
if ($this->payloadModel) {
$jsonHelper = new JSONHelper();
$attributionSettings = $jsonHelper->decodeObject(
$this->contactClient->getAttributionSettings(),
'AttributionSettings'
);
if (
$attributionSettings
&& isset($attributionSettings->mode)
&& is_object($attributionSettings->mode)
&& !empty($attributionSettings->mode->key)
&& method_exists($this->payloadModel, 'getAggregateActualResponses')
) {
// Dynamic mode.
$key = $attributionSettings->mode->key;
// Attempt to get this field value from the response operations.
$responseFieldValue = $this->payloadModel->getAggregateActualResponses($key);
if (!empty($responseFieldValue) && is_numeric($responseFieldValue)) {
// We have a value, apply sign.
$sign = isset($attributionSettings->mode->sign) ? $attributionSettings->mode->sign : '+';
if ('+' == $sign) {
$attributionChange = abs($responseFieldValue);
} elseif ('-' == $sign) {
$attributionChange = abs($responseFieldValue) * -1;
} else {
$attributionChange = $responseFieldValue;
}
// Apply maths.
$math = isset($attributionSettings->mode->math) ? $attributionSettings->mode->math : null;
if ('/100' == $math) {
$attributionChange = $attributionChange / 100;
} elseif ('*100' == $math) {
$attributionChange = $attributionChange * 100;
}
$update = true;
}
}
}
// If we were not able to apply a dynamic cost/attribution, then fall back to the default (if set).
if (!$update) {
$attributionDefault = $this->contactClient->getAttributionDefault();
if (!empty($attributionDefault) && is_numeric($attributionDefault)) {
$attributionChange = $attributionDefault;
$update = true;
}
}
if ($update && $attributionChange) {
$this->attributionChange = $attributionChange;
$this->contact->addUpdatedField(
'attribution',
$originalAttribution + $attributionChange,
$originalAttribution
);
// Unsure if we should keep this next line for BC.
$this->contact->addUpdatedField('attribution_date', (new \DateTime())->format('Y-m-d H:i:s'));
}
return $update;
} | [
"public",
"function",
"applyAttribution",
"(",
")",
"{",
"$",
"update",
"=",
"false",
";",
"$",
"originalAttribution",
"=",
"$",
"this",
"->",
"contact",
"->",
"getFieldValue",
"(",
"'attribution'",
")",
";",
"$",
"originalAttribution",
"=",
"!",
"empty",
"(",
"$",
"originalAttribution",
")",
"?",
"$",
"originalAttribution",
":",
"0",
";",
"$",
"attributionChange",
"=",
"0",
";",
"if",
"(",
"$",
"this",
"->",
"payloadModel",
")",
"{",
"$",
"jsonHelper",
"=",
"new",
"JSONHelper",
"(",
")",
";",
"$",
"attributionSettings",
"=",
"$",
"jsonHelper",
"->",
"decodeObject",
"(",
"$",
"this",
"->",
"contactClient",
"->",
"getAttributionSettings",
"(",
")",
",",
"'AttributionSettings'",
")",
";",
"if",
"(",
"$",
"attributionSettings",
"&&",
"isset",
"(",
"$",
"attributionSettings",
"->",
"mode",
")",
"&&",
"is_object",
"(",
"$",
"attributionSettings",
"->",
"mode",
")",
"&&",
"!",
"empty",
"(",
"$",
"attributionSettings",
"->",
"mode",
"->",
"key",
")",
"&&",
"method_exists",
"(",
"$",
"this",
"->",
"payloadModel",
",",
"'getAggregateActualResponses'",
")",
")",
"{",
"// Dynamic mode.",
"$",
"key",
"=",
"$",
"attributionSettings",
"->",
"mode",
"->",
"key",
";",
"// Attempt to get this field value from the response operations.",
"$",
"responseFieldValue",
"=",
"$",
"this",
"->",
"payloadModel",
"->",
"getAggregateActualResponses",
"(",
"$",
"key",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"responseFieldValue",
")",
"&&",
"is_numeric",
"(",
"$",
"responseFieldValue",
")",
")",
"{",
"// We have a value, apply sign.",
"$",
"sign",
"=",
"isset",
"(",
"$",
"attributionSettings",
"->",
"mode",
"->",
"sign",
")",
"?",
"$",
"attributionSettings",
"->",
"mode",
"->",
"sign",
":",
"'+'",
";",
"if",
"(",
"'+'",
"==",
"$",
"sign",
")",
"{",
"$",
"attributionChange",
"=",
"abs",
"(",
"$",
"responseFieldValue",
")",
";",
"}",
"elseif",
"(",
"'-'",
"==",
"$",
"sign",
")",
"{",
"$",
"attributionChange",
"=",
"abs",
"(",
"$",
"responseFieldValue",
")",
"*",
"-",
"1",
";",
"}",
"else",
"{",
"$",
"attributionChange",
"=",
"$",
"responseFieldValue",
";",
"}",
"// Apply maths.",
"$",
"math",
"=",
"isset",
"(",
"$",
"attributionSettings",
"->",
"mode",
"->",
"math",
")",
"?",
"$",
"attributionSettings",
"->",
"mode",
"->",
"math",
":",
"null",
";",
"if",
"(",
"'/100'",
"==",
"$",
"math",
")",
"{",
"$",
"attributionChange",
"=",
"$",
"attributionChange",
"/",
"100",
";",
"}",
"elseif",
"(",
"'*100'",
"==",
"$",
"math",
")",
"{",
"$",
"attributionChange",
"=",
"$",
"attributionChange",
"*",
"100",
";",
"}",
"$",
"update",
"=",
"true",
";",
"}",
"}",
"}",
"// If we were not able to apply a dynamic cost/attribution, then fall back to the default (if set).",
"if",
"(",
"!",
"$",
"update",
")",
"{",
"$",
"attributionDefault",
"=",
"$",
"this",
"->",
"contactClient",
"->",
"getAttributionDefault",
"(",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"attributionDefault",
")",
"&&",
"is_numeric",
"(",
"$",
"attributionDefault",
")",
")",
"{",
"$",
"attributionChange",
"=",
"$",
"attributionDefault",
";",
"$",
"update",
"=",
"true",
";",
"}",
"}",
"if",
"(",
"$",
"update",
"&&",
"$",
"attributionChange",
")",
"{",
"$",
"this",
"->",
"attributionChange",
"=",
"$",
"attributionChange",
";",
"$",
"this",
"->",
"contact",
"->",
"addUpdatedField",
"(",
"'attribution'",
",",
"$",
"originalAttribution",
"+",
"$",
"attributionChange",
",",
"$",
"originalAttribution",
")",
";",
"// Unsure if we should keep this next line for BC.",
"$",
"this",
"->",
"contact",
"->",
"addUpdatedField",
"(",
"'attribution_date'",
",",
"(",
"new",
"\\",
"DateTime",
"(",
")",
")",
"->",
"format",
"(",
"'Y-m-d H:i:s'",
")",
")",
";",
"}",
"return",
"$",
"update",
";",
"}"
] | Apply attribution to the current contact based on payload and settings of the Contact Client.
This assumes the Payload was successfully delivered (valid = true).
@return bool
@throws \Exception | [
"Apply",
"attribution",
"to",
"the",
"current",
"contact",
"based",
"on",
"payload",
"and",
"settings",
"of",
"the",
"Contact",
"Client",
".",
"This",
"assumes",
"the",
"Payload",
"was",
"successfully",
"delivered",
"(",
"valid",
"=",
"true",
")",
"."
] | train | https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Model/Attribution.php#L57-L127 |
TheDMSGroup/mautic-contact-client | Controller/FilesController.php | FilesController.fileAction | public function fileAction($objectId, $fileId)
{
if (empty($objectId) || empty($fileId)) {
return $this->accessDenied();
}
$contactClient = $this->checkContactClientAccess($objectId, 'view');
if ($contactClient instanceof Response) {
return $contactClient;
}
$file = $this->checkContactClientFileAccess($fileId, 'view');
if ($file instanceof Response) {
return $file;
}
if (!$file || !$file->getLocation() || !file_exists($file->getLocation())) {
return $this->accessDenied();
}
$response = new BinaryFileResponse($file->getLocation());
$response->setPrivate();
$response->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT);
return $response;
} | php | public function fileAction($objectId, $fileId)
{
if (empty($objectId) || empty($fileId)) {
return $this->accessDenied();
}
$contactClient = $this->checkContactClientAccess($objectId, 'view');
if ($contactClient instanceof Response) {
return $contactClient;
}
$file = $this->checkContactClientFileAccess($fileId, 'view');
if ($file instanceof Response) {
return $file;
}
if (!$file || !$file->getLocation() || !file_exists($file->getLocation())) {
return $this->accessDenied();
}
$response = new BinaryFileResponse($file->getLocation());
$response->setPrivate();
$response->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT);
return $response;
} | [
"public",
"function",
"fileAction",
"(",
"$",
"objectId",
",",
"$",
"fileId",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"objectId",
")",
"||",
"empty",
"(",
"$",
"fileId",
")",
")",
"{",
"return",
"$",
"this",
"->",
"accessDenied",
"(",
")",
";",
"}",
"$",
"contactClient",
"=",
"$",
"this",
"->",
"checkContactClientAccess",
"(",
"$",
"objectId",
",",
"'view'",
")",
";",
"if",
"(",
"$",
"contactClient",
"instanceof",
"Response",
")",
"{",
"return",
"$",
"contactClient",
";",
"}",
"$",
"file",
"=",
"$",
"this",
"->",
"checkContactClientFileAccess",
"(",
"$",
"fileId",
",",
"'view'",
")",
";",
"if",
"(",
"$",
"file",
"instanceof",
"Response",
")",
"{",
"return",
"$",
"file",
";",
"}",
"if",
"(",
"!",
"$",
"file",
"||",
"!",
"$",
"file",
"->",
"getLocation",
"(",
")",
"||",
"!",
"file_exists",
"(",
"$",
"file",
"->",
"getLocation",
"(",
")",
")",
")",
"{",
"return",
"$",
"this",
"->",
"accessDenied",
"(",
")",
";",
"}",
"$",
"response",
"=",
"new",
"BinaryFileResponse",
"(",
"$",
"file",
"->",
"getLocation",
"(",
")",
")",
";",
"$",
"response",
"->",
"setPrivate",
"(",
")",
";",
"$",
"response",
"->",
"setContentDisposition",
"(",
"ResponseHeaderBag",
"::",
"DISPOSITION_ATTACHMENT",
")",
";",
"return",
"$",
"response",
";",
"}"
] | Downloads a file securely.
@param null $contactClientId
@param null $fileId
@return array|\MauticPlugin\MauticContactClientBundle\Entity\ContactClient|BinaryFileResponse|\Symfony\Component\HttpFoundation\JsonResponse|\Symfony\Component\HttpFoundation\RedirectResponse
@throws \Exception | [
"Downloads",
"a",
"file",
"securely",
"."
] | train | https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Controller/FilesController.php#L75-L100 |
TheDMSGroup/mautic-contact-client | Event/ContactClientTimelineEvent.php | ContactClientTimelineEvent.addEvent | public function addEvent(array $data)
{
if ($this->countOnly) {
// BC support for old format
if ($this->groupUnit && $this->chartQuery) {
$countData = [
[
'date' => $data['timestamp'],
'count' => 1,
],
];
$count = $this->chartQuery->completeTimeData($countData);
$this->addToCounter($data['event'], $count);
} else {
if (!isset($this->totalEvents[$data['event']])) {
$this->totalEvents[$data['event']] = 0;
}
++$this->totalEvents[$data['event']];
}
} else {
if (!isset($this->events[$data['event']])) {
$this->events[$data['event']] = [];
}
if (!$this->isForTimeline()) {
// standardize the payload
$keepThese = [
'event' => true,
'eventId' => true,
'eventLabel' => true,
'eventType' => true,
'timestamp' => true,
'message' => true,
'integratonEntityId' => true,
'contactId' => true,
'extra' => true,
];
$data = array_intersect_key($data, $keepThese);
// Rename extra to details
if (isset($data['extra'])) {
$data['details'] = $data['extra'];
$data['details'] = $this->prepareDetailsForAPI($data['details']);
unset($data['extra']);
}
// Ensure a full URL
if ($this->siteDomain && isset($data['eventLabel']) && is_array(
$data['eventLabel']
) && isset($data['eventLabel']['href'])) {
// If this does not have a http, then assume a Mautic URL
if (false === strpos($data['eventLabel']['href'], '://')) {
$data['eventLabel']['href'] = $this->siteDomain.$data['eventLabel']['href'];
}
}
}
if (empty($data['eventId'])) {
// Every entry should have an eventId so generate one if the listener itself didn't handle this
$data['eventId'] = $this->generateEventId($data);
}
$this->events[$data['event']][] = $data;
}
} | php | public function addEvent(array $data)
{
if ($this->countOnly) {
// BC support for old format
if ($this->groupUnit && $this->chartQuery) {
$countData = [
[
'date' => $data['timestamp'],
'count' => 1,
],
];
$count = $this->chartQuery->completeTimeData($countData);
$this->addToCounter($data['event'], $count);
} else {
if (!isset($this->totalEvents[$data['event']])) {
$this->totalEvents[$data['event']] = 0;
}
++$this->totalEvents[$data['event']];
}
} else {
if (!isset($this->events[$data['event']])) {
$this->events[$data['event']] = [];
}
if (!$this->isForTimeline()) {
// standardize the payload
$keepThese = [
'event' => true,
'eventId' => true,
'eventLabel' => true,
'eventType' => true,
'timestamp' => true,
'message' => true,
'integratonEntityId' => true,
'contactId' => true,
'extra' => true,
];
$data = array_intersect_key($data, $keepThese);
// Rename extra to details
if (isset($data['extra'])) {
$data['details'] = $data['extra'];
$data['details'] = $this->prepareDetailsForAPI($data['details']);
unset($data['extra']);
}
// Ensure a full URL
if ($this->siteDomain && isset($data['eventLabel']) && is_array(
$data['eventLabel']
) && isset($data['eventLabel']['href'])) {
// If this does not have a http, then assume a Mautic URL
if (false === strpos($data['eventLabel']['href'], '://')) {
$data['eventLabel']['href'] = $this->siteDomain.$data['eventLabel']['href'];
}
}
}
if (empty($data['eventId'])) {
// Every entry should have an eventId so generate one if the listener itself didn't handle this
$data['eventId'] = $this->generateEventId($data);
}
$this->events[$data['event']][] = $data;
}
} | [
"public",
"function",
"addEvent",
"(",
"array",
"$",
"data",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"countOnly",
")",
"{",
"// BC support for old format",
"if",
"(",
"$",
"this",
"->",
"groupUnit",
"&&",
"$",
"this",
"->",
"chartQuery",
")",
"{",
"$",
"countData",
"=",
"[",
"[",
"'date'",
"=>",
"$",
"data",
"[",
"'timestamp'",
"]",
",",
"'count'",
"=>",
"1",
",",
"]",
",",
"]",
";",
"$",
"count",
"=",
"$",
"this",
"->",
"chartQuery",
"->",
"completeTimeData",
"(",
"$",
"countData",
")",
";",
"$",
"this",
"->",
"addToCounter",
"(",
"$",
"data",
"[",
"'event'",
"]",
",",
"$",
"count",
")",
";",
"}",
"else",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"totalEvents",
"[",
"$",
"data",
"[",
"'event'",
"]",
"]",
")",
")",
"{",
"$",
"this",
"->",
"totalEvents",
"[",
"$",
"data",
"[",
"'event'",
"]",
"]",
"=",
"0",
";",
"}",
"++",
"$",
"this",
"->",
"totalEvents",
"[",
"$",
"data",
"[",
"'event'",
"]",
"]",
";",
"}",
"}",
"else",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"events",
"[",
"$",
"data",
"[",
"'event'",
"]",
"]",
")",
")",
"{",
"$",
"this",
"->",
"events",
"[",
"$",
"data",
"[",
"'event'",
"]",
"]",
"=",
"[",
"]",
";",
"}",
"if",
"(",
"!",
"$",
"this",
"->",
"isForTimeline",
"(",
")",
")",
"{",
"// standardize the payload",
"$",
"keepThese",
"=",
"[",
"'event'",
"=>",
"true",
",",
"'eventId'",
"=>",
"true",
",",
"'eventLabel'",
"=>",
"true",
",",
"'eventType'",
"=>",
"true",
",",
"'timestamp'",
"=>",
"true",
",",
"'message'",
"=>",
"true",
",",
"'integratonEntityId'",
"=>",
"true",
",",
"'contactId'",
"=>",
"true",
",",
"'extra'",
"=>",
"true",
",",
"]",
";",
"$",
"data",
"=",
"array_intersect_key",
"(",
"$",
"data",
",",
"$",
"keepThese",
")",
";",
"// Rename extra to details",
"if",
"(",
"isset",
"(",
"$",
"data",
"[",
"'extra'",
"]",
")",
")",
"{",
"$",
"data",
"[",
"'details'",
"]",
"=",
"$",
"data",
"[",
"'extra'",
"]",
";",
"$",
"data",
"[",
"'details'",
"]",
"=",
"$",
"this",
"->",
"prepareDetailsForAPI",
"(",
"$",
"data",
"[",
"'details'",
"]",
")",
";",
"unset",
"(",
"$",
"data",
"[",
"'extra'",
"]",
")",
";",
"}",
"// Ensure a full URL",
"if",
"(",
"$",
"this",
"->",
"siteDomain",
"&&",
"isset",
"(",
"$",
"data",
"[",
"'eventLabel'",
"]",
")",
"&&",
"is_array",
"(",
"$",
"data",
"[",
"'eventLabel'",
"]",
")",
"&&",
"isset",
"(",
"$",
"data",
"[",
"'eventLabel'",
"]",
"[",
"'href'",
"]",
")",
")",
"{",
"// If this does not have a http, then assume a Mautic URL",
"if",
"(",
"false",
"===",
"strpos",
"(",
"$",
"data",
"[",
"'eventLabel'",
"]",
"[",
"'href'",
"]",
",",
"'://'",
")",
")",
"{",
"$",
"data",
"[",
"'eventLabel'",
"]",
"[",
"'href'",
"]",
"=",
"$",
"this",
"->",
"siteDomain",
".",
"$",
"data",
"[",
"'eventLabel'",
"]",
"[",
"'href'",
"]",
";",
"}",
"}",
"}",
"if",
"(",
"empty",
"(",
"$",
"data",
"[",
"'eventId'",
"]",
")",
")",
"{",
"// Every entry should have an eventId so generate one if the listener itself didn't handle this",
"$",
"data",
"[",
"'eventId'",
"]",
"=",
"$",
"this",
"->",
"generateEventId",
"(",
"$",
"data",
")",
";",
"}",
"$",
"this",
"->",
"events",
"[",
"$",
"data",
"[",
"'event'",
"]",
"]",
"[",
"]",
"=",
"$",
"data",
";",
"}",
"}"
] | Add an event to the container.
The data should be an associative array with the following data:
'event' => string The event name
'timestamp' => \DateTime The timestamp of the event
'extra' => array An optional array of extra data for the event
@param array $data Data array for the table | [
"Add",
"an",
"event",
"to",
"the",
"container",
"."
] | train | https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Event/ContactClientTimelineEvent.php#L187-L253 |
TheDMSGroup/mautic-contact-client | Event/ContactClientTimelineEvent.php | ContactClientTimelineEvent.addToCounter | public function addToCounter($eventType, $count)
{
if (!isset($this->totalEvents[$eventType])) {
$this->totalEvents[$eventType] = 0;
}
if (is_array($count)) {
if (isset($count['total'])) {
$this->totalEvents[$eventType] += $count['total'];
} elseif ($this->isEngagementCount() && $this->groupUnit) {
// Group counts across events by unit
foreach ($count as $key => $data) {
if (!isset($this->totalEventsByUnit[$key])) {
$this->totalEventsByUnit[$key] = 0;
}
$this->totalEventsByUnit[$key] += (int) $data;
$this->totalEvents[$eventType] += (int) $data;
}
} else {
$this->totalEvents[$eventType] = array_sum($count);
}
} else {
$this->totalEvents[$eventType] += (int) $count;
}
} | php | public function addToCounter($eventType, $count)
{
if (!isset($this->totalEvents[$eventType])) {
$this->totalEvents[$eventType] = 0;
}
if (is_array($count)) {
if (isset($count['total'])) {
$this->totalEvents[$eventType] += $count['total'];
} elseif ($this->isEngagementCount() && $this->groupUnit) {
// Group counts across events by unit
foreach ($count as $key => $data) {
if (!isset($this->totalEventsByUnit[$key])) {
$this->totalEventsByUnit[$key] = 0;
}
$this->totalEventsByUnit[$key] += (int) $data;
$this->totalEvents[$eventType] += (int) $data;
}
} else {
$this->totalEvents[$eventType] = array_sum($count);
}
} else {
$this->totalEvents[$eventType] += (int) $count;
}
} | [
"public",
"function",
"addToCounter",
"(",
"$",
"eventType",
",",
"$",
"count",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"totalEvents",
"[",
"$",
"eventType",
"]",
")",
")",
"{",
"$",
"this",
"->",
"totalEvents",
"[",
"$",
"eventType",
"]",
"=",
"0",
";",
"}",
"if",
"(",
"is_array",
"(",
"$",
"count",
")",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"count",
"[",
"'total'",
"]",
")",
")",
"{",
"$",
"this",
"->",
"totalEvents",
"[",
"$",
"eventType",
"]",
"+=",
"$",
"count",
"[",
"'total'",
"]",
";",
"}",
"elseif",
"(",
"$",
"this",
"->",
"isEngagementCount",
"(",
")",
"&&",
"$",
"this",
"->",
"groupUnit",
")",
"{",
"// Group counts across events by unit",
"foreach",
"(",
"$",
"count",
"as",
"$",
"key",
"=>",
"$",
"data",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"totalEventsByUnit",
"[",
"$",
"key",
"]",
")",
")",
"{",
"$",
"this",
"->",
"totalEventsByUnit",
"[",
"$",
"key",
"]",
"=",
"0",
";",
"}",
"$",
"this",
"->",
"totalEventsByUnit",
"[",
"$",
"key",
"]",
"+=",
"(",
"int",
")",
"$",
"data",
";",
"$",
"this",
"->",
"totalEvents",
"[",
"$",
"eventType",
"]",
"+=",
"(",
"int",
")",
"$",
"data",
";",
"}",
"}",
"else",
"{",
"$",
"this",
"->",
"totalEvents",
"[",
"$",
"eventType",
"]",
"=",
"array_sum",
"(",
"$",
"count",
")",
";",
"}",
"}",
"else",
"{",
"$",
"this",
"->",
"totalEvents",
"[",
"$",
"eventType",
"]",
"+=",
"(",
"int",
")",
"$",
"count",
";",
"}",
"}"
] | Add to the event counters.
@param int|array $count | [
"Add",
"to",
"the",
"event",
"counters",
"."
] | train | https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Event/ContactClientTimelineEvent.php#L260-L284 |
TheDMSGroup/mautic-contact-client | Event/ContactClientTimelineEvent.php | ContactClientTimelineEvent.getEvents | public function getEvents()
{
if (empty($this->events)) {
return [];
}
$events = call_user_func_array('array_merge', $this->events);
foreach ($events as &$e) {
if (!$e['timestamp'] instanceof \DateTime) {
$dt = new DateTimeHelper($e['timestamp'], 'Y-m-d H:i:s', 'UTC');
$e['timestamp'] = $dt->getDateTime();
unset($dt);
}
}
if (!empty($this->orderBy)) {
usort(
$events,
function ($a, $b) {
switch ($this->orderBy[0]) {
case 'eventLabel':
$aLabel = '';
if (isset($a['eventLabel'])) {
$aLabel = (is_array($a['eventLabel'])) ? $a['eventLabel']['label'] : $a['eventLabel'];
}
$bLabel = '';
if (isset($b['eventLabel'])) {
$bLabel = (is_array($b['eventLabel'])) ? $b['eventLabel']['label'] : $b['eventLabel'];
}
return strnatcmp($aLabel, $bLabel);
case 'date_added':
if ($a['timestamp'] == $b['timestamp']) {
$aPriority = isset($a['eventPriority']) ? (int) $a['eventPriority'] : 0;
$bPriority = isset($b['eventPriority']) ? (int) $b['eventPriority'] : 0;
return $aPriority - $bPriority;
}
return $a['timestamp'] < $b['timestamp'] ? -1 : 1;
case 'contact_id':
if ($a['contactId'] == $b['contactId']) {
return 0;
}
return $a['contactId'] < $b['contactId'] ? -1 : 1;
case 'type':
return strnatcmp($a['eventType'], $b['eventType']);
default:
return strnatcmp($a[$this->orderBy[0]], $b[$this->orderBy[0]]);
}
}
);
if ('DESC' == $this->orderBy[1]) {
$events = array_reverse($events);
}
}
return $events;
} | php | public function getEvents()
{
if (empty($this->events)) {
return [];
}
$events = call_user_func_array('array_merge', $this->events);
foreach ($events as &$e) {
if (!$e['timestamp'] instanceof \DateTime) {
$dt = new DateTimeHelper($e['timestamp'], 'Y-m-d H:i:s', 'UTC');
$e['timestamp'] = $dt->getDateTime();
unset($dt);
}
}
if (!empty($this->orderBy)) {
usort(
$events,
function ($a, $b) {
switch ($this->orderBy[0]) {
case 'eventLabel':
$aLabel = '';
if (isset($a['eventLabel'])) {
$aLabel = (is_array($a['eventLabel'])) ? $a['eventLabel']['label'] : $a['eventLabel'];
}
$bLabel = '';
if (isset($b['eventLabel'])) {
$bLabel = (is_array($b['eventLabel'])) ? $b['eventLabel']['label'] : $b['eventLabel'];
}
return strnatcmp($aLabel, $bLabel);
case 'date_added':
if ($a['timestamp'] == $b['timestamp']) {
$aPriority = isset($a['eventPriority']) ? (int) $a['eventPriority'] : 0;
$bPriority = isset($b['eventPriority']) ? (int) $b['eventPriority'] : 0;
return $aPriority - $bPriority;
}
return $a['timestamp'] < $b['timestamp'] ? -1 : 1;
case 'contact_id':
if ($a['contactId'] == $b['contactId']) {
return 0;
}
return $a['contactId'] < $b['contactId'] ? -1 : 1;
case 'type':
return strnatcmp($a['eventType'], $b['eventType']);
default:
return strnatcmp($a[$this->orderBy[0]], $b[$this->orderBy[0]]);
}
}
);
if ('DESC' == $this->orderBy[1]) {
$events = array_reverse($events);
}
}
return $events;
} | [
"public",
"function",
"getEvents",
"(",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"this",
"->",
"events",
")",
")",
"{",
"return",
"[",
"]",
";",
"}",
"$",
"events",
"=",
"call_user_func_array",
"(",
"'array_merge'",
",",
"$",
"this",
"->",
"events",
")",
";",
"foreach",
"(",
"$",
"events",
"as",
"&",
"$",
"e",
")",
"{",
"if",
"(",
"!",
"$",
"e",
"[",
"'timestamp'",
"]",
"instanceof",
"\\",
"DateTime",
")",
"{",
"$",
"dt",
"=",
"new",
"DateTimeHelper",
"(",
"$",
"e",
"[",
"'timestamp'",
"]",
",",
"'Y-m-d H:i:s'",
",",
"'UTC'",
")",
";",
"$",
"e",
"[",
"'timestamp'",
"]",
"=",
"$",
"dt",
"->",
"getDateTime",
"(",
")",
";",
"unset",
"(",
"$",
"dt",
")",
";",
"}",
"}",
"if",
"(",
"!",
"empty",
"(",
"$",
"this",
"->",
"orderBy",
")",
")",
"{",
"usort",
"(",
"$",
"events",
",",
"function",
"(",
"$",
"a",
",",
"$",
"b",
")",
"{",
"switch",
"(",
"$",
"this",
"->",
"orderBy",
"[",
"0",
"]",
")",
"{",
"case",
"'eventLabel'",
":",
"$",
"aLabel",
"=",
"''",
";",
"if",
"(",
"isset",
"(",
"$",
"a",
"[",
"'eventLabel'",
"]",
")",
")",
"{",
"$",
"aLabel",
"=",
"(",
"is_array",
"(",
"$",
"a",
"[",
"'eventLabel'",
"]",
")",
")",
"?",
"$",
"a",
"[",
"'eventLabel'",
"]",
"[",
"'label'",
"]",
":",
"$",
"a",
"[",
"'eventLabel'",
"]",
";",
"}",
"$",
"bLabel",
"=",
"''",
";",
"if",
"(",
"isset",
"(",
"$",
"b",
"[",
"'eventLabel'",
"]",
")",
")",
"{",
"$",
"bLabel",
"=",
"(",
"is_array",
"(",
"$",
"b",
"[",
"'eventLabel'",
"]",
")",
")",
"?",
"$",
"b",
"[",
"'eventLabel'",
"]",
"[",
"'label'",
"]",
":",
"$",
"b",
"[",
"'eventLabel'",
"]",
";",
"}",
"return",
"strnatcmp",
"(",
"$",
"aLabel",
",",
"$",
"bLabel",
")",
";",
"case",
"'date_added'",
":",
"if",
"(",
"$",
"a",
"[",
"'timestamp'",
"]",
"==",
"$",
"b",
"[",
"'timestamp'",
"]",
")",
"{",
"$",
"aPriority",
"=",
"isset",
"(",
"$",
"a",
"[",
"'eventPriority'",
"]",
")",
"?",
"(",
"int",
")",
"$",
"a",
"[",
"'eventPriority'",
"]",
":",
"0",
";",
"$",
"bPriority",
"=",
"isset",
"(",
"$",
"b",
"[",
"'eventPriority'",
"]",
")",
"?",
"(",
"int",
")",
"$",
"b",
"[",
"'eventPriority'",
"]",
":",
"0",
";",
"return",
"$",
"aPriority",
"-",
"$",
"bPriority",
";",
"}",
"return",
"$",
"a",
"[",
"'timestamp'",
"]",
"<",
"$",
"b",
"[",
"'timestamp'",
"]",
"?",
"-",
"1",
":",
"1",
";",
"case",
"'contact_id'",
":",
"if",
"(",
"$",
"a",
"[",
"'contactId'",
"]",
"==",
"$",
"b",
"[",
"'contactId'",
"]",
")",
"{",
"return",
"0",
";",
"}",
"return",
"$",
"a",
"[",
"'contactId'",
"]",
"<",
"$",
"b",
"[",
"'contactId'",
"]",
"?",
"-",
"1",
":",
"1",
";",
"case",
"'type'",
":",
"return",
"strnatcmp",
"(",
"$",
"a",
"[",
"'eventType'",
"]",
",",
"$",
"b",
"[",
"'eventType'",
"]",
")",
";",
"default",
":",
"return",
"strnatcmp",
"(",
"$",
"a",
"[",
"$",
"this",
"->",
"orderBy",
"[",
"0",
"]",
"]",
",",
"$",
"b",
"[",
"$",
"this",
"->",
"orderBy",
"[",
"0",
"]",
"]",
")",
";",
"}",
"}",
")",
";",
"if",
"(",
"'DESC'",
"==",
"$",
"this",
"->",
"orderBy",
"[",
"1",
"]",
")",
"{",
"$",
"events",
"=",
"array_reverse",
"(",
"$",
"events",
")",
";",
"}",
"}",
"return",
"$",
"events",
";",
"}"
] | Fetch the events.
@return array Events sorted by timestamp with most recent event first | [
"Fetch",
"the",
"events",
"."
] | train | https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Event/ContactClientTimelineEvent.php#L353-L421 |
TheDMSGroup/mautic-contact-client | Event/ContactClientTimelineEvent.php | ContactClientTimelineEvent.getEventLimit | public function getEventLimit()
{
return [
'contactClientId' => ($this->contactClient instanceof ContactClient) ? $this->contactClient->getId() : null,
'limit' => $this->limit,
'start' => (1 >= $this->page) ? 0 : ($this->page - 1) * $this->limit,
];
} | php | public function getEventLimit()
{
return [
'contactClientId' => ($this->contactClient instanceof ContactClient) ? $this->contactClient->getId() : null,
'limit' => $this->limit,
'start' => (1 >= $this->page) ? 0 : ($this->page - 1) * $this->limit,
];
} | [
"public",
"function",
"getEventLimit",
"(",
")",
"{",
"return",
"[",
"'contactClientId'",
"=>",
"(",
"$",
"this",
"->",
"contactClient",
"instanceof",
"ContactClient",
")",
"?",
"$",
"this",
"->",
"contactClient",
"->",
"getId",
"(",
")",
":",
"null",
",",
"'limit'",
"=>",
"$",
"this",
"->",
"limit",
",",
"'start'",
"=>",
"(",
"1",
">=",
"$",
"this",
"->",
"page",
")",
"?",
"0",
":",
"(",
"$",
"this",
"->",
"page",
"-",
"1",
")",
"*",
"$",
"this",
"->",
"limit",
",",
"]",
";",
"}"
] | Fetch start/limit for queries.
@return array | [
"Fetch",
"start",
"/",
"limit",
"for",
"queries",
"."
] | train | https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Event/ContactClientTimelineEvent.php#L499-L506 |
TheDMSGroup/mautic-contact-client | Event/ContactClientTimelineEvent.php | ContactClientTimelineEvent.getEventCounter | public function getEventCounter()
{
// BC support for old formats
foreach ($this->events as $type => $events) {
if (!isset($this->totalEvents[$type])) {
$this->totalEvents[$type] = count($events);
}
}
$counter = [
'total' => array_sum($this->totalEvents),
];
if ($this->countOnly && $this->groupUnit) {
$counter['byUnit'] = $this->totalEventsByUnit;
}
return $counter;
} | php | public function getEventCounter()
{
// BC support for old formats
foreach ($this->events as $type => $events) {
if (!isset($this->totalEvents[$type])) {
$this->totalEvents[$type] = count($events);
}
}
$counter = [
'total' => array_sum($this->totalEvents),
];
if ($this->countOnly && $this->groupUnit) {
$counter['byUnit'] = $this->totalEventsByUnit;
}
return $counter;
} | [
"public",
"function",
"getEventCounter",
"(",
")",
"{",
"// BC support for old formats",
"foreach",
"(",
"$",
"this",
"->",
"events",
"as",
"$",
"type",
"=>",
"$",
"events",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"totalEvents",
"[",
"$",
"type",
"]",
")",
")",
"{",
"$",
"this",
"->",
"totalEvents",
"[",
"$",
"type",
"]",
"=",
"count",
"(",
"$",
"events",
")",
";",
"}",
"}",
"$",
"counter",
"=",
"[",
"'total'",
"=>",
"array_sum",
"(",
"$",
"this",
"->",
"totalEvents",
")",
",",
"]",
";",
"if",
"(",
"$",
"this",
"->",
"countOnly",
"&&",
"$",
"this",
"->",
"groupUnit",
")",
"{",
"$",
"counter",
"[",
"'byUnit'",
"]",
"=",
"$",
"this",
"->",
"totalEventsByUnit",
";",
"}",
"return",
"$",
"counter",
";",
"}"
] | Get total number of events for pagination. | [
"Get",
"total",
"number",
"of",
"events",
"for",
"pagination",
"."
] | train | https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Event/ContactClientTimelineEvent.php#L566-L584 |
TheDMSGroup/mautic-contact-client | Event/ContactClientTimelineEvent.php | ContactClientTimelineEvent.setCountOnly | public function setCountOnly(
\DateTime $dateFrom,
\DateTime $dateTo,
$groupUnit = '',
ChartQuery $chartQuery = null
) {
$this->countOnly = true;
$this->dateFrom = $dateFrom;
$this->dateTo = $dateTo;
$this->groupUnit = $groupUnit;
$this->chartQuery = $chartQuery;
} | php | public function setCountOnly(
\DateTime $dateFrom,
\DateTime $dateTo,
$groupUnit = '',
ChartQuery $chartQuery = null
) {
$this->countOnly = true;
$this->dateFrom = $dateFrom;
$this->dateTo = $dateTo;
$this->groupUnit = $groupUnit;
$this->chartQuery = $chartQuery;
} | [
"public",
"function",
"setCountOnly",
"(",
"\\",
"DateTime",
"$",
"dateFrom",
",",
"\\",
"DateTime",
"$",
"dateTo",
",",
"$",
"groupUnit",
"=",
"''",
",",
"ChartQuery",
"$",
"chartQuery",
"=",
"null",
")",
"{",
"$",
"this",
"->",
"countOnly",
"=",
"true",
";",
"$",
"this",
"->",
"dateFrom",
"=",
"$",
"dateFrom",
";",
"$",
"this",
"->",
"dateTo",
"=",
"$",
"dateTo",
";",
"$",
"this",
"->",
"groupUnit",
"=",
"$",
"groupUnit",
";",
"$",
"this",
"->",
"chartQuery",
"=",
"$",
"chartQuery",
";",
"}"
] | Calculate engagement counts only.
@param \DateTime $dateFrom
@param \DateTime $dateTo
@param string $groupUnit
@param ChartQuery|null $chartQuery | [
"Calculate",
"engagement",
"counts",
"only",
"."
] | train | https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Event/ContactClientTimelineEvent.php#L605-L616 |
TheDMSGroup/mautic-contact-client | Event/ContactClientTimelineEvent.php | ContactClientTimelineEvent.addSerializerGroup | public function addSerializerGroup($group)
{
if (is_array($group)) {
$this->serializerGroups = array_merge(
$this->serializerGroups,
$group
);
} else {
$this->serializerGroups[$group] = $group;
}
} | php | public function addSerializerGroup($group)
{
if (is_array($group)) {
$this->serializerGroups = array_merge(
$this->serializerGroups,
$group
);
} else {
$this->serializerGroups[$group] = $group;
}
} | [
"public",
"function",
"addSerializerGroup",
"(",
"$",
"group",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"group",
")",
")",
"{",
"$",
"this",
"->",
"serializerGroups",
"=",
"array_merge",
"(",
"$",
"this",
"->",
"serializerGroups",
",",
"$",
"group",
")",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"serializerGroups",
"[",
"$",
"group",
"]",
"=",
"$",
"group",
";",
"}",
"}"
] | Add a serializer group for API formatting.
@param $group | [
"Add",
"a",
"serializer",
"group",
"for",
"API",
"formatting",
"."
] | train | https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Event/ContactClientTimelineEvent.php#L633-L643 |
TheDMSGroup/mautic-contact-client | Helper/TokenHelper.php | TokenHelper.addHelper | private function addHelper($type)
{
switch ($type) {
case 'number':
if (!$this->engine->hasHelper('lpad')) {
$this->engine->addHelper(
'lpad',
[
'2' => function ($value) {
return str_pad((string) $value, 2, '0', STR_PAD_LEFT);
},
'4' => function ($value) {
return str_pad((string) $value, 4, '0', STR_PAD_LEFT);
},
]
);
}
if (!$this->engine->hasHelper('rpad')) {
$this->engine->addHelper(
'rpad',
[
'2' => function ($value) {
return str_pad((string) $value, 2, '0', STR_PAD_RIGHT);
},
'4' => function ($value) {
return str_pad((string) $value, 4, '0', STR_PAD_RIGHT);
},
]
);
}
break;
case 'date':
// If there are new timezones, recreate the helper.
if (
!$this->engine->hasHelper('date')
|| ($this->engine->hasHelper('date')
&& (
$this->timezoneSource !== $this->dateFormatHelper->getTimezoneSource()
|| $this->timezoneDestination !== $this->dateFormatHelper->getTimezoneDestination()
)
)
) {
$this->dateFormatHelper = new DateFormatHelper($this->timezoneSource, $this->timezoneDestination);
$this->engine->addHelper('date', $this->dateFormatHelper);
}
break;
case 'boolean':
if (!$this->engine->hasHelper('bool')) {
$this->engine->addHelper(
'bool',
[
'YesNo' => function ($value) {
return $value ? 'Yes' : 'No';
},
'YESNO' => function ($value) {
return $value ? 'YES' : 'NO';
},
'yesno' => function ($value) {
return $value ? 'yes' : 'no';
},
'YN' => function ($value) {
return $value ? 'Y' : 'N';
},
'yn' => function ($value) {
return $value ? 'y' : 'n';
},
'10' => function ($value) {
return $value ? '1' : '0';
},
'TrueFalse' => function ($value) {
return $value ? 'True' : 'False';
},
'TRUEFALSE' => function ($value) {
return $value ? 'TRUE' : 'FALSE';
},
'truefalse' => function ($value) {
return $value ? 'true' : 'false';
},
'TF' => function ($value) {
return $value ? 'T' : 'F';
},
'tf' => function ($value) {
return $value ? 't' : 'f';
},
]
);
}
break;
case 'string':
case 'text':
if (!$this->engine->hasHelper('zip')) {
$this->engine->addHelper(
'zip',
[
'short' => function ($value) {
$dash = strpos((string) $value, '-');
return $dash ? substr((string) $value, 0, $dash) : $value;
},
]
);
}
if (!$this->engine->hasHelper('trim')) {
$this->engine->addHelper(
'trim',
[
'ws' => function ($value) {
return trim((string) $value);
},
'255' => function ($value) {
if (strlen((string) $value) > 255) {
$value = trim($value);
}
return substr((string) $value, 0, 255);
},
'65535' => function ($value) {
if (strlen((string) $value) > 255) {
$value = trim($value);
}
return substr((string) $value, 0, 255);
},
]
);
}
if (!$this->engine->hasHelper('strip')) {
$this->engine->addHelper(
'strip',
[
'comma' => function ($value) {
return str_replace(',', '', $value);
},
'doublequote' => function ($value) {
return str_replace('"', '', $value);
},
'singlequote' => function ($value) {
return str_replace("'", '', $value);
},
'html' => function ($value) {
return strip_tags($value);
},
// Not currently documented (will not show up in suggestions).
'nonascii' => function ($value) {
return utf8_strip_non_ascii($value);
},
'nonnumeric' => function ($value) {
return preg_replace('/[^0-9,.]/', '', $value);
},
'numeric' => function ($value) {
return preg_replace('/[0-9]+/', '', $value);
},
]
);
}
if (!$this->engine->hasHelper('case')) {
$this->engine->addHelper(
'case',
[
'first' => function ($value) {
return utf8_ucfirst($value);
},
'lower' => function ($value) {
return utf8_strtolower($value);
},
'upper' => function ($value) {
return utf8_strtoupper($value);
},
]
);
}
if (!$this->engine->hasHelper('url')) {
$this->engine->addHelper(
'url',
[
// Not currently documented (will not show up in suggestions).
'decode' => function ($value) {
return rawurldecode($value);
},
'encode' => function ($value) {
return rawurlencode($value);
},
]
);
}
if (!$this->engine->hasHelper('tel')) {
$this->engine->addHelper(
'tel',
[
'10' => function ($value) {
$phone = trim($value);
if (!empty($value)) {
if (!$this->phoneHelper) {
$this->phoneHelper = new PhoneNumberHelper();
}
try {
$phone = $this->phoneHelper->format($phone);
if (!empty($phone)) {
// 12223334444
$value = substr($phone, -10);
}
} catch (\Exception $e) {
}
}
return $value;
},
'area' => function ($value) {
$phone = trim($value);
if (!empty($value)) {
if (!$this->phoneHelper) {
$this->phoneHelper = new PhoneNumberHelper();
}
try {
$phone = $this->phoneHelper->format($phone);
if (!empty($phone)) {
// 222
$value = substr($phone, -10, 3);
}
} catch (\Exception $e) {
}
}
return $value;
},
'area2' => function ($value) {
$phone = trim($value);
if (!empty($value)) {
if (!$this->phoneHelper) {
$this->phoneHelper = new PhoneNumberHelper();
}
try {
$phone = $this->phoneHelper->format($phone);
if (!empty($phone)) {
// 222
$value = '('.substr($phone, -10, 3).')';
}
} catch (\Exception $e) {
}
}
return $value;
},
'7' => function ($value) {
$phone = trim($value);
if (!empty($value)) {
if (!$this->phoneHelper) {
$this->phoneHelper = new PhoneNumberHelper();
}
try {
$phone = $this->phoneHelper->format($phone);
if (!empty($phone)) {
// 3334444
$value = substr($phone, -7);
}
} catch (\Exception $e) {
}
}
return $value;
},
'lpar2' => function ($value) {
$phone = trim($value);
if (!empty($value)) {
if (!$this->phoneHelper) {
$this->phoneHelper = new PhoneNumberHelper();
}
try {
$phone = $this->phoneHelper->format($phone);
if (!empty($phone)) {
// (222)333-4444
$value = '('.substr($phone, -10, 3).')'
.substr($phone, -8, 3).'-'
.substr($phone, -4, 4);
}
} catch (\Exception $e) {
}
}
return $value;
},
'inum' => function ($value) {
$phone = trim($value);
if (!empty($value)) {
if (!$this->phoneHelper) {
$this->phoneHelper = new PhoneNumberHelper();
}
try {
$phone = $this->phoneHelper->format($phone);
if (!empty($phone)) {
// 12223334444
$value = substr($phone, 1);
}
} catch (\Exception $e) {
}
}
return $value;
},
'country' => function ($value) {
$phone = trim($value);
if (!empty($value)) {
if (!$this->phoneHelper) {
$this->phoneHelper = new PhoneNumberHelper();
}
try {
$phone = $this->phoneHelper->format($phone);
if (!empty($phone)) {
// 1
$value = substr($phone, 1, strlen($phone) - 10);
}
} catch (\Exception $e) {
}
}
return $value;
},
'country2' => function ($value) {
$phone = trim($value);
if (!empty($value)) {
if (!$this->phoneHelper) {
$this->phoneHelper = new PhoneNumberHelper();
}
try {
$phone = $this->phoneHelper->format($phone);
if (!empty($phone)) {
// +1
$value = substr($phone, 0, strlen($phone) - 10);
}
} catch (\Exception $e) {
}
}
return $value;
},
'e164' => function ($value) {
$phone = trim($value);
if (!empty($value)) {
if (!$this->phoneHelper) {
$this->phoneHelper = new PhoneNumberHelper();
}
try {
$phone = $this->phoneHelper->format($phone);
if (!empty($phone)) {
// +12223334444
$value = $phone;
}
} catch (\Exception $e) {
}
}
return $value;
},
'idash' => function ($value) {
$phone = trim($value);
if (!empty($value)) {
if (!$this->phoneHelper) {
$this->phoneHelper = new PhoneNumberHelper();
}
try {
$phone = $this->phoneHelper->format($phone);
if (!empty($phone)) {
// 1-222-333-4444
$value = substr($phone, 1, strlen($phone) - 10).'-'
.substr($phone, -10, 3).'-'
.substr($phone, -7, 3).'-'
.substr($phone, -4, 4);
}
} catch (\Exception $e) {
}
}
return $value;
},
'ldash' => function ($value) {
$phone = trim($value);
if (!empty($value)) {
if (!$this->phoneHelper) {
$this->phoneHelper = new PhoneNumberHelper();
}
try {
$phone = $this->phoneHelper->format($phone);
if (!empty($phone)) {
// 222-333-4444
$value = substr($phone, -10, 3).'-'
.substr($phone, -7, 3).'-'
.substr($phone, -4, 4);
}
} catch (\Exception $e) {
}
}
return $value;
},
'ipar' => function ($value) {
$phone = trim($value);
if (!empty($value)) {
if (!$this->phoneHelper) {
$this->phoneHelper = new PhoneNumberHelper();
}
try {
$phone = $this->phoneHelper->format($phone);
if (!empty($phone)) {
// 1 (222) 333-4444
$value = substr($phone, 1, strlen($phone) - 10).
' ('.substr($phone, -10, 3).') '
.substr($phone, -8, 3).'-'
.substr($phone, -4, 4);
}
} catch (\Exception $e) {
}
}
return $value;
},
'lpar' => function ($value) {
$phone = trim($value);
if (!empty($value)) {
if (!$this->phoneHelper) {
$this->phoneHelper = new PhoneNumberHelper();
}
try {
$phone = $this->phoneHelper->format($phone);
if (!empty($phone)) {
// (222) 333-4444
$value = '('.substr($phone, -10, 3).') '
.substr($phone, -7, 3).'-'
.substr($phone, -4, 4);
}
} catch (\Exception $e) {
}
}
return $value;
},
'idot' => function ($value) {
$phone = trim($value);
if (!empty($value)) {
if (!$this->phoneHelper) {
$this->phoneHelper = new PhoneNumberHelper();
}
try {
$phone = $this->phoneHelper->format($phone);
if (!empty($phone)) {
// 1.222.333.4444
$value = substr($phone, 1, strlen($phone) - 10).'.'
.substr($phone, -10, 3).'.'
.substr($phone, -7, 3).'.'
.substr($phone, -4, 4);
}
} catch (\Exception $e) {
}
}
return $value;
},
'ldot' => function ($value) {
$phone = trim($value);
if (!empty($value)) {
if (!$this->phoneHelper) {
$this->phoneHelper = new PhoneNumberHelper();
}
try {
$phone = $this->phoneHelper->format($phone);
if (!empty($phone)) {
// 222.333.4444
$value = substr($phone, -10, 3).'.'
.substr($phone, -7, 3).'.'
.substr($phone, -4, 4);
}
} catch (\Exception $e) {
}
}
return $value;
},
]
);
}
break;
}
} | php | private function addHelper($type)
{
switch ($type) {
case 'number':
if (!$this->engine->hasHelper('lpad')) {
$this->engine->addHelper(
'lpad',
[
'2' => function ($value) {
return str_pad((string) $value, 2, '0', STR_PAD_LEFT);
},
'4' => function ($value) {
return str_pad((string) $value, 4, '0', STR_PAD_LEFT);
},
]
);
}
if (!$this->engine->hasHelper('rpad')) {
$this->engine->addHelper(
'rpad',
[
'2' => function ($value) {
return str_pad((string) $value, 2, '0', STR_PAD_RIGHT);
},
'4' => function ($value) {
return str_pad((string) $value, 4, '0', STR_PAD_RIGHT);
},
]
);
}
break;
case 'date':
// If there are new timezones, recreate the helper.
if (
!$this->engine->hasHelper('date')
|| ($this->engine->hasHelper('date')
&& (
$this->timezoneSource !== $this->dateFormatHelper->getTimezoneSource()
|| $this->timezoneDestination !== $this->dateFormatHelper->getTimezoneDestination()
)
)
) {
$this->dateFormatHelper = new DateFormatHelper($this->timezoneSource, $this->timezoneDestination);
$this->engine->addHelper('date', $this->dateFormatHelper);
}
break;
case 'boolean':
if (!$this->engine->hasHelper('bool')) {
$this->engine->addHelper(
'bool',
[
'YesNo' => function ($value) {
return $value ? 'Yes' : 'No';
},
'YESNO' => function ($value) {
return $value ? 'YES' : 'NO';
},
'yesno' => function ($value) {
return $value ? 'yes' : 'no';
},
'YN' => function ($value) {
return $value ? 'Y' : 'N';
},
'yn' => function ($value) {
return $value ? 'y' : 'n';
},
'10' => function ($value) {
return $value ? '1' : '0';
},
'TrueFalse' => function ($value) {
return $value ? 'True' : 'False';
},
'TRUEFALSE' => function ($value) {
return $value ? 'TRUE' : 'FALSE';
},
'truefalse' => function ($value) {
return $value ? 'true' : 'false';
},
'TF' => function ($value) {
return $value ? 'T' : 'F';
},
'tf' => function ($value) {
return $value ? 't' : 'f';
},
]
);
}
break;
case 'string':
case 'text':
if (!$this->engine->hasHelper('zip')) {
$this->engine->addHelper(
'zip',
[
'short' => function ($value) {
$dash = strpos((string) $value, '-');
return $dash ? substr((string) $value, 0, $dash) : $value;
},
]
);
}
if (!$this->engine->hasHelper('trim')) {
$this->engine->addHelper(
'trim',
[
'ws' => function ($value) {
return trim((string) $value);
},
'255' => function ($value) {
if (strlen((string) $value) > 255) {
$value = trim($value);
}
return substr((string) $value, 0, 255);
},
'65535' => function ($value) {
if (strlen((string) $value) > 255) {
$value = trim($value);
}
return substr((string) $value, 0, 255);
},
]
);
}
if (!$this->engine->hasHelper('strip')) {
$this->engine->addHelper(
'strip',
[
'comma' => function ($value) {
return str_replace(',', '', $value);
},
'doublequote' => function ($value) {
return str_replace('"', '', $value);
},
'singlequote' => function ($value) {
return str_replace("'", '', $value);
},
'html' => function ($value) {
return strip_tags($value);
},
// Not currently documented (will not show up in suggestions).
'nonascii' => function ($value) {
return utf8_strip_non_ascii($value);
},
'nonnumeric' => function ($value) {
return preg_replace('/[^0-9,.]/', '', $value);
},
'numeric' => function ($value) {
return preg_replace('/[0-9]+/', '', $value);
},
]
);
}
if (!$this->engine->hasHelper('case')) {
$this->engine->addHelper(
'case',
[
'first' => function ($value) {
return utf8_ucfirst($value);
},
'lower' => function ($value) {
return utf8_strtolower($value);
},
'upper' => function ($value) {
return utf8_strtoupper($value);
},
]
);
}
if (!$this->engine->hasHelper('url')) {
$this->engine->addHelper(
'url',
[
// Not currently documented (will not show up in suggestions).
'decode' => function ($value) {
return rawurldecode($value);
},
'encode' => function ($value) {
return rawurlencode($value);
},
]
);
}
if (!$this->engine->hasHelper('tel')) {
$this->engine->addHelper(
'tel',
[
'10' => function ($value) {
$phone = trim($value);
if (!empty($value)) {
if (!$this->phoneHelper) {
$this->phoneHelper = new PhoneNumberHelper();
}
try {
$phone = $this->phoneHelper->format($phone);
if (!empty($phone)) {
// 12223334444
$value = substr($phone, -10);
}
} catch (\Exception $e) {
}
}
return $value;
},
'area' => function ($value) {
$phone = trim($value);
if (!empty($value)) {
if (!$this->phoneHelper) {
$this->phoneHelper = new PhoneNumberHelper();
}
try {
$phone = $this->phoneHelper->format($phone);
if (!empty($phone)) {
// 222
$value = substr($phone, -10, 3);
}
} catch (\Exception $e) {
}
}
return $value;
},
'area2' => function ($value) {
$phone = trim($value);
if (!empty($value)) {
if (!$this->phoneHelper) {
$this->phoneHelper = new PhoneNumberHelper();
}
try {
$phone = $this->phoneHelper->format($phone);
if (!empty($phone)) {
// 222
$value = '('.substr($phone, -10, 3).')';
}
} catch (\Exception $e) {
}
}
return $value;
},
'7' => function ($value) {
$phone = trim($value);
if (!empty($value)) {
if (!$this->phoneHelper) {
$this->phoneHelper = new PhoneNumberHelper();
}
try {
$phone = $this->phoneHelper->format($phone);
if (!empty($phone)) {
// 3334444
$value = substr($phone, -7);
}
} catch (\Exception $e) {
}
}
return $value;
},
'lpar2' => function ($value) {
$phone = trim($value);
if (!empty($value)) {
if (!$this->phoneHelper) {
$this->phoneHelper = new PhoneNumberHelper();
}
try {
$phone = $this->phoneHelper->format($phone);
if (!empty($phone)) {
// (222)333-4444
$value = '('.substr($phone, -10, 3).')'
.substr($phone, -8, 3).'-'
.substr($phone, -4, 4);
}
} catch (\Exception $e) {
}
}
return $value;
},
'inum' => function ($value) {
$phone = trim($value);
if (!empty($value)) {
if (!$this->phoneHelper) {
$this->phoneHelper = new PhoneNumberHelper();
}
try {
$phone = $this->phoneHelper->format($phone);
if (!empty($phone)) {
// 12223334444
$value = substr($phone, 1);
}
} catch (\Exception $e) {
}
}
return $value;
},
'country' => function ($value) {
$phone = trim($value);
if (!empty($value)) {
if (!$this->phoneHelper) {
$this->phoneHelper = new PhoneNumberHelper();
}
try {
$phone = $this->phoneHelper->format($phone);
if (!empty($phone)) {
// 1
$value = substr($phone, 1, strlen($phone) - 10);
}
} catch (\Exception $e) {
}
}
return $value;
},
'country2' => function ($value) {
$phone = trim($value);
if (!empty($value)) {
if (!$this->phoneHelper) {
$this->phoneHelper = new PhoneNumberHelper();
}
try {
$phone = $this->phoneHelper->format($phone);
if (!empty($phone)) {
// +1
$value = substr($phone, 0, strlen($phone) - 10);
}
} catch (\Exception $e) {
}
}
return $value;
},
'e164' => function ($value) {
$phone = trim($value);
if (!empty($value)) {
if (!$this->phoneHelper) {
$this->phoneHelper = new PhoneNumberHelper();
}
try {
$phone = $this->phoneHelper->format($phone);
if (!empty($phone)) {
// +12223334444
$value = $phone;
}
} catch (\Exception $e) {
}
}
return $value;
},
'idash' => function ($value) {
$phone = trim($value);
if (!empty($value)) {
if (!$this->phoneHelper) {
$this->phoneHelper = new PhoneNumberHelper();
}
try {
$phone = $this->phoneHelper->format($phone);
if (!empty($phone)) {
// 1-222-333-4444
$value = substr($phone, 1, strlen($phone) - 10).'-'
.substr($phone, -10, 3).'-'
.substr($phone, -7, 3).'-'
.substr($phone, -4, 4);
}
} catch (\Exception $e) {
}
}
return $value;
},
'ldash' => function ($value) {
$phone = trim($value);
if (!empty($value)) {
if (!$this->phoneHelper) {
$this->phoneHelper = new PhoneNumberHelper();
}
try {
$phone = $this->phoneHelper->format($phone);
if (!empty($phone)) {
// 222-333-4444
$value = substr($phone, -10, 3).'-'
.substr($phone, -7, 3).'-'
.substr($phone, -4, 4);
}
} catch (\Exception $e) {
}
}
return $value;
},
'ipar' => function ($value) {
$phone = trim($value);
if (!empty($value)) {
if (!$this->phoneHelper) {
$this->phoneHelper = new PhoneNumberHelper();
}
try {
$phone = $this->phoneHelper->format($phone);
if (!empty($phone)) {
// 1 (222) 333-4444
$value = substr($phone, 1, strlen($phone) - 10).
' ('.substr($phone, -10, 3).') '
.substr($phone, -8, 3).'-'
.substr($phone, -4, 4);
}
} catch (\Exception $e) {
}
}
return $value;
},
'lpar' => function ($value) {
$phone = trim($value);
if (!empty($value)) {
if (!$this->phoneHelper) {
$this->phoneHelper = new PhoneNumberHelper();
}
try {
$phone = $this->phoneHelper->format($phone);
if (!empty($phone)) {
// (222) 333-4444
$value = '('.substr($phone, -10, 3).') '
.substr($phone, -7, 3).'-'
.substr($phone, -4, 4);
}
} catch (\Exception $e) {
}
}
return $value;
},
'idot' => function ($value) {
$phone = trim($value);
if (!empty($value)) {
if (!$this->phoneHelper) {
$this->phoneHelper = new PhoneNumberHelper();
}
try {
$phone = $this->phoneHelper->format($phone);
if (!empty($phone)) {
// 1.222.333.4444
$value = substr($phone, 1, strlen($phone) - 10).'.'
.substr($phone, -10, 3).'.'
.substr($phone, -7, 3).'.'
.substr($phone, -4, 4);
}
} catch (\Exception $e) {
}
}
return $value;
},
'ldot' => function ($value) {
$phone = trim($value);
if (!empty($value)) {
if (!$this->phoneHelper) {
$this->phoneHelper = new PhoneNumberHelper();
}
try {
$phone = $this->phoneHelper->format($phone);
if (!empty($phone)) {
// 222.333.4444
$value = substr($phone, -10, 3).'.'
.substr($phone, -7, 3).'.'
.substr($phone, -4, 4);
}
} catch (\Exception $e) {
}
}
return $value;
},
]
);
}
break;
}
} | [
"private",
"function",
"addHelper",
"(",
"$",
"type",
")",
"{",
"switch",
"(",
"$",
"type",
")",
"{",
"case",
"'number'",
":",
"if",
"(",
"!",
"$",
"this",
"->",
"engine",
"->",
"hasHelper",
"(",
"'lpad'",
")",
")",
"{",
"$",
"this",
"->",
"engine",
"->",
"addHelper",
"(",
"'lpad'",
",",
"[",
"'2'",
"=>",
"function",
"(",
"$",
"value",
")",
"{",
"return",
"str_pad",
"(",
"(",
"string",
")",
"$",
"value",
",",
"2",
",",
"'0'",
",",
"STR_PAD_LEFT",
")",
";",
"}",
",",
"'4'",
"=>",
"function",
"(",
"$",
"value",
")",
"{",
"return",
"str_pad",
"(",
"(",
"string",
")",
"$",
"value",
",",
"4",
",",
"'0'",
",",
"STR_PAD_LEFT",
")",
";",
"}",
",",
"]",
")",
";",
"}",
"if",
"(",
"!",
"$",
"this",
"->",
"engine",
"->",
"hasHelper",
"(",
"'rpad'",
")",
")",
"{",
"$",
"this",
"->",
"engine",
"->",
"addHelper",
"(",
"'rpad'",
",",
"[",
"'2'",
"=>",
"function",
"(",
"$",
"value",
")",
"{",
"return",
"str_pad",
"(",
"(",
"string",
")",
"$",
"value",
",",
"2",
",",
"'0'",
",",
"STR_PAD_RIGHT",
")",
";",
"}",
",",
"'4'",
"=>",
"function",
"(",
"$",
"value",
")",
"{",
"return",
"str_pad",
"(",
"(",
"string",
")",
"$",
"value",
",",
"4",
",",
"'0'",
",",
"STR_PAD_RIGHT",
")",
";",
"}",
",",
"]",
")",
";",
"}",
"break",
";",
"case",
"'date'",
":",
"// If there are new timezones, recreate the helper.",
"if",
"(",
"!",
"$",
"this",
"->",
"engine",
"->",
"hasHelper",
"(",
"'date'",
")",
"||",
"(",
"$",
"this",
"->",
"engine",
"->",
"hasHelper",
"(",
"'date'",
")",
"&&",
"(",
"$",
"this",
"->",
"timezoneSource",
"!==",
"$",
"this",
"->",
"dateFormatHelper",
"->",
"getTimezoneSource",
"(",
")",
"||",
"$",
"this",
"->",
"timezoneDestination",
"!==",
"$",
"this",
"->",
"dateFormatHelper",
"->",
"getTimezoneDestination",
"(",
")",
")",
")",
")",
"{",
"$",
"this",
"->",
"dateFormatHelper",
"=",
"new",
"DateFormatHelper",
"(",
"$",
"this",
"->",
"timezoneSource",
",",
"$",
"this",
"->",
"timezoneDestination",
")",
";",
"$",
"this",
"->",
"engine",
"->",
"addHelper",
"(",
"'date'",
",",
"$",
"this",
"->",
"dateFormatHelper",
")",
";",
"}",
"break",
";",
"case",
"'boolean'",
":",
"if",
"(",
"!",
"$",
"this",
"->",
"engine",
"->",
"hasHelper",
"(",
"'bool'",
")",
")",
"{",
"$",
"this",
"->",
"engine",
"->",
"addHelper",
"(",
"'bool'",
",",
"[",
"'YesNo'",
"=>",
"function",
"(",
"$",
"value",
")",
"{",
"return",
"$",
"value",
"?",
"'Yes'",
":",
"'No'",
";",
"}",
",",
"'YESNO'",
"=>",
"function",
"(",
"$",
"value",
")",
"{",
"return",
"$",
"value",
"?",
"'YES'",
":",
"'NO'",
";",
"}",
",",
"'yesno'",
"=>",
"function",
"(",
"$",
"value",
")",
"{",
"return",
"$",
"value",
"?",
"'yes'",
":",
"'no'",
";",
"}",
",",
"'YN'",
"=>",
"function",
"(",
"$",
"value",
")",
"{",
"return",
"$",
"value",
"?",
"'Y'",
":",
"'N'",
";",
"}",
",",
"'yn'",
"=>",
"function",
"(",
"$",
"value",
")",
"{",
"return",
"$",
"value",
"?",
"'y'",
":",
"'n'",
";",
"}",
",",
"'10'",
"=>",
"function",
"(",
"$",
"value",
")",
"{",
"return",
"$",
"value",
"?",
"'1'",
":",
"'0'",
";",
"}",
",",
"'TrueFalse'",
"=>",
"function",
"(",
"$",
"value",
")",
"{",
"return",
"$",
"value",
"?",
"'True'",
":",
"'False'",
";",
"}",
",",
"'TRUEFALSE'",
"=>",
"function",
"(",
"$",
"value",
")",
"{",
"return",
"$",
"value",
"?",
"'TRUE'",
":",
"'FALSE'",
";",
"}",
",",
"'truefalse'",
"=>",
"function",
"(",
"$",
"value",
")",
"{",
"return",
"$",
"value",
"?",
"'true'",
":",
"'false'",
";",
"}",
",",
"'TF'",
"=>",
"function",
"(",
"$",
"value",
")",
"{",
"return",
"$",
"value",
"?",
"'T'",
":",
"'F'",
";",
"}",
",",
"'tf'",
"=>",
"function",
"(",
"$",
"value",
")",
"{",
"return",
"$",
"value",
"?",
"'t'",
":",
"'f'",
";",
"}",
",",
"]",
")",
";",
"}",
"break",
";",
"case",
"'string'",
":",
"case",
"'text'",
":",
"if",
"(",
"!",
"$",
"this",
"->",
"engine",
"->",
"hasHelper",
"(",
"'zip'",
")",
")",
"{",
"$",
"this",
"->",
"engine",
"->",
"addHelper",
"(",
"'zip'",
",",
"[",
"'short'",
"=>",
"function",
"(",
"$",
"value",
")",
"{",
"$",
"dash",
"=",
"strpos",
"(",
"(",
"string",
")",
"$",
"value",
",",
"'-'",
")",
";",
"return",
"$",
"dash",
"?",
"substr",
"(",
"(",
"string",
")",
"$",
"value",
",",
"0",
",",
"$",
"dash",
")",
":",
"$",
"value",
";",
"}",
",",
"]",
")",
";",
"}",
"if",
"(",
"!",
"$",
"this",
"->",
"engine",
"->",
"hasHelper",
"(",
"'trim'",
")",
")",
"{",
"$",
"this",
"->",
"engine",
"->",
"addHelper",
"(",
"'trim'",
",",
"[",
"'ws'",
"=>",
"function",
"(",
"$",
"value",
")",
"{",
"return",
"trim",
"(",
"(",
"string",
")",
"$",
"value",
")",
";",
"}",
",",
"'255'",
"=>",
"function",
"(",
"$",
"value",
")",
"{",
"if",
"(",
"strlen",
"(",
"(",
"string",
")",
"$",
"value",
")",
">",
"255",
")",
"{",
"$",
"value",
"=",
"trim",
"(",
"$",
"value",
")",
";",
"}",
"return",
"substr",
"(",
"(",
"string",
")",
"$",
"value",
",",
"0",
",",
"255",
")",
";",
"}",
",",
"'65535'",
"=>",
"function",
"(",
"$",
"value",
")",
"{",
"if",
"(",
"strlen",
"(",
"(",
"string",
")",
"$",
"value",
")",
">",
"255",
")",
"{",
"$",
"value",
"=",
"trim",
"(",
"$",
"value",
")",
";",
"}",
"return",
"substr",
"(",
"(",
"string",
")",
"$",
"value",
",",
"0",
",",
"255",
")",
";",
"}",
",",
"]",
")",
";",
"}",
"if",
"(",
"!",
"$",
"this",
"->",
"engine",
"->",
"hasHelper",
"(",
"'strip'",
")",
")",
"{",
"$",
"this",
"->",
"engine",
"->",
"addHelper",
"(",
"'strip'",
",",
"[",
"'comma'",
"=>",
"function",
"(",
"$",
"value",
")",
"{",
"return",
"str_replace",
"(",
"','",
",",
"''",
",",
"$",
"value",
")",
";",
"}",
",",
"'doublequote'",
"=>",
"function",
"(",
"$",
"value",
")",
"{",
"return",
"str_replace",
"(",
"'\"'",
",",
"''",
",",
"$",
"value",
")",
";",
"}",
",",
"'singlequote'",
"=>",
"function",
"(",
"$",
"value",
")",
"{",
"return",
"str_replace",
"(",
"\"'\"",
",",
"''",
",",
"$",
"value",
")",
";",
"}",
",",
"'html'",
"=>",
"function",
"(",
"$",
"value",
")",
"{",
"return",
"strip_tags",
"(",
"$",
"value",
")",
";",
"}",
",",
"// Not currently documented (will not show up in suggestions).",
"'nonascii'",
"=>",
"function",
"(",
"$",
"value",
")",
"{",
"return",
"utf8_strip_non_ascii",
"(",
"$",
"value",
")",
";",
"}",
",",
"'nonnumeric'",
"=>",
"function",
"(",
"$",
"value",
")",
"{",
"return",
"preg_replace",
"(",
"'/[^0-9,.]/'",
",",
"''",
",",
"$",
"value",
")",
";",
"}",
",",
"'numeric'",
"=>",
"function",
"(",
"$",
"value",
")",
"{",
"return",
"preg_replace",
"(",
"'/[0-9]+/'",
",",
"''",
",",
"$",
"value",
")",
";",
"}",
",",
"]",
")",
";",
"}",
"if",
"(",
"!",
"$",
"this",
"->",
"engine",
"->",
"hasHelper",
"(",
"'case'",
")",
")",
"{",
"$",
"this",
"->",
"engine",
"->",
"addHelper",
"(",
"'case'",
",",
"[",
"'first'",
"=>",
"function",
"(",
"$",
"value",
")",
"{",
"return",
"utf8_ucfirst",
"(",
"$",
"value",
")",
";",
"}",
",",
"'lower'",
"=>",
"function",
"(",
"$",
"value",
")",
"{",
"return",
"utf8_strtolower",
"(",
"$",
"value",
")",
";",
"}",
",",
"'upper'",
"=>",
"function",
"(",
"$",
"value",
")",
"{",
"return",
"utf8_strtoupper",
"(",
"$",
"value",
")",
";",
"}",
",",
"]",
")",
";",
"}",
"if",
"(",
"!",
"$",
"this",
"->",
"engine",
"->",
"hasHelper",
"(",
"'url'",
")",
")",
"{",
"$",
"this",
"->",
"engine",
"->",
"addHelper",
"(",
"'url'",
",",
"[",
"// Not currently documented (will not show up in suggestions).",
"'decode'",
"=>",
"function",
"(",
"$",
"value",
")",
"{",
"return",
"rawurldecode",
"(",
"$",
"value",
")",
";",
"}",
",",
"'encode'",
"=>",
"function",
"(",
"$",
"value",
")",
"{",
"return",
"rawurlencode",
"(",
"$",
"value",
")",
";",
"}",
",",
"]",
")",
";",
"}",
"if",
"(",
"!",
"$",
"this",
"->",
"engine",
"->",
"hasHelper",
"(",
"'tel'",
")",
")",
"{",
"$",
"this",
"->",
"engine",
"->",
"addHelper",
"(",
"'tel'",
",",
"[",
"'10'",
"=>",
"function",
"(",
"$",
"value",
")",
"{",
"$",
"phone",
"=",
"trim",
"(",
"$",
"value",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"value",
")",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"phoneHelper",
")",
"{",
"$",
"this",
"->",
"phoneHelper",
"=",
"new",
"PhoneNumberHelper",
"(",
")",
";",
"}",
"try",
"{",
"$",
"phone",
"=",
"$",
"this",
"->",
"phoneHelper",
"->",
"format",
"(",
"$",
"phone",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"phone",
")",
")",
"{",
"// 12223334444",
"$",
"value",
"=",
"substr",
"(",
"$",
"phone",
",",
"-",
"10",
")",
";",
"}",
"}",
"catch",
"(",
"\\",
"Exception",
"$",
"e",
")",
"{",
"}",
"}",
"return",
"$",
"value",
";",
"}",
",",
"'area'",
"=>",
"function",
"(",
"$",
"value",
")",
"{",
"$",
"phone",
"=",
"trim",
"(",
"$",
"value",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"value",
")",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"phoneHelper",
")",
"{",
"$",
"this",
"->",
"phoneHelper",
"=",
"new",
"PhoneNumberHelper",
"(",
")",
";",
"}",
"try",
"{",
"$",
"phone",
"=",
"$",
"this",
"->",
"phoneHelper",
"->",
"format",
"(",
"$",
"phone",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"phone",
")",
")",
"{",
"// 222",
"$",
"value",
"=",
"substr",
"(",
"$",
"phone",
",",
"-",
"10",
",",
"3",
")",
";",
"}",
"}",
"catch",
"(",
"\\",
"Exception",
"$",
"e",
")",
"{",
"}",
"}",
"return",
"$",
"value",
";",
"}",
",",
"'area2'",
"=>",
"function",
"(",
"$",
"value",
")",
"{",
"$",
"phone",
"=",
"trim",
"(",
"$",
"value",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"value",
")",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"phoneHelper",
")",
"{",
"$",
"this",
"->",
"phoneHelper",
"=",
"new",
"PhoneNumberHelper",
"(",
")",
";",
"}",
"try",
"{",
"$",
"phone",
"=",
"$",
"this",
"->",
"phoneHelper",
"->",
"format",
"(",
"$",
"phone",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"phone",
")",
")",
"{",
"// 222",
"$",
"value",
"=",
"'('",
".",
"substr",
"(",
"$",
"phone",
",",
"-",
"10",
",",
"3",
")",
".",
"')'",
";",
"}",
"}",
"catch",
"(",
"\\",
"Exception",
"$",
"e",
")",
"{",
"}",
"}",
"return",
"$",
"value",
";",
"}",
",",
"'7'",
"=>",
"function",
"(",
"$",
"value",
")",
"{",
"$",
"phone",
"=",
"trim",
"(",
"$",
"value",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"value",
")",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"phoneHelper",
")",
"{",
"$",
"this",
"->",
"phoneHelper",
"=",
"new",
"PhoneNumberHelper",
"(",
")",
";",
"}",
"try",
"{",
"$",
"phone",
"=",
"$",
"this",
"->",
"phoneHelper",
"->",
"format",
"(",
"$",
"phone",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"phone",
")",
")",
"{",
"// 3334444",
"$",
"value",
"=",
"substr",
"(",
"$",
"phone",
",",
"-",
"7",
")",
";",
"}",
"}",
"catch",
"(",
"\\",
"Exception",
"$",
"e",
")",
"{",
"}",
"}",
"return",
"$",
"value",
";",
"}",
",",
"'lpar2'",
"=>",
"function",
"(",
"$",
"value",
")",
"{",
"$",
"phone",
"=",
"trim",
"(",
"$",
"value",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"value",
")",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"phoneHelper",
")",
"{",
"$",
"this",
"->",
"phoneHelper",
"=",
"new",
"PhoneNumberHelper",
"(",
")",
";",
"}",
"try",
"{",
"$",
"phone",
"=",
"$",
"this",
"->",
"phoneHelper",
"->",
"format",
"(",
"$",
"phone",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"phone",
")",
")",
"{",
"// (222)333-4444",
"$",
"value",
"=",
"'('",
".",
"substr",
"(",
"$",
"phone",
",",
"-",
"10",
",",
"3",
")",
".",
"')'",
".",
"substr",
"(",
"$",
"phone",
",",
"-",
"8",
",",
"3",
")",
".",
"'-'",
".",
"substr",
"(",
"$",
"phone",
",",
"-",
"4",
",",
"4",
")",
";",
"}",
"}",
"catch",
"(",
"\\",
"Exception",
"$",
"e",
")",
"{",
"}",
"}",
"return",
"$",
"value",
";",
"}",
",",
"'inum'",
"=>",
"function",
"(",
"$",
"value",
")",
"{",
"$",
"phone",
"=",
"trim",
"(",
"$",
"value",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"value",
")",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"phoneHelper",
")",
"{",
"$",
"this",
"->",
"phoneHelper",
"=",
"new",
"PhoneNumberHelper",
"(",
")",
";",
"}",
"try",
"{",
"$",
"phone",
"=",
"$",
"this",
"->",
"phoneHelper",
"->",
"format",
"(",
"$",
"phone",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"phone",
")",
")",
"{",
"// 12223334444",
"$",
"value",
"=",
"substr",
"(",
"$",
"phone",
",",
"1",
")",
";",
"}",
"}",
"catch",
"(",
"\\",
"Exception",
"$",
"e",
")",
"{",
"}",
"}",
"return",
"$",
"value",
";",
"}",
",",
"'country'",
"=>",
"function",
"(",
"$",
"value",
")",
"{",
"$",
"phone",
"=",
"trim",
"(",
"$",
"value",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"value",
")",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"phoneHelper",
")",
"{",
"$",
"this",
"->",
"phoneHelper",
"=",
"new",
"PhoneNumberHelper",
"(",
")",
";",
"}",
"try",
"{",
"$",
"phone",
"=",
"$",
"this",
"->",
"phoneHelper",
"->",
"format",
"(",
"$",
"phone",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"phone",
")",
")",
"{",
"// 1",
"$",
"value",
"=",
"substr",
"(",
"$",
"phone",
",",
"1",
",",
"strlen",
"(",
"$",
"phone",
")",
"-",
"10",
")",
";",
"}",
"}",
"catch",
"(",
"\\",
"Exception",
"$",
"e",
")",
"{",
"}",
"}",
"return",
"$",
"value",
";",
"}",
",",
"'country2'",
"=>",
"function",
"(",
"$",
"value",
")",
"{",
"$",
"phone",
"=",
"trim",
"(",
"$",
"value",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"value",
")",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"phoneHelper",
")",
"{",
"$",
"this",
"->",
"phoneHelper",
"=",
"new",
"PhoneNumberHelper",
"(",
")",
";",
"}",
"try",
"{",
"$",
"phone",
"=",
"$",
"this",
"->",
"phoneHelper",
"->",
"format",
"(",
"$",
"phone",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"phone",
")",
")",
"{",
"// +1",
"$",
"value",
"=",
"substr",
"(",
"$",
"phone",
",",
"0",
",",
"strlen",
"(",
"$",
"phone",
")",
"-",
"10",
")",
";",
"}",
"}",
"catch",
"(",
"\\",
"Exception",
"$",
"e",
")",
"{",
"}",
"}",
"return",
"$",
"value",
";",
"}",
",",
"'e164'",
"=>",
"function",
"(",
"$",
"value",
")",
"{",
"$",
"phone",
"=",
"trim",
"(",
"$",
"value",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"value",
")",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"phoneHelper",
")",
"{",
"$",
"this",
"->",
"phoneHelper",
"=",
"new",
"PhoneNumberHelper",
"(",
")",
";",
"}",
"try",
"{",
"$",
"phone",
"=",
"$",
"this",
"->",
"phoneHelper",
"->",
"format",
"(",
"$",
"phone",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"phone",
")",
")",
"{",
"// +12223334444",
"$",
"value",
"=",
"$",
"phone",
";",
"}",
"}",
"catch",
"(",
"\\",
"Exception",
"$",
"e",
")",
"{",
"}",
"}",
"return",
"$",
"value",
";",
"}",
",",
"'idash'",
"=>",
"function",
"(",
"$",
"value",
")",
"{",
"$",
"phone",
"=",
"trim",
"(",
"$",
"value",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"value",
")",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"phoneHelper",
")",
"{",
"$",
"this",
"->",
"phoneHelper",
"=",
"new",
"PhoneNumberHelper",
"(",
")",
";",
"}",
"try",
"{",
"$",
"phone",
"=",
"$",
"this",
"->",
"phoneHelper",
"->",
"format",
"(",
"$",
"phone",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"phone",
")",
")",
"{",
"// 1-222-333-4444",
"$",
"value",
"=",
"substr",
"(",
"$",
"phone",
",",
"1",
",",
"strlen",
"(",
"$",
"phone",
")",
"-",
"10",
")",
".",
"'-'",
".",
"substr",
"(",
"$",
"phone",
",",
"-",
"10",
",",
"3",
")",
".",
"'-'",
".",
"substr",
"(",
"$",
"phone",
",",
"-",
"7",
",",
"3",
")",
".",
"'-'",
".",
"substr",
"(",
"$",
"phone",
",",
"-",
"4",
",",
"4",
")",
";",
"}",
"}",
"catch",
"(",
"\\",
"Exception",
"$",
"e",
")",
"{",
"}",
"}",
"return",
"$",
"value",
";",
"}",
",",
"'ldash'",
"=>",
"function",
"(",
"$",
"value",
")",
"{",
"$",
"phone",
"=",
"trim",
"(",
"$",
"value",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"value",
")",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"phoneHelper",
")",
"{",
"$",
"this",
"->",
"phoneHelper",
"=",
"new",
"PhoneNumberHelper",
"(",
")",
";",
"}",
"try",
"{",
"$",
"phone",
"=",
"$",
"this",
"->",
"phoneHelper",
"->",
"format",
"(",
"$",
"phone",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"phone",
")",
")",
"{",
"// 222-333-4444",
"$",
"value",
"=",
"substr",
"(",
"$",
"phone",
",",
"-",
"10",
",",
"3",
")",
".",
"'-'",
".",
"substr",
"(",
"$",
"phone",
",",
"-",
"7",
",",
"3",
")",
".",
"'-'",
".",
"substr",
"(",
"$",
"phone",
",",
"-",
"4",
",",
"4",
")",
";",
"}",
"}",
"catch",
"(",
"\\",
"Exception",
"$",
"e",
")",
"{",
"}",
"}",
"return",
"$",
"value",
";",
"}",
",",
"'ipar'",
"=>",
"function",
"(",
"$",
"value",
")",
"{",
"$",
"phone",
"=",
"trim",
"(",
"$",
"value",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"value",
")",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"phoneHelper",
")",
"{",
"$",
"this",
"->",
"phoneHelper",
"=",
"new",
"PhoneNumberHelper",
"(",
")",
";",
"}",
"try",
"{",
"$",
"phone",
"=",
"$",
"this",
"->",
"phoneHelper",
"->",
"format",
"(",
"$",
"phone",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"phone",
")",
")",
"{",
"// 1 (222) 333-4444",
"$",
"value",
"=",
"substr",
"(",
"$",
"phone",
",",
"1",
",",
"strlen",
"(",
"$",
"phone",
")",
"-",
"10",
")",
".",
"' ('",
".",
"substr",
"(",
"$",
"phone",
",",
"-",
"10",
",",
"3",
")",
".",
"') '",
".",
"substr",
"(",
"$",
"phone",
",",
"-",
"8",
",",
"3",
")",
".",
"'-'",
".",
"substr",
"(",
"$",
"phone",
",",
"-",
"4",
",",
"4",
")",
";",
"}",
"}",
"catch",
"(",
"\\",
"Exception",
"$",
"e",
")",
"{",
"}",
"}",
"return",
"$",
"value",
";",
"}",
",",
"'lpar'",
"=>",
"function",
"(",
"$",
"value",
")",
"{",
"$",
"phone",
"=",
"trim",
"(",
"$",
"value",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"value",
")",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"phoneHelper",
")",
"{",
"$",
"this",
"->",
"phoneHelper",
"=",
"new",
"PhoneNumberHelper",
"(",
")",
";",
"}",
"try",
"{",
"$",
"phone",
"=",
"$",
"this",
"->",
"phoneHelper",
"->",
"format",
"(",
"$",
"phone",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"phone",
")",
")",
"{",
"// (222) 333-4444",
"$",
"value",
"=",
"'('",
".",
"substr",
"(",
"$",
"phone",
",",
"-",
"10",
",",
"3",
")",
".",
"') '",
".",
"substr",
"(",
"$",
"phone",
",",
"-",
"7",
",",
"3",
")",
".",
"'-'",
".",
"substr",
"(",
"$",
"phone",
",",
"-",
"4",
",",
"4",
")",
";",
"}",
"}",
"catch",
"(",
"\\",
"Exception",
"$",
"e",
")",
"{",
"}",
"}",
"return",
"$",
"value",
";",
"}",
",",
"'idot'",
"=>",
"function",
"(",
"$",
"value",
")",
"{",
"$",
"phone",
"=",
"trim",
"(",
"$",
"value",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"value",
")",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"phoneHelper",
")",
"{",
"$",
"this",
"->",
"phoneHelper",
"=",
"new",
"PhoneNumberHelper",
"(",
")",
";",
"}",
"try",
"{",
"$",
"phone",
"=",
"$",
"this",
"->",
"phoneHelper",
"->",
"format",
"(",
"$",
"phone",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"phone",
")",
")",
"{",
"// 1.222.333.4444",
"$",
"value",
"=",
"substr",
"(",
"$",
"phone",
",",
"1",
",",
"strlen",
"(",
"$",
"phone",
")",
"-",
"10",
")",
".",
"'.'",
".",
"substr",
"(",
"$",
"phone",
",",
"-",
"10",
",",
"3",
")",
".",
"'.'",
".",
"substr",
"(",
"$",
"phone",
",",
"-",
"7",
",",
"3",
")",
".",
"'.'",
".",
"substr",
"(",
"$",
"phone",
",",
"-",
"4",
",",
"4",
")",
";",
"}",
"}",
"catch",
"(",
"\\",
"Exception",
"$",
"e",
")",
"{",
"}",
"}",
"return",
"$",
"value",
";",
"}",
",",
"'ldot'",
"=>",
"function",
"(",
"$",
"value",
")",
"{",
"$",
"phone",
"=",
"trim",
"(",
"$",
"value",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"value",
")",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"phoneHelper",
")",
"{",
"$",
"this",
"->",
"phoneHelper",
"=",
"new",
"PhoneNumberHelper",
"(",
")",
";",
"}",
"try",
"{",
"$",
"phone",
"=",
"$",
"this",
"->",
"phoneHelper",
"->",
"format",
"(",
"$",
"phone",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"phone",
")",
")",
"{",
"// 222.333.4444",
"$",
"value",
"=",
"substr",
"(",
"$",
"phone",
",",
"-",
"10",
",",
"3",
")",
".",
"'.'",
".",
"substr",
"(",
"$",
"phone",
",",
"-",
"7",
",",
"3",
")",
".",
"'.'",
".",
"substr",
"(",
"$",
"phone",
",",
"-",
"4",
",",
"4",
")",
";",
"}",
"}",
"catch",
"(",
"\\",
"Exception",
"$",
"e",
")",
"{",
"}",
"}",
"return",
"$",
"value",
";",
"}",
",",
"]",
")",
";",
"}",
"break",
";",
"}",
"}"
] | Add token helpers/filters to the engine.
@param $type | [
"Add",
"token",
"helpers",
"/",
"filters",
"to",
"the",
"engine",
"."
] | train | https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Helper/TokenHelper.php#L245-L729 |
TheDMSGroup/mautic-contact-client | Helper/TokenHelper.php | TokenHelper.getTokens | public function getTokens($string)
{
$tokens = [];
$scanResults = $this->engine->getTokenizer()->scan($string);
foreach ($scanResults as $scanResult) {
if (
isset($scanResult['type'])
&& isset($scanResult['name'])
&& \Mustache_Tokenizer::T_ESCAPED === $scanResult['type']
) {
$tokens[$scanResult['name']] = true;
}
}
return array_keys($tokens);
} | php | public function getTokens($string)
{
$tokens = [];
$scanResults = $this->engine->getTokenizer()->scan($string);
foreach ($scanResults as $scanResult) {
if (
isset($scanResult['type'])
&& isset($scanResult['name'])
&& \Mustache_Tokenizer::T_ESCAPED === $scanResult['type']
) {
$tokens[$scanResult['name']] = true;
}
}
return array_keys($tokens);
} | [
"public",
"function",
"getTokens",
"(",
"$",
"string",
")",
"{",
"$",
"tokens",
"=",
"[",
"]",
";",
"$",
"scanResults",
"=",
"$",
"this",
"->",
"engine",
"->",
"getTokenizer",
"(",
")",
"->",
"scan",
"(",
"$",
"string",
")",
";",
"foreach",
"(",
"$",
"scanResults",
"as",
"$",
"scanResult",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"scanResult",
"[",
"'type'",
"]",
")",
"&&",
"isset",
"(",
"$",
"scanResult",
"[",
"'name'",
"]",
")",
"&&",
"\\",
"Mustache_Tokenizer",
"::",
"T_ESCAPED",
"===",
"$",
"scanResult",
"[",
"'type'",
"]",
")",
"{",
"$",
"tokens",
"[",
"$",
"scanResult",
"[",
"'name'",
"]",
"]",
"=",
"true",
";",
"}",
"}",
"return",
"array_keys",
"(",
"$",
"tokens",
")",
";",
"}"
] | Scan a string for tokens using the same engine.
@param $string
@return array a unique list of all the raw mustache tags found in the string | [
"Scan",
"a",
"string",
"for",
"tokens",
"using",
"the",
"same",
"engine",
"."
] | train | https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Helper/TokenHelper.php#L738-L754 |
TheDMSGroup/mautic-contact-client | Helper/TokenHelper.php | TokenHelper.getFormats | public function getFormats()
{
return [
'date' => $this->getDateFormatHelper()->getFormatsDate(),
'datetime' => $this->getDateFormatHelper()->getFormatsDateTime(),
'time' => $this->getDateFormatHelper()->getFormatsTime(),
'number' => $this->formatNumber,
'boolean' => $this->formatBoolean,
'string' => $this->formatString,
'region' => $this->formatString,
'tel' => $this->formatTel,
'text' => $this->formatText,
'email' => $this->formatEmail,
];
} | php | public function getFormats()
{
return [
'date' => $this->getDateFormatHelper()->getFormatsDate(),
'datetime' => $this->getDateFormatHelper()->getFormatsDateTime(),
'time' => $this->getDateFormatHelper()->getFormatsTime(),
'number' => $this->formatNumber,
'boolean' => $this->formatBoolean,
'string' => $this->formatString,
'region' => $this->formatString,
'tel' => $this->formatTel,
'text' => $this->formatText,
'email' => $this->formatEmail,
];
} | [
"public",
"function",
"getFormats",
"(",
")",
"{",
"return",
"[",
"'date'",
"=>",
"$",
"this",
"->",
"getDateFormatHelper",
"(",
")",
"->",
"getFormatsDate",
"(",
")",
",",
"'datetime'",
"=>",
"$",
"this",
"->",
"getDateFormatHelper",
"(",
")",
"->",
"getFormatsDateTime",
"(",
")",
",",
"'time'",
"=>",
"$",
"this",
"->",
"getDateFormatHelper",
"(",
")",
"->",
"getFormatsTime",
"(",
")",
",",
"'number'",
"=>",
"$",
"this",
"->",
"formatNumber",
",",
"'boolean'",
"=>",
"$",
"this",
"->",
"formatBoolean",
",",
"'string'",
"=>",
"$",
"this",
"->",
"formatString",
",",
"'region'",
"=>",
"$",
"this",
"->",
"formatString",
",",
"'tel'",
"=>",
"$",
"this",
"->",
"formatTel",
",",
"'text'",
"=>",
"$",
"this",
"->",
"formatText",
",",
"'email'",
"=>",
"$",
"this",
"->",
"formatEmail",
",",
"]",
";",
"}"
] | Outputs an array of formats by field type for the front-end tokenization.
@return array | [
"Outputs",
"an",
"array",
"of",
"formats",
"by",
"field",
"type",
"for",
"the",
"front",
"-",
"end",
"tokenization",
"."
] | train | https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Helper/TokenHelper.php#L761-L775 |
TheDMSGroup/mautic-contact-client | Helper/TokenHelper.php | TokenHelper.newSession | public function newSession(
ContactClient $contactClient = null,
Contact $contact = null,
$payload = [],
$campaign = null,
$event = []
) {
$this->context = [];
$this->renderCache = [];
$this->setContactClient($contactClient);
$this->addContextPayload($payload);
$this->addContextContact($contact);
$this->addContextCampaign($campaign);
$this->addContextEvent($event);
return $this;
} | php | public function newSession(
ContactClient $contactClient = null,
Contact $contact = null,
$payload = [],
$campaign = null,
$event = []
) {
$this->context = [];
$this->renderCache = [];
$this->setContactClient($contactClient);
$this->addContextPayload($payload);
$this->addContextContact($contact);
$this->addContextCampaign($campaign);
$this->addContextEvent($event);
return $this;
} | [
"public",
"function",
"newSession",
"(",
"ContactClient",
"$",
"contactClient",
"=",
"null",
",",
"Contact",
"$",
"contact",
"=",
"null",
",",
"$",
"payload",
"=",
"[",
"]",
",",
"$",
"campaign",
"=",
"null",
",",
"$",
"event",
"=",
"[",
"]",
")",
"{",
"$",
"this",
"->",
"context",
"=",
"[",
"]",
";",
"$",
"this",
"->",
"renderCache",
"=",
"[",
"]",
";",
"$",
"this",
"->",
"setContactClient",
"(",
"$",
"contactClient",
")",
";",
"$",
"this",
"->",
"addContextPayload",
"(",
"$",
"payload",
")",
";",
"$",
"this",
"->",
"addContextContact",
"(",
"$",
"contact",
")",
";",
"$",
"this",
"->",
"addContextCampaign",
"(",
"$",
"campaign",
")",
";",
"$",
"this",
"->",
"addContextEvent",
"(",
"$",
"event",
")",
";",
"return",
"$",
"this",
";",
"}"
] | @param ContactClient|null $contactClient
@param Contact|null $contact
@param array $payload
@param null $campaign
@param array $event
@return $this | [
"@param",
"ContactClient|null",
"$contactClient",
"@param",
"Contact|null",
"$contact",
"@param",
"array",
"$payload",
"@param",
"null",
"$campaign",
"@param",
"array",
"$event"
] | train | https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Helper/TokenHelper.php#L802-L818 |
TheDMSGroup/mautic-contact-client | Helper/TokenHelper.php | TokenHelper.setContactClient | public function setContactClient(ContactClient $contactClient = null)
{
if ($contactClient && $contactClient !== $this->contactClient) {
$this->contactClient = $contactClient;
// Set the timezones for date/time conversion.
$tza = $this->coreParametersHelper->getParameter(
'default_timezone'
);
$this->timezoneSource = !empty($tza) ? $tza : date_default_timezone_get();
if ($this->contactClient) {
$tzb = $this->contactClient->getScheduleTimezone();
}
$this->timezoneDestination = !empty($tzb) ? $tzb : date_default_timezone_get();
}
$this->addHelper('date');
return $this;
} | php | public function setContactClient(ContactClient $contactClient = null)
{
if ($contactClient && $contactClient !== $this->contactClient) {
$this->contactClient = $contactClient;
// Set the timezones for date/time conversion.
$tza = $this->coreParametersHelper->getParameter(
'default_timezone'
);
$this->timezoneSource = !empty($tza) ? $tza : date_default_timezone_get();
if ($this->contactClient) {
$tzb = $this->contactClient->getScheduleTimezone();
}
$this->timezoneDestination = !empty($tzb) ? $tzb : date_default_timezone_get();
}
$this->addHelper('date');
return $this;
} | [
"public",
"function",
"setContactClient",
"(",
"ContactClient",
"$",
"contactClient",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"contactClient",
"&&",
"$",
"contactClient",
"!==",
"$",
"this",
"->",
"contactClient",
")",
"{",
"$",
"this",
"->",
"contactClient",
"=",
"$",
"contactClient",
";",
"// Set the timezones for date/time conversion.",
"$",
"tza",
"=",
"$",
"this",
"->",
"coreParametersHelper",
"->",
"getParameter",
"(",
"'default_timezone'",
")",
";",
"$",
"this",
"->",
"timezoneSource",
"=",
"!",
"empty",
"(",
"$",
"tza",
")",
"?",
"$",
"tza",
":",
"date_default_timezone_get",
"(",
")",
";",
"if",
"(",
"$",
"this",
"->",
"contactClient",
")",
"{",
"$",
"tzb",
"=",
"$",
"this",
"->",
"contactClient",
"->",
"getScheduleTimezone",
"(",
")",
";",
"}",
"$",
"this",
"->",
"timezoneDestination",
"=",
"!",
"empty",
"(",
"$",
"tzb",
")",
"?",
"$",
"tzb",
":",
"date_default_timezone_get",
"(",
")",
";",
"}",
"$",
"this",
"->",
"addHelper",
"(",
"'date'",
")",
";",
"return",
"$",
"this",
";",
"}"
] | @param ContactClient $contactClient
@return $this | [
"@param",
"ContactClient",
"$contactClient"
] | train | https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Helper/TokenHelper.php#L825-L843 |
TheDMSGroup/mautic-contact-client | Helper/TokenHelper.php | TokenHelper.addContextPayload | public function addContextPayload($payload = [], $operationId = null, $responseActual = [])
{
if (!$payload) {
return $this;
}
$payload = json_decode(json_encode($payload), true);
if ($payload === $this->previousPayload && !$responseActual) {
// The payload is the same.
// No additional response data has not been provided to append.
// No need to recalculate this context.
$this->context['payload'] = $this->previousContextPayload;
return $this;
}
// Set the context of the payload and reset the pivot data need flags.
$this->context['payload'] = $payload;
$this->previousPayload = $payload;
$this->needsDeviceData = false;
$this->needsUtmData = false;
$this->needsDncData = false;
// File payload pivot data check.
if (!empty($payload['body']) && !empty($payload['settings'])) {
if (!empty($payload['body']) && is_array($payload['body'])) {
foreach ($payload['body'] as $column) {
foreach (['value', 'default_value', 'test_value'] as $key) {
if (!empty($column[$key])) {
$this->findPivotDataTokens($column[$key]);
}
}
}
}
}
// API Payload pivot data check, and addition of actual response data from previous request operations.
if (!empty($payload['operations'])) {
foreach ($payload['operations'] as $id => $operation) {
foreach (['request', 'response'] as $opType) {
if (!empty($operation[$opType])) {
foreach (['headers', 'body'] as $fieldType) {
if (!empty($operation[$opType][$fieldType])) {
$fieldSet = [];
if (
'response' === $opType
&& $id === $operationId
&& null !== $responseActual[$fieldType]
) {
// While running in realtime.
$fieldSet = $responseActual[$fieldType];
} else {
foreach ($operation[$opType][$fieldType] as $field) {
if (null !== $field['key']) {
$fieldSet[$field['key']] = isset($field['value']) ? $field['value'] : null;
if ('request' === $opType) {
$this->findPivotDataTokens($field['value']);
}
}
}
}
$this->context['payload']['operations'][$id][$opType][$fieldType] = $fieldSet;
if (
'request' === $opType
&& !empty($operation[$opType]['manual'])
&& $operation[$opType]['manual']
&& !empty($operation[$opType]['template'])
) {
$this->findPivotDataTokens($operation[$opType]['template']);
}
}
}
}
}
}
}
$this->previousContextPayload = $this->context['payload'];
return $this;
} | php | public function addContextPayload($payload = [], $operationId = null, $responseActual = [])
{
if (!$payload) {
return $this;
}
$payload = json_decode(json_encode($payload), true);
if ($payload === $this->previousPayload && !$responseActual) {
// The payload is the same.
// No additional response data has not been provided to append.
// No need to recalculate this context.
$this->context['payload'] = $this->previousContextPayload;
return $this;
}
// Set the context of the payload and reset the pivot data need flags.
$this->context['payload'] = $payload;
$this->previousPayload = $payload;
$this->needsDeviceData = false;
$this->needsUtmData = false;
$this->needsDncData = false;
// File payload pivot data check.
if (!empty($payload['body']) && !empty($payload['settings'])) {
if (!empty($payload['body']) && is_array($payload['body'])) {
foreach ($payload['body'] as $column) {
foreach (['value', 'default_value', 'test_value'] as $key) {
if (!empty($column[$key])) {
$this->findPivotDataTokens($column[$key]);
}
}
}
}
}
// API Payload pivot data check, and addition of actual response data from previous request operations.
if (!empty($payload['operations'])) {
foreach ($payload['operations'] as $id => $operation) {
foreach (['request', 'response'] as $opType) {
if (!empty($operation[$opType])) {
foreach (['headers', 'body'] as $fieldType) {
if (!empty($operation[$opType][$fieldType])) {
$fieldSet = [];
if (
'response' === $opType
&& $id === $operationId
&& null !== $responseActual[$fieldType]
) {
// While running in realtime.
$fieldSet = $responseActual[$fieldType];
} else {
foreach ($operation[$opType][$fieldType] as $field) {
if (null !== $field['key']) {
$fieldSet[$field['key']] = isset($field['value']) ? $field['value'] : null;
if ('request' === $opType) {
$this->findPivotDataTokens($field['value']);
}
}
}
}
$this->context['payload']['operations'][$id][$opType][$fieldType] = $fieldSet;
if (
'request' === $opType
&& !empty($operation[$opType]['manual'])
&& $operation[$opType]['manual']
&& !empty($operation[$opType]['template'])
) {
$this->findPivotDataTokens($operation[$opType]['template']);
}
}
}
}
}
}
}
$this->previousContextPayload = $this->context['payload'];
return $this;
} | [
"public",
"function",
"addContextPayload",
"(",
"$",
"payload",
"=",
"[",
"]",
",",
"$",
"operationId",
"=",
"null",
",",
"$",
"responseActual",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"!",
"$",
"payload",
")",
"{",
"return",
"$",
"this",
";",
"}",
"$",
"payload",
"=",
"json_decode",
"(",
"json_encode",
"(",
"$",
"payload",
")",
",",
"true",
")",
";",
"if",
"(",
"$",
"payload",
"===",
"$",
"this",
"->",
"previousPayload",
"&&",
"!",
"$",
"responseActual",
")",
"{",
"// The payload is the same.",
"// No additional response data has not been provided to append.",
"// No need to recalculate this context.",
"$",
"this",
"->",
"context",
"[",
"'payload'",
"]",
"=",
"$",
"this",
"->",
"previousContextPayload",
";",
"return",
"$",
"this",
";",
"}",
"// Set the context of the payload and reset the pivot data need flags.",
"$",
"this",
"->",
"context",
"[",
"'payload'",
"]",
"=",
"$",
"payload",
";",
"$",
"this",
"->",
"previousPayload",
"=",
"$",
"payload",
";",
"$",
"this",
"->",
"needsDeviceData",
"=",
"false",
";",
"$",
"this",
"->",
"needsUtmData",
"=",
"false",
";",
"$",
"this",
"->",
"needsDncData",
"=",
"false",
";",
"// File payload pivot data check.",
"if",
"(",
"!",
"empty",
"(",
"$",
"payload",
"[",
"'body'",
"]",
")",
"&&",
"!",
"empty",
"(",
"$",
"payload",
"[",
"'settings'",
"]",
")",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"payload",
"[",
"'body'",
"]",
")",
"&&",
"is_array",
"(",
"$",
"payload",
"[",
"'body'",
"]",
")",
")",
"{",
"foreach",
"(",
"$",
"payload",
"[",
"'body'",
"]",
"as",
"$",
"column",
")",
"{",
"foreach",
"(",
"[",
"'value'",
",",
"'default_value'",
",",
"'test_value'",
"]",
"as",
"$",
"key",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"column",
"[",
"$",
"key",
"]",
")",
")",
"{",
"$",
"this",
"->",
"findPivotDataTokens",
"(",
"$",
"column",
"[",
"$",
"key",
"]",
")",
";",
"}",
"}",
"}",
"}",
"}",
"// API Payload pivot data check, and addition of actual response data from previous request operations.",
"if",
"(",
"!",
"empty",
"(",
"$",
"payload",
"[",
"'operations'",
"]",
")",
")",
"{",
"foreach",
"(",
"$",
"payload",
"[",
"'operations'",
"]",
"as",
"$",
"id",
"=>",
"$",
"operation",
")",
"{",
"foreach",
"(",
"[",
"'request'",
",",
"'response'",
"]",
"as",
"$",
"opType",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"operation",
"[",
"$",
"opType",
"]",
")",
")",
"{",
"foreach",
"(",
"[",
"'headers'",
",",
"'body'",
"]",
"as",
"$",
"fieldType",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"operation",
"[",
"$",
"opType",
"]",
"[",
"$",
"fieldType",
"]",
")",
")",
"{",
"$",
"fieldSet",
"=",
"[",
"]",
";",
"if",
"(",
"'response'",
"===",
"$",
"opType",
"&&",
"$",
"id",
"===",
"$",
"operationId",
"&&",
"null",
"!==",
"$",
"responseActual",
"[",
"$",
"fieldType",
"]",
")",
"{",
"// While running in realtime.",
"$",
"fieldSet",
"=",
"$",
"responseActual",
"[",
"$",
"fieldType",
"]",
";",
"}",
"else",
"{",
"foreach",
"(",
"$",
"operation",
"[",
"$",
"opType",
"]",
"[",
"$",
"fieldType",
"]",
"as",
"$",
"field",
")",
"{",
"if",
"(",
"null",
"!==",
"$",
"field",
"[",
"'key'",
"]",
")",
"{",
"$",
"fieldSet",
"[",
"$",
"field",
"[",
"'key'",
"]",
"]",
"=",
"isset",
"(",
"$",
"field",
"[",
"'value'",
"]",
")",
"?",
"$",
"field",
"[",
"'value'",
"]",
":",
"null",
";",
"if",
"(",
"'request'",
"===",
"$",
"opType",
")",
"{",
"$",
"this",
"->",
"findPivotDataTokens",
"(",
"$",
"field",
"[",
"'value'",
"]",
")",
";",
"}",
"}",
"}",
"}",
"$",
"this",
"->",
"context",
"[",
"'payload'",
"]",
"[",
"'operations'",
"]",
"[",
"$",
"id",
"]",
"[",
"$",
"opType",
"]",
"[",
"$",
"fieldType",
"]",
"=",
"$",
"fieldSet",
";",
"if",
"(",
"'request'",
"===",
"$",
"opType",
"&&",
"!",
"empty",
"(",
"$",
"operation",
"[",
"$",
"opType",
"]",
"[",
"'manual'",
"]",
")",
"&&",
"$",
"operation",
"[",
"$",
"opType",
"]",
"[",
"'manual'",
"]",
"&&",
"!",
"empty",
"(",
"$",
"operation",
"[",
"$",
"opType",
"]",
"[",
"'template'",
"]",
")",
")",
"{",
"$",
"this",
"->",
"findPivotDataTokens",
"(",
"$",
"operation",
"[",
"$",
"opType",
"]",
"[",
"'template'",
"]",
")",
";",
"}",
"}",
"}",
"}",
"}",
"}",
"}",
"$",
"this",
"->",
"previousContextPayload",
"=",
"$",
"this",
"->",
"context",
"[",
"'payload'",
"]",
";",
"return",
"$",
"this",
";",
"}"
] | Simplify the payload for tokens, including actual response data when possible.
@param array $payload
@param null $operationId
@param array $responseActual
@return $this | [
"Simplify",
"the",
"payload",
"for",
"tokens",
"including",
"actual",
"response",
"data",
"when",
"possible",
"."
] | train | https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Helper/TokenHelper.php#L854-L933 |
TheDMSGroup/mautic-contact-client | Helper/TokenHelper.php | TokenHelper.findPivotDataTokens | private function findPivotDataTokens($string)
{
if (
!$this->needsDeviceData
&& 1 === preg_match('/{{\s?device\..*\s?}}/', $string)
) {
$this->needsDeviceData = true;
}
if (
!$this->needsUtmData
&& 1 === preg_match('/{{\s?utm\..*\s?}}/', $string)
) {
$this->needsUtmData = true;
}
if (
!$this->needsDncData
&& 1 === preg_match('/{{\s?doNotContact\..*\s?}}/', $string)
) {
$this->needsDncData = true;
}
} | php | private function findPivotDataTokens($string)
{
if (
!$this->needsDeviceData
&& 1 === preg_match('/{{\s?device\..*\s?}}/', $string)
) {
$this->needsDeviceData = true;
}
if (
!$this->needsUtmData
&& 1 === preg_match('/{{\s?utm\..*\s?}}/', $string)
) {
$this->needsUtmData = true;
}
if (
!$this->needsDncData
&& 1 === preg_match('/{{\s?doNotContact\..*\s?}}/', $string)
) {
$this->needsDncData = true;
}
} | [
"private",
"function",
"findPivotDataTokens",
"(",
"$",
"string",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"needsDeviceData",
"&&",
"1",
"===",
"preg_match",
"(",
"'/{{\\s?device\\..*\\s?}}/'",
",",
"$",
"string",
")",
")",
"{",
"$",
"this",
"->",
"needsDeviceData",
"=",
"true",
";",
"}",
"if",
"(",
"!",
"$",
"this",
"->",
"needsUtmData",
"&&",
"1",
"===",
"preg_match",
"(",
"'/{{\\s?utm\\..*\\s?}}/'",
",",
"$",
"string",
")",
")",
"{",
"$",
"this",
"->",
"needsUtmData",
"=",
"true",
";",
"}",
"if",
"(",
"!",
"$",
"this",
"->",
"needsDncData",
"&&",
"1",
"===",
"preg_match",
"(",
"'/{{\\s?doNotContact\\..*\\s?}}/'",
",",
"$",
"string",
")",
")",
"{",
"$",
"this",
"->",
"needsDncData",
"=",
"true",
";",
"}",
"}"
] | Check for the need for device data to keep queries low later.
@param $string | [
"Check",
"for",
"the",
"need",
"for",
"device",
"data",
"to",
"keep",
"queries",
"low",
"later",
"."
] | train | https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Helper/TokenHelper.php#L940-L960 |
TheDMSGroup/mautic-contact-client | Helper/TokenHelper.php | TokenHelper.addContextContact | public function addContextContact(Contact $contact = null)
{
if (!$contact) {
return $this;
}
$context = [];
$conType = [];
// Append contact ID.
$contactId = (int) $contact->getId();
$context['id'] = isset($contactId) ? $contactId : null;
$conType['id'] = 'number';
// Append contact owner data.
$owner = $contact->getOwner();
$context['owner'] = [];
$context['owner']['id'] = $owner ? $owner->getId() : null;
$conType['owner']['id'] = 'number';
$context['owner']['username'] = $owner ? $owner->getUsername() : null;
$context['owner']['firstName'] = $owner ? $owner->getFirstName() : null;
$context['owner']['lastName'] = $owner ? $owner->getLastName() : null;
$context['owner']['email'] = $owner ? $owner->getEmail() : null;
// Append points value.
$points = $contact->getPoints();
$context['points'] = isset($points) ? $points : null;
$conType['points'] = 'number';
// Append IP Addresses.
$context['ipAddresses'] = [];
$context['ip'] = null;
foreach ($contact->getIpAddresses()->toArray() as $ip => $value) {
$context['ipAddresses'][] = $ip;
$context['ip'] = $ip;
}
// Add Identified date.
/** @var \DateTime $dateIdentified */
$dateIdentified = $contact->getDateIdentified();
$context['dateIdentified'] = $dateIdentified ? $this->dateFormatHelper->format($dateIdentified) : null;
$conType['dateIdentified'] = 'datetime';
// Add Modified date.
/** @var \DateTime $dateModified */
$dateModified = $contact->getDateModified();
$context['dateModified'] = $dateModified ? $this->dateFormatHelper->format($dateModified) : null;
$conType['dateModified'] = 'datetime';
// Add DNC data.
$context['doNotContacts'] = [];
$context['doNotContact'] = false;
if ($contactId && $this->needsDncData) {
/** @var \Mautic\LeadBundle\Model\DoNotContact $record */
foreach ($contact->getDoNotContact() as $record) {
$context['doNotContacts'][$record->getChannel()] = [
'comments' => $record->getComments(),
'reason' => $record->getReason(),
'exists' => true,
];
$conType['doNotContacts'][$record->getChannel()]['exists'] = 'boolean';
$context['doNotContact'] = true;
}
$conType['doNotContact'] = 'boolean';
}
// Add UTM data.
$context['utm'] = [
'campaign' => null,
'content' => null,
'medium' => null,
'query' => null,
'referrer' => null,
'remoteHost' => null,
'source' => null,
'term' => null,
'url' => null,
'userAgent' => null,
];
if ($contactId && $this->needsUtmData) {
$utmTags = $this->utmSourceHelper->getSortedUtmTags($contact);
$context['utmTags'] = [];
if ($utmTags) {
foreach ($utmTags as $utmTag) {
$tags = [
'campaign' => $utmTag->getUtmCampaign(),
'content' => $utmTag->getUtmContent(),
'medium' => $utmTag->getUtmMedium(),
'query' => $utmTag->getQuery(),
'referrer' => $utmTag->getReferer(),
'remoteHost' => $utmTag->getRemoteHost(),
'source' => $utmTag->getUtmSource(),
'term' => $utmTag->getUtmTerm(),
'url' => $utmTag->getUrl(),
'userAgent' => $utmTag->getUserAgent(),
];
$context['utmTags'][] = $tags;
// Override the {{ utm.values }} to be the latest non-empty version of each found.
foreach ($tags as $key => $value) {
if (!empty($value)) {
$context['utm'][$key] = $value;
}
}
}
}
}
// Add Device data.
$context['device'] = [
'name' => null,
'brand' => null,
'model' => null,
'fingerprint' => null,
'trackingId' => null,
'os' => [
'osName' => null,
'osShortName' => null,
'osVersion' => null,
'osPlatform' => null,
],
];
if ($contactId && $this->needsDeviceData) {
/** @var LeadDeviceRepository $deviceRepo */
$deviceRepo = $this->contactModel->getDeviceRepository();
$devices = $deviceRepo->getEntities(
[
'limit' => 1,
'orderBy' => $deviceRepo->getTableAlias().'.id',
'orderByDir' => 'DESC',
'filter' => [
'force' => [
[
'column' => 'IDENTITY('.$deviceRepo->getTableAlias().'.lead)',
'expr' => 'eq',
'value' => $contactId,
],
],
],
'ignore_paginator' => true,
]
);
if ($devices && $device = reset($devices)) {
$context['device'] = [
'name' => $device->getDevice(),
'brand' => $device->getDeviceBrand(),
'model' => $device->getDeviceModel(),
'fingerprint' => $device->getDeviceFingerprint(),
'trackingId' => $device->getTrackingId(),
'os' => [
'osName' => $device->getDeviceOsName(),
'osShortName' => $device->getDeviceOsShortName(),
'osVersion' => $device->getDeviceOsVersion(),
'osPlatform' => $device->getDeviceOsPlatform(),
],
];
}
}
$fieldGroups = $contact->getFields();
if ($fieldGroups) {
foreach ($fieldGroups as $fgKey => $fieldGroup) {
foreach ($fieldGroup as $fkey => $field) {
$value = isset($field['value']) ? $field['value'] : '';
$type = isset($field['type']) ? $field['type'] : '';
if ('' !== $value && in_array($type, ['datetime', 'date', 'time'])) {
// Soft support for labels/values as dates/times.
@$newValue = $this->dateFormatHelper->format($value);
if (null !== $newValue && '' !== $newValue) {
$value = $newValue;
}
}
$context[$fkey] = $value;
if ($type) {
$conType[$fkey] = $type;
}
}
}
}
// Support multiple contacts in the future if needed by uncommenting a bit here.
// $contacts = !empty($this->context['contacts']) ? $this->context['contacts'] : [];
// Set the context to this contact.
$this->sanitizeContext($context);
$this->context = array_merge($this->context, $context);
$this->conType = array_merge($this->conType, $conType);
// Support multiple contacts for future batch processing.
// $this->context['contacts'] = $contacts;
// $this->context['contacts'][$context['id']] = $context;
return $this;
} | php | public function addContextContact(Contact $contact = null)
{
if (!$contact) {
return $this;
}
$context = [];
$conType = [];
// Append contact ID.
$contactId = (int) $contact->getId();
$context['id'] = isset($contactId) ? $contactId : null;
$conType['id'] = 'number';
// Append contact owner data.
$owner = $contact->getOwner();
$context['owner'] = [];
$context['owner']['id'] = $owner ? $owner->getId() : null;
$conType['owner']['id'] = 'number';
$context['owner']['username'] = $owner ? $owner->getUsername() : null;
$context['owner']['firstName'] = $owner ? $owner->getFirstName() : null;
$context['owner']['lastName'] = $owner ? $owner->getLastName() : null;
$context['owner']['email'] = $owner ? $owner->getEmail() : null;
// Append points value.
$points = $contact->getPoints();
$context['points'] = isset($points) ? $points : null;
$conType['points'] = 'number';
// Append IP Addresses.
$context['ipAddresses'] = [];
$context['ip'] = null;
foreach ($contact->getIpAddresses()->toArray() as $ip => $value) {
$context['ipAddresses'][] = $ip;
$context['ip'] = $ip;
}
// Add Identified date.
/** @var \DateTime $dateIdentified */
$dateIdentified = $contact->getDateIdentified();
$context['dateIdentified'] = $dateIdentified ? $this->dateFormatHelper->format($dateIdentified) : null;
$conType['dateIdentified'] = 'datetime';
// Add Modified date.
/** @var \DateTime $dateModified */
$dateModified = $contact->getDateModified();
$context['dateModified'] = $dateModified ? $this->dateFormatHelper->format($dateModified) : null;
$conType['dateModified'] = 'datetime';
// Add DNC data.
$context['doNotContacts'] = [];
$context['doNotContact'] = false;
if ($contactId && $this->needsDncData) {
/** @var \Mautic\LeadBundle\Model\DoNotContact $record */
foreach ($contact->getDoNotContact() as $record) {
$context['doNotContacts'][$record->getChannel()] = [
'comments' => $record->getComments(),
'reason' => $record->getReason(),
'exists' => true,
];
$conType['doNotContacts'][$record->getChannel()]['exists'] = 'boolean';
$context['doNotContact'] = true;
}
$conType['doNotContact'] = 'boolean';
}
// Add UTM data.
$context['utm'] = [
'campaign' => null,
'content' => null,
'medium' => null,
'query' => null,
'referrer' => null,
'remoteHost' => null,
'source' => null,
'term' => null,
'url' => null,
'userAgent' => null,
];
if ($contactId && $this->needsUtmData) {
$utmTags = $this->utmSourceHelper->getSortedUtmTags($contact);
$context['utmTags'] = [];
if ($utmTags) {
foreach ($utmTags as $utmTag) {
$tags = [
'campaign' => $utmTag->getUtmCampaign(),
'content' => $utmTag->getUtmContent(),
'medium' => $utmTag->getUtmMedium(),
'query' => $utmTag->getQuery(),
'referrer' => $utmTag->getReferer(),
'remoteHost' => $utmTag->getRemoteHost(),
'source' => $utmTag->getUtmSource(),
'term' => $utmTag->getUtmTerm(),
'url' => $utmTag->getUrl(),
'userAgent' => $utmTag->getUserAgent(),
];
$context['utmTags'][] = $tags;
// Override the {{ utm.values }} to be the latest non-empty version of each found.
foreach ($tags as $key => $value) {
if (!empty($value)) {
$context['utm'][$key] = $value;
}
}
}
}
}
// Add Device data.
$context['device'] = [
'name' => null,
'brand' => null,
'model' => null,
'fingerprint' => null,
'trackingId' => null,
'os' => [
'osName' => null,
'osShortName' => null,
'osVersion' => null,
'osPlatform' => null,
],
];
if ($contactId && $this->needsDeviceData) {
/** @var LeadDeviceRepository $deviceRepo */
$deviceRepo = $this->contactModel->getDeviceRepository();
$devices = $deviceRepo->getEntities(
[
'limit' => 1,
'orderBy' => $deviceRepo->getTableAlias().'.id',
'orderByDir' => 'DESC',
'filter' => [
'force' => [
[
'column' => 'IDENTITY('.$deviceRepo->getTableAlias().'.lead)',
'expr' => 'eq',
'value' => $contactId,
],
],
],
'ignore_paginator' => true,
]
);
if ($devices && $device = reset($devices)) {
$context['device'] = [
'name' => $device->getDevice(),
'brand' => $device->getDeviceBrand(),
'model' => $device->getDeviceModel(),
'fingerprint' => $device->getDeviceFingerprint(),
'trackingId' => $device->getTrackingId(),
'os' => [
'osName' => $device->getDeviceOsName(),
'osShortName' => $device->getDeviceOsShortName(),
'osVersion' => $device->getDeviceOsVersion(),
'osPlatform' => $device->getDeviceOsPlatform(),
],
];
}
}
$fieldGroups = $contact->getFields();
if ($fieldGroups) {
foreach ($fieldGroups as $fgKey => $fieldGroup) {
foreach ($fieldGroup as $fkey => $field) {
$value = isset($field['value']) ? $field['value'] : '';
$type = isset($field['type']) ? $field['type'] : '';
if ('' !== $value && in_array($type, ['datetime', 'date', 'time'])) {
// Soft support for labels/values as dates/times.
@$newValue = $this->dateFormatHelper->format($value);
if (null !== $newValue && '' !== $newValue) {
$value = $newValue;
}
}
$context[$fkey] = $value;
if ($type) {
$conType[$fkey] = $type;
}
}
}
}
// Support multiple contacts in the future if needed by uncommenting a bit here.
// $contacts = !empty($this->context['contacts']) ? $this->context['contacts'] : [];
// Set the context to this contact.
$this->sanitizeContext($context);
$this->context = array_merge($this->context, $context);
$this->conType = array_merge($this->conType, $conType);
// Support multiple contacts for future batch processing.
// $this->context['contacts'] = $contacts;
// $this->context['contacts'][$context['id']] = $context;
return $this;
} | [
"public",
"function",
"addContextContact",
"(",
"Contact",
"$",
"contact",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"$",
"contact",
")",
"{",
"return",
"$",
"this",
";",
"}",
"$",
"context",
"=",
"[",
"]",
";",
"$",
"conType",
"=",
"[",
"]",
";",
"// Append contact ID.",
"$",
"contactId",
"=",
"(",
"int",
")",
"$",
"contact",
"->",
"getId",
"(",
")",
";",
"$",
"context",
"[",
"'id'",
"]",
"=",
"isset",
"(",
"$",
"contactId",
")",
"?",
"$",
"contactId",
":",
"null",
";",
"$",
"conType",
"[",
"'id'",
"]",
"=",
"'number'",
";",
"// Append contact owner data.",
"$",
"owner",
"=",
"$",
"contact",
"->",
"getOwner",
"(",
")",
";",
"$",
"context",
"[",
"'owner'",
"]",
"=",
"[",
"]",
";",
"$",
"context",
"[",
"'owner'",
"]",
"[",
"'id'",
"]",
"=",
"$",
"owner",
"?",
"$",
"owner",
"->",
"getId",
"(",
")",
":",
"null",
";",
"$",
"conType",
"[",
"'owner'",
"]",
"[",
"'id'",
"]",
"=",
"'number'",
";",
"$",
"context",
"[",
"'owner'",
"]",
"[",
"'username'",
"]",
"=",
"$",
"owner",
"?",
"$",
"owner",
"->",
"getUsername",
"(",
")",
":",
"null",
";",
"$",
"context",
"[",
"'owner'",
"]",
"[",
"'firstName'",
"]",
"=",
"$",
"owner",
"?",
"$",
"owner",
"->",
"getFirstName",
"(",
")",
":",
"null",
";",
"$",
"context",
"[",
"'owner'",
"]",
"[",
"'lastName'",
"]",
"=",
"$",
"owner",
"?",
"$",
"owner",
"->",
"getLastName",
"(",
")",
":",
"null",
";",
"$",
"context",
"[",
"'owner'",
"]",
"[",
"'email'",
"]",
"=",
"$",
"owner",
"?",
"$",
"owner",
"->",
"getEmail",
"(",
")",
":",
"null",
";",
"// Append points value.",
"$",
"points",
"=",
"$",
"contact",
"->",
"getPoints",
"(",
")",
";",
"$",
"context",
"[",
"'points'",
"]",
"=",
"isset",
"(",
"$",
"points",
")",
"?",
"$",
"points",
":",
"null",
";",
"$",
"conType",
"[",
"'points'",
"]",
"=",
"'number'",
";",
"// Append IP Addresses.",
"$",
"context",
"[",
"'ipAddresses'",
"]",
"=",
"[",
"]",
";",
"$",
"context",
"[",
"'ip'",
"]",
"=",
"null",
";",
"foreach",
"(",
"$",
"contact",
"->",
"getIpAddresses",
"(",
")",
"->",
"toArray",
"(",
")",
"as",
"$",
"ip",
"=>",
"$",
"value",
")",
"{",
"$",
"context",
"[",
"'ipAddresses'",
"]",
"[",
"]",
"=",
"$",
"ip",
";",
"$",
"context",
"[",
"'ip'",
"]",
"=",
"$",
"ip",
";",
"}",
"// Add Identified date.",
"/** @var \\DateTime $dateIdentified */",
"$",
"dateIdentified",
"=",
"$",
"contact",
"->",
"getDateIdentified",
"(",
")",
";",
"$",
"context",
"[",
"'dateIdentified'",
"]",
"=",
"$",
"dateIdentified",
"?",
"$",
"this",
"->",
"dateFormatHelper",
"->",
"format",
"(",
"$",
"dateIdentified",
")",
":",
"null",
";",
"$",
"conType",
"[",
"'dateIdentified'",
"]",
"=",
"'datetime'",
";",
"// Add Modified date.",
"/** @var \\DateTime $dateModified */",
"$",
"dateModified",
"=",
"$",
"contact",
"->",
"getDateModified",
"(",
")",
";",
"$",
"context",
"[",
"'dateModified'",
"]",
"=",
"$",
"dateModified",
"?",
"$",
"this",
"->",
"dateFormatHelper",
"->",
"format",
"(",
"$",
"dateModified",
")",
":",
"null",
";",
"$",
"conType",
"[",
"'dateModified'",
"]",
"=",
"'datetime'",
";",
"// Add DNC data.",
"$",
"context",
"[",
"'doNotContacts'",
"]",
"=",
"[",
"]",
";",
"$",
"context",
"[",
"'doNotContact'",
"]",
"=",
"false",
";",
"if",
"(",
"$",
"contactId",
"&&",
"$",
"this",
"->",
"needsDncData",
")",
"{",
"/** @var \\Mautic\\LeadBundle\\Model\\DoNotContact $record */",
"foreach",
"(",
"$",
"contact",
"->",
"getDoNotContact",
"(",
")",
"as",
"$",
"record",
")",
"{",
"$",
"context",
"[",
"'doNotContacts'",
"]",
"[",
"$",
"record",
"->",
"getChannel",
"(",
")",
"]",
"=",
"[",
"'comments'",
"=>",
"$",
"record",
"->",
"getComments",
"(",
")",
",",
"'reason'",
"=>",
"$",
"record",
"->",
"getReason",
"(",
")",
",",
"'exists'",
"=>",
"true",
",",
"]",
";",
"$",
"conType",
"[",
"'doNotContacts'",
"]",
"[",
"$",
"record",
"->",
"getChannel",
"(",
")",
"]",
"[",
"'exists'",
"]",
"=",
"'boolean'",
";",
"$",
"context",
"[",
"'doNotContact'",
"]",
"=",
"true",
";",
"}",
"$",
"conType",
"[",
"'doNotContact'",
"]",
"=",
"'boolean'",
";",
"}",
"// Add UTM data.",
"$",
"context",
"[",
"'utm'",
"]",
"=",
"[",
"'campaign'",
"=>",
"null",
",",
"'content'",
"=>",
"null",
",",
"'medium'",
"=>",
"null",
",",
"'query'",
"=>",
"null",
",",
"'referrer'",
"=>",
"null",
",",
"'remoteHost'",
"=>",
"null",
",",
"'source'",
"=>",
"null",
",",
"'term'",
"=>",
"null",
",",
"'url'",
"=>",
"null",
",",
"'userAgent'",
"=>",
"null",
",",
"]",
";",
"if",
"(",
"$",
"contactId",
"&&",
"$",
"this",
"->",
"needsUtmData",
")",
"{",
"$",
"utmTags",
"=",
"$",
"this",
"->",
"utmSourceHelper",
"->",
"getSortedUtmTags",
"(",
"$",
"contact",
")",
";",
"$",
"context",
"[",
"'utmTags'",
"]",
"=",
"[",
"]",
";",
"if",
"(",
"$",
"utmTags",
")",
"{",
"foreach",
"(",
"$",
"utmTags",
"as",
"$",
"utmTag",
")",
"{",
"$",
"tags",
"=",
"[",
"'campaign'",
"=>",
"$",
"utmTag",
"->",
"getUtmCampaign",
"(",
")",
",",
"'content'",
"=>",
"$",
"utmTag",
"->",
"getUtmContent",
"(",
")",
",",
"'medium'",
"=>",
"$",
"utmTag",
"->",
"getUtmMedium",
"(",
")",
",",
"'query'",
"=>",
"$",
"utmTag",
"->",
"getQuery",
"(",
")",
",",
"'referrer'",
"=>",
"$",
"utmTag",
"->",
"getReferer",
"(",
")",
",",
"'remoteHost'",
"=>",
"$",
"utmTag",
"->",
"getRemoteHost",
"(",
")",
",",
"'source'",
"=>",
"$",
"utmTag",
"->",
"getUtmSource",
"(",
")",
",",
"'term'",
"=>",
"$",
"utmTag",
"->",
"getUtmTerm",
"(",
")",
",",
"'url'",
"=>",
"$",
"utmTag",
"->",
"getUrl",
"(",
")",
",",
"'userAgent'",
"=>",
"$",
"utmTag",
"->",
"getUserAgent",
"(",
")",
",",
"]",
";",
"$",
"context",
"[",
"'utmTags'",
"]",
"[",
"]",
"=",
"$",
"tags",
";",
"// Override the {{ utm.values }} to be the latest non-empty version of each found.",
"foreach",
"(",
"$",
"tags",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"value",
")",
")",
"{",
"$",
"context",
"[",
"'utm'",
"]",
"[",
"$",
"key",
"]",
"=",
"$",
"value",
";",
"}",
"}",
"}",
"}",
"}",
"// Add Device data.",
"$",
"context",
"[",
"'device'",
"]",
"=",
"[",
"'name'",
"=>",
"null",
",",
"'brand'",
"=>",
"null",
",",
"'model'",
"=>",
"null",
",",
"'fingerprint'",
"=>",
"null",
",",
"'trackingId'",
"=>",
"null",
",",
"'os'",
"=>",
"[",
"'osName'",
"=>",
"null",
",",
"'osShortName'",
"=>",
"null",
",",
"'osVersion'",
"=>",
"null",
",",
"'osPlatform'",
"=>",
"null",
",",
"]",
",",
"]",
";",
"if",
"(",
"$",
"contactId",
"&&",
"$",
"this",
"->",
"needsDeviceData",
")",
"{",
"/** @var LeadDeviceRepository $deviceRepo */",
"$",
"deviceRepo",
"=",
"$",
"this",
"->",
"contactModel",
"->",
"getDeviceRepository",
"(",
")",
";",
"$",
"devices",
"=",
"$",
"deviceRepo",
"->",
"getEntities",
"(",
"[",
"'limit'",
"=>",
"1",
",",
"'orderBy'",
"=>",
"$",
"deviceRepo",
"->",
"getTableAlias",
"(",
")",
".",
"'.id'",
",",
"'orderByDir'",
"=>",
"'DESC'",
",",
"'filter'",
"=>",
"[",
"'force'",
"=>",
"[",
"[",
"'column'",
"=>",
"'IDENTITY('",
".",
"$",
"deviceRepo",
"->",
"getTableAlias",
"(",
")",
".",
"'.lead)'",
",",
"'expr'",
"=>",
"'eq'",
",",
"'value'",
"=>",
"$",
"contactId",
",",
"]",
",",
"]",
",",
"]",
",",
"'ignore_paginator'",
"=>",
"true",
",",
"]",
")",
";",
"if",
"(",
"$",
"devices",
"&&",
"$",
"device",
"=",
"reset",
"(",
"$",
"devices",
")",
")",
"{",
"$",
"context",
"[",
"'device'",
"]",
"=",
"[",
"'name'",
"=>",
"$",
"device",
"->",
"getDevice",
"(",
")",
",",
"'brand'",
"=>",
"$",
"device",
"->",
"getDeviceBrand",
"(",
")",
",",
"'model'",
"=>",
"$",
"device",
"->",
"getDeviceModel",
"(",
")",
",",
"'fingerprint'",
"=>",
"$",
"device",
"->",
"getDeviceFingerprint",
"(",
")",
",",
"'trackingId'",
"=>",
"$",
"device",
"->",
"getTrackingId",
"(",
")",
",",
"'os'",
"=>",
"[",
"'osName'",
"=>",
"$",
"device",
"->",
"getDeviceOsName",
"(",
")",
",",
"'osShortName'",
"=>",
"$",
"device",
"->",
"getDeviceOsShortName",
"(",
")",
",",
"'osVersion'",
"=>",
"$",
"device",
"->",
"getDeviceOsVersion",
"(",
")",
",",
"'osPlatform'",
"=>",
"$",
"device",
"->",
"getDeviceOsPlatform",
"(",
")",
",",
"]",
",",
"]",
";",
"}",
"}",
"$",
"fieldGroups",
"=",
"$",
"contact",
"->",
"getFields",
"(",
")",
";",
"if",
"(",
"$",
"fieldGroups",
")",
"{",
"foreach",
"(",
"$",
"fieldGroups",
"as",
"$",
"fgKey",
"=>",
"$",
"fieldGroup",
")",
"{",
"foreach",
"(",
"$",
"fieldGroup",
"as",
"$",
"fkey",
"=>",
"$",
"field",
")",
"{",
"$",
"value",
"=",
"isset",
"(",
"$",
"field",
"[",
"'value'",
"]",
")",
"?",
"$",
"field",
"[",
"'value'",
"]",
":",
"''",
";",
"$",
"type",
"=",
"isset",
"(",
"$",
"field",
"[",
"'type'",
"]",
")",
"?",
"$",
"field",
"[",
"'type'",
"]",
":",
"''",
";",
"if",
"(",
"''",
"!==",
"$",
"value",
"&&",
"in_array",
"(",
"$",
"type",
",",
"[",
"'datetime'",
",",
"'date'",
",",
"'time'",
"]",
")",
")",
"{",
"// Soft support for labels/values as dates/times.",
"@",
"$",
"newValue",
"=",
"$",
"this",
"->",
"dateFormatHelper",
"->",
"format",
"(",
"$",
"value",
")",
";",
"if",
"(",
"null",
"!==",
"$",
"newValue",
"&&",
"''",
"!==",
"$",
"newValue",
")",
"{",
"$",
"value",
"=",
"$",
"newValue",
";",
"}",
"}",
"$",
"context",
"[",
"$",
"fkey",
"]",
"=",
"$",
"value",
";",
"if",
"(",
"$",
"type",
")",
"{",
"$",
"conType",
"[",
"$",
"fkey",
"]",
"=",
"$",
"type",
";",
"}",
"}",
"}",
"}",
"// Support multiple contacts in the future if needed by uncommenting a bit here.",
"// $contacts = !empty($this->context['contacts']) ? $this->context['contacts'] : [];",
"// Set the context to this contact.",
"$",
"this",
"->",
"sanitizeContext",
"(",
"$",
"context",
")",
";",
"$",
"this",
"->",
"context",
"=",
"array_merge",
"(",
"$",
"this",
"->",
"context",
",",
"$",
"context",
")",
";",
"$",
"this",
"->",
"conType",
"=",
"array_merge",
"(",
"$",
"this",
"->",
"conType",
",",
"$",
"conType",
")",
";",
"// Support multiple contacts for future batch processing.",
"// $this->context['contacts'] = $contacts;",
"// $this->context['contacts'][$context['id']] = $context;",
"return",
"$",
"this",
";",
"}"
] | Given a Contact, flatten the field values a bit into a more user friendly list of token possibilities.
@param Contact|null $contact
@return $this | [
"Given",
"a",
"Contact",
"flatten",
"the",
"field",
"values",
"a",
"bit",
"into",
"a",
"more",
"user",
"friendly",
"list",
"of",
"token",
"possibilities",
"."
] | train | https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Helper/TokenHelper.php#L969-L1160 |
TheDMSGroup/mautic-contact-client | Helper/TokenHelper.php | TokenHelper.addContextEvent | public function addContextEvent($event = [])
{
$contactId = isset($this->context['id']) ? $this->context['id'] : 0;
$this->context['event']['id'] = !empty($event['id']) ? (int) $event['id'] : null;
$this->context['event']['name'] = !empty($event['name']) ? $event['name'] : null;
$this->context['event']['token'] = null;
if ($contactId || $this->context['event']['id'] || $this->context['campaign']['id']) {
$this->context['event']['token'] = $this->eventTokenEncode(
[
$this->context['campaign']['id'],
$this->context['event']['id'],
$contactId,
]
);
}
} | php | public function addContextEvent($event = [])
{
$contactId = isset($this->context['id']) ? $this->context['id'] : 0;
$this->context['event']['id'] = !empty($event['id']) ? (int) $event['id'] : null;
$this->context['event']['name'] = !empty($event['name']) ? $event['name'] : null;
$this->context['event']['token'] = null;
if ($contactId || $this->context['event']['id'] || $this->context['campaign']['id']) {
$this->context['event']['token'] = $this->eventTokenEncode(
[
$this->context['campaign']['id'],
$this->context['event']['id'],
$contactId,
]
);
}
} | [
"public",
"function",
"addContextEvent",
"(",
"$",
"event",
"=",
"[",
"]",
")",
"{",
"$",
"contactId",
"=",
"isset",
"(",
"$",
"this",
"->",
"context",
"[",
"'id'",
"]",
")",
"?",
"$",
"this",
"->",
"context",
"[",
"'id'",
"]",
":",
"0",
";",
"$",
"this",
"->",
"context",
"[",
"'event'",
"]",
"[",
"'id'",
"]",
"=",
"!",
"empty",
"(",
"$",
"event",
"[",
"'id'",
"]",
")",
"?",
"(",
"int",
")",
"$",
"event",
"[",
"'id'",
"]",
":",
"null",
";",
"$",
"this",
"->",
"context",
"[",
"'event'",
"]",
"[",
"'name'",
"]",
"=",
"!",
"empty",
"(",
"$",
"event",
"[",
"'name'",
"]",
")",
"?",
"$",
"event",
"[",
"'name'",
"]",
":",
"null",
";",
"$",
"this",
"->",
"context",
"[",
"'event'",
"]",
"[",
"'token'",
"]",
"=",
"null",
";",
"if",
"(",
"$",
"contactId",
"||",
"$",
"this",
"->",
"context",
"[",
"'event'",
"]",
"[",
"'id'",
"]",
"||",
"$",
"this",
"->",
"context",
"[",
"'campaign'",
"]",
"[",
"'id'",
"]",
")",
"{",
"$",
"this",
"->",
"context",
"[",
"'event'",
"]",
"[",
"'token'",
"]",
"=",
"$",
"this",
"->",
"eventTokenEncode",
"(",
"[",
"$",
"this",
"->",
"context",
"[",
"'campaign'",
"]",
"[",
"'id'",
"]",
",",
"$",
"this",
"->",
"context",
"[",
"'event'",
"]",
"[",
"'id'",
"]",
",",
"$",
"contactId",
",",
"]",
")",
";",
"}",
"}"
] | Take an event array and use it to enhance the context for later dispositional callback.
Campaign context should be added before this, as it is used for the token.
@param array $event | [
"Take",
"an",
"event",
"array",
"and",
"use",
"it",
"to",
"enhance",
"the",
"context",
"for",
"later",
"dispositional",
"callback",
".",
"Campaign",
"context",
"should",
"be",
"added",
"before",
"this",
"as",
"it",
"is",
"used",
"for",
"the",
"token",
"."
] | train | https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Helper/TokenHelper.php#L1186-L1201 |
TheDMSGroup/mautic-contact-client | Helper/TokenHelper.php | TokenHelper.eventTokenEncode | private function eventTokenEncode($values)
{
list($campaignId, $eventId, $contactId) = $values;
$campaignIdString = $this->baseEncode((int) $campaignId);
$eventIdString = $this->baseEncode((int) $eventId);
$contactIdString = $this->baseEncode((int) $contactId);
return $campaignIdString.'0'.$eventIdString.'0'.$contactIdString;
} | php | private function eventTokenEncode($values)
{
list($campaignId, $eventId, $contactId) = $values;
$campaignIdString = $this->baseEncode((int) $campaignId);
$eventIdString = $this->baseEncode((int) $eventId);
$contactIdString = $this->baseEncode((int) $contactId);
return $campaignIdString.'0'.$eventIdString.'0'.$contactIdString;
} | [
"private",
"function",
"eventTokenEncode",
"(",
"$",
"values",
")",
"{",
"list",
"(",
"$",
"campaignId",
",",
"$",
"eventId",
",",
"$",
"contactId",
")",
"=",
"$",
"values",
";",
"$",
"campaignIdString",
"=",
"$",
"this",
"->",
"baseEncode",
"(",
"(",
"int",
")",
"$",
"campaignId",
")",
";",
"$",
"eventIdString",
"=",
"$",
"this",
"->",
"baseEncode",
"(",
"(",
"int",
")",
"$",
"eventId",
")",
";",
"$",
"contactIdString",
"=",
"$",
"this",
"->",
"baseEncode",
"(",
"(",
"int",
")",
"$",
"contactId",
")",
";",
"return",
"$",
"campaignIdString",
".",
"'0'",
".",
"$",
"eventIdString",
".",
"'0'",
".",
"$",
"contactIdString",
";",
"}"
] | Encode Campaign ID, Event ID, and Contact ID into a short base62 string.
Zeros are used as delimiters reducing the subsequent integers to base61.
@param $values
@return string | [
"Encode",
"Campaign",
"ID",
"Event",
"ID",
"and",
"Contact",
"ID",
"into",
"a",
"short",
"base62",
"string",
".",
"Zeros",
"are",
"used",
"as",
"delimiters",
"reducing",
"the",
"subsequent",
"integers",
"to",
"base61",
"."
] | train | https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Helper/TokenHelper.php#L1211-L1219 |
TheDMSGroup/mautic-contact-client | Helper/TokenHelper.php | TokenHelper.baseEncode | private function baseEncode($integer)
{
$b = 61;
$base = '123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$r = $integer % $b;
$result = $base[$r];
$q = floor($integer / $b);
while ($q) {
$r = $q % $b;
$q = floor($q / $b);
$result = $base[$r].$result;
}
return $result;
} | php | private function baseEncode($integer)
{
$b = 61;
$base = '123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$r = $integer % $b;
$result = $base[$r];
$q = floor($integer / $b);
while ($q) {
$r = $q % $b;
$q = floor($q / $b);
$result = $base[$r].$result;
}
return $result;
} | [
"private",
"function",
"baseEncode",
"(",
"$",
"integer",
")",
"{",
"$",
"b",
"=",
"61",
";",
"$",
"base",
"=",
"'123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'",
";",
"$",
"r",
"=",
"$",
"integer",
"%",
"$",
"b",
";",
"$",
"result",
"=",
"$",
"base",
"[",
"$",
"r",
"]",
";",
"$",
"q",
"=",
"floor",
"(",
"$",
"integer",
"/",
"$",
"b",
")",
";",
"while",
"(",
"$",
"q",
")",
"{",
"$",
"r",
"=",
"$",
"q",
"%",
"$",
"b",
";",
"$",
"q",
"=",
"floor",
"(",
"$",
"q",
"/",
"$",
"b",
")",
";",
"$",
"result",
"=",
"$",
"base",
"[",
"$",
"r",
"]",
".",
"$",
"result",
";",
"}",
"return",
"$",
"result",
";",
"}"
] | @param $integer
@param int $b
@return string | [
"@param",
"$integer",
"@param",
"int",
"$b"
] | train | https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Helper/TokenHelper.php#L1227-L1241 |
TheDMSGroup/mautic-contact-client | Helper/TokenHelper.php | TokenHelper.addContext | public function addContext($context = [])
{
if (!$context || empty($context)) {
return $this;
}
$this->nestContext($context);
$this->sanitizeContext($context);
$this->context = array_merge($this->context, $context);
return $this;
} | php | public function addContext($context = [])
{
if (!$context || empty($context)) {
return $this;
}
$this->nestContext($context);
$this->sanitizeContext($context);
$this->context = array_merge($this->context, $context);
return $this;
} | [
"public",
"function",
"addContext",
"(",
"$",
"context",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"!",
"$",
"context",
"||",
"empty",
"(",
"$",
"context",
")",
")",
"{",
"return",
"$",
"this",
";",
"}",
"$",
"this",
"->",
"nestContext",
"(",
"$",
"context",
")",
";",
"$",
"this",
"->",
"sanitizeContext",
"(",
"$",
"context",
")",
";",
"$",
"this",
"->",
"context",
"=",
"array_merge",
"(",
"$",
"this",
"->",
"context",
",",
"$",
"context",
")",
";",
"return",
"$",
"this",
";",
"}"
] | @param array $context
@return $this | [
"@param",
"array",
"$context"
] | train | https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Helper/TokenHelper.php#L1248-L1258 |
TheDMSGroup/mautic-contact-client | Helper/TokenHelper.php | TokenHelper.nestContext | private function nestContext(&$context)
{
foreach ($context as $key => $value) {
$dot = strpos($key, '.');
if ($dot && $dot !== strlen($key) - 1) {
$currentContext = &$context;
foreach (explode('.', $key) as $k) {
if (!isset($currentContext[$k])) {
$currentContext[$k] = [];
}
$currentContext = &$currentContext[$k];
}
$currentContext = $value;
unset($context[$key]);
}
}
return $context;
} | php | private function nestContext(&$context)
{
foreach ($context as $key => $value) {
$dot = strpos($key, '.');
if ($dot && $dot !== strlen($key) - 1) {
$currentContext = &$context;
foreach (explode('.', $key) as $k) {
if (!isset($currentContext[$k])) {
$currentContext[$k] = [];
}
$currentContext = &$currentContext[$k];
}
$currentContext = $value;
unset($context[$key]);
}
}
return $context;
} | [
"private",
"function",
"nestContext",
"(",
"&",
"$",
"context",
")",
"{",
"foreach",
"(",
"$",
"context",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"$",
"dot",
"=",
"strpos",
"(",
"$",
"key",
",",
"'.'",
")",
";",
"if",
"(",
"$",
"dot",
"&&",
"$",
"dot",
"!==",
"strlen",
"(",
"$",
"key",
")",
"-",
"1",
")",
"{",
"$",
"currentContext",
"=",
"&",
"$",
"context",
";",
"foreach",
"(",
"explode",
"(",
"'.'",
",",
"$",
"key",
")",
"as",
"$",
"k",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"currentContext",
"[",
"$",
"k",
"]",
")",
")",
"{",
"$",
"currentContext",
"[",
"$",
"k",
"]",
"=",
"[",
"]",
";",
"}",
"$",
"currentContext",
"=",
"&",
"$",
"currentContext",
"[",
"$",
"k",
"]",
";",
"}",
"$",
"currentContext",
"=",
"$",
"value",
";",
"unset",
"(",
"$",
"context",
"[",
"$",
"key",
"]",
")",
";",
"}",
"}",
"return",
"$",
"context",
";",
"}"
] | Nest keys containing dots as Mustache contextual arrays.
ex. ['utm.source' => 'value'] becomes ['utm' => ['source' => 'value']].
@param $context
@return mixed | [
"Nest",
"keys",
"containing",
"dots",
"as",
"Mustache",
"contextual",
"arrays",
".",
"ex",
".",
"[",
"utm",
".",
"source",
"=",
">",
"value",
"]",
"becomes",
"[",
"utm",
"=",
">",
"[",
"source",
"=",
">",
"value",
"]]",
"."
] | train | https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Helper/TokenHelper.php#L1268-L1286 |
TheDMSGroup/mautic-contact-client | Helper/TokenHelper.php | TokenHelper.render | public function render($template = '')
{
$result = $template;
if (is_array($template) || is_object($template)) {
// Recursively go down into an object/array to tokenize.
foreach ($result as &$val) {
$val = $this->render($val);
}
} elseif (
is_string($template)
&& strlen($template) >= self::TEMPLATE_MIN_LENGTH
&& false !== strpos($template, self::TOKEN_KEY_START)
&& false !== strpos($template, self::TOKEN_KEY_END)
) {
if (isset($this->renderCache[$template])) {
// Already tokenized this exact string.
$result = $this->renderCache[$template];
} else {
// A new or non-tokenized string.
$this->lastTemplate = $template;
set_error_handler([$this, 'handleMustacheErrors'], E_WARNING | E_NOTICE);
$result = $this->engine->render($template, $this->context);
restore_error_handler();
if (null !== $result && '' !== $result) {
// Store the result in cache for faster lookup later.
$this->renderCache[$template] = $result;
}
}
}
return $result;
} | php | public function render($template = '')
{
$result = $template;
if (is_array($template) || is_object($template)) {
// Recursively go down into an object/array to tokenize.
foreach ($result as &$val) {
$val = $this->render($val);
}
} elseif (
is_string($template)
&& strlen($template) >= self::TEMPLATE_MIN_LENGTH
&& false !== strpos($template, self::TOKEN_KEY_START)
&& false !== strpos($template, self::TOKEN_KEY_END)
) {
if (isset($this->renderCache[$template])) {
// Already tokenized this exact string.
$result = $this->renderCache[$template];
} else {
// A new or non-tokenized string.
$this->lastTemplate = $template;
set_error_handler([$this, 'handleMustacheErrors'], E_WARNING | E_NOTICE);
$result = $this->engine->render($template, $this->context);
restore_error_handler();
if (null !== $result && '' !== $result) {
// Store the result in cache for faster lookup later.
$this->renderCache[$template] = $result;
}
}
}
return $result;
} | [
"public",
"function",
"render",
"(",
"$",
"template",
"=",
"''",
")",
"{",
"$",
"result",
"=",
"$",
"template",
";",
"if",
"(",
"is_array",
"(",
"$",
"template",
")",
"||",
"is_object",
"(",
"$",
"template",
")",
")",
"{",
"// Recursively go down into an object/array to tokenize.",
"foreach",
"(",
"$",
"result",
"as",
"&",
"$",
"val",
")",
"{",
"$",
"val",
"=",
"$",
"this",
"->",
"render",
"(",
"$",
"val",
")",
";",
"}",
"}",
"elseif",
"(",
"is_string",
"(",
"$",
"template",
")",
"&&",
"strlen",
"(",
"$",
"template",
")",
">=",
"self",
"::",
"TEMPLATE_MIN_LENGTH",
"&&",
"false",
"!==",
"strpos",
"(",
"$",
"template",
",",
"self",
"::",
"TOKEN_KEY_START",
")",
"&&",
"false",
"!==",
"strpos",
"(",
"$",
"template",
",",
"self",
"::",
"TOKEN_KEY_END",
")",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"renderCache",
"[",
"$",
"template",
"]",
")",
")",
"{",
"// Already tokenized this exact string.",
"$",
"result",
"=",
"$",
"this",
"->",
"renderCache",
"[",
"$",
"template",
"]",
";",
"}",
"else",
"{",
"// A new or non-tokenized string.",
"$",
"this",
"->",
"lastTemplate",
"=",
"$",
"template",
";",
"set_error_handler",
"(",
"[",
"$",
"this",
",",
"'handleMustacheErrors'",
"]",
",",
"E_WARNING",
"|",
"E_NOTICE",
")",
";",
"$",
"result",
"=",
"$",
"this",
"->",
"engine",
"->",
"render",
"(",
"$",
"template",
",",
"$",
"this",
"->",
"context",
")",
";",
"restore_error_handler",
"(",
")",
";",
"if",
"(",
"null",
"!==",
"$",
"result",
"&&",
"''",
"!==",
"$",
"result",
")",
"{",
"// Store the result in cache for faster lookup later.",
"$",
"this",
"->",
"renderCache",
"[",
"$",
"template",
"]",
"=",
"$",
"result",
";",
"}",
"}",
"}",
"return",
"$",
"result",
";",
"}"
] | Replace Tokens in a simple string using an array for context.
@param string|array|object $template
@return string|array|object | [
"Replace",
"Tokens",
"in",
"a",
"simple",
"string",
"using",
"an",
"array",
"for",
"context",
"."
] | train | https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Helper/TokenHelper.php#L1295-L1326 |
TheDMSGroup/mautic-contact-client | Helper/TokenHelper.php | TokenHelper.getContext | public function getContext($flattened = false)
{
$result = [];
if ($flattened) {
$this->flattenArray($this->context, $result);
} else {
$result = $this->context;
}
return $result;
} | php | public function getContext($flattened = false)
{
$result = [];
if ($flattened) {
$this->flattenArray($this->context, $result);
} else {
$result = $this->context;
}
return $result;
} | [
"public",
"function",
"getContext",
"(",
"$",
"flattened",
"=",
"false",
")",
"{",
"$",
"result",
"=",
"[",
"]",
";",
"if",
"(",
"$",
"flattened",
")",
"{",
"$",
"this",
"->",
"flattenArray",
"(",
"$",
"this",
"->",
"context",
",",
"$",
"result",
")",
";",
"}",
"else",
"{",
"$",
"result",
"=",
"$",
"this",
"->",
"context",
";",
"}",
"return",
"$",
"result",
";",
"}"
] | @param bool $flattened
@return array | [
"@param",
"bool",
"$flattened"
] | train | https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Helper/TokenHelper.php#L1333-L1343 |
TheDMSGroup/mautic-contact-client | Helper/TokenHelper.php | TokenHelper.getContextLabeled | public function getContextLabeled($sort = true)
{
$result = [];
$labels = $this->describe($this->context);
$this->flattenArray($labels, $result);
$result['file_count'] = 'File: Number of contacts in this file';
$result['file_test'] = 'File: Inserts ".test" if testing';
$result['file_date'] = 'File: Date/time of file creation';
$result['file_type'] = 'File: Type of file, such as csv/xsl';
$result['file_compression'] = 'File: Compression of the file, such as zip/gz';
$result['file_extension'] = 'File: Automatic extension such as xsl/zip/csv';
$result['api_date'] = 'API: Date/time of the API request';
if ($sort) {
asort($result, SORT_STRING | SORT_FLAG_CASE | SORT_NATURAL);
}
return $result;
} | php | public function getContextLabeled($sort = true)
{
$result = [];
$labels = $this->describe($this->context);
$this->flattenArray($labels, $result);
$result['file_count'] = 'File: Number of contacts in this file';
$result['file_test'] = 'File: Inserts ".test" if testing';
$result['file_date'] = 'File: Date/time of file creation';
$result['file_type'] = 'File: Type of file, such as csv/xsl';
$result['file_compression'] = 'File: Compression of the file, such as zip/gz';
$result['file_extension'] = 'File: Automatic extension such as xsl/zip/csv';
$result['api_date'] = 'API: Date/time of the API request';
if ($sort) {
asort($result, SORT_STRING | SORT_FLAG_CASE | SORT_NATURAL);
}
return $result;
} | [
"public",
"function",
"getContextLabeled",
"(",
"$",
"sort",
"=",
"true",
")",
"{",
"$",
"result",
"=",
"[",
"]",
";",
"$",
"labels",
"=",
"$",
"this",
"->",
"describe",
"(",
"$",
"this",
"->",
"context",
")",
";",
"$",
"this",
"->",
"flattenArray",
"(",
"$",
"labels",
",",
"$",
"result",
")",
";",
"$",
"result",
"[",
"'file_count'",
"]",
"=",
"'File: Number of contacts in this file'",
";",
"$",
"result",
"[",
"'file_test'",
"]",
"=",
"'File: Inserts \".test\" if testing'",
";",
"$",
"result",
"[",
"'file_date'",
"]",
"=",
"'File: Date/time of file creation'",
";",
"$",
"result",
"[",
"'file_type'",
"]",
"=",
"'File: Type of file, such as csv/xsl'",
";",
"$",
"result",
"[",
"'file_compression'",
"]",
"=",
"'File: Compression of the file, such as zip/gz'",
";",
"$",
"result",
"[",
"'file_extension'",
"]",
"=",
"'File: Automatic extension such as xsl/zip/csv'",
";",
"$",
"result",
"[",
"'api_date'",
"]",
"=",
"'API: Date/time of the API request'",
";",
"if",
"(",
"$",
"sort",
")",
"{",
"asort",
"(",
"$",
"result",
",",
"SORT_STRING",
"|",
"SORT_FLAG_CASE",
"|",
"SORT_NATURAL",
")",
";",
"}",
"return",
"$",
"result",
";",
"}"
] | Get the context array labels instead of values for use in token suggestions.
@param bool $sort
@return array | [
"Get",
"the",
"context",
"array",
"labels",
"instead",
"of",
"values",
"for",
"use",
"in",
"token",
"suggestions",
"."
] | train | https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Helper/TokenHelper.php#L1382-L1401 |
TheDMSGroup/mautic-contact-client | Helper/TokenHelper.php | TokenHelper.describe | private function describe($array = [], $keys = '', $sort = true, $payload = false)
{
foreach ($array as $key => &$value) {
if (is_array($value)) {
if (0 === count($value)) {
// Currently such groups are undocumented, so labels are not needed.
unset($array[$key]);
continue;
} else {
$value = $this->describe($value, $keys.' '.$key, $sort, ($payload || 'payload' === $key));
}
} else {
if ($payload) {
// $value = implode('.', explode(' ', trim($keys))).'.'.$key;
// Use the last key for easy finding as these get long.
$value = $key;
} elseif (is_bool($value) || null === $value || 0 === $value) {
// Discern the "label" given the key and previous keys conjoined.
$totalKey = str_replace('_', ' ', $keys.' '.trim($key));
preg_match_all('/(?:|[A-Z])[a-z]*/', $totalKey, $words);
foreach ($words[0] as &$word) {
if (strlen($word) > 1) {
// Change the case of the first letter without dropping the case of the rest of the word.
$word = strtoupper(substr($word, 0, 1)).substr($word, 1);
}
}
// Combine down to one string without extra whitespace.
$value = trim(preg_replace('/\s+/', ' ', implode(' ', $words[0])));
// One exception is UTM variables.
$value = str_replace('Utm ', 'UTM ', $value);
}
}
}
if ($sort) {
ksort($array, SORT_NATURAL);
}
return $array;
} | php | private function describe($array = [], $keys = '', $sort = true, $payload = false)
{
foreach ($array as $key => &$value) {
if (is_array($value)) {
if (0 === count($value)) {
// Currently such groups are undocumented, so labels are not needed.
unset($array[$key]);
continue;
} else {
$value = $this->describe($value, $keys.' '.$key, $sort, ($payload || 'payload' === $key));
}
} else {
if ($payload) {
// $value = implode('.', explode(' ', trim($keys))).'.'.$key;
// Use the last key for easy finding as these get long.
$value = $key;
} elseif (is_bool($value) || null === $value || 0 === $value) {
// Discern the "label" given the key and previous keys conjoined.
$totalKey = str_replace('_', ' ', $keys.' '.trim($key));
preg_match_all('/(?:|[A-Z])[a-z]*/', $totalKey, $words);
foreach ($words[0] as &$word) {
if (strlen($word) > 1) {
// Change the case of the first letter without dropping the case of the rest of the word.
$word = strtoupper(substr($word, 0, 1)).substr($word, 1);
}
}
// Combine down to one string without extra whitespace.
$value = trim(preg_replace('/\s+/', ' ', implode(' ', $words[0])));
// One exception is UTM variables.
$value = str_replace('Utm ', 'UTM ', $value);
}
}
}
if ($sort) {
ksort($array, SORT_NATURAL);
}
return $array;
} | [
"private",
"function",
"describe",
"(",
"$",
"array",
"=",
"[",
"]",
",",
"$",
"keys",
"=",
"''",
",",
"$",
"sort",
"=",
"true",
",",
"$",
"payload",
"=",
"false",
")",
"{",
"foreach",
"(",
"$",
"array",
"as",
"$",
"key",
"=>",
"&",
"$",
"value",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"value",
")",
")",
"{",
"if",
"(",
"0",
"===",
"count",
"(",
"$",
"value",
")",
")",
"{",
"// Currently such groups are undocumented, so labels are not needed.",
"unset",
"(",
"$",
"array",
"[",
"$",
"key",
"]",
")",
";",
"continue",
";",
"}",
"else",
"{",
"$",
"value",
"=",
"$",
"this",
"->",
"describe",
"(",
"$",
"value",
",",
"$",
"keys",
".",
"' '",
".",
"$",
"key",
",",
"$",
"sort",
",",
"(",
"$",
"payload",
"||",
"'payload'",
"===",
"$",
"key",
")",
")",
";",
"}",
"}",
"else",
"{",
"if",
"(",
"$",
"payload",
")",
"{",
"// $value = implode('.', explode(' ', trim($keys))).'.'.$key;",
"// Use the last key for easy finding as these get long.",
"$",
"value",
"=",
"$",
"key",
";",
"}",
"elseif",
"(",
"is_bool",
"(",
"$",
"value",
")",
"||",
"null",
"===",
"$",
"value",
"||",
"0",
"===",
"$",
"value",
")",
"{",
"// Discern the \"label\" given the key and previous keys conjoined.",
"$",
"totalKey",
"=",
"str_replace",
"(",
"'_'",
",",
"' '",
",",
"$",
"keys",
".",
"' '",
".",
"trim",
"(",
"$",
"key",
")",
")",
";",
"preg_match_all",
"(",
"'/(?:|[A-Z])[a-z]*/'",
",",
"$",
"totalKey",
",",
"$",
"words",
")",
";",
"foreach",
"(",
"$",
"words",
"[",
"0",
"]",
"as",
"&",
"$",
"word",
")",
"{",
"if",
"(",
"strlen",
"(",
"$",
"word",
")",
">",
"1",
")",
"{",
"// Change the case of the first letter without dropping the case of the rest of the word.",
"$",
"word",
"=",
"strtoupper",
"(",
"substr",
"(",
"$",
"word",
",",
"0",
",",
"1",
")",
")",
".",
"substr",
"(",
"$",
"word",
",",
"1",
")",
";",
"}",
"}",
"// Combine down to one string without extra whitespace.",
"$",
"value",
"=",
"trim",
"(",
"preg_replace",
"(",
"'/\\s+/'",
",",
"' '",
",",
"implode",
"(",
"' '",
",",
"$",
"words",
"[",
"0",
"]",
")",
")",
")",
";",
"// One exception is UTM variables.",
"$",
"value",
"=",
"str_replace",
"(",
"'Utm '",
",",
"'UTM '",
",",
"$",
"value",
")",
";",
"}",
"}",
"}",
"if",
"(",
"$",
"sort",
")",
"{",
"ksort",
"(",
"$",
"array",
",",
"SORT_NATURAL",
")",
";",
"}",
"return",
"$",
"array",
";",
"}"
] | Given a token array, set the values to the labels for the context if possible.
@param array $array
@param string $keys
@param bool $sort
@param bool $payload
@return array | [
"Given",
"a",
"token",
"array",
"set",
"the",
"values",
"to",
"the",
"labels",
"for",
"the",
"context",
"if",
"possible",
"."
] | train | https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Helper/TokenHelper.php#L1413-L1452 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.