You are here

public function OnlyOneConstraintValidator::validate in Allow a content type only once (Only One) 8

File

src/Plugin/Validation/Constraint/OnlyOneConstraintValidator.php, line 67

Class

OnlyOneConstraintValidator
Validates the OnlyOne constraint.

Namespace

Drupal\onlyone\Plugin\Validation\Constraint

Code

public function validate($node, Constraint $constraint) {

  // Getting the configured content types.
  $onlyone_content_types = $this->configFactory
    ->get('onlyone.settings')
    ->get('onlyone_node_types');

  // If the content type is configured we need to check if exits a node
  // created in the node language.
  // @see https://www.drupal.org/project/onlyone/issues/2962186
  // @see https://www.drupal.org/project/onlyone/issues/2969293
  if (in_array($node
    ->getType(), $onlyone_content_types)) {

    // If we have a node in the current language we should not insert a new
    // one.
    $nid = $this->onlyone
      ->existsNodesContentType($node
      ->getType(), $node
      ->language()
      ->getId());

    // If the existing node have the same id that the node that is being saved
    // then is the same node that is being updated.
    if ($nid && $nid != $node
      ->id()) {

      /** @var \Drupal\node\NodeInterface $existing_node */
      $existing_node = $this->entityTypeManager
        ->getStorage('node')
        ->load($nid);
      $values = [
        '%content_type' => $node
          ->getType(),
        ':href' => $existing_node
          ->toUrl()
          ->toString(),
        '@title' => $existing_node
          ->getTitle(),
        '%language' => $node
          ->language()
          ->getName(),
      ];

      /** @var  \Drupal\onlyone\Plugin\Validation\Constraint\OnlyOneConstraint $constraint */
      $this->context
        ->buildViolation($constraint->nodeExists, $values)
        ->atPath('langcode')
        ->addViolation();
    }
  }
}