views_handler_field_math.inc

  1. 3.x handlers/views_handler_field_math.inc
  2. 2.x handlers/views_handler_field_math.inc

File

handlers/views_handler_field_math.inc
View source
  1. <?php
  2. /**
  3. * Render a mathematical expression as a numeric value
  4. *
  5. * Definition terms:
  6. * - float: If true this field contains a decimal value. If unset this field
  7. * will be assumed to be integer.
  8. *
  9. * @ingroup views_field_handlers
  10. */
  11. class views_handler_field_math extends views_handler_field_numeric {
  12. function option_definition() {
  13. $options = parent::option_definition();
  14. $options['expression'] = array('default' => '');
  15. return $options;
  16. }
  17. function options_form(&$form, &$form_state) {
  18. $form['expression'] = array(
  19. '#type' => 'textarea',
  20. '#title' => t('Expression'),
  21. '#description' => t('Enter mathematical expressions such as 2 + 2 or sqrt(5). You my assign variables and create mathematical functions and evaluate them. Use the ; to separate these. For example: f(x) = x + 2; f(2).'),
  22. '#default_value' => $this->options['expression'],
  23. );
  24. // Create a place for the help
  25. $form['expression_help'] = array();
  26. parent::options_form($form, $form_state);
  27. // Then move the existing help:
  28. $form['expression_help'] = $form['alter']['help'];
  29. unset($form['expression_help']['#dependency']);
  30. unset($form['expression_help']['#process']);
  31. unset($form['alter']['help']);
  32. }
  33. function render($values) {
  34. ctools_include('math-expr');
  35. $value = strtr($this->options['expression'], $this->get_render_tokens(array()));
  36. $expressions = explode(';', $value);
  37. $math = new ctools_math_expr;
  38. foreach ($expressions as $expression) {
  39. if ($expression !== '') {
  40. $value = $math->evaluate($expression);
  41. }
  42. }
  43. // The rest is directly from views_handler_field_numeric but because it
  44. // does not allow the value to be passed in, it is copied.
  45. if (!empty($this->options['set_precision'])) {
  46. $value = number_format($value, $this->options['precision'], $this->options['decimal'], $this->options['separator']);
  47. }
  48. else {
  49. $remainder = abs($value) - intval(abs($value));
  50. $value = $value > 0 ? floor($value) : ceil($value);
  51. $value = number_format($value, 0, '', $this->options['separator']);
  52. if ($remainder) {
  53. // The substr may not be locale safe.
  54. $value .= $this->options['decimal'] . substr($remainder, 2);
  55. }
  56. }
  57. // Check to see if hiding should happen before adding prefix and suffix.
  58. if ($this->options['hide_empty'] && empty($value) && ($value !== 0 || $this->options['empty_zero'])) {
  59. return '';
  60. }
  61. return check_plain($this->options['prefix'] . $value . $this->options['suffix']);
  62. }
  63. function query() { }
  64. }