You are here

protected function AccountRegistration::allUnknownNumbers in SMS Framework 8

Same name and namespace in other branches
  1. 2.x modules/sms_user/src/AccountRegistration.php \Drupal\sms_user\AccountRegistration::allUnknownNumbers()
  2. 2.1.x modules/sms_user/src/AccountRegistration.php \Drupal\sms_user\AccountRegistration::allUnknownNumbers()

Process incoming message and create a user if the phone number is unknown.

Parameters

\Drupal\sms\Message\SmsMessageInterface $sms_message: An incoming SMS message.

1 call to AccountRegistration::allUnknownNumbers()
AccountRegistration::createAccount in modules/sms_user/src/AccountRegistration.php
Process an incoming SMS to see if a new account should be created.

File

modules/sms_user/src/AccountRegistration.php, line 110

Class

AccountRegistration
Defines the account registration service.

Namespace

Drupal\sms_user

Code

protected function allUnknownNumbers(SmsMessageInterface $sms_message) {
  $user = User::create([
    'name' => $this
      ->generateUniqueUsername(),
  ]);
  $user
    ->activate();

  // Sender phone number.
  $sender_number = $sms_message
    ->getSenderNumber();
  $t_args['%sender_phone_number'] = $sender_number;
  $phone_field_name = $this->userPhoneNumberSettings
    ->getFieldName('phone_number');
  $user->{$phone_field_name}[] = $sender_number;

  // Password.
  $password = user_password();
  $user
    ->setPassword($password);
  $validate = $this
    ->removeAcceptableViolations($user
    ->validate());
  if ($validate
    ->count() == 0) {
    $user
      ->save();

    // @todo autoconfirm the number?
    // @see https://www.drupal.org/node/2709911
    $t_args['%name'] = $user
      ->label();
    $t_args['%uid'] = $user
      ->id();
    \Drupal::logger('sms_user.account_registration.unrecognized_sender')
      ->info('Creating new account for %sender_phone_number. Username: %name. User ID: %uid', $t_args);

    // Optionally send a reply.
    if (!empty($this
      ->settings('unrecognized_sender.reply.status'))) {
      $message = $this
        ->settings('unrecognized_sender.reply.message');
      $message = str_replace('[user:password]', $password, $message);
      $this
        ->sendReply($sender_number, $user, $message);
    }
  }
  else {
    $t_args['@error'] = $this
      ->buildError($validate);
    \Drupal::logger('sms_user.account_registration.unrecognized_sender')
      ->error('Could not create new account for %sender_phone_number because there was a problem with validation: @error', $t_args);
  }
}