You are here

public function BackupMigrate::backup in Backup and Migrate 5.0.x

Perform the backup from a given source, save it to the given destination.

Parameters

string $source_id: The id of the source to backup.

string $destination_id: The id of the destination to save the backup to.

Overrides BackupMigrateInterface::backup

File

src/Core/Main/BackupMigrate.php, line 51

Class

BackupMigrate
The core Backup and Migrate service.

Namespace

Drupal\backup_migrate\Core\Main

Code

public function backup($source_id, $destination_id) {
  try {

    // Allow the plugins to set up.
    $this
      ->plugins()
      ->call('setUp', NULL, [
      'operation' => 'backup',
      'source_id' => $source_id,
      'destination_id' => $destination_id,
    ]);

    // Get the source and the destination to use.
    $source = $this
      ->sources()
      ->get($source_id);
    $destinations = [];

    // Allow a single destination or multiple destinations.
    foreach ((array) $destination_id as $id) {
      $destinations[$id] = $this
        ->destinations()
        ->get($id);

      // Check that the destination is valid.
      if (!$destinations[$id]) {
        throw new BackupMigrateException('The destination !id does not exist.', [
          '!id' => $destination_id,
        ]);
      }

      // Check that the destination can be written to.
      // @todo Catch exceptions and continue if at least one dest is valid.
      $destinations[$id]
        ->checkWritable();
    }

    // Check that the source is valid.
    if (!$source) {
      throw new BackupMigrateException('The source !id does not exist.', [
        '!id' => $source_id,
      ]);
    }

    // Run each of the installed plugins which implements the 'beforeBackup'
    // operation.
    $this
      ->plugins()
      ->call('beforeBackup');

    // Do the actual backup.
    $file = $source
      ->exportToFile();

    // Run each of the installed plugins which implements the 'afterBackup'
    // operation.
    $file = $this
      ->plugins()
      ->call('afterBackup', $file);

    // Save the file to each destination.
    foreach ($destinations as $destination) {
      $destination
        ->saveFile($file);
    }

    // Let plugins react to a successful operation.
    $this
      ->plugins()
      ->call('backupSucceed', $file);
  } catch (\Exception $e) {

    // Let plugins react to a failed operation.
    $this
      ->plugins()
      ->call('backupFail', $e);

    // The consuming software needs to deal with this.
    throw $e;
  }

  // Allow the plugins to tear down.
  $this
    ->plugins()
    ->call('tearDown', NULL, [
    'operation' => 'backup',
    'source_id' => $source_id,
    'destination_id' => $destination_id,
  ]);
}