You are here

function media_acquiadam_media_presave in Media: Acquia DAM 8

Implements hook_ENTITY_TYPE_presave().

Override the preSave function from \Drupal\media\Entity\Media because it ignores empty values (e.g. status = 0) and doesn't set date values for created/changed because they are already set by Drupal core.

File

./media_acquiadam.module, line 95
Integrates Drupal with Acquia DAM.

Code

function media_acquiadam_media_presave(MediaInterface $entity) {

  // Only go for a resync when updating existing entities.
  if ($entity
    ->isNew()) {
    return;
  }

  /** @var \Drupal\media_acquiadam\Plugin\media\Source\AcquiadamAsset $source */
  $source = $entity
    ->getSource();
  if ($source
    ->getPluginId() !== 'acquiadam_asset') {
    return;
  }

  /** @var \Drupal\media_acquiadam\Service\AssetMediaFactory $asset_media_factory */
  $asset_media_factory = Drupal::service('media_acquiadam.asset_media.factory');
  $media_helper = $asset_media_factory
    ->get($entity);
  $assetID = $media_helper
    ->getAssetId();
  if (empty($assetID)) {
    return;
  }
  $asset = $media_helper
    ->getAsset();
  if (empty($asset)) {
    Drupal::logger('media_acquiadam')
      ->warning('Unable to retrieve asset @assetID.', [
      '@assetID' => $assetID,
    ]);
    return;
  }
  foreach ($entity->bundle->entity
    ->getFieldMap() as $source_field => $destination_field) {
    if ($entity
      ->hasField($destination_field)) {
      $entity
        ->set($destination_field, $source
        ->getMetadata($entity, $source_field));
    }
  }

  /** @var \Drupal\media\Entity\Media $entity */
  $entity
    ->updateQueuedThumbnail();
}