Commit e32a11e7 authored by alexpott's avatar alexpott

Issue #2110345 by mr.york, effulgentsia, Désiré, fgm, fago, pfrenssen,...

Issue #2110345 by mr.york, effulgentsia, Désiré, fgm, fago, pfrenssen, stefan.r, Berdir, Rajendar Reddy: Simplify validation constraint implementations for fields.
parent 4a476328
...@@ -18,12 +18,12 @@ class CommentNameConstraintValidator extends ConstraintValidator { ...@@ -18,12 +18,12 @@ class CommentNameConstraintValidator extends ConstraintValidator {
/** /**
* {@inheritdoc} * {@inheritdoc}
*/ */
public function validate($field_item, Constraint $constraint) { public function validate($items, Constraint $constraint) {
$author_name = $field_item->value; $author_name = $items->first()->value;
if (isset($author_name) && $author_name !== '') { if (isset($author_name) && $author_name !== '') {
// Do not allow unauthenticated comment authors to use a name that is // Do not allow unauthenticated comment authors to use a name that is
// taken by a registered user. // taken by a registered user.
if ($field_item->getEntity()->getOwnerId() === 0) { if ($items->getEntity()->getOwnerId() === 0) {
// @todo Properly inject dependency https://drupal.org/node/2197029 // @todo Properly inject dependency https://drupal.org/node/2197029
$users = \Drupal::entityManager()->getStorage('user')->loadByProperties(array('name' => $author_name)); $users = \Drupal::entityManager()->getStorage('user')->loadByProperties(array('name' => $author_name));
if (!empty($users)) { if (!empty($users)) {
......
...@@ -472,7 +472,7 @@ public static function baseFieldDefinitions(EntityTypeInterface $entity_type) { ...@@ -472,7 +472,7 @@ public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
->setLabel(t('Name')) ->setLabel(t('Name'))
->setDescription(t('The name of this user.')) ->setDescription(t('The name of this user.'))
->setDefaultValue('') ->setDefaultValue('')
->setPropertyConstraints('value', array( ->setConstraints(array(
// No Length constraint here because the UserName constraint also covers // No Length constraint here because the UserName constraint also covers
// that. // that.
'UserName' => array(), 'UserName' => array(),
...@@ -487,7 +487,7 @@ public static function baseFieldDefinitions(EntityTypeInterface $entity_type) { ...@@ -487,7 +487,7 @@ public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
->setLabel(t('Email')) ->setLabel(t('Email'))
->setDescription(t('The email of this user.')) ->setDescription(t('The email of this user.'))
->setDefaultValue('') ->setDefaultValue('')
->setPropertyConstraints('value', array('UserMailUnique' => array())); ->setConstraints(array('UserMailUnique' => array()));
// @todo Convert to a text field in https://drupal.org/node/1548204. // @todo Convert to a text field in https://drupal.org/node/1548204.
$fields['signature'] = BaseFieldDefinition::create('string') $fields['signature'] = BaseFieldDefinition::create('string')
......
...@@ -14,7 +14,7 @@ ...@@ -14,7 +14,7 @@
* *
* @Plugin( * @Plugin(
* id = "UserName", * id = "UserName",
* label = @Translation("User name", context = "Validation") * label = @Translation("User name", context = "Validation"),
* ) * )
*/ */
class UserNameConstraint extends Constraint { class UserNameConstraint extends Constraint {
......
...@@ -18,11 +18,12 @@ class UserNameConstraintValidator extends ConstraintValidator { ...@@ -18,11 +18,12 @@ class UserNameConstraintValidator extends ConstraintValidator {
/** /**
* {@inheritdoc} * {@inheritdoc}
*/ */
public function validate($name, Constraint $constraint) { public function validate($items, Constraint $constraint) {
if (!$name) { if (!isset($items) || !$items->value) {
$this->context->addViolation($constraint->emptyMessage); $this->context->addViolation($constraint->emptyMessage);
return; return;
} }
$name = $items->first()->value;
if (substr($name, 0, 1) == ' ') { if (substr($name, 0, 1) == ' ') {
$this->context->addViolation($constraint->spaceBeginMessage); $this->context->addViolation($constraint->spaceBeginMessage);
} }
......
...@@ -14,7 +14,7 @@ ...@@ -14,7 +14,7 @@
* *
* @Plugin( * @Plugin(
* id = "UserNameUnique", * id = "UserNameUnique",
* label = @Translation("User name unique", context = "Validation") * label = @Translation("User name unique", context = "Validation"),
* ) * )
*/ */
class UserNameUnique extends Constraint { class UserNameUnique extends Constraint {
......
...@@ -18,20 +18,22 @@ class UserUniqueValidator extends ConstraintValidator { ...@@ -18,20 +18,22 @@ class UserUniqueValidator extends ConstraintValidator {
/** /**
* {@inheritdoc} * {@inheritdoc}
*/ */
public function validate($value, Constraint $constraint) { public function validate($items, Constraint $constraint) {
$field = $this->context->getMetadata()->getTypedData()->getParent(); if (!isset($items)) {
$uid = $field->getParent()->id(); return;
}
$field_name = $items->getFieldDefinition()->getName();
$value_taken = (bool) \Drupal::entityQuery('user') $value_taken = (bool) \Drupal::entityQuery('user')
// The UID could be NULL, so we cast it to 0 in that case. // The UID could be NULL, so we cast it to 0 in that case.
->condition('uid', (int) $uid, '<>') ->condition('uid', (int) $items->getEntity()->id(), '<>')
->condition($field->getName(), $value) ->condition($field_name, db_like($items->first()->value), 'LIKE')
->range(0, 1) ->range(0, 1)
->count() ->count()
->execute(); ->execute();
if ($value_taken) { if ($value_taken) {
$this->context->addViolation($constraint->message, array("%value" => $value)); $this->context->addViolation($constraint->message, array("%value" => $items->value));
} }
} }
} }
...@@ -78,7 +78,7 @@ function testValidation() { ...@@ -78,7 +78,7 @@ function testValidation() {
$user->set('name', $name); $user->set('name', $name);
$violations = $user->validate(); $violations = $user->validate();
$this->assertEqual(count($violations), 1, 'Violation found when name is too long.'); $this->assertEqual(count($violations), 1, 'Violation found when name is too long.');
$this->assertEqual($violations[0]->getPropertyPath(), 'name.0.value'); $this->assertEqual($violations[0]->getPropertyPath(), 'name');
$this->assertEqual($violations[0]->getMessage(), t('The username %name is too long: it must be %max characters or less.', array('%name' => $name, '%max' => 60))); $this->assertEqual($violations[0]->getMessage(), t('The username %name is too long: it must be %max characters or less.', array('%name' => $name, '%max' => 60)));
// Create a second test user to provoke a name collision. // Create a second test user to provoke a name collision.
...@@ -90,7 +90,7 @@ function testValidation() { ...@@ -90,7 +90,7 @@ function testValidation() {
$user->set('name', 'existing'); $user->set('name', 'existing');
$violations = $user->validate(); $violations = $user->validate();
$this->assertEqual(count($violations), 1, 'Violation found on name collision.'); $this->assertEqual(count($violations), 1, 'Violation found on name collision.');
$this->assertEqual($violations[0]->getPropertyPath(), 'name.0.value'); $this->assertEqual($violations[0]->getPropertyPath(), 'name');
$this->assertEqual($violations[0]->getMessage(), t('The name %name is already taken.', array('%name' => 'existing'))); $this->assertEqual($violations[0]->getMessage(), t('The name %name is already taken.', array('%name' => 'existing')));
// Make the name valid. // Make the name valid.
...@@ -115,11 +115,11 @@ function testValidation() { ...@@ -115,11 +115,11 @@ function testValidation() {
$this->assertEqual($violations[1]->getPropertyPath(), 'mail.0.value'); $this->assertEqual($violations[1]->getPropertyPath(), 'mail.0.value');
$this->assertEqual($violations[1]->getMessage(), t('This value is not a valid email address.')); $this->assertEqual($violations[1]->getMessage(), t('This value is not a valid email address.'));
// Provoke a email collision with an exsiting user. // Provoke an email collision with an existing user.
$user->set('mail', 'existing@example.com'); $user->set('mail', 'existing@example.com');
$violations = $user->validate(); $violations = $user->validate();
$this->assertEqual(count($violations), 1, 'Violation found when email already exists.'); $this->assertEqual(count($violations), 1, 'Violation found when email already exists.');
$this->assertEqual($violations[0]->getPropertyPath(), 'mail.0.value'); $this->assertEqual($violations[0]->getPropertyPath(), 'mail');
$this->assertEqual($violations[0]->getMessage(), t('The email address %mail is already taken.', array('%mail' => 'existing@example.com'))); $this->assertEqual($violations[0]->getMessage(), t('The email address %mail is already taken.', array('%mail' => 'existing@example.com')));
$user->set('mail', NULL); $user->set('mail', NULL);
......
...@@ -17,7 +17,7 @@ ...@@ -17,7 +17,7 @@
use Drupal\user\UserInterface; use Drupal\user\UserInterface;
use Drupal\user\RoleInterface; use Drupal\user\RoleInterface;
use Drupal\Core\Template\Attribute; use Drupal\Core\Template\Attribute;
use Drupal\Core\TypedData\DataDefinition; use Drupal\Core\Field\BaseFieldDefinition;
use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Drupal\menu_link\Entity\MenuLink; use Drupal\menu_link\Entity\MenuLink;
...@@ -332,7 +332,7 @@ function user_load_by_name($name) { ...@@ -332,7 +332,7 @@ function user_load_by_name($name) {
* *
*/ */
function user_validate_name($name) { function user_validate_name($name) {
$definition = DataDefinition::create('string') $definition = BaseFieldDefinition::create('string')
->addConstraint('UserName', array()); ->addConstraint('UserName', array());
$data = \Drupal::typedDataManager()->create($definition); $data = \Drupal::typedDataManager()->create($definition);
$data->setValue($name); $data->setValue($name);
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment