You are here

public function DatabaseLogger::cleanupJob in Ultimate Cron 8.2

File

src/Plugin/ultimate_cron/Logger/DatabaseLogger.php, line 114

Class

DatabaseLogger
Database logger.

Namespace

Drupal\ultimate_cron\Plugin\ultimate_cron\Logger

Code

public function cleanupJob(CronJobInterface $job) {
  switch ($this->configuration['method']) {
    case static::CLEANUP_METHOD_DISABLED:
      return;
    case static::CLEANUP_METHOD_EXPIRE:
      $expire = $this->configuration['expire'];

      // Let's not delete more than ONE BILLION log entries :-o.
      $max = 10000000000;
      $chunk = 100;
      break;
    case static::CLEANUP_METHOD_RETAIN:
      $expire = 0;
      $max = $this->connection
        ->query("SELECT COUNT(lid) FROM {ultimate_cron_log} WHERE name = :name", array(
        ':name' => $job
          ->id(),
      ))
        ->fetchField();
      $max -= $this->configuration['retain'];
      if ($max <= 0) {
        return;
      }
      $chunk = min($max, 100);
      break;
    default:
      \Drupal::logger('ultimate_cron')
        ->warning('Invalid cleanup method: @method', array(
        '@method' => $this->configuration['method'],
      ));
      return;
  }

  // Chunked delete.
  $count = 0;
  do {
    $lids = $this->connection
      ->select('ultimate_cron_log', 'l')
      ->fields('l', array(
      'lid',
    ))
      ->condition('l.name', $job
      ->id())
      ->condition('l.start_time', microtime(TRUE) - $expire, '<')
      ->range(0, $chunk)
      ->orderBy('l.start_time', 'ASC')
      ->orderBy('l.end_time', 'ASC')
      ->execute()
      ->fetchCol();
    if ($lids) {
      $count += count($lids);
      $max -= count($lids);
      $chunk = min($max, 100);
      $this->connection
        ->delete('ultimate_cron_log')
        ->condition('lid', $lids, 'IN')
        ->execute();
    }
  } while ($lids && $max > 0);
  return $count;
}