You are here

function update_bynder_media_usage_info in Bynder 8

Auxiliary function ran during cron to update all media usage information.

Throws

\Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException

1 call to update_bynder_media_usage_info()
bynder_cron in ./bynder.module
Implements hook_cron().

File

./bynder.module, line 207
Provides bynder integration.

Code

function update_bynder_media_usage_info() {
  $entity_type_manager = \Drupal::entityTypeManager();
  $bundle = $entity_type_manager
    ->getStorage('media_bundle')
    ->load('bynder');
  $source_field = $bundle
    ->getTypeConfiguration()['source_field'];
  $query = \Drupal::entityQuery('media');
  $query
    ->condition('bundle', 'bynder');
  $entity_ids = $query
    ->execute();
  $entities = $entity_type_manager
    ->getStorage('media')
    ->loadMultiple($entity_ids);
  foreach ($entities as $id => $media) {
    foreach (\Drupal::service('entity_usage.usage')
      ->listUsage($media) as $type => $usage) {
      if ($type == 'node') {
        foreach ($usage as $nid => $count) {
          $usage_url = Url::fromRoute('entity.node.canonical', [
            'node' => $nid,
          ], [
            'fragment' => "node/{$nid}",
          ]);
          $media_id = $media->{$source_field}->value;
          try {
            $usages = \Drupal::service('bynder_api')
              ->getAssetUsages($media_id);
            foreach ($usages as $usage_info) {
              $old_usage_url = $usage_info['uri'];
              $url_parts = explode('#', $old_usage_url);
              $node_info = isset($url_parts[1]) ? $url_parts[1] : null;
              if ($node_info == "node/{$nid}" && $usage_info['uri'] !== $usage_url
                ->setAbsolute(TRUE)
                ->toString() && $usage_info['integration']['id'] && \Drupal::service('bynder_api')
                ->getIntegrationId()) {
                \Drupal::service('bynder_api')
                  ->removeAssetUsage($media_id, $usage_info['uri']);
                \Drupal::service('bynder_api')
                  ->addAssetUsage($media_id, $usage_url, $usage_info['timestamp'], $usage_info['additional']);
              }
            }
          } catch (\Exception $exception) {
            \Drupal::logger('bynder')
              ->error(t('Unable to update asset usage. Check the error logs for more details.'));
          }
        }
      }
    }
  }
}