You are here

class ProcessForm in Module Builder 8.3

Form for running the DCB analysis process.

Hierarchy

Expanded class hierarchy of ProcessForm

2 files declare their use of ProcessForm
ProcessFormExtra.php in module_builder_devel/src/Form/ProcessFormExtra.php
ProcessTestSamplesForm.php in module_builder_devel/src/Form/ProcessTestSamplesForm.php
1 string reference to 'ProcessForm'
module_builder.routing.yml in ./module_builder.routing.yml
module_builder.routing.yml

File

src/Form/ProcessForm.php, line 14

Namespace

Drupal\module_builder\Form
View source
class ProcessForm extends FormBase {

  /**
   * The Messenger service.
   *
   * @var \Drupal\Core\Messenger\MessengerInterface
   */
  protected $messenger;

  /**
   * Creates a ProcessForm instance.
   *
   * @param \Drupal\Core\Messenger\MessengerInterface $messenger
   *   The Messenger service.
   */
  public function __construct($drupal_code_builder, MessengerInterface $messenger) {
    $this->drupalCodeBuilder = $drupal_code_builder;
    $this->messenger = $messenger;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {

    // Note that we can't inject the DCB tasks because they throw sanity
    // exceptions.
    return new static($container
      ->get('module_builder.drupal_code_builder'), $container
      ->get('messenger'));
  }

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

  /**
   * Gets the collect task.
   *
   * This exists to allow easy overriding of the task by the MB devel module.
   */
  protected static function getCollectTask() {
    return \Drupal::service('module_builder.drupal_code_builder')
      ->getTask('Collect');
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    try {
      $task_handler_report = $this->drupalCodeBuilder
        ->getTask('ReportHookDataFolder');
      $task_report_summary = $this->drupalCodeBuilder
        ->getTask('ReportSummary');
    } catch (SanityException $e) {
      if ($e
        ->getFailedSanityLevel() == 'data_directory_exists') {
        $this->messenger
          ->addError($this
          ->t("The hooks data directory does not exist, or is not writeable. Check your settings and your filesystem."));
        return $form;
      }

      // We're in right place to do something about a hooks processed sanity
      // problem, so no need to show a message for that.
    }

    // The task handler returns sane values for these even if there's no hook
    // data.
    $last_update = $task_handler_report
      ->lastUpdatedDate();
    $directory = \DrupalCodeBuilder\Factory::getEnvironment()
      ->getHooksDirectory();
    $form['intro'] = array(
      '#markup' => '<p>' . t("Module Builder analyses your site's code to find data about Drupal components such as hooks, plugins, tagged services, and more." . ' ' . "This processed data is stored in your local filesystem." . ' ' . "You should update the code analysis when updating site code, or updating Module Builder or Drupal Code Builder.") . '</p>',
    );
    $form['analyse'] = [
      '#type' => 'fieldset',
      '#title' => "Perform analysis",
    ];
    $form['analyse']['last_update'] = array(
      '#markup' => '<p>' . ($last_update ? t('Your last data update was %date.', array(
        '%date' => \Drupal::service('date.formatter')
          ->format($last_update, 'large'),
      )) : t("The site's code has not yet been analysed.")) . '</p>',
    );
    $form['analyse']['submit'] = array(
      '#type' => 'submit',
      '#value' => $last_update ? t('Update code analysis') : t('Perform code analysis'),
    );
    if ($last_update) {
      try {
        $analysis_data = $task_report_summary
          ->listStoredData();
      } catch (\DrupalCodeBuilder\Exception\StorageException $e) {

        // Bail if the storage has a problem.
        $this
          ->messenger()
          ->addError($e
          ->getMessage());
        return $form;
      }
      $form['results'] = [
        '#type' => 'fieldset',
        '#title' => "Analysis results",
      ];
      $form['results']['text'] = array(
        '#markup' => '<p>' . t('You have the following data saved in %dir: ', array(
          '%dir' => $directory,
        )) . '</p>',
      );
      foreach ($analysis_data as $type => $type_data) {
        $form['results'][$type] = [
          '#type' => 'details',
          '#title' => "{$type_data['label']} ({$type_data['count']})",
          '#open' => FALSE,
        ];
        if (is_array(reset($type_data['list']))) {
          $items = [];
          foreach ($type_data['list'] as $group_name => $group_items) {
            $items = array_merge($items, array_keys($group_items));
          }
        }
        else {
          $items = array_keys($type_data['list']);
        }
        $form['results'][$type]['items'] = [
          '#theme' => 'item_list',
          '#items' => $items,
        ];
      }
    }
    return $form;
  }

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

    // Safe to do this without exception handling: it's already been checked in
    // the form builder.
    $task_handler_collect = static::getCollectTask();
    $job_list = $task_handler_collect
      ->getJobList();
    $batch = array(
      'title' => t('Analysing site code'),
      'operations' => array(),
      'file' => drupal_get_path('module', 'module_builder') . '/includes/module_builder.admin.inc',
      'finished' => [
        get_class($this),
        'batchFinished',
      ],
    );

    // Split the jobs into batches of 10.
    $job_batches = array_chunk($job_list, 10);
    foreach ($job_batches as $job_batch) {

      // Run all jobs directly, without batch API. Also need to comment out
      // the call to batch_set()! Useful for seeing debug output.
      // $fake = [];
      // $task_handler_collect->collectComponentDataIncremental($job_batch, $fake);
      $batch['operations'][] = [
        [
          get_class($this),
          'batchOperation',
        ],
        [
          $job_batch,
        ],
      ];
    }
    batch_set($batch);
  }

