Skip to content

Instantly share code, notes, and snippets.

@dmsmidt
Created January 19, 2016 15:03
Show Gist options
  • Save dmsmidt/6f0f498a9dbaea8602fb to your computer and use it in GitHub Desktop.
Save dmsmidt/6f0f498a9dbaea8602fb to your computer and use it in GitHub Desktop.
MigrateEntityFileUri Allow saving File Entity fields with Drupal 7 Migrate
<?php
/**
* Handle cases where we're handed a URI, or local filespec. Extra functionallity: Allow saving file entity fields.
*/
class MigrateEntityFileUri extends MigrateFileUri {
public function __construct($arguments = array(), $default_file = NULL) {
parent::__construct($arguments, $default_file);
if (isset($arguments['fields'])) {
$this->fields = $arguments['fields'];
}
}
/**
* Code copied and modified to allow saving a file with field values.
*
* Setup a file entity object suitable for saving.
*
* @param $destination
* Path to the Drupal copy of the file.
* @param $owner
* Uid of the file owner.
* @return stdClass
* A file object ready to be saved.
*/
protected function createFileEntity($destination, $owner) {
$file = clone $this->defaultFile;
$file->uri = $destination;
$file->uid = $owner;
if (!isset($file->filename)) {
$file->filename = drupal_basename($destination);
}
if (!isset($file->filemime)) {
$file->filemime = file_get_mimetype(urldecode($destination));
}
if (!isset($file->status)) {
$file->status = FILE_STATUS_PERMANENT;
}
if (empty($file->type) || $file->type == 'file') {
// Try to determine the file type.
if (module_exists('file_entity')) {
$type = file_get_type($file);
}
elseif ($slash_pos = strpos($file->filemime, '/')) {
$type = substr($file->filemime, 0, $slash_pos);
}
$file->type = isset($type) ? $type : 'file';
}
// Added to also save file entity fields.
if (!empty($this->fields)) {
foreach ($this->fields as $field => $value) {
$file->$field = $value;
}
}
// If we are replacing or reusing an existing filesystem entry,
// also re-use its database record.
if ($this->fileReplace == FILE_EXISTS_REPLACE ||
$this->fileReplace == self::FILE_EXISTS_REUSE) {
$existing_files = file_load_multiple(array(), array('uri' => $destination));
if (count($existing_files)) {
$existing = reset($existing_files);
$file->fid = $existing->fid;
$file->filename = $existing->filename;
}
}
return $file;
}
}
@UltraBob
Copy link

Thanks! May I suggest contributing over at https://www.drupal.org/node/2649330?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment