M
M
Maxemp2018-02-06 17:52:56
Yii
Maxemp, 2018-02-06 17:52:56

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;
  }

Password change service code
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);
  }

}

It also highlights this line
if (!$user){
      throw new \DomainException('User not found.');
    }

How to solve this problem ?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Fedorov, 2018-02-06
@Maxemp

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 question

Ask a Question

731 491 924 answers to any question