You are here

public function PhoneNumberVerification::purgeExpiredVerifications in SMS Framework 8

Same name and namespace in other branches
  1. 2.x src/Provider/PhoneNumberVerification.php \Drupal\sms\Provider\PhoneNumberVerification::purgeExpiredVerifications()
  2. 2.1.x src/Provider/PhoneNumberVerification.php \Drupal\sms\Provider\PhoneNumberVerification::purgeExpiredVerifications()

Cleans up expired phone number verifications.

Removes phone numbers from entities if setting is verification expires, and setting is enabled.

Overrides PhoneNumberVerificationInterface::purgeExpiredVerifications

File

src/Provider/PhoneNumberVerification.php, line 247

Class

PhoneNumberVerification
Phone number verification provider.

Namespace

Drupal\sms\Provider

Code

public function purgeExpiredVerifications() {
  $current_time = \Drupal::request()->server
    ->get('REQUEST_TIME');
  $verification_ids = [];
  foreach ($this->configFactory
    ->listAll('sms.phone.') as $config_id) {
    $config = $this->configFactory
      ->get($config_id);
    $lifetime = $config
      ->get('verification_code_lifetime');
    if (!empty($lifetime)) {
      $verification_ids += $this->phoneNumberVerificationStorage
        ->getQuery()
        ->condition('entity__target_type', $config
        ->get('entity_type'))
        ->condition('bundle', $config
        ->get('bundle'))
        ->condition('status', 0)
        ->condition('created', $current_time - $lifetime, '<')
        ->execute();
    }
  }

  /** @var \Drupal\sms\Entity\PhoneNumberVerificationInterface $phone_number_verification */
  foreach ($this->phoneNumberVerificationStorage
    ->loadMultiple($verification_ids) as $phone_number_verification) {
    if ($entity = $phone_number_verification
      ->getEntity()) {
      try {
        $config = $this
          ->getPhoneNumberSettingsForEntity($entity);
        $purge = $config
          ->getPurgeVerificationPhoneNumber();
        $field_name = $config
          ->getFieldName('phone_number');
        if (!empty($purge) && isset($entity->{$field_name})) {
          $entity->{$field_name}
            ->filter(function ($item) use ($phone_number_verification) {
            return $item->value != $phone_number_verification
              ->getPhoneNumber();
          });
          $entity
            ->save();
        }
      } catch (EntityStorageException $e) {

        // Failed to save entity.
      }
    }
    $this->phoneNumberVerificationStorage
      ->delete([
      $phone_number_verification,
    ]);
  }
}