You are here

function varbase_media_entity_presave in Varbase Media 9.0.x

Same name and namespace in other branches
  1. 8.7 varbase_media.module \varbase_media_entity_presave()

Implements hook_entity_presave().

File

./varbase_media.module, line 159
Contains varbase_media.module.

Code

function varbase_media_entity_presave(EntityInterface $entity) {
  if ($entity
    ->getEntityType()
    ->id() == 'media' && $entity->bundle->target_id == 'remote_video') {

    // If the field_provider exists in the remote video media type.
    $field_field_media_remote_video_field_provider = FieldConfig::loadByName('media', 'remote_video', 'field_provider');
    if (isset($field_field_media_remote_video_field_provider)) {

      // Fetch the resource from the URL and save in the field_provider.
      $url_resolver = \Drupal::service('media.oembed.url_resolver');
      $resource_fetcher = \Drupal::service('media.oembed.resource_fetcher');
      $resource_url = $url_resolver
        ->getResourceUrl($entity->field_media_oembed_video->value);
      $resource = $resource_fetcher
        ->fetchResource($resource_url);
      $provider = strtolower($resource
        ->getProvider()
        ->getName());
      if ($entity->field_provider->value != $provider) {
        $entity
          ->set('field_provider', $provider);
      }
    }
  }
}