You are here

public function SynonymsEntity::validateArgument in Synonyms 2.0.x

Same name and namespace in other branches
  1. 8 synonyms_views_argument_validator/src/Plugin/views/argument_validator/SynonymsEntity.php \Drupal\synonyms_views_argument_validator\Plugin\views\argument_validator\SynonymsEntity::validateArgument()

Performs validation for a given argument.

Overrides Entity::validateArgument

File

modules/synonyms_views_argument_validator/src/Plugin/views/argument_validator/SynonymsEntity.php, line 36

Class

SynonymsEntity
Synonyms-friendly entity validator.

Namespace

Drupal\synonyms_views_argument_validator\Plugin\views\argument_validator

Code

public function validateArgument($argument) {
  if ($this->options['transform']) {
    $argument = str_replace('-', ' ', $argument);
  }
  $entity_type = $this->entityTypeManager
    ->getDefinition($this->definition['entity_type']);
  if ($entity_type
    ->hasKey('label') || $entity_type
    ->id() == 'user') {
    $query = $this->entityTypeManager
      ->getStorage($entity_type
      ->id())
      ->getQuery();

    // User entity type does not declare its label, while it does have one.
    $label_column = $entity_type
      ->id() == 'user' ? 'name' : $entity_type
      ->getKey('label');
    $query
      ->condition($label_column, $argument, '=');
    if ($entity_type
      ->hasKey('bundle') && !empty($this->options['bundles'])) {
      $query
        ->condition($entity_type
        ->getKey('bundle'), $this->options['bundles'], 'IN');
    }
    $result = $query
      ->execute();
    if (!empty($result)) {
      $entities = $this->entityTypeManager
        ->getStorage($entity_type
        ->id())
        ->loadMultiple($result);
      foreach ($entities as $entity) {
        if ($this
          ->validateEntity($entity)) {
          $this->argument->argument = $entity
            ->id();
          return TRUE;
        }
      }
    }
  }

  // We've fallen through with search by entity name, now it's time to search
  // by synonyms.
  $condition = new Condition('AND');
  $condition
    ->condition(FindInterface::COLUMN_SYNONYM_PLACEHOLDER, $argument, '=');
  foreach (\Drupal::service('synonyms.provider_service')
    ->findSynonyms($condition, $entity_type, empty($this->options['bundles']) ? NULL : $this->options['bundles']) as $synonym) {
    $entity = $this->entityTypeManager
      ->getStorage($entity_type
      ->id())
      ->load($synonym->entity_id);
    if ($this
      ->validateEntity($entity)) {
      $this->argument->argument = $entity
        ->id();
      return TRUE;
    }
  }
  return FALSE;
}