You are here

function fraction_feeds_set_target in Fraction 7

Callback for mapping fraction fields in Feeds.

1 string reference to 'fraction_feeds_set_target'
fraction_feeds_processor_targets in ./fraction.feeds.inc
Implements hook_feeds_processor_targets().

File

./fraction.feeds.inc, line 46

Code

function fraction_feeds_set_target(FeedsSource $source, $entity, $target, array $values, array $mapping) {
  $language = $mapping['language'];

  // Determine what type of value is being saved (decimal, fraction, numerator,
  // or denominator).
  $type = 'decimal';
  if (strpos($target, ':')) {
    $parts = explode(':', $target);
    $target = $parts[0];
    if ($parts[1] == 'fraction') {
      $type = 'fraction';
    }
    elseif ($parts[1] == 'numerator' || $parts[1] == 'denominator') {
      $type = $parts[1];
    }
  }

  // Load field info.
  $info = field_info_field($target);

  // Populate the field(s).
  $field = isset($entity->{$target}) ? $entity->{$target} : array(
    $language => array(),
  );
  $delta = 0;
  foreach ($values as $value) {

    // Only store as many values as are allowed in the field config..
    if ($info['cardinality'] == $delta) {
      break;
    }

    // Load the value.
    if (is_object($value) && $value instanceof FeedsElement) {
      $value = $value
        ->getValue();
    }

    // If the value is a fraction, pull out the numerator and denominator.
    if ($type == 'fraction') {
      $parts = explode('/', $value);
      if (!empty($parts[0]) && is_numeric($parts[0]) && !empty($parts[1]) && is_numeric($parts[1])) {
        $field[$language][$delta]['numerator'] = $parts[0];
        $field[$language][$delta]['denominator'] = $parts[1];
      }
    }
    elseif (is_numeric($value)) {

      // If the value is a decimal, convert to a fraction.
      if ($type == 'decimal') {
        $fraction = fraction_from_decimal($value);
        $field[$language][$delta]['numerator'] = $fraction
          ->getNumerator();
        $field[$language][$delta]['denominator'] = $fraction
          ->getDenominator();
      }
      else {

        // If no values have been stored yet, and the value is not empty,
        // initialize both field values to ensure that both they are set to
        // sane defaults (in case one is omitted in the source).
        if (!isset($field[$language][$delta]) && !empty($value)) {
          $field[$language][$delta] = array(
            'numerator' => 0,
            'denominator' => 1,
          );
        }

        // Save the numerator/denominator. Do not allow empty denominator.
        if ($type == 'numerator') {
          $field[$language][$delta]['numerator'] = $value;
        }
        elseif ($type == 'denominator' && !empty($value)) {
          $field[$language][$delta]['denominator'] = $value;
        }
      }
    }
    $delta++;
  }
  $entity->{$target} = $field;
}