You are here

function avatars_cron in Avatar Kit 8

Implements hook_cron().

File

./avatars.module, line 38

Code

function avatars_cron() {
  $intervals = \Drupal::config('avatars.settings')
    ->get('refresh_interval');
  $avatars_preview_storage = \Drupal::entityTypeManager()
    ->getStorage('avatars_preview');

  /** @var \Drupal\avatars\AvatarGeneratorStorageInterface $avatars_generator_storage */
  $avatars_generator_storage = \Drupal::entityTypeManager()
    ->getStorage('avatar_generator');
  $avatars_generators = $avatars_generator_storage
    ->getEnabledAvatarGenerators();

  /** @var \Drupal\Component\Datetime\TimeInterface $timeService */
  $timeService = \Drupal::time();
  $now = $timeService
    ->getRequestTime();

  // Remove expired previews.
  foreach ($avatars_generators as $avatar_generator) {
    $definition = $avatar_generator
      ->getPlugin()
      ->getPluginDefinition();
    $query = $avatars_preview_storage
      ->getQuery()
      ->condition('avatar_generator', $avatar_generator
      ->id());
    if ($definition['dynamic']) {
      $offset = $intervals['dynamic'] > 0 ? $intervals['dynamic'] : 0;
      $query
        ->condition('created', $now - $offset, '<');
    }
    else {
      $offset = $intervals['static'] > 0 ? $intervals['static'] : 0;
      if ($offset) {
        $query
          ->condition('created', $now - $offset, '<');
        $query
          ->condition('scope', AvatarPreviewInterface::SCOPE_TEMPORARY, '=');
      }
      else {
        continue;
      }
    }
    $ids = $query
      ->execute();
    $avatars_preview_storage
      ->delete($avatars_preview_storage
      ->loadMultiple($ids));
  }
}