You are here

class TaxonomyUniqueValidator in Taxonomy unique 8.2

Taxonomy unique constraint validator.

Hierarchy

  • class \Drupal\taxonomy_unique\Plugin\Validation\Constraint\TaxonomyUniqueValidator extends \Symfony\Component\Validator\ConstraintValidator

Expanded class hierarchy of TaxonomyUniqueValidator

File

src/Plugin/Validation/Constraint/TaxonomyUniqueValidator.php, line 12

Namespace

Drupal\taxonomy_unique\Plugin\Validation\Constraint
View source
class TaxonomyUniqueValidator extends ConstraintValidator {

  /**
   * {@inheritdoc}
   */
  public function validate($value, Constraint $constraint) {

    /** @var TermInterface $term */
    $term = $value
      ->getEntity();
    if (\Drupal::config('taxonomy_unique.settings')
      ->get($term
      ->bundle()) && !$this
      ->isUnique($term)) {
      $message = \Drupal::config('taxonomy_unique.settings')
        ->get($term
        ->bundle() . '_message');
      if ($message != '') {
        $constraint
          ->setErrorMessage($message);
      }
      $this->context
        ->addViolation($constraint->notUnique, [
        '%term' => $term
          ->getName(),
        '%vocabulary' => $term
          ->bundle(),
      ]);
    }
  }

  /**
   * Checks if given term is unique inside its vocabulary.
   *
   * @param TermInterface $term
   *   The term to check.
   *
   * @return bool
   *   Whether the term is unique or not
   */
  private function isUnique(TermInterface $term) {
    $terms = \Drupal::entityTypeManager()
      ->getStorage('taxonomy_term')
      ->loadByProperties([
      'name' => $term
        ->getName(),
      'vid' => $term
        ->bundle(),
    ]);
    if (empty($terms)) {
      return TRUE;
    }
    if (count($terms) == 1) {
      $found_term = current($terms);
      if ($found_term
        ->id() == $term
        ->id()) {
        return TRUE;
      }
    }
    return FALSE;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
TaxonomyUniqueValidator::isUnique private function Checks if given term is unique inside its vocabulary.
TaxonomyUniqueValidator::validate public function Checks if the passed value is valid.