You are here

class MigrateDestinationFile in Migrate 7.2

Destination class implementing migration into the files table.

Hierarchy

Expanded class hierarchy of MigrateDestinationFile

File

plugins/destinations/file.inc, line 534
Support for file entity as destination. Note that File Fields have their own destination in fields.inc

View source
class MigrateDestinationFile extends MigrateDestinationEntity {

  /**
   * File class (MigrateFileUri etc.) doing the dirty wrk.
   *
   * @var string
   */
  protected $fileClass;
  public function setFileClass($file_class) {
    $this->fileClass = $file_class;
  }

  /**
   * Boolean indicating whether we should avoid deleting the actual file on
   * rollback.
   *
   * @var bool
   */
  protected $preserveFiles = FALSE;

  /**
   * Implementation of MigrateDestination::getKeySchema().
   *
   * @return array
   */
  public static function getKeySchema() {
    return array(
      'fid' => array(
        'type' => 'int',
        'unsigned' => TRUE,
        'description' => 'file_managed ID',
      ),
    );
  }

  /**
   * Basic initialization
   *
   * @param array $options
   *  Options applied to files.
   */
  public function __construct($bundle = 'file', $file_class = 'MigrateFileUri', $options = array()) {
    parent::__construct('file', $bundle, $options);
    $this->fileClass = $file_class;
  }

  /**
   * Returns a list of fields available to be mapped for the entity type
   * (bundle)
   *
   * @param Migration $migration
   *  Optionally, the migration containing this destination.
   *
   * @return array
   *  Keys: machine names of the fields (to be passed to addFieldMapping)
   *  Values: Human-friendly descriptions of the fields.
   */
  public function fields($migration = NULL) {
    $fields = array();

    // First the core properties
    $fields['fid'] = t('Existing file ID');
    $fields['uid'] = t('Uid of user associated with file');
    $fields['value'] = t('Representation of the source file (usually a URI)');
    $fields['timestamp'] = t('UNIX timestamp for the date the file was added');

    // Then add in anything provided by handlers
    $fields += migrate_handler_invoke_all('Entity', 'fields', $this->entityType, $this->bundle, $migration);
    $fields += migrate_handler_invoke_all('File', 'fields', $this->entityType, $this->bundle, $migration);

    // Plus anything provided by the file class
    $fields += call_user_func(array(
      $this->fileClass,
      'fields',
    ));
    return $fields;
  }

  /**
   * Delete a file entry.
   *
   * @param array $fid
   *  Fid to delete, arrayed.
   */
  public function rollback(array $fid) {
    migrate_instrument_start('file_load');
    $file = file_load(reset($fid));
    migrate_instrument_stop('file_load');
    if ($file) {
      migrate_instrument_start('file_delete');

      // If we're preserving files, roll our own version of file_delete() to make
      // sure we don't delete them. If we're not, make sure we do the job completely.
      $migration = Migration::currentMigration();
      $mappings = $migration
        ->getFieldMappings();
      if (isset($mappings['preserve_files'])) {

        // Assumes it's set using defaultValue
        $preserve_files = $mappings['preserve_files']
          ->getDefaultValue();
      }
      else {
        $preserve_files = FALSE;
      }
      $this
        ->prepareRollback($fid);
      if ($preserve_files) {
        $this
          ->fileDelete($file);
      }
      else {
        file_delete($file, TRUE);
      }
      $this
        ->completeRollback($fid);
      migrate_instrument_stop('file_delete');
    }
  }

  /**
   * Delete database references to a file without deleting the file itself.
   *
   * @param $file
   */
  protected function fileDelete($file) {

    // Let other modules clean up any references to the deleted file.
    module_invoke_all('file_delete', $file);
    module_invoke_all('entity_delete', $file, 'file');
    db_delete('file_managed')
      ->condition('fid', $file->fid)
      ->execute();
    db_delete('file_usage')
      ->condition('fid', $file->fid)
      ->execute();
  }

