DrupalGatherContentClient.php in GatherContent 8.4
File
src/DrupalGatherContentClient.php
View source
<?php
namespace Drupal\gathercontent;
use Cheppers\GatherContent\GatherContentClient;
use GuzzleHttp\ClientInterface;
use GuzzleHttp\Pool;
class DrupalGatherContentClient extends GatherContentClient {
public function __construct(ClientInterface $client) {
parent::__construct($client);
$this
->setCredentials();
}
public function setCredentials() {
$config = \Drupal::config('gathercontent.settings');
$this
->setEmail($config
->get('gathercontent_username') ?: '');
$this
->setApiKey($config
->get('gathercontent_api_key') ?: '');
}
public static function getAccountId($account_name = NULL) {
$account = \Drupal::config('gathercontent.settings')
->get('gathercontent_account');
$account = unserialize($account);
if (!is_array($account)) {
return NULL;
}
if (!$account_name) {
if (reset($account)) {
return key($account);
}
}
foreach ($account as $id => $name) {
if ($name === $account_name) {
return $id;
}
}
return NULL;
}
public function getActiveProjects($account_id) {
$projects = $this
->projectsGet($account_id);
foreach ($projects as $id => $project) {
if (!$project->active) {
unset($projects[$id]);
}
}
return $projects;
}
public function getTemplatesOptionArray($project_id) {
$formatted = [];
$templates = $this
->templatesGet($project_id);
foreach ($templates as $id => $template) {
$formatted[$id] = $template->name;
}
return $formatted;
}
public function getBody($json_decoded = FALSE) {
$body = $this
->getResponse()
->getBody();
if ($json_decoded) {
return \GuzzleHttp\json_decode($body);
}
return $body;
}
public function downloadFiles(array $files, $directory, $language) {
$httpClient = $this->client;
$options = [
'auth' => $this
->getRequestAuth(),
'headers' => [],
];
$options['headers'] += $this
->getRequestHeaders();
$files = array_values($files);
$importedFiles = [];
$requests = function () use ($httpClient, $files, $options) {
foreach ($files as $file) {
$url = $this
->getUri("files/{$file->id}/download");
(yield function () use ($httpClient, $url, $options) {
return $httpClient
->getAsync($url, $options);
});
}
};
$pool = new Pool($httpClient, $requests(), [
'fulfilled' => function ($response, $index) use ($files, $directory, $language, &$importedFiles) {
if ($response
->getStatusCode() === 200) {
$path = $directory . '/' . $files[$index]->fileName;
$importedFile = file_save_data($response
->getBody(), $path);
if ($importedFile) {
$importedFile
->set('gc_id', $files[$index]->id)
->set('langcode', $language)
->set('filesize', $files[$index]->size)
->save();
$importedFiles[$index] = $importedFile
->id();
}
}
},
]);
$promise = $pool
->promise();
$promise
->wait();
ksort($importedFiles);
return $importedFiles;
}
}