AvatarKitEntityFieldHandler.php in Avatar Kit 8.2
File
src/AvatarKitEntityFieldHandler.php
View source
<?php
namespace Drupal\avatars;
use Drupal\avatars\Entity\AvatarCacheInterface;
use Drupal\avatars\Entity\AvatarKitEntityMap;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\FieldableEntityInterface;
use Drupal\field\Entity\FieldConfig;
use Drupal\field\FieldConfigInterface;
use Drupal\file\FileInterface;
class AvatarKitEntityFieldHandler implements AvatarKitEntityFieldHandlerInterface {
protected $entityHandler;
public function __construct(AvatarKitEntityHandlerInterface $entityHandler) {
$this->entityHandler = $entityHandler;
}
public function copyCacheToEntity(FieldableEntityInterface $entity, AvatarCacheInterface $avatar_cache) : void {
$field_name = $this
->getAvatarFieldName($entity);
if (!$field_name) {
throw new \Exception('Entity does not accept avatars.');
}
$file = $avatar_cache
->getAvatar();
$this
->pushFileIntoEntity($entity, $field_name, $file);
}
public function checkUpdates(FieldableEntityInterface $entity) : void {
$field_name = $this
->getAvatarFieldName($entity);
if (!$field_name) {
return;
}
$first = $this->entityHandler
->findFirst($entity);
if ($first) {
$this
->copyCacheToEntity($entity, $first);
}
}
protected function pushFileIntoEntity(FieldableEntityInterface $entity, string $field_name, FileInterface $file) {
$field_item_list = $entity
->get($field_name);
$files = $field_item_list
->referencedEntities();
$current_file = reset($files);
if ($current_file instanceof FileInterface && $current_file
->id() == $file
->id()) {
return;
}
$field_item_list
->setValue([
$file,
]);
$entity
->save();
}
public function getAvatarFieldName(EntityInterface $entity) : ?string {
$entity_type = $entity
->getEntityTypeId();
$bundle = $entity
->bundle();
$entity_map = AvatarKitEntityMap::load($entity_type . '.' . $bundle . '.' . 'default');
return $entity_map ? $entity_map
->getFieldName() : NULL;
}
public function getAvatarFieldConfig(EntityInterface $entity) : ?FieldConfigInterface {
$field_name = $this
->getAvatarFieldName($entity);
if (!$field_name) {
return NULL;
}
$field_config_id = $entity
->getEntityTypeId() . '.' . $entity
->bundle() . '.' . $field_name;
$field_config = FieldConfig::load($field_config_id);
return $field_config ? $field_config : NULL;
}
}