You are here

function mvf_items_convert in Measured Value Field 7

Supportive function, normally should be used in formatters of MVF field.

Convert $items array of MVF field instance from the original unit measures into $destination_unit

Parameters

array $field: Field definition array of MVF field $items of which are supplied for conversion

array $items: $items array of MVF field instance

object|string|int $destination_unit: Into what unit measure $items should be converted to. You may supply a fully loaded entity 'units_unit', or string, which will be considered to be machine name of destination unit, or int, which will be considered to be umid of destination unit. You may also provide constant MVF_FORMATTER_ORIGINAL_UNIT if want to keep the units in which values were originally entered

Return value

array Converted $items array

1 call to mvf_items_convert()
mvf_field_formatter_prepare_view in ./mvf.module
Implements hook_field_formatter_prepare_view().

File

./mvf.module, line 1481
Define a field type of measured value.

Code

function mvf_items_convert($field, $items, $destination_unit) {
  if (in_array($destination_unit, array(
    MVF_UNIT_ORIGINAL,
    MVF_UNIT_UNKNOWN,
  ))) {

    // We were either asked not to do any conversion with $items or we do not
    // know into what units it should be converted. So we just return it as it
    // is.
    return $items;
  }
  if (is_numeric($destination_unit)) {
    $destination_unit = units_unit_load($destination_unit);
  }
  elseif (!is_object($destination_unit)) {
    $destination_unit = units_unit_machine_name_load($destination_unit);
  }
  if (!is_object($destination_unit)) {

    // We couldn't find 'units_unit' entity for destination units. As fallback
    // we return untouched $items array.
    return $items;
  }

  // For scaling we load all origin units at once.
  $origin_units = array();
  foreach ($items as $item) {
    $origin_units[$item[mvf_subfield_to_column('unit')]] = $item[mvf_subfield_to_column('unit')];
  }
  $origin_units = array_keys($origin_units);
  $origin_units = units_unit_load_multiple($origin_units);
  foreach ($items as $delta => $item) {
    $items[$delta][mvf_subfield_to_column('value')] = units_convert($item[mvf_subfield_to_column('value')], $origin_units[$item[mvf_subfield_to_column('unit')]]->machine_name, $destination_unit->machine_name);
    $items[$delta][mvf_subfield_to_column('unit')] = $destination_unit->umid;
  }
  return $items;
}