Answer the question
In order to leave comments, you need to log in
Why does the user search function not return it?
I'm redoing password replacement in advanced app.
I created services, repositories and went to test, but it turned out that the following code does not return the user.
Mistake:
PHP Notice – yii\base\ErrorException
Undefined variable: user
public function getByEmail(string $email):User
{
return $this->getBy(['email' => $email]);
}
private function getBy(array $condition):User
{
if (!$user = User::find()->where($condition)->limit(1)->one()){
throw new NotFoundException('User not found.');
}
return $user;
}
class PasswordResetService
{
private $mailer;
private $users;
public function __construct(MailerInterface $mailer, UserRepository $users)
{
$this->mailer = $mailer;
$this->users = $users;
}
public function request(PasswordResetRequestForm $form):void
{
/* @var $user User */
$this->users->getByEmail($form->email);
if (!$user){
throw new \DomainException('User not found.');
}
$user->requestPasswordReset();
$this->users->save($user);
$sent = $this
->mailer
->compose(
['html' => 'passwordResetToken-html', 'text' => 'passwordResetToken-text'],
['user' => $user]
)
->setTo($user->email)
->setSubject('Password reset for'. Yii::$app->name)
->send();
if (!$sent){
throw new \RuntimeException('Sending Error');
}
}
public function validateToken($token):void
{
if (empty($token || !is_string($token))){
throw new \DomainException('Password reset token cannot be blank');
}
if (!$this->users->existsByPasswordResetToken($token)){
throw new \DomainException('Wrong password reset token');
}
}
public function reset(string $token, ResetPasswordForm $form):void
{
$user = $this->users->getByPasswordResetToken($token);
$user->resetPassword($form->password);
$this->users->save($user);
}
}
if (!$user){
throw new \DomainException('User not found.');
}
Answer the question
In order to leave comments, you need to log in
What makes you think that the function does not return the user?
In my opinion, you simply do not save this user to the $user variable with which you work in the future
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question