Looking to replicate behaviour from CakePHP 2 - is this the best way?
I want to prompt the user for their current password, new password and repeat password. In my form I have these fields
echo $this->Form->control('_currentPassword', ['label' => 'Current Password', 'type' => 'password']);
echo $this->Form->control('_newPassword', ['label' => 'New Password', 'type' => 'password']);
echo $this->Form->control('_repeatNewPassword', ['label' => 'Current Password', 'type' => 'password']);
Validation rules handle the basic “your new password doesn’t match”
$validator
->notEmptyString('_newPassword','The new password should not be blank');
$validator
->equalToField('_repeatNewPassword','_newPassword','The new password and its repeat should match exactly');
A build rule handles checking the current password is correct
// Custom validation rule for matching to current password
$matchToPassword = function ($entity, $options) {
// We only call if the password is being set by the user
if(isset($entity->_currentPassword)){
$hasher = new DefaultPasswordHasher;
if ($hasher->check($entity->_currentPassword, $entity->password)) {
return true;
} else {
return false;
}
} else {
return true;
}
};
$rules->add($matchToPassword, ['errorField' => '_currentPassword', 'message' => 'Your current password is incorrect']);
In afterRules, we save the new password
// Password fields are now validated so it's okay to save it
if (isset($entity->_newPassword) === true) {
$entity->password = $entity->_newPassword;
}
Everything works as expected - have I missed anything? Is there a better way to do it?