You are here

views_summarize.module in Views Summarize 7

File

views_summarize.module
View source
<?php

/**
 * Implementation of hook_views_api().
 */
function views_summarize_views_api() {
  return array(
    'api' => 3,
  );
}

/*
 * Implementation of hook_theme()
 */
function views_summarize_theme() {
  return array(
    'views_summarize_plugin_style_tablesummarized' => array(
      'render element' => 'form',
    ),
    'views_summarize_type_none' => array(
      'variables' => array(
        'data' => array(),
      ),
    ),
    'views_summarize_type_count' => array(
      'variables' => array(
        'data' => array(),
      ),
    ),
    'views_summarize_type_range' => array(
      'variables' => array(
        'data' => array(),
      ),
    ),
    'views_summarize_type_spread' => array(
      'variables' => array(
        'data' => array(),
      ),
    ),
    'views_summarize_type_total' => array(
      'variables' => array(
        'data' => array(),
      ),
    ),
    'views_summarize_type_currency' => array(
      'variables' => array(
        'data' => array(),
      ),
    ),
    'views_summarize_type_average' => array(
      'variables' => array(
        'data' => array(),
      ),
    ),
    'views_summarize_type_average_no_empties' => array(
      'variables' => array(
        'data' => array(),
      ),
    ),
  );
}

/**
 * List all of the handlers
 */
function views_summarize_get_handlers() {
  return array(
    'none' => t('None'),
    'count' => t('Count'),
    'range' => t('Range'),
    'total' => t('Total'),
    'currency' => t('Total (Currency)'),
    'average' => t('Average (include empty values)'),
    'average_no_empties' => t('Average (exclude empty values)'),
    'spread' => t('Spread'),
  );
}

/**
 * Display a view as a table summary.
 */
function template_preprocess_views_summarize_views_tablesummarized(&$vars) {
  template_preprocess_views_view_table($vars);
  if (!count($vars['rows'])) {
    return;
  }
  $opts =& $vars['view']->style_plugin->options['info'];
  if (isset($vars['view']->style_plugin->options['summary_only'])) {
    $vars['summary_only'] = $vars['view']->style_plugin->options['summary_only'];
  }
  $data = array();
  foreach ($vars['rows'] as $row) {
    foreach ($row as $field => $value) {
      $data[$field][] = $value;
    }
  }
  $current_display = $vars['view']->current_display;
  if (empty($vars['view']->display[$current_display]->display_options['fields'])) {
    $display = $vars['view']->display['default'];
  }
  else {
    $display = $vars['view']->display[$current_display];
  }
  $vars['summarized'] = array();
  foreach ($opts as $field => $settings) {
    if (isset($data[$field])) {

      // Get the display style settings.
      $field_settings = array();
      if (!empty($vars['view']->field[$field]->options['settings'])) {
        $field_settings = $vars['view']->field[$field]->options['settings'];
      }

      // Get the field instance data.
      if (!empty($display->display_options['fields'][$field]['field'])) {
        $real_field_name = $display->display_options['fields'][$field]['field'];
      }
      $field_data = $vars['view']->result[0]->_field_data['nid'];
      $entity_type = $field_data['entity_type'];
      $bundle = $field_data['entity']->type;
      if (!empty($real_field_name)) {
        $field_instance = field_info_instance($entity_type, $real_field_name, $bundle);
      }
      $theme = 'views_summarize_type_' . $settings['summarize'];
      $options = array(
        'field' => $field,
        'views_field_settings' => $field_settings,
        'field_instance_settings' => empty($field_instance['settings']) ? array() : $field_instance['settings'],
      );
      $variables = array(
        'data' => $data[$field],
        'options' => $options,
      );
      $vars['summarized'][$field] = theme($theme, $variables);
    }
  }
}

/**
 * Theme the form for the table style plugin
 *
 * This is almost the same as theme_views_ui_style_plugin_table().
 */
