You are here

public function RevisionsManager::revisionsToDelete in Node Revisions Autoclean 8

Loads revisions to delete of a node according to settings.

Parameters

Drupal\node\Entity\Node $node: The node.

Drupal\node\Entity\Node[] $revisions: Revisions if they are already loaded.

Return value

array Returns all revisions IDs to delete.

File

src/Services/RevisionsManager.php, line 117

Class

RevisionsManager
Class RevisionsManager.

Namespace

Drupal\node_revisions_autoclean\Services

Code

public function revisionsToDelete(Node $node, array $revisions = []) {
  $settings = \Drupal::config('node_revisions_autoclean.settings');
  $max = $settings
    ->get('node.' . $node
    ->bundle());
  $szDi = $settings
    ->get('interval.' . $node
    ->bundle());
  $minDate = FALSE;
  try {
    $di = new \DateInterval($szDi);
    $minDate = new \DateTime('now', new \DateTimeZone('UTC'));
    $minDate
      ->sub($di);
  } catch (\Exception $exc) {
  }
  $ret = [];
  if ($max != '-1') {
    $select = $this->database
      ->select('node_revision', 'nr');
    $select
      ->join('node_field_revision', 'nfr', 'nfr.vid = nr.vid');
    $select
      ->fields('nr', [
      'vid',
      'langcode',
      'revision_timestamp',
    ]);
    $select
      ->addField('nfr', 'status');
    $select
      ->condition('nr.nid', $node
      ->id());
    $select
      ->orderBy('nr.langcode', 'DESC');
    $select
      ->orderBy('nr.vid', 'DESC');
    $result = $select
      ->execute();
    $resultSet = $result
      ->fetchAll();
    $languages = $this->languageManager
      ->getLanguages();

    /* @var $language \Drupal\Core\Language\LanguageInterface */
    foreach ($languages as $language) {
      $revisionLanguage = array_filter($resultSet, function ($item) use ($language) {
        return $item->langcode === $language
          ->getId();
      });
      $count = 0;
      $bStart = FALSE;

      /* @var $revision Node */
      foreach ($revisionLanguage as $revision) {
        if ($bStart) {
          $count++;
        }
        if ($revision->status) {
          $bStart = TRUE;
        }
        if ($minDate && $minDate instanceof \DateTime && $count > $max) {
          if ($revision->revision_timestamp < $minDate
            ->getTimestamp()) {
            $ret[] = $revision->vid;
          }
        }
        elseif ($count > $max) {
          $ret[] = $revision->vid;
        }
      }
    }
  }
  return $ret;
}