diff --git a/handlers/views_handler_field_math.inc b/handlers/views_handler_field_math.inc index 08fba06..5bdfbff 100644 --- a/handlers/views_handler_field_math.inc +++ b/handlers/views_handler_field_math.inc @@ -40,9 +40,88 @@ class views_handler_field_math extends views_handler_field_numeric { unset($form['alter']['help']); } + /** + * Unformat number. + * + * @param string $number + * The formatted number. + * @param bool $force_number + * Force to convert to number or not. + * @param string $dec_point + * Decimal point. + * @param string $thousands_sep + * Thousand separator. + * + * @return string + * Unformat number. + */ + function number_unformat($number, $force_number = FALSE, $dec_point = '.', $thousands_sep = ',') { + if ($force_number) { + $number = preg_replace('/^[^\d-]+/', '', $number); + } + else { + if (preg_match('/^[^\d]+/', $number)) { + return FALSE; + } + } + $type = (strpos($number, $dec_point) === FALSE) ? 'int' : 'float'; + $number = str_replace(array($dec_point, $thousands_sep), array( + '.', + '' + ), $number); + settype($number, $type); + return $number; + } + + /** + * Unformat token value. + * + * @param string $token_value + * The token value. + * @param string $token_name + * The token name ([field_a]). + * @param object $values + * View result at each row. + * + * @return float + * Unformat token value. + */ + function unformat_token_value($token_value, $token_name, $values) { + $token_name = str_replace('[', '', $token_name); + $token_name = str_replace(']', '', $token_name); + if (!empty($this->view->field[$token_name])) { + $handler = $this->view->field[$token_name]; + if (is_a($handler, 'views_handler_field_numeric')) { + // Remove link. + $token_value = $handler->original_value; + // Remove prefix and suffix. + $prefix = $handler->options['prefix']; + $suffix = $handler->options['suffix']; + $token_value = str_replace($prefix, '', $token_value); + $token_value = str_replace($suffix, '', $token_value); + + // Unformat number. + $token_value = $this->number_unformat($token_value, TRUE, $handler->options['decimal'], $handler->options['separator']); + return floatval($token_value); + } + + // Support for field commerce_price. + if (is_a($handler, 'commerce_price_handler_field_commerce_price')) { + $amount = $handler->get_value($values); + $amount = $amount[0]; + return floatval(a_currency_amount_to_decimal($amount['amount'], $amount['currency_code'])); + } + } + return $token_value; + } + function render($values) { ctools_include('math-expr'); - $tokens = array_map('floatval', $this->get_render_tokens(array())); + $tokens = $this->get_render_tokens(array()); + foreach ($tokens as $token_name => &$token_value) { + $token_value = $this->unformat_token_value($token_value, $token_name, $values); + } + $value = strtr($this->options['expression'], $tokens); $expressions = explode(';', $value); $math = new ctools_math_expr;