You are here

public function AvatarManager::getAvatarFile in Avatar Kit 8

Download avatar and insert it into a file.

Ignores any existing caches. Use refreshAvatarGenerator to take advantage of internal caching.

Parameters

\Drupal\avatars\AvatarGeneratorInterface $avatar_generator: An avatar generator instance.

\Drupal\user\UserInterface $user: A user entity.

Return value

\Drupal\file\FileInterface|false The file containing an avatar.

Overrides AvatarManagerInterface::getAvatarFile

1 call to AvatarManager::getAvatarFile()
AvatarManager::refreshAvatarGenerator in src/AvatarManager.php
Create avatar if it does not exist.

File

src/AvatarManager.php, line 189

Class

AvatarManager
Provides an avatar manager service.

Namespace

Drupal\avatars

Code

public function getAvatarFile(AvatarGeneratorInterface $avatar_generator, UserInterface $user) {
  $plugin = $avatar_generator
    ->getPlugin();

  // Get avatar if it is already local.
  $file = $plugin
    ->getFile($user);

  // Otherwise get the URL of the avatar, download it, and store it as a file.
  if (!$file && ($url = $plugin
    ->generateUri($user))) {
    $directory = 'public://avatar_kit/' . $avatar_generator
      ->id();

    /** @var \Drupal\Core\File\FileSystemInterface $fileSystem */
    $fileSystem = \Drupal::service('file_system');
    if ($fileSystem
      ->prepareDirectory($directory, FileSystemInterface::CREATE_DIRECTORY)) {
      try {
        if (($result = $this->httpClient
          ->get($url)) && $result
          ->getStatusCode() == 200) {
          $file_path = $directory . '/' . $user
            ->id() . '.jpg';
          $file = file_save_data($result
            ->getBody(), $file_path, FileSystemInterface::EXISTS_REPLACE);
        }
      } catch (ClientException $e) {

        // 4xx errors are acceptable, do not need to log.
        return FALSE;
      } catch (\Exception $e) {
        $this->loggerFactory
          ->get('avatars')
          ->error($this
          ->t('Failed to get @id avatar for @generator: %exception', [
          '@id' => $user
            ->id(),
          '@generator' => $avatar_generator
            ->id(),
          '%exception' => $e
            ->getMessage(),
        ]));
        return FALSE;
      }
    }
    else {
      throw new \Exception('Cannot create avatar kit directory.');
    }
  }
  return $file;
}