You are here

public function UsageEventSubscriber::onDeleteBySourceEntity in Bynder 4.0.x

Same name and namespace in other branches
  1. 8.3 modules/bynder_usage/src/EventSubscriber/UsageEventSubscriber.php \Drupal\bynder_usage\EventSubscriber\UsageEventSubscriber::onDeleteBySourceEntity()

Triggers when the source entity is deleted.

Parameters

\Drupal\entity_usage\Events\EntityUsageEvent $event: The event to process.

File

modules/bynder_usage/src/EventSubscriber/UsageEventSubscriber.php, line 219

Class

UsageEventSubscriber
Listens for the usage events from Entity Usage module.

Namespace

Drupal\bynder_usage\EventSubscriber

Code

public function onDeleteBySourceEntity(EntityUsageEvent $event) {

  // Skip if a non-default revision or translation is deleted.
  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;
  }

  // At this point, the entity usages are already deleted so we can't query
  // the entity usage table to find the relevant media usages. Instead, loop
  // over the references of the source entity and delete all usages of the
  // Bynder media assets on this URI.
  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();
      }
    }
  }
}