OnlyOneConstraintValidator.php in Allow a content type only once (Only One) 8
File
src/Plugin/Validation/Constraint/OnlyOneConstraintValidator.php
View source
<?php
namespace Drupal\onlyone\Plugin\Validation\Constraint;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\onlyone\OnlyOneInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
class OnlyOneConstraintValidator extends ConstraintValidator implements ContainerInjectionInterface {
protected $configFactory;
protected $onlyone;
protected $entityTypeManager;
public function __construct(ConfigFactoryInterface $config_factory, OnlyOneInterface $onlyone, EntityTypeManagerInterface $entity_type_manager) {
$this->configFactory = $config_factory;
$this->onlyone = $onlyone;
$this->entityTypeManager = $entity_type_manager;
}
public static function create(ContainerInterface $container) {
return new static($container
->get('config.factory'), $container
->get('onlyone'), $container
->get('entity_type.manager'));
}
public function validate($node, Constraint $constraint) {
$onlyone_content_types = $this->configFactory
->get('onlyone.settings')
->get('onlyone_node_types');
if (in_array($node
->getType(), $onlyone_content_types)) {
$nid = $this->onlyone
->existsNodesContentType($node
->getType(), $node
->language()
->getId());
if ($nid && $nid != $node
->id()) {
$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(),
];
$this->context
->buildViolation($constraint->nodeExists, $values)
->atPath('langcode')
->addViolation();
}
}
}
}