  /**
   * Implements callback_batch_operation().
   */
  public static function batchOperation($job_batch, &$context) {
    $task_handler_collect = static::getCollectTask();
    try {
      $task_handler_collect
        ->collectComponentDataIncremental($job_batch, $context['results']);
    } catch (\Exception $e) {

      // Store an exception message and bail on this operation.
      $context['results']['errors'][] = $e
        ->getMessage();
      return;
    }

    // Assemble a progress message.
    $labels = [];
    $message_pieces = [];
    foreach ($job_batch as $job) {
      if (isset($job['item_label'])) {

        // One job among several for a collector.
        $labels[$job['process_label']][] = $job['item_label'];
      }
      else {

        // Singleton job.
        // Put it in the labels array to preserve the order.
        $labels[$job['process_label']] = NULL;
      }
    }
    foreach ($labels as $process_label => $item_labels) {
      if (is_null($item_labels)) {
        $message_pieces[] = $process_label;
      }
      else {
        $message_pieces[] = t('@task for @items', array(
          '@task' => $process_label,
          '@items' => implode(', ', $item_labels),
        ));
      }
    }
    $context['message'] = t("Processed: @list.", array(
      '@list' => implode(', ', $message_pieces),
    ));
  }

  /**
   * Implements callback_batch_finished().
   */
  public static function batchFinished($success, $results, $operations) {
    if (isset($results['errors'])) {
      foreach ($results['errors'] as $error_message) {
        \Drupal::messenger()
          ->addError(t("Error with a code analysis process: @message", [
          '@message' => $error_message,
        ]));
      }
    }
    \Drupal::messenger()
      ->addStatus(t("Finished analysing site code. See results below for details."));
  }

}

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
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 public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
ProcessForm::$messenger protected property The Messenger service. Overrides MessengerTrait::$messenger
ProcessForm::batchFinished public static function Implements callback_batch_finished(). 1
ProcessForm::batchOperation public static function Implements callback_batch_operation(). 1
ProcessForm::buildForm public function Form constructor. Overrides FormInterface::buildForm 1
ProcessForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create 1
ProcessForm::getCollectTask protected static function Gets the collect task. 1
ProcessForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
ProcessForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm 1
ProcessForm::__construct public function Creates a ProcessForm instance.
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.