You are here

public function AvatarKitLocalCache::cacheRemote in Avatar Kit 8.2

Download and save the file to an avatar cache entity.

Parameters

string $service_id: An avatar service ID.

string $uri: The URL of an avatar to download.

\Drupal\avatars\EntityAvatarIdentifierInterface $identifier: An entity avatar identifier.

Return value

\Drupal\avatars\Entity\AvatarCacheInterface|null An avatar cache entity, or NULL if the avatar failed to download.

Overrides AvatarKitLocalCacheInterface::cacheRemote

File

src/AvatarKitLocalCache.php, line 103

Class

AvatarKitLocalCache
Cache remote files locally into file entities.

Namespace

Drupal\avatars

Code

public function cacheRemote(string $service_id, string $uri, EntityAvatarIdentifierInterface $identifier) : ?AvatarCacheInterface {
  $entity = $identifier
    ->getEntity();
  $identifier_hash = $identifier
    ->getHashed();
  $file = NULL;
  try {
    $response = $this->downloadUtility
      ->get($uri);
  } catch (\Exception $e) {

    // Acceptable exceptions.
    $log_args = [
      '@service' => $service_id,
      '@entity_type' => $entity
        ->getEntityTypeId(),
      '@entity_id' => $entity
        ->id(),
      '@message' => $e
        ->getMessage(),
    ];
    $this->logger
      ->debug('Failed to download @service avatar for @entity_type #@entity_id. This failure is probably acceptable. Message is: @message', $log_args);
  }
  if (isset($response)) {

    // Different try block since we want to log these exceptions.
    try {
      $filepath = $this
        ->avatarFileName($service_id, $identifier);
      $file = $this->downloadUtility
        ->createFile($response, $filepath);
    } catch (\Exception $e) {
      $this->logger
        ->error('Failed to create avatar file: @exception', [
        '@exception' => $e
          ->getMessage(),
      ]);
    }
  }
  if (!$file) {
    return NULL;
  }

  /** @var \Drupal\avatars\Entity\AvatarCacheInterface $avatar_cache */
  $avatar_cache = $this->avatarCacheStorage
    ->create([
    'avatar_service' => $service_id,
    'identifier' => $identifier_hash,
    'avatar' => $file,
  ]);
  $avatar_cache
    ->save();
  return $avatar_cache;
}