ProtectedUserFieldConstraintValidator.php in Drupal 8
File
core/modules/user/src/Plugin/Validation/Constraint/ProtectedUserFieldConstraintValidator.php
View source
<?php
namespace Drupal\user\Plugin\Validation\Constraint;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Session\AccountProxyInterface;
use Drupal\user\UserStorageInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
class ProtectedUserFieldConstraintValidator extends ConstraintValidator implements ContainerInjectionInterface {
protected $userStorage;
protected $currentUser;
public function __construct(UserStorageInterface $user_storage, AccountProxyInterface $current_user) {
$this->userStorage = $user_storage;
$this->currentUser = $current_user;
}
public static function create(ContainerInterface $container) {
return new static($container
->get('entity_type.manager')
->getStorage('user'), $container
->get('current_user'));
}
public function validate($items, Constraint $constraint) {
if (!isset($items)) {
return;
}
$field = $items
->getFieldDefinition();
$account = $items
->getEntity();
if (!isset($account) || !empty($account->_skipProtectedUserFieldConstraint)) {
return;
}
if (!$account
->isNew() && $account
->id() == $this->currentUser
->id()) {
$account_unchanged = $this->userStorage
->loadUnchanged($account
->id());
$changed = FALSE;
$value = $items->value;
if ($field
->getName() != 'pass' || !empty($value)) {
$changed = $items
->getValue() != $account_unchanged
->get($field
->getName())
->getValue();
}
if ($changed && !$account
->checkExistingPassword($account_unchanged)) {
$this->context
->addViolation($constraint->message, [
'%name' => $field
->getLabel(),
]);
}
}
}
}