public function LetterAvatar::getFile in Letter Avatar 8
Gets File object for an avatar.
Parameters
\Drupal\Core\Session\AccountInterface $account: A user account.
Return value
\Drupal\file\FileInterface A file object.
Overrides AvatarGeneratorBase::getFile
File
- src/
Plugin/ AvatarGenerator/ LetterAvatar.php, line 32 - Contains \Drupal\letter_avatar\Plugin\AvatarGenerator\LetterAvatar.
Class
- LetterAvatar
- Gravatar avatar generator.
Namespace
Drupal\letter_avatar\Plugin\AvatarGeneratorCode
public function getFile(AccountInterface $account) {
$directory = 'public://avatar_kit/ak_letter';
if (file_prepare_directory($directory, FILE_CREATE_DIRECTORY)) {
/** @var \Drupal\Core\File\FileSystemInterface $file_system */
$file_system = \Drupal::service('file_system');
$letter = mb_substr($account
->getUsername(), 0, 1);
$path = $directory . '/' . $account
->id() . '.png';
// todo: update existing file entity
// if you update a file on the file system directly, page caches and image
// styles will not flush.
$ids = \Drupal::entityManager()
->getStorage('file')
->getQuery()
->condition('uri', $path)
->execute();
if ($id = reset($ids)) {
$file = File::load($id);
$file
->delete();
}
$letterAvatar = new LetterAvatarAPI();
$letterAvatar
->generate($letter, 256)
->saveAsPng($file_system
->realpath($path));
// File cannot chain methods.
$file = File::create();
$file
->setFileUri($path);
$file
->setOwnerId($account
->id());
// Temporary until AvatarPreview adds usage.
$file
->setTemporary();
return $file;
}
return NULL;
}