3 namespace Drupal\comment\Plugin\Validation\Constraint;
5 use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
6 use Drupal\user\UserStorageInterface;
7 use Symfony\Component\DependencyInjection\ContainerInterface;
8 use Drupal\comment\CommentInterface;
9 use Symfony\Component\Validator\Constraint;
10 use Symfony\Component\Validator\ConstraintValidator;
13 * Validates the CommentName constraint.
15 class CommentNameConstraintValidator extends ConstraintValidator implements ContainerInjectionInterface {
18 * Validator 2.5 and upwards compatible execution context.
20 * @var \Symfony\Component\Validator\Context\ExecutionContextInterface
25 * User storage handler.
27 * @var \Drupal\user\UserStorageInterface
29 protected $userStorage;
32 * Constructs a new CommentNameConstraintValidator.
34 * @param \Drupal\user\UserStorageInterface $user_storage
35 * The user storage handler.
37 public function __construct(UserStorageInterface $user_storage) {
38 $this->userStorage = $user_storage;
44 public static function create(ContainerInterface $container) {
45 return new static($container->get('entity.manager')->getStorage('user'));
51 public function validate($entity, Constraint $constraint) {
52 $author_name = $entity->name->value;
53 $owner_id = (int) $entity->uid->target_id;
55 // Do not allow unauthenticated comment authors to use a name that is
56 // taken by a registered user.
57 if (isset($author_name) && $author_name !== '' && $owner_id === 0) {
58 $users = $this->userStorage->loadByProperties(['name' => $author_name]);
60 $this->context->buildViolation($constraint->messageNameTaken, ['%name' => $author_name])
65 // If an author name and owner are given, make sure they match.
66 elseif (isset($author_name) && $author_name !== '' && $owner_id) {
67 $owner = $this->userStorage->load($owner_id);
68 if ($owner->getUsername() != $author_name) {
69 $this->context->buildViolation($constraint->messageMatch)
75 // Anonymous account might be required - depending on field settings.
76 if ($owner_id === 0 && empty($author_name) &&
77 $this->getAnonymousContactDetailsSetting($entity) === COMMENT_ANONYMOUS_MUST_CONTACT) {
78 $this->context->buildViolation($constraint->messageRequired)
85 * Gets the anonymous contact details setting from the comment.
87 * @param \Drupal\comment\CommentInterface $comment
91 * The anonymous contact setting.
93 protected function getAnonymousContactDetailsSetting(CommentInterface $comment) {
95 ->getCommentedEntity()
96 ->get($comment->getFieldName())
97 ->getFieldDefinition()
98 ->getSetting('anonymous');