function units_mathematical_expression_create_from_infix in Units of Measurement 7.2
Create mathematical expression object from infix notation.
Parameters
string $infix_mathematical_expression: Mathematical expression written down in infix notation
Return value
\UnitsMathematicalExpressionWrapper In-memory representation of the provided mathematical expression
Throws
\UnitsMathematicalExpressionMalformedException
1 call to units_mathematical_expression_create_from_infix()
- units_mathematical_expression_element_validate in ./
units.module - Validate function for 'units_mathematical_expression' form element.
File
- ./
units.module, line 683 - Provide API for managing and converting units of measurement.
Code
function units_mathematical_expression_create_from_infix($infix_mathematical_expression) {
$infix_mathematical_expression = array_filter(explode(' ', $infix_mathematical_expression), 'units_mathematical_expression_array_filter');
if (empty($infix_mathematical_expression)) {
return NULL;
}
$operators = units_get_operator_by_sign();
// This is an implementation of shunting-yard algorithm.
$stack = array();
$output = array();
foreach ($infix_mathematical_expression as $token) {
if (is_numeric($token) || $token == UNITS_QUANTITY) {
$output[] = $token;
}
elseif ($unit = units_unit_machine_name_load($token)) {
$output[] = $unit
->toPostfix();
}
elseif (isset($operators[$token])) {
while (!empty($stack) && isset($operators[$stack[count($stack) - 1]]) && $operators[$token]['precedence'] <= $operators[$stack[count($stack) - 1]]['precedence']) {
$output[] = array_pop($stack);
}
$stack[] = $token;
}
elseif ($token == '(') {
$stack[] = $token;
}
elseif ($token == ')') {
while (!empty($stack) && end($stack) != '(') {
$output[] = array_pop($stack);
}
// Popping out the opening parenthesis "(" symbol.
array_pop($stack);
}
else {
throw new UnitsMathematicalExpressionMalformedException(t('Unknown token: @token', array(
'@token' => $token,
)));
}
}
while (!empty($stack)) {
$output[] = array_pop($stack);
}
return units_mathematical_expression_create_from_postfix(implode(' ', $output));
}