bridtv-8.x-1.x-dev/src/BridPlaylistEntityResolver.php
src/BridPlaylistEntityResolver.php
<?php
namespace Drupal\bridtv;
use Drupal\Core\Cache\MemoryCache\MemoryCacheInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Entity\FieldableEntityInterface;
/**
* The Brid Playlist Entity Resolver.
*/
class BridPlaylistEntityResolver extends BridEntityResolver {
const BUNDLE = 'brid_tv_playlist';
const FIELD = 'field_media_bridtv_playlist';
/**
* BridEntityResolver constructor.
*
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager.
* @param \Drupal\Core\Cache\MemoryCache\MemoryCacheInterface $entity_memory_cache
* The entity memory cache.
*/
public function __construct(EntityTypeManagerInterface $entity_type_manager, MemoryCacheInterface $entity_memory_cache) {
parent::__construct($entity_type_manager, $entity_memory_cache);
$this->type = 'playlist';
$this->cached = [$this->type => []];
}
/**
* Get the representing entity for the given playlist id.
*
* @param int $id
* The Brid.TV playlist id.
*
* @return \Drupal\Core\Entity\FieldableEntityInterface|null
* The entity if existent, or NULL if not existent.
*/
public function getEntityForPlaylistId($id) {
$storage = $this->getEntityStorage();
if (!isset($this->cached['playlist'][$id])) {
$this->usingInternalCache();
$query = $storage->getQuery();
$query->condition(static::FIELD . '.playlist_id', $id, '=');
$query->range(0, 1);
$query->accessCheck(TRUE);
if ($result = $query->execute()) {
$this->cached['playlist'][$id] = reset($result);
}
}
return isset($this->cached['playlist'][$id]) ? $storage->load($this->cached['playlist'][$id]) : NULL;
}
/**
* The using Internal Cache function.
*/
protected function usingInternalCache() {
$this->cacheResetCounter++;
if ($this->cacheResetCounter > 100) {
$this->cacheResetCounter = 0;
$this->cached = ['playlist' => []];
$this->getEntityStorage()->resetCache();
$this->entityMemoryCache->deleteAll();
}
}
/**
* Gets a field item list.
*
* @param \Drupal\Core\Entity\FieldableEntityInterface $entity
* The entity.
*
* @return \Drupal\Core\Field\FieldItemListInterface|null
* Returns FieldItemListInterface|null.
*/
public function getFieldItemList(FieldableEntityInterface $entity) {
foreach ($entity->getFieldDefinitions() as $definition) {
if ($definition->getType() === 'bridtv_playlist') {
$field = $definition->getName();
return $entity->get($field);
}
}
return NULL;
}
}