function theme_views_summarize_plugin_style_tablesummarized($variables) {
  $form = $variables['form'];
  $output = drupal_render($form['description_markup']);
  $header = array(
    t('Field'),
    t('Column'),
    t('Align'),
    t('Summarize'),
    t('Separator'),
    array(
      'data' => t('Sortable'),
      'align' => 'center',
    ),
    array(
      'data' => t('Default order'),
      'align' => 'center',
    ),
    array(
      'data' => t('Default sort'),
      'align' => 'center',
    ),
    array(
      'data' => t('Hide empty column'),
      'align' => 'center',
    ),
  );
  $rows = array();
  foreach (element_children($form['columns']) as $id) {
    $row = array();
    $row[] = drupal_render($form['info'][$id]['name']);
    $row[] = drupal_render($form['columns'][$id]);
    $row[] = drupal_render($form['info'][$id]['align']);
    $row[] = drupal_render($form['info'][$id]['summarize']);
    $row[] = drupal_render($form['info'][$id]['separator']);
    if (!empty($form['info'][$id]['sortable'])) {
      $row[] = array(
        'data' => drupal_render($form['info'][$id]['sortable']),
        'align' => 'center',
      );
      $row[] = array(
        'data' => drupal_render($form['info'][$id]['default_sort_order']),
        'align' => 'center',
      );
      $row[] = array(
        'data' => drupal_render($form['default'][$id]),
        'align' => 'center',
      );
    }
    else {
      $row[] = '';
      $row[] = '';
      $row[] = '';
    }
    $row[] = array(
      'data' => drupal_render($form['info'][$id]['empty_column']),
      'align' => 'center',
    );
    $rows[] = $row;
  }

  // Add the special 'None' row.
  $rows[] = array(
    t('None'),
    '',
    '',
    '',
    '',
    '',
    '',
    array(
      'align' => 'center',
      'data' => drupal_render($form['default'][-1]),
    ),
    '',
  );
  $output .= theme('table', array(
    'header' => $header,
    'rows' => $rows,
  ));
  $output .= drupal_render_children($form);
  return $output;
}

/**
 * Theme: No summary for this column
 */
function theme_views_summarize_type_none($variables) {
  return '';
}

/**
 * Theme: Total number of non-empty values in this column
 */
function theme_views_summarize_type_count($variables) {
  $data = $variables['data'];
  foreach ($data as $val) {
    $data2[] = strip_tags($val);
  }
  return '<div class="label">' . t('Count:') . '</div>' . count(array_filter($data2, '_views_summarize_type_count_filter'));
}

/**
 * Checks whether the given value is set (i.e., not null) or not.
 *
 * @param int $value
 *   The value to check.
 */
function _views_summarize_type_count_filter($value) {
  return isset($value);
}

/**
 * Theme: Maximum and minimum values in this column
 */
function theme_views_summarize_type_range($variables) {
  $data = $variables['data'];
  $rows = array(
    array(
      t('Min'),
      strip_tags(min($data)),
    ),
    array(
      t('Max'),
      strip_tags(max($data)),
    ),
  );
  $header = array(
    array(
      'data' => t('Range'),
      'colspan' => 2,
    ),
  );
  return theme('table', array(
    'header' => $header,
    'rows' => $rows,
  ));
}

/**
 * Theme: Total value for a currency amount
 */
function theme_views_summarize_type_currency($variables) {
  $data = $variables['data'];
  $options = $variables['options'];
  $total = 0;
  foreach ($data as $val) {
    $total += floatval(_views_summarize_get_cleaned_value($val, $options));
  }
  $result = _views_summarize_get_formatted_summary($total, $options);
  $prefix_suffix = _views_summarize_get_prefix_suffix($variables['options']);
  $summary = $prefix_suffix['prefix'] . $result . $prefix_suffix['suffix'];
  return '<div class="label">' . t('Total:') . '</div>' . $summary;
}

/**
 * Theme: Total value for a numeric column
 */
function theme_views_summarize_type_total($variables) {
  $data = $variables['data'];
  $options = $variables['options'];
  $total = 0;
  foreach ($data as $val) {
    $total += floatval(_views_summarize_get_cleaned_value($val, $options));
  }
  return '<div class="label">' . t('Total:') . '</div>' . _views_summarize_get_formatted_summary($total, $options);
}

/**
 * Theme: Total value for an average column w/empty data values included.
 */
function theme_views_summarize_type_average($variables) {
  $data = $variables['data'];
  $options = $variables['options'];
  $total = 0;
  foreach ($data as $val) {
    $total += floatval(_views_summarize_get_cleaned_value($val, $options));
  }
  return '<div class="label">' . t('Average (including empty values):') . '</div>' . _views_summarize_get_formatted_summary($total / count($data), $options);
}

/**
 * Theme: Total value for an average column w/empty data values excluded.
 */
function theme_views_summarize_type_average_no_empties($variables) {
  $data = $variables['data'];
  $options = $variables['options'];
  $total = 0;
  $count = 0;
  foreach ($data as $val) {
    if (isset($val) && $val != '') {
      $total += floatval(_views_summarize_get_cleaned_value($val, $options));
      $count++;
    }
  }
  if ($total != 0 && $count != 0) {
    $summary = _views_summarize_get_formatted_summary($total / $count, $options);
  }
  else {
    $summary = sprintf("%.2f", '0');
  }
  return '<div class="label">' . t('Average (excluding empty values):') . '</div>' . $summary;
}

/**
 * Theme: Spread table for a column
 */
function theme_views_summarize_type_spread($variables) {
  $data = $variables['data'];
  $hist = array();
  foreach ($data as $val) {
    if (!isset($hist[$val])) {
      $hist[$val] = 0;
    }
    $hist[$val]++;
  }
  $rows = array();
  foreach ($hist as $value => $count) {
    if (empty($value)) {
      $empty_string = t('(empty)');
      $rows[$empty_string] = array(
        $empty_string,
        $count,
      );
    }
    else {
      $value = strip_tags($value);
      $rows[$value] = array(
        $value,
        $count,
      );
    }
  }
  if (version_compare(phpversion(), '5.4.0', '>=')) {
    ksort($rows, SORT_NATURAL);
  }
  else {
    ksort($rows);
  }
  $header = array(
    array(
      'data' => t('Spread'),
      'colspan' => 2,
    ),
  );
  return theme('table', array(
    'header' => $header,
    'rows' => $rows,
  ));
}

/**
 * Gets the record's value after stripping invalid characters.
 *
 * @param type $value
 *   The value from which to strip invalid characters.
 * @param type $options
 *   The options element of the variables array that is passed into the summary
 *   theme function.
 *
 * @return array
 *  The value with invalid characters removed.
 */
function _views_summarize_get_cleaned_value($value, $options) {
  $value = preg_replace('/[^0-9\\.\\,\\-]/', '', strip_tags($value));
  if (!empty($options['views_field_settings']['thousand_separator'])) {
    $value = str_replace($options['views_field_settings']['thousand_separator'], '', $value);
  }
  if (!empty($options['views_field_settings']['decimal_separator'])) {
    $value = str_replace($options['views_field_settings']['decimal_separator'], '.', $value);
  }
  return $value;
}

/**
 * Gets the summary's formatted result.
 *
 * @param type $total
 *   The summary to format.
 * @param type $options
 *   The options element of the variables array that is passed into the summary
 *   theme function.
 *
 * @return array
 *   The format settings in an associative array.
 */
function _views_summarize_get_formatted_summary($total, $options) {
  $format_settings = _views_summarize_get_format_settings($options);
  $summary = number_format($total, $format_settings['precision'], $format_settings['decimal_separator'], $format_settings['thousand_separator']);
  return $summary;
}

/**
 * Gets the field's settings for formatting a number.
 *
 * @param type $options
 *   The options element of the variables array that is passed into the summary
 *   theme function.
 *
 * @return array
 *   The format settings in an associative array.
 */
function _views_summarize_get_format_settings($options) {
  $format_settings = array(
    'precision' => 0,
    'decimal_separator' => NULL,
    'thousand_separator' => NULL,
  );
  if (!empty($options['views_field_settings']['scale'])) {
    $format_settings['precision'] = $options['views_field_settings']['scale'];
  }
  if (!empty($options['views_field_settings']['decimal_separator'])) {
    $format_settings['decimal_separator'] = $options['views_field_settings']['decimal_separator'];
  }
  if (!empty($options['views_field_settings']['thousand_separator'])) {
    $format_settings['thousand_separator'] = $options['views_field_settings']['thousand_separator'];
  }
  return $format_settings;
}

/**
 * Gets the prefix and suffix for a summary's output, if they exist.
 *
 * @param type $options
 *   The options element of the variables array that is passed into the summary
 *   theme function.
 *
 * @return array
 *   The prefix and suffix in an associative array.
 */
function _views_summarize_get_prefix_suffix($options) {
  $prefix_suffix = array(
    'prefix' => '',
    'suffix' => '',
  );
  if (!empty($options['views_field_settings']['prefix_suffix'])) {
    if (!empty($options['field_instance_settings']['prefix'])) {
      $prefix_suffix['prefix'] = $options['field_instance_settings']['prefix'];
    }
    if (!empty($options['field_instance_settings']['suffix'])) {
      $prefix_suffix['suffix'] = $options['field_instance_settings']['suffix'];
    }
  }
  return $prefix_suffix;
}

Functions

Namesort descending Description
template_preprocess_views_summarize_views_tablesummarized Display a view as a table summary.
theme_views_summarize_plugin_style_tablesummarized Theme the form for the table style plugin
theme_views_summarize_type_average Theme: Total value for an average column w/empty data values included.
theme_views_summarize_type_average_no_empties Theme: Total value for an average column w/empty data values excluded.
theme_views_summarize_type_count Theme: Total number of non-empty values in this column
theme_views_summarize_type_currency Theme: Total value for a currency amount
theme_views_summarize_type_none Theme: No summary for this column
theme_views_summarize_type_range Theme: Maximum and minimum values in this column
theme_views_summarize_type_spread Theme: Spread table for a column
theme_views_summarize_type_total Theme: Total value for a numeric column
views_summarize_get_handlers List all of the handlers
views_summarize_theme
views_summarize_views_api Implementation of hook_views_api().
_views_summarize_get_cleaned_value Gets the record's value after stripping invalid characters.
_views_summarize_get_formatted_summary Gets the summary's formatted result.
_views_summarize_get_format_settings Gets the field's settings for formatting a number.
_views_summarize_get_prefix_suffix Gets the prefix and suffix for a summary's output, if they exist.
_views_summarize_type_count_filter Checks whether the given value is set (i.e., not null) or not.