You are here

public function UsageEventSubscriber::onDeleteByTargetEntity 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::onDeleteByTargetEntity()

Triggers if the target (media) entity is deleted. Remove all Bynder usages.

Parameters

\Drupal\entity_usage\Events\EntityUsageEvent $event: The entity usage event.

File

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

Class

UsageEventSubscriber
Listens for the usage events from Entity Usage module.

Namespace

Drupal\bynder_usage\EventSubscriber

Code

public function onDeleteByTargetEntity(EntityUsageEvent $event) {
  if ($event
    ->getTargetEntityType() === 'media') {

    /** @var \Drupal\media\MediaInterface $media */
    $media = $this->entityTypeManager
      ->getStorage('media')
      ->load($event
      ->getTargetEntityId());
    if ($media) {
      $remote_id = $this
        ->getRemoteMediaId($media);
      if ($remote_id) {
        try {

          // The Bynder media entity is deleted from the system. Delete all
          // remote usages for this asset.
          $usages = $this->bynderApi
            ->getAssetUsages($remote_id);
          $base_url = Url::fromUri('base:/')
            ->setAbsolute()
            ->toString();
          foreach ($usages as $usage) {

            // If the usage appears to be on this site remove all the usages.
            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();
        }
      }
    }
  }
}