You are here

public function MigrateDestinationFieldCollection::import in Field collection 7

Import a single field collection item.

Parameters

object $collection: Collection object to build. Pre-filled with any fields mapped in the migration.

object $row: Raw source data object - passed through to prepare/complete handlers.

Return value

array|bool Array of key fields (item_id only in this case) of the collection that was saved or FALSE on failure.

Overrides MigrateDestination::import

File

./field_collection.migrate.inc, line 99
Support for the Migrate API.

Class

MigrateDestinationFieldCollection
Destination class implementing migration into field_collection.

Code

public function import(stdClass $collection, stdClass $row) {
  $updating = FALSE;
  if (isset($row->migrate_map_destid1)) {

    // We're updated an existing entity - start from the previous data.
    // entity_load() returns an array, so we get the field collection entity
    // with reset().
    $result = entity_load('field_collection_item', array(
      $row->migrate_map_destid1,
    ), array(), TRUE);
    $entity = reset($result);
    if ($entity) {
      $entity_old = clone $entity;
      $updating = TRUE;
    }
  }
  if (!$updating) {

    // Skip the collection if it has no host.
    if (empty($collection->host_entity_id)) {
      throw new MigrateException('Could not find host entity of the field collection to import.');
    }
    $entity = entity_create('field_collection_item', array(
      'field_name' => $this->bundle,
    ));
    $updating = FALSE;
    $host_entity = entity_load_single($this->hostEntityType, $collection->host_entity_id);
    entity_get_controller($this->hostEntityType)
      ->resetCache();
    if (isset($row->language)) {
      $entity
        ->setHostEntity($this->hostEntityType, $host_entity, $row->language, TRUE);
    }
    else {
      $entity
        ->setHostEntity($this->hostEntityType, $host_entity);
    }
  }
  unset($collection->host_entity_id);
  foreach ((array) $collection as $field => $value) {
    $entity->{$field} = $value;
  }
  $this
    ->prepare($entity, $row);

  // Restore fields from original field_collection_item if updating.
  if ($updating) {
    foreach ($entity as $field => $value) {
      if ('field_' != substr($field, 0, 6)) {
        continue;
      }
      if (property_exists($entity_old, $field) && !property_exists($collection, $field)) {
        $entity->{$field} = $entity_old->{$field};
      }
    }
  }
  migrate_instrument_start('field_collection_save');
  $status = entity_save('field_collection_item', $entity);
  migrate_instrument_stop('field_collection_save');
  if ($status !== FALSE || in_array($this->hostEntityType, array(
    'node',
    'field_collection_item',
  ))) {
    $this
      ->complete($entity, $row);
    if ($updating) {
      $this->numUpdated++;
    }
    else {
      $this->numCreated++;
    }
    return array(
      $entity->item_id,
    );
  }
  return FALSE;
}