You are here

protected function PackageDownloader::downloadArchive in Ludwig 8

Downloads an archive from the given URL to the temporary directory.

Returns the local path if the file has already been downloaded.

Parameters

string $package: The package for download.

Return value

string The path to the local file.

Throws

\Exception

1 call to PackageDownloader::downloadArchive()
PackageDownloader::download in src/PackageDownloader.php
Downloads and places packages into their modules.

File

src/PackageDownloader.php, line 129

Class

PackageDownloader
Download packages defined in ludwig.json files.

Namespace

Drupal\ludwig

Code

protected function downloadArchive($package) {
  $parsed_url = parse_url($package['download_url']);
  $cache_dir = $this->cacheDir . '/' . str_replace('/', '-', $package['name']);
  if (!file_exists($cache_dir)) {
    mkdir($cache_dir);
  }
  $local = $cache_dir . '/' . $this->fileSystem
    ->basename($parsed_url['path']);
  if (!file_exists($local)) {
    $destination = $local;
    try {
      $data = $this->httpClient
        ->request('get', $package['download_url'])
        ->getBody()
        ->getContents();
      $local = $this->fileSystem
        ->saveData($data, $destination, FileSystemInterface::EXISTS_REPLACE);
    } catch (RequestException $exception) {
      throw new \Exception(sprintf('Failed to fetch file due to error "%s". Fix the related "url" record in "%s" module ludwig.json file.', $exception
        ->getMessage(), $package['provider']));
    }
    if (!$local) {
      throw new \Exception(sprintf('%s could not be saved to %s', $package['download_url'], $destination));
    }
    return $local;
  }
  else {
    return $local;
  }
}