Same filename and directory in other branches
- 8.9.x core/modules/comment/src/Plugin/Validation/Constraint/CommentNameConstraintValidator.php
- 9 core/modules/comment/src/Plugin/Validation/Constraint/CommentNameConstraintValidator.php
Namespace
Drupal\comment\Plugin\Validation\Constraint
File
core/modules/comment/src/Plugin/Validation/Constraint/CommentNameConstraintValidator.php
View source
<?php
namespace Drupal\comment\Plugin\Validation\Constraint;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\user\UserStorageInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\comment\CommentInterface;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
class CommentNameConstraintValidator extends ConstraintValidator implements ContainerInjectionInterface {
protected $userStorage;
public function __construct(UserStorageInterface $user_storage) {
$this->userStorage = $user_storage;
}
public static function create(ContainerInterface $container) {
return new static($container
->get('entity_type.manager')
->getStorage('user'));
}
public function validate($entity, Constraint $constraint) {
$author_name = $entity->name->value;
$owner_id = (int) $entity->uid->target_id;
if (isset($author_name) && $author_name !== '' && $owner_id === 0) {
$users = $this->userStorage
->loadByProperties([
'name' => $author_name,
]);
if (!empty($users)) {
$this->context
->buildViolation($constraint->messageNameTaken, [
'%name' => $author_name,
])
->atPath('name')
->addViolation();
}
}
elseif (isset($author_name) && $author_name !== '' && $owner_id) {
$owner = $this->userStorage
->load($owner_id);
if ($owner
->getAccountName() != $author_name) {
$this->context
->buildViolation($constraint->messageMatch)
->atPath('name')
->addViolation();
}
}
if ($owner_id === 0 && empty($author_name) && $entity
->getCommentedEntity() && $entity
->getFieldName() && $this
->getAnonymousContactDetailsSetting($entity) === CommentInterface::ANONYMOUS_MUST_CONTACT) {
$this->context
->buildViolation($constraint->messageRequired)
->atPath('name')
->addViolation();
}
}
protected function getAnonymousContactDetailsSetting(CommentInterface $comment) {
return $comment
->getCommentedEntity()
->get($comment
->getFieldName())
->getFieldDefinition()
->getSetting('anonymous');
}
}
Classes