You are here

public function BynderService::updateMediaEntities in Bynder 4.0.x

Updates a set of media entities based on the remote metadata information.

Parameters

\Drupal\media\MediaInterface[] $bynder_media_entities: A list of media entities with a bynder source, keyed by the bynder ID, updates entities are removed from the list.

Return value

\Drupal\media\MediaInterface[] A list of updated media entities.

Overrides BynderServiceInterface::updateMediaEntities

1 call to BynderService::updateMediaEntities()
BynderService::updateMetadataLastMediaEntities in src/BynderService.php
Updates metadata of the next N media entities starting at the minimum ID.

File

src/BynderService.php, line 252

Class

BynderService
Bynder service.

Namespace

Drupal\bynder

Code

public function updateMediaEntities(array &$bynder_media_entities) {

  // Get the most recent metadata for the queried IDs.
  $query = [
    'ids' => implode(',', array_keys($bynder_media_entities)),
  ];
  try {
    $media_list = $this->bynderApi
      ->getMediaList($query);
  } catch (ClientException $e) {
    $this->logger
      ->error($e
      ->getMessage());
    return [];
  }
  $updated_entities = [];
  foreach ($media_list as $index => $item) {
    $media_entity = $bynder_media_entities[$item['id']];

    /** @var \Drupal\bynder\Plugin\media\Source\Bynder $source */
    $source = $media_entity
      ->getSource();
    $remote_metadata = $source
      ->filterRemoteMetadata($item);
    $has_changed = FALSE;
    if ($source
      ->hasMetadataChanged($media_entity, $remote_metadata)) {
      $media_entity
        ->set(BynderMetadataItem::METADATA_FIELD_NAME, Json::encode($remote_metadata));
      $has_changed = TRUE;
    }

    // Allow other modules to alter the media entity.
    $this->moduleHandler
      ->alter('bynder_media_update', $media_entity, $item, $has_changed);
    if ($has_changed) {
      $media_entity
        ->save();
    }
    $updated_entities[$media_entity
      ->id()] = $media_entity;

    // Remove the processed item.
    unset($bynder_media_entities[$item['id']]);
  }
  return $updated_entities;
}