<?php

namespace Drupal\acquia_contenthub_subscriber\EventSubscriber\ReplaceEntityUuidWithId;

use Drupal\Component\Uuid\Uuid;

/**
 * Replaces entity uuid with id for taxonomy_index_id plugin filter.
 *
 * @package \Drupal\acquia_contenthub_subscriber\Event\ReplaceEntityUuidWithIdEvent
 */
class TaxonomyIndexIdViewFilterPlugin extends ViewFilterPluginReplaceEntityUuidWithIdBase {

  /**
   * Replaces entity uuid with id for taxonomy_index_tid plugin.
   *
   * @param array $filter_data
   *   The filter data.
   *
   * @return array
   *   The updated filter data.
   *
   * @throws \Exception
   */
  public function replaceEntityUuidWithIdForViewFilterPlugin(array $filter_data): array {
    if ($filter_data['plugin_id'] !== 'taxonomy_index_tid') {
      return [];
    }
    $entity_type = 'taxonomy_term';
    // Updating entity uuid with entity id.
    foreach ($filter_data['value'] as $key => $uuid) {
      if (!Uuid::isValid($uuid)) {
        continue;
      }
      $entities = $this->entityTypeManager->getStorage($entity_type)->loadByProperties(['uuid' => [$uuid]]);
      if ($entities) {
        /** @var \Drupal\Core\Entity\EntityInterface $entity */
        $entity = reset($entities);
        $filter_data['value'][$key] = $entity->id();
        continue;
      }
      $this->logMissingEntity($entity_type, $uuid, $filter_data['plugin_id']);
    }
    return $filter_data;
  }

}