  /**
   * Import a single file record.
   *
   * @param $file
   *  File object to build. Prefilled with any fields mapped in the Migration.
   * @param $row
   *  Raw source data object - passed through to prepare/complete handlers.
   *
   * @return array
   *  Array of key fields (fid only in this case) of the file that was saved if
   *  successful. FALSE on failure.
   */
  public function import(stdClass $file, stdClass $row) {

    // Updating previously-migrated content?
    $migration = Migration::currentMigration();
    if (isset($row->migrate_map_destid1)) {
      if (isset($file->fid)) {
        if ($file->fid != $row->migrate_map_destid1) {
          throw new MigrateException(t("Incoming fid !fid and map destination fid !destid1 don't match", array(
            '!fid' => $file->fid,
            '!destid1' => $row->migrate_map_destid1,
          )));
        }
      }
      else {
        $file->fid = $row->migrate_map_destid1;
      }
    }
    if ($migration
      ->getSystemOfRecord() == Migration::DESTINATION) {
      if (!isset($file->fid)) {
        throw new MigrateException(t('System-of-record is DESTINATION, but no destination fid provided'));
      }

      // @todo: Support DESTINATION case
      $old_file = file_load($file->fid);
    }

    // 'type' is the bundle property on file entities. It must be set here for
    // the sake of the prepare handlers, although it may be overridden later
    // based on the detected mime type.
    if (empty($file->type)) {

      // If a bundle was specified in the constructor we use it for filetype.
      if ($this->bundle != 'file') {
        $file->type = $this->bundle;
      }
      else {
        $file->type = 'file';
      }
    }

    // Invoke migration prepare handlers
    $this
      ->prepare($file, $row);
    if (isset($file->fid)) {
      $updating = TRUE;
    }
    else {
      $updating = FALSE;
    }
    if (!isset($file->uid)) {
      $file->uid = 1;
    }

    // file_save() unconditionally sets timestamp - if we have an explicit
    // value we want, we need to set it manually after file_save.
    if (isset($file->timestamp)) {
      $timestamp = MigrationBase::timestamp($file->timestamp);
    }

    // Don't pass preserve_files through to the file class, which will add
    // file_usage - we will handle it ourselves in rollback().
    $file->preserve_files = FALSE;
    $file_class = $this->fileClass;
    $source = new $file_class((array) $file, $file);
    $file = $source
      ->processFile($file->value, $file->uid);
    if (is_object($file) && isset($file->fid)) {
      $this
        ->complete($file, $row);
      if (isset($timestamp)) {
        db_update('file_managed')
          ->fields(array(
          'timestamp' => $timestamp,
        ))
          ->condition('fid', $file->fid)
          ->execute();
        $file->timestamp = $timestamp;
      }
      $return = array(
        $file->fid,
      );
      if ($updating) {
        $this->numUpdated++;
      }
      else {
        $this->numCreated++;
      }
    }
    else {
      $return = FALSE;
    }
    return $return;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
MigrateDestination::$numCreated protected property Maintain stats on the number of destination objects created or updated.
MigrateDestination::$numUpdated protected property
MigrateDestination::getCreated public function
MigrateDestination::getUpdated public function
MigrateDestination::resetStats public function Reset numCreated and numUpdated back to 0.
MigrateDestinationEntity::$bundle protected property The bundle (node type, vocabulary, etc.) of the destination.
MigrateDestinationEntity::$entityType protected property The entity type (node, user, taxonomy_term, etc.) of the destination.
MigrateDestinationEntity::$language protected property Default language for text fields in this destination.
MigrateDestinationEntity::$textFormat protected property Default input format for text fields in this destination.
MigrateDestinationEntity::array_flatten public static function Flattens an array of allowed values.
MigrateDestinationEntity::complete public function Give handlers a shot at modifying the object (or taking additional action) after saving it.
MigrateDestinationEntity::completeRollback public function Give handlers a shot at cleaning up after an entity has been rolled back.
MigrateDestinationEntity::fieldAttachValidate public static function Perform field validation against the field data in an entity. Wraps field_attach_validate to handle exceptions cleanly and provide maximum information for identifying the cause of validation errors.
MigrateDestinationEntity::getBundle public function
MigrateDestinationEntity::getEntityType public function
MigrateDestinationEntity::getLanguage public function
MigrateDestinationEntity::getTextFormat public function
MigrateDestinationEntity::prepare public function Give handlers a shot at modifying the object before saving it.
MigrateDestinationEntity::prepareRollback public function Give handlers a shot at cleaning up before an entity has been rolled back.
MigrateDestinationEntity::__toString public function Derived classes must implement __toString(). Overrides MigrateDestination::__toString
MigrateDestinationFile::$fileClass protected property File class (MigrateFileUri etc.) doing the dirty wrk.
MigrateDestinationFile::$preserveFiles protected property Boolean indicating whether we should avoid deleting the actual file on rollback.
MigrateDestinationFile::fields public function Returns a list of fields available to be mapped for the entity type (bundle) Overrides MigrateDestination::fields
MigrateDestinationFile::fileDelete protected function Delete database references to a file without deleting the file itself.
MigrateDestinationFile::getKeySchema public static function Implementation of MigrateDestination::getKeySchema().
MigrateDestinationFile::import public function Import a single file record. Overrides MigrateDestination::import
MigrateDestinationFile::rollback public function Delete a file entry.
MigrateDestinationFile::setFileClass public function
MigrateDestinationFile::__construct public function Basic initialization Overrides MigrateDestinationEntity::__construct