/** * Given a relationship, gets the stub entity for the source. * * @param array $relationship The relationship array. * * @return bool|mixed Either the stub entity or false on error. */ protected function getSourceStubEntity(array $relationship) { $field_name = $relationship['field_name']; $source_entity_ids = entity_get_id_by_uuid($relationship['source_type'], array($relationship['source_uuid'])); $source_entity_id = count($source_entity_ids) > 0 ? reset($source_entity_ids) : null; $source_entity_vids = entity_get_id_by_uuid($relationship['source_type'], array($relationship['source_vuuid']), true); $source_entity_vid = count($source_entity_vids) > 0 ? reset($source_entity_vids) : false; if (!$source_entity_id) { return false; } // Get the bundle for the source entity. $source_entity_bundle = Entity::getBundleFromID($relationship['source_type'], $source_entity_id); if (!$source_entity_bundle) { return false; } // Get the stub entity for the source. $source_stub = Entity::getStub($relationship['source_type'], $source_entity_id, $source_entity_bundle, $source_entity_vid); // Load the existing field onto the entity. $field_instance_info = field_info_instance($relationship['source_type'], $field_name, $source_entity_bundle); if ($field_instance_info === false) { return false; } try { // First, load the revisions. field_attach_load_revision($relationship['source_type'], array($source_entity_id => $source_stub), array('field_id' => $field_instance_info['field_id'])); // Second, get the original deltas for the revision. $deltas = db_select('field_revision_' . $field_name, 'fr')->fields('fr', array('language', 'delta'))->condition($source_entity_vid ? 'revision_id' : 'entity_id', $source_entity_vid ? $source_entity_vid : $source_entity_id)->condition('language', field_available_languages($relationship['source_type'], $field_instance_info), 'IN')->orderBy('delta')->execute(); // Assign the deltas to their languages. $deltas_languages = array(); foreach ($deltas as $delta) { if (!array_key_exists($delta->language, $deltas_languages)) { $deltas_languages[$delta->language] = array(); } $deltas_languages[$delta->language][] = $delta->delta; } // Reset the deltas to their correct orders. $field_value =& $source_stub->{$field_name}; foreach ($deltas_languages as $language => $deltas) { $new_value = array(); for ($i = 0; $i < count($field_value[$language]); $i++) { $new_value[$deltas[$i]] = $field_value[$language][$i]; } $field_value[$language] = $new_value; } } catch (\Exception $ex) { // If an exception was thrown, that probably means the field doesn't // exist, so we should return false. return false; } return $source_stub; }