<?php

namespace Drupal\acquia_contenthub\Libs\Traits;

/**
 * Trait with helper functions view filter plugins.
 *
 * @package Drupal\acquia_contenthub
 */
trait ViewFilterPluginHelperTrait {

  /**
   * Provides entity type id of target reference entity based on table name.
   *
   * @param string $table_name
   *   The table's name created during field initialization.
   *
   * @return string
   *   Entity type id.
   *
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   */
  protected function getTargetEntityReferenceTypeIdFromTableName(string $table_name): string {
    /** @var \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager */
    $entity_type_manager = \Drupal::service('entity_type.manager');
    $entity_type = '';
    $field_name = str_replace('__', '.', $table_name);
    $field_definition = $entity_type_manager->getStorage('field_storage_config')->load($field_name);
    if (!empty($field_definition) && $field_definition->getType() === 'entity_reference') {
      $entity_type = $field_definition->getSettings()['target_type'] ?? '';
    }
    return $entity_type;
  }

}
