You are here

public function ClipboardJsCommands::downloadLibrary in Clipboard.js 8

Same name and namespace in other branches
  1. 2.0.x src/Commands/ClipboardJsCommands.php \Drupal\clipboardjs\Commands\ClipboardJsCommands::downloadLibrary()

Download and extract a library.

Parameters

string $url: The URL to download.

string $destination: The path to copy the files to.

Throws

\Exception

1 call to ClipboardJsCommands::downloadLibrary()
ClipboardJsCommands::download in src/Commands/ClipboardJsCommands.php
Command to download and extract the library.

File

src/Commands/ClipboardJsCommands.php, line 46

Class

ClipboardJsCommands
Drush commandfile.

Namespace

Drupal\clipboardjs\Commands

Code

public function downloadLibrary($url, $destination) {
  if (!is_dir(self::LIBRARY_DESTINATION)) {
    drush_op('mkdir', self::LIBRARY_DESTINATION);
    $this
      ->logger()
      ->notice('Directory ' . self::LIBRARY_DESTINATION . ' was created.');
  }

  // Set the directory to the download location.
  $olddir = getcwd();
  chdir(self::LIBRARY_DESTINATION);

  // Download the archive.
  $filename = basename($url);
  if ($filepath = $this
    ->downloadFile($url, FALSE, FALSE, \Drupal::service('file_system')
    ->getTempDirectory() . '/' . $filename, TRUE)) {
    $filename = basename($url);

    // Remove any existing plugin directory.
    if (is_dir($destination)) {
      \Drupal::service('file_system')
        ->deleteRecursive($destination);
    }

    // Decompress the archive.
    $zip = new \ZipArchive();
    if ($zip
      ->open($filepath) === TRUE) {
      $index = $zip
        ->getNameIndex(0);
      $zip
        ->extractTo('.');
      $zip
        ->close();
      \Drupal::service('file_system')
        ->move($index, $destination);
      $this
        ->logger()
        ->notice('The library has been downloaded to ' . $destination);
    }
    else {
      throw new \Exception("Cannot extract '{$filename}', not a valid archive");
    }
  }

  // Set working directory back to the previous working directory.
  chdir($olddir);
  if (is_dir(self::LIBRARY_DESTINATION . '/' . $destination)) {
    $this
      ->logger()
      ->info('The plugin has been installed to ' . self::LIBRARY_DESTINATION . '/' . $destination);
  }
  else {
    $this
      ->logger()
      ->error('Drush was unable to install the plugin to ' . self::LIBRARY_DESTINATION . '/' . $destination);
  }
}