You are here

class LinkCleanUp in Link checker 8

Class LinkCleanUp.

Hierarchy

Expanded class hierarchy of LinkCleanUp

2 files declare their use of LinkCleanUp
LinkCheckerAdminSettingsForm.php in src/Form/LinkCheckerAdminSettingsForm.php
LinkCheckerCommands.php in src/Commands/LinkCheckerCommands.php
1 string reference to 'LinkCleanUp'
linkchecker.services.yml in ./linkchecker.services.yml
linkchecker.services.yml
1 service uses LinkCleanUp
linkchecker.clean_up in ./linkchecker.services.yml
Drupal\linkchecker\LinkCleanUp

File

src/LinkCleanUp.php, line 15

Namespace

Drupal\linkchecker
View source
class LinkCleanUp {
  use DependencySerializationTrait;
  use MessengerTrait;
  use StringTranslationTrait;

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * The link extractor.
   *
   * @var \Drupal\linkchecker\LinkExtractorService
   */
  protected $extractor;

  /**
   * The database connection.
   *
   * @var \Drupal\Core\Database\Connection
   */
  protected $database;

  /**
   * LinkCleanUp constructor.
   */
  public function __construct(EntityTypeManagerInterface $entityTypeManager, LinkExtractorService $linkExtractorService, Connection $dbConnection) {
    $this->entityTypeManager = $entityTypeManager;
    $this->extractor = $linkExtractorService;
    $this->database = $dbConnection;
  }

  /**
   * Removes all extracted links.
   */
  public function removeAllBatch() {

    // Clear index to reindex all entities.
    $this->database
      ->truncate('linkchecker_index');
    $batch = new BatchBuilder();
    $batch
      ->setTitle('Remove links')
      ->addOperation([
      $this,
      'batchProcessDelete',
    ])
      ->setProgressive()
      ->setFinishCallback([
      $this,
      'batchFinished',
    ]);
    batch_set($batch
      ->toArray());
  }

  /**
   * Process link deletion.
   *
   * @param array $ids
   *   Array of ids to delete.
   */
  public function processDelete(array $ids) {
    $storage = $this->entityTypeManager
      ->getStorage('linkcheckerlink');
    $links = $storage
      ->loadMultiple($ids);
    $storage
      ->delete($links);
  }

  /**
   * Proccess link deletion within batch operation.
   *
   * @param mixed $context
   *   Batch context.
   */
  public function batchProcessDelete(&$context) {
    $storage = $this->entityTypeManager
      ->getStorage('linkcheckerlink');
    if (!isset($context['sandbox']['total'])) {
      $context['sandbox']['total'] = $storage
        ->getQuery()
        ->count()
        ->execute();
    }
    $ids = $storage
      ->getQuery()
      ->range(0, 10)
      ->execute();
    $this
      ->processDelete($ids);

    // Count how many items are not proceed.
    $toProcess = $storage
      ->getQuery()
      ->count()
      ->execute();
    $context['sandbox']['current'] = $context['sandbox']['total'] - $toProcess;
    if (!empty($toProcess)) {
      $context['finished'] = $context['sandbox']['current'] / $context['sandbox']['total'];
    }
    else {
      $context['finished'] = 1;
    }
  }

  /**
   * Removes non-existing links for given entity.
   *
   * @param \Drupal\Core\Entity\FieldableEntityInterface $entity
   *   The entity.
   */
  public function cleanUpForEntity(FieldableEntityInterface $entity) {

    // Trying to reload the entity
    // If it was removed then we should remove all links related to the entity.
    $isEntityDeleted = !$this->entityTypeManager
      ->getStorage($entity
      ->getEntityTypeId())
      ->load($entity
      ->id());
    $extractedIds = [];

    /** @var \Drupal\linkchecker\LinkCheckerStorage $storage */
    $storage = $this->entityTypeManager
      ->getStorage('linkcheckerlink');

    // If entity is not deleted, gather all links that exists in fields.
    if (!$isEntityDeleted) {
      $links = $this->extractor
        ->extractFromEntity($entity);
      foreach ($links as $link) {
        $extractedIds = array_merge($storage
          ->getExistingIdsFromLink($link), $extractedIds);
      }
    }
    else {

      // Remove entity from index.
      $this->database
        ->delete('linkchecker_index')
        ->condition('entity_id', $entity
        ->id())
        ->condition('entity_type', $entity
        ->getEntityTypeId())
        ->execute();
    }

    // Get list of link IDs that should be deleted.
    $query = $storage
      ->getQuery();
    $query
      ->condition('entity_id.target_id', $entity
      ->id());
    $query
      ->condition('entity_id.target_type', $entity
      ->getEntityTypeId());
    if (!empty($extractedIds)) {
      $query
        ->condition('lid', $extractedIds, 'NOT IN');
    }
    $ids = $query
      ->execute();
    if (!empty($ids)) {

      // Delete the links.
      $linksToDelete = $storage
        ->loadMultiple($ids);
      $storage
        ->delete($linksToDelete);
    }
  }

  /**
   * Finished callback for batch.
   */
  public function batchFinished($success) {
    if ($success) {
      $this
        ->messenger()
        ->addStatus($this
        ->t('Links were successfully checked.'));
    }
    else {
      $this
        ->messenger()
        ->addError($this
        ->t('Links were not checked.'));
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
LinkCleanUp::$database protected property The database connection.
LinkCleanUp::$entityTypeManager protected property The entity type manager.
LinkCleanUp::$extractor protected property The link extractor.
LinkCleanUp::batchFinished public function Finished callback for batch.
LinkCleanUp::batchProcessDelete public function Proccess link deletion within batch operation.
LinkCleanUp::cleanUpForEntity public function Removes non-existing links for given entity.
LinkCleanUp::processDelete public function Process link deletion.
LinkCleanUp::removeAllBatch public function Removes all extracted links.
LinkCleanUp::__construct public function LinkCleanUp constructor.
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.