You are here

public function DrupalGatherContentClient::downloadFiles in GatherContent 8.5

Same name and namespace in other branches
  1. 8.4 src/DrupalGatherContentClient.php \Drupal\gathercontent\DrupalGatherContentClient::downloadFiles()

Downloads all files asynchronously.

Parameters

array $files: Files object array.

string $directory: Destination directory.

string $language: Language string.

Return value

array Imported files array.

1 method overrides DrupalGatherContentClient::downloadFiles()
MockDrupalGatherContentClient::downloadFiles in tests/modules/gathercontent_test/src/MockDrupalGatherContentClient.php
Mock download.

File

src/DrupalGatherContentClient.php, line 129

Class

DrupalGatherContentClient
Extends the GatherContentClient class with Drupal specific functionality.

Namespace

Drupal\gathercontent

Code

public function downloadFiles(array $files, $directory, $language) {
  $entityTypeManager = \Drupal::service('entity_type.manager');

  /** @var \GuzzleHttp\Client $httpClient */
  $httpClient = $this->client;
  $options = [
    'auth' => $this
      ->getRequestAuth(),
    'headers' => [],
  ];
  $options['headers'] += $this
    ->getRequestHeaders();

  // Remove unnecessary associative array keys.
  $files = array_values($files);
  $importedFiles = [];
  $requests = function () use ($httpClient, $files, $options) {
    foreach ($files as $file) {
      if (!$file) {
        continue;
      }
      (yield function () use ($httpClient, $file, $options) {
        return $httpClient
          ->getAsync($file->url, $options);
      });
    }
  };
  $pool = new Pool($httpClient, $requests(), [
    'fulfilled' => function ($response, $index) use ($files, $directory, $language, &$importedFiles, $entityTypeManager) {
      if ($response
        ->getStatusCode() === 200) {
        $file = $entityTypeManager
          ->getStorage('file')
          ->loadByProperties([
          'gc_file_id' => $files[$index]->fileId,
        ]);
        if ($file) {
          $file = reset($file);
          $importedFiles[$index] = $file
            ->id();
          return;
        }
        $path = $directory . '/' . $files[$index]->filename;
        $importedFile = file_save_data($response
          ->getBody(), $path);
        if ($importedFile) {
          $importedFile
            ->set('gc_file_id', $files[$index]->fileId)
            ->set('langcode', $language)
            ->set('filesize', $files[$index]->size)
            ->save();
          $importedFiles[$index] = $importedFile
            ->id();
        }
      }
    },
  ]);
  $promise = $pool
    ->promise();
  $promise
    ->wait();
  ksort($importedFiles);
  return $importedFiles;
}