You are here

class BatchUpdateForm in Entity Usage 8.3

Same name and namespace in other branches
  1. 8 src/Form/BatchUpdateForm.php \Drupal\entity_usage\Form\BatchUpdateForm
  2. 8.2 src/Form/BatchUpdateForm.php \Drupal\entity_usage\Form\BatchUpdateForm

Form to launch batch tracking of existing entities.

Hierarchy

Expanded class hierarchy of BatchUpdateForm

1 string reference to 'BatchUpdateForm'
entity_usage.routing.yml in ./entity_usage.routing.yml
entity_usage.routing.yml

File

src/Form/BatchUpdateForm.php, line 14

Namespace

Drupal\entity_usage\Form
View source
class BatchUpdateForm extends FormBase {

  /**
   * The EntityTypeManager service.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * BatchUpdateForm constructor.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_manager
   *   The EntityTypeManager service.
   */
  public function __construct(EntityTypeManagerInterface $entity_manager) {
    $this->entityTypeManager = $entity_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('entity_type.manager'));
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'entity_update_batch_update_form';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['description'] = [
      '#markup' => $this
        ->t("This page allows you to delete and re-generate again all entity usage statistics in your system.<br /><br />You may want to check the settings page to fine-tune what entities should be tracked, and other options."),
    ];
    $form['actions'] = [
      '#type' => 'actions',
    ];
    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#button_type' => 'primary',
      '#value' => $this
        ->t('Recreate all entity usage statistics'),
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {

    // Generate a batch to recreate the statistics for all entities.
    // Note that if we force all statistics to be created, there is no need to
    // separate them between source / target cases. If all entities are
    // going to be re-tracked, tracking all of them as source is enough, because
    // there could never be a target without a source.
    $batch = $this
      ->generateBatch();
    batch_set($batch);
  }

  /**
   * Create a batch to process the entity types in bulk.
   *
   * @return array
   *   The batch array.
   */
  public function generateBatch() {
    $operations = [];
    $to_track = \Drupal::config('entity_usage.settings')
      ->get('track_enabled_source_entity_types');
    foreach ($this->entityTypeManager
      ->getDefinitions() as $entity_type_id => $entity_type) {

      // Only look for entities enabled for tracking on the settings form.
      $track_this_entity_type = FALSE;
      if (!is_array($to_track) && $entity_type
        ->entityClassImplements('\\Drupal\\Core\\Entity\\ContentEntityInterface')) {

        // When no settings are defined, track all content entities by default,
        // except for Files and Users.
        if (!in_array($entity_type_id, [
          'file',
          'user',
        ])) {
          $track_this_entity_type = TRUE;
        }
      }
      elseif (is_array($to_track) && in_array($entity_type_id, $to_track, TRUE)) {
        $track_this_entity_type = TRUE;
      }
      if ($track_this_entity_type) {
        $operations[] = [
          'Drupal\\entity_usage\\Form\\BatchUpdateForm::updateSourcesBatchWorker',
          [
            $entity_type_id,
          ],
        ];
      }
    }
    $batch = [
      'operations' => $operations,
      'finished' => 'Drupal\\entity_usage\\Form\\BatchUpdateForm::batchFinished',
      'title' => $this
        ->t('Updating entity usage statistics.'),
      'progress_message' => $this
        ->t('Processed @current of @total entity types.'),
      'error_message' => $this
        ->t('This batch encountered an error.'),
    ];
    return $batch;
  }

  /**
   * Batch operation worker for recreating statistics for source entities.
   *
   * @param string $entity_type_id
   *   The entity type id, for example 'node'.
   * @param array $context
   *   The context array.
   */
  public static function updateSourcesBatchWorker($entity_type_id, array &$context) {
    $entity_storage = \Drupal::entityTypeManager()
      ->getStorage($entity_type_id);
    $entity_type = \Drupal::entityTypeManager()
      ->getDefinition($entity_type_id);
    $entity_type_key = $entity_type
      ->getKey('id');
    if (empty($context['sandbox']['total'])) {

      // Delete current usage statistics for these entities.
      \Drupal::service('entity_usage.usage')
        ->bulkDeleteSources($entity_type_id);
      $context['sandbox']['progress'] = 0;
      $context['sandbox']['current_id'] = -1;
      $context['sandbox']['total'] = (int) $entity_storage
        ->getQuery()
        ->accessCheck(FALSE)
        ->count()
        ->execute();
    }
    $entity_ids = $entity_storage
      ->getQuery()
      ->condition($entity_type_key, $context['sandbox']['current_id'], '>')
      ->range(0, 1)
      ->accessCheck(FALSE)
      ->sort($entity_type_key)
      ->execute();

    /** @var \Drupal\Core\Entity\EntityInterface $entity */
    $entity = $entity_storage
      ->load(reset($entity_ids));
    if ($entity) {
      if (EntityUsageSourceLevel::isTopLevel($entity)) {
        if ($entity
          ->getEntityType()
          ->isRevisionable()) {

          // Track all revisions and translations of the source entity. Sources
          // are tracked as if they were new entities.
          $result = $entity_storage
            ->getQuery()
            ->allRevisions()
            ->condition($entity
            ->getEntityType()
            ->getKey('id'), $entity
            ->id())
            ->sort($entity
            ->getEntityType()
            ->getKey('revision'), 'DESC')
            ->execute();
          $revision_ids = array_keys($result);
          foreach ($revision_ids as $revision_id) {

            /** @var \Drupal\Core\Entity\EntityInterface $entity_revision */
            if (!($entity_revision = $entity_storage
              ->loadRevision($revision_id))) {
              continue;
            }
            \Drupal::service('entity_usage.entity_update_manager')
              ->recalculateUsageInformation($entity_revision);
          }
        }
        else {
          \Drupal::service('entity_usage.entity_update_manager')
            ->recalculateUsageInformation($entity);
        }
      }
      else {
        $context['sandbox']['progress']++;
        $context['sandbox']['current_id'] = $entity
          ->id();
        $context['results'][] = $entity_type_id . ':' . $entity
          ->id();
      }
      $context['sandbox']['progress']++;
      $context['sandbox']['current_id'] = $entity
        ->id();
      $context['results'][] = $entity_type_id . ':' . $entity
        ->id();
    }
    if ($context['sandbox']['progress'] < $context['sandbox']['total']) {
      $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['total'];
    }
    else {
      $context['finished'] = 1;
    }
    $context['message'] = t('Updating entity usage for @entity_type: @current of @total', [
      '@entity_type' => $entity_type_id,
      '@current' => $context['sandbox']['progress'],
      '@total' => $context['sandbox']['total'],
    ]);
  }

  /**
   * Finish callback for our batch processing.
   *
   * @param bool $success
   *   Whether the batch completed successfully.
   * @param array $results
   *   The results array.
   * @param array $operations
   *   The operations array.
   */
  public static function batchFinished($success, array $results, array $operations) {
    if ($success) {
      drupal_set_message(t('Recreated entity usage for @count entities.', [
        '@count' => count($results),
      ]));
      \Drupal::state()
        ->set('entity_usage_needs_regeneration', FALSE);
    }
    else {

      // An error occurred.
      // $operations contains the operations that remained unprocessed.
      $error_operation = reset($operations);
      drupal_set_message(t('An error occurred while processing @operation with arguments : @args', [
        '@operation' => $error_operation[0],
        '@args' => print_r($error_operation[0], TRUE),
      ]));
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
BatchUpdateForm::$entityTypeManager protected property The EntityTypeManager service.
BatchUpdateForm::batchFinished public static function Finish callback for our batch processing.
BatchUpdateForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
BatchUpdateForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
BatchUpdateForm::generateBatch public function Create a batch to process the entity types in bulk.
BatchUpdateForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
BatchUpdateForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
BatchUpdateForm::updateSourcesBatchWorker public static function Batch operation worker for recreating statistics for source entities.
BatchUpdateForm::__construct public function BatchUpdateForm constructor.
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
FormBase::$configFactory protected property The config factory. 1
FormBase::$requestStack protected property The request stack. 1
FormBase::$routeMatch protected property The route match.
FormBase::config protected function Retrieves a configuration object.
FormBase::configFactory protected function Gets the config factory for this form. 1
FormBase::container private function Returns the service container.
FormBase::currentUser protected function Gets the current user.
FormBase::getRequest protected function Gets the request object.
FormBase::getRouteMatch protected function Gets the route match.
FormBase::logger protected function Gets the logger for a specific channel.
FormBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
FormBase::resetConfigFactory public function Resets the configuration factory.
FormBase::setConfigFactory public function Sets the config factory for this form.
FormBase::setRequestStack public function Sets the request stack object to use.
FormBase::validateForm public function Form validation handler. Overrides FormInterface::validateForm 62
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
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.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.