UsageEventSubscriber.php in Bynder 4.0.x
File
modules/bynder_usage/src/EventSubscriber/UsageEventSubscriber.php
View source
<?php
namespace Drupal\bynder_usage\EventSubscriber;
use Drupal\bynder\BynderApiInterface;
use Drupal\bynder\Plugin\media\Source\Bynder;
use Drupal\bynder_usage\Exception\UnableToAddUsageException;
use Drupal\bynder_usage\Exception\UnableToDeleteUsageException;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Url;
use Drupal\entity_usage\Events\EntityUsageEvent;
use Drupal\entity_usage\Events\Events;
use Drupal\media\MediaInterface;
use Drupal\paragraphs\ParagraphInterface;
use GuzzleHttp\Exception\RequestException;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RequestStack;
class UsageEventSubscriber implements EventSubscriberInterface {
protected $bynderApi;
protected $entityTypeManager;
protected $requestStack;
public function __construct(BynderApiInterface $bynder_api_service, EntityTypeManagerInterface $entity_type_manager, RequestStack $request_stack) {
$this->bynderApi = $bynder_api_service;
$this->entityTypeManager = $entity_type_manager;
$this->requestStack = $request_stack;
}
public static function getSubscribedEvents() {
$events[Events::USAGE_REGISTER][] = [
'onUsageRegister',
];
$events[Events::DELETE_BY_SOURCE_ENTITY][] = [
'onDeleteBySourceEntity',
];
$events[Events::DELETE_BY_TARGET_ENTITY][] = [
'onDeleteByTargetEntity',
];
return $events;
}
protected function getRemoteMediaId(MediaInterface $media) {
$source_plugin = $media
->getSource();
if (!$source_plugin instanceof Bynder) {
return NULL;
}
return $source_plugin
->getSourceFieldValue($media);
}
protected function getEntityUrl(EntityInterface $entity) {
while ($entity && $entity instanceof ParagraphInterface) {
$entity = $entity
->getParentEntity();
}
return $entity && $entity
->hasLinkTemplate('canonical') ? $entity
->toUrl('canonical')
->setOption('path_processing', FALSE)
->setAbsolute() : NULL;
}
private function getUsageEventMediainformation(EntityUsageEvent $event) {
if ($event
->getTargetEntityType() !== 'media') {
return NULL;
}
$media = $this->entityTypeManager
->getStorage('media')
->load($event
->getTargetEntityId());
if (!isset($media)) {
return NULL;
}
$source_plugin = $media
->getSource();
if (!$source_plugin instanceof Bynder) {
return NULL;
}
$url = NULL;
if ($source_id = $event
->getSourceEntityId()) {
if ($entity = $this->entityTypeManager
->getStorage($event
->getSourceEntityType())
->load($source_id)) {
$url = $this
->getEntityUrl($entity);
}
}
if ($url) {
return [
'mediaId' => $source_plugin
->getSourceFieldValue($media),
'url' => $url,
];
}
}
protected function hasRemoteUsageByUri($remote_id, $uri) {
$usages = $this->bynderApi
->getAssetUsages($remote_id);
if (empty($usages)) {
return FALSE;
}
foreach ($usages as $usage) {
if ($usage['uri'] === $uri) {
return TRUE;
}
}
return FALSE;
}
public function onUsageRegister(EntityUsageEvent $event) {
$mediaInfo = $this
->getUsageEventMediainformation($event);
if (isset($mediaInfo)) {
try {
if ($event
->getCount() > 0) {
$usage_url = $mediaInfo['url'];
if (!$this
->hasRemoteUsageByUri($mediaInfo['mediaId'], $usage_url
->toString())) {
$this->bynderApi
->addAssetUsage($mediaInfo['mediaId'], $usage_url, date(DATE_ISO8601, \Drupal::time()
->getRequestTime()), 'Added asset by user ' . \Drupal::currentUser()
->getAccountName() . '.');
}
}
else {
$this->bynderApi
->removeAssetUsage($mediaInfo['mediaId'], $mediaInfo['url']
->toString());
}
} catch (RequestException $e) {
watchdog_exception('bynder', $e);
(new UnableToAddUsageException($e
->getMessage()))
->logException()
->displayMessage();
}
}
}
public function onDeleteBySourceEntity(EntityUsageEvent $event) {
if ($event
->getSourceEntityRevisionId() || $event
->getSourceEntityLangcode()) {
return;
}
$storage = $this->entityTypeManager
->getStorage($event
->getSourceEntityType());
$entity = $storage
->load($event
->getSourceEntityId());
if (!$entity) {
return;
}
$usage_url = $this
->getEntityUrl($entity);
if (!$usage_url) {
return;
}
foreach ($entity
->referencedEntities() as $referenced_entity) {
if ($referenced_entity instanceof MediaInterface && ($remote_id = $this
->getRemoteMediaId($referenced_entity))) {
try {
$this->bynderApi
->removeAssetUsage($remote_id, $usage_url
->toString());
} catch (RequestException $e) {
watchdog_exception('bynder', $e);
(new UnableToDeleteUsageException($e
->getMessage()))
->logException()
->displayMessage();
}
}
}
}
public function onDeleteByTargetEntity(EntityUsageEvent $event) {
if ($event
->getTargetEntityType() === 'media') {
$media = $this->entityTypeManager
->getStorage('media')
->load($event
->getTargetEntityId());
if ($media) {
$remote_id = $this
->getRemoteMediaId($media);
if ($remote_id) {
try {
$usages = $this->bynderApi
->getAssetUsages($remote_id);
$base_url = Url::fromUri('base:/')
->setAbsolute()
->toString();
foreach ($usages as $usage) {
if (strpos($usage['uri'], $base_url) === 0) {
$this->bynderApi
->removeAssetUsage($remote_id, $usage['uri']);
}
}
} catch (RequestException $e) {
watchdog_exception('bynder', $e);
(new UnableToDeleteUsageException($e
->getMessage()))
->logException()
->displayMessage();
}
}
}
}
}
}