You are here

public function MediaService::getMediaEntityAutoCompleteData in Gutenberg 8.2

Same name and namespace in other branches
  1. 8 src/Service/MediaService.php \Drupal\gutenberg\Service\MediaService::getMediaEntityAutoCompleteData()

Get media entity results for autocomplete endpoint.

Parameters

string $search: Text to search. Can be an ID.

Return value

array The media entity results.

File

src/Service/MediaService.php, line 403

Class

MediaService
The media service class.

Namespace

Drupal\gutenberg\Service

Code

public function getMediaEntityAutoCompleteData(string $search) {
  try {
    $query = $this->entityTypeManager
      ->getStorage('media')
      ->getQuery();
    if (is_numeric($search)) {
      $query
        ->condition('id', $search);
    }
    else {
      $query
        ->condition('name', $search, 'CONTAINS');
    }
    $query
      ->condition('uid', \Drupal::currentUser()
      ->id());
    $query
      ->sort('created', 'DESC');
    $media_ids = $query
      ->execute();
    $media_entities = $this->entityTypeManager
      ->getStorage('media')
      ->loadMultiple($media_ids ?: []);
    return array_values(array_map(function (MediaInterface $media_entity) {
      return [
        'title' => $media_entity
          ->getName(),
        'url' => $media_entity
          ->getName() . ' (' . $media_entity
          ->id() . ')',
        'id' => $media_entity
          ->id(),
        'media_type' => $media_entity
          ->bundle(),
        'file_id' => $media_entity
          ->getSource()
          ->getSourceFieldValue($media_entity),
      ];
    }, $media_entities));
  } catch (\Throwable $exception) {
    return [];
  }
}