Create a farm_metrics() helper function for loading metrics.

This commit is contained in:
Michael Stenta 2020-02-26 11:10:44 -05:00
parent 98c682b0cb
commit 6b20ba1a04
2 changed files with 28 additions and 23 deletions

View File

@ -24,32 +24,14 @@ function farm_metrics_farm_dashboard_panes() {
*/
function farm_metrics_dashboard_pane() {
// Ask modules for metrics.
$metrics = module_invoke_all('farm_metrics');
// Load metrics.
$metrics = farm_metrics();
// If no metrics are available, show a message.
if (empty($metrics)) {
return 'No metrics available.';
}
// Make sure all metrics have defaults set.
$defaults = array(
'label' => '',
'value' => '0',
'link' => 'farm',
'weight' => 0,
);
foreach ($metrics as $key => $metric) {
$metrics[$key] = array_merge($defaults, $metric);
}
// Sort the metrics by weight ascending, value descending.
$weight_index = array();
$value_index = array();
foreach ($metrics as $key => $row) {
$weight_index[$key] = $row['weight'];
$value_index[$key] = $row['value'];
}
array_multisort($weight_index, SORT_ASC, $value_index, SORT_DESC, $metrics);
// Iterate through the metrics and build rendered metrics.
$rendered_metrics = array();
foreach ($metrics as $metric) {

View File

@ -57,10 +57,23 @@ function farm_metrics_menu() {
* Farm metrics API callback.
*/
function farm_metrics_info() {
$metrics = farm_metrics();
drupal_json_output($metrics);
}
/**
* Returns a sorted array of all metrics.
*/
function farm_metrics() {
// Ask modules for metrics.
$metrics = module_invoke_all('farm_metrics');
// If no metrics are available, return an empty array.
if (empty($metrics)) {
return array();
}
// Make sure all metrics have defaults set.
$defaults = array(
'label' => '',
@ -72,5 +85,15 @@ function farm_metrics_info() {
$metrics[$key] = array_merge($defaults, $metric);
}
drupal_json_output($metrics);
// Sort the metrics by weight ascending, value descending.
$weight_index = array();
$value_index = array();
foreach ($metrics as $key => $row) {
$weight_index[$key] = $row['weight'];
$value_index[$key] = $row['value'];
}
array_multisort($weight_index, SORT_ASC, $value_index, SORT_DESC, $metrics);
// Return metrics.
return $metrics;
}