You are here

class UpdaterForm in Automatic Updates 8.2

Defines a form to update Drupal core.

@internal Form classes are internal.

Hierarchy

Expanded class hierarchy of UpdaterForm

1 string reference to 'UpdaterForm'
automatic_updates.routing.yml in ./automatic_updates.routing.yml
automatic_updates.routing.yml

File

src/Form/UpdaterForm.php, line 25

Namespace

Drupal\automatic_updates\Form
View source
class UpdaterForm extends FormBase {

  /**
   * The updater service.
   *
   * @var \Drupal\automatic_updates\Updater
   */
  protected $updater;

  /**
   * The state service.
   *
   * @var \Drupal\Core\State\StateInterface
   */
  protected $state;

  /**
   * The readiness validation manager service.
   *
   * @var \Drupal\automatic_updates\Validation\ReadinessValidationManager
   */
  protected $readinessValidationManager;

  /**
   * Constructs a new UpdaterForm object.
   *
   * @param \Drupal\Core\State\StateInterface $state
   *   The state service.
   * @param \Drupal\automatic_updates\Updater $updater
   *   The updater service.
   * @param \Drupal\automatic_updates\Validation\ReadinessValidationManager $readiness_validation_manager
   *   The readiness validation manager service.
   */
  public function __construct(StateInterface $state, Updater $updater, ReadinessValidationManager $readiness_validation_manager) {
    $this->updater = $updater;
    $this->state = $state;
    $this->readinessValidationManager = $readiness_validation_manager;
  }

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

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('state'), $container
      ->get('automatic_updates.updater'), $container
      ->get('automatic_updates.readiness_validation_manager'));
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $this
      ->messenger()
      ->addWarning($this
      ->t('This is an experimental Automatic Updater using Composer. Use at your own risk.'));
    $form['last_check'] = [
      '#theme' => 'update_last_check',
      '#last' => $this->state
        ->get('update.last_check', 0),
    ];
    $recommender = new UpdateRecommender();
    try {
      $recommended_release = $recommender
        ->getRecommendedRelease(TRUE);
    } catch (\RuntimeException $e) {
      $form['message'] = [
        '#markup' => $e
          ->getMessage(),
      ];
      return $form;
    }

    // @todo Should we be using the Update module's library here, or our own?
    $form['#attached']['library'][] = 'update/drupal.update.admin';

    // If we're already up-to-date, there's nothing else we need to do.
    if ($recommended_release === NULL) {
      $this
        ->messenger()
        ->addMessage('No update available');
      return $form;
    }
    $form['update_version'] = [
      '#type' => 'value',
      '#value' => [
        'drupal' => $recommended_release
          ->getVersion(),
      ],
    ];
    $project = $recommender
      ->getProjectInfo();
    if (empty($project['title']) || empty($project['link'])) {
      throw new \UnexpectedValueException('Expected project data to have a title and link.');
    }
    $title = Link::fromTextAndUrl($project['title'], Url::fromUri($project['link']))
      ->toRenderable();
    switch ($project['status']) {
      case UpdateManagerInterface::NOT_SECURE:
      case UpdateManagerInterface::REVOKED:
        $title['#suffix'] = ' ' . $this
          ->t('(Security update)');
        $type = 'update-security';
        break;
      case UpdateManagerInterface::NOT_SUPPORTED:
        $title['#suffix'] = ' ' . $this
          ->t('(Unsupported)');
        $type = 'unsupported';
        break;
      default:
        $type = 'recommended';
        break;
    }

    // Create an entry for this project.
    $entry = [
      'title' => [
        'data' => $title,
      ],
      'installed_version' => $project['existing_version'],
      'recommended_version' => [
        'data' => [
          // @todo Is an inline template the right tool here? Is there an Update
          // module template we should use instead?
          '#type' => 'inline_template',
          '#template' => '{{ release_version }} (<a href="{{ release_link }}" title="{{ project_title }}">{{ release_notes }}</a>)',
          '#context' => [
            'release_version' => $recommended_release
              ->getVersion(),
            'release_link' => $recommended_release
              ->getReleaseUrl(),
            'project_title' => $this
              ->t('Release notes for @project_title', [
              '@project_title' => $project['title'],
            ]),
            'release_notes' => $this
              ->t('Release notes'),
          ],
        ],
      ],
    ];
    $form['projects'] = [
      '#type' => 'table',
      '#header' => [
        'title' => [
          'data' => $this
            ->t('Name'),
          'class' => [
            'update-project-name',
          ],
        ],
        'installed_version' => $this
          ->t('Installed version'),
        'recommended_version' => [
          'data' => $this
            ->t('Recommended version'),
        ],
      ],
      '#rows' => [
        'drupal' => [
          'class' => "update-{$type}",
          'data' => $entry,
        ],
      ],
    ];

    // @todo Add a hasErrors() or getErrors() method to
    // ReadinessValidationManager to make validation more introspectable.
    // Re-running the readiness checks now should mean that when we display
    // cached errors in automatic_updates_page_top(), we'll see errors that
    // were raised during this run, instead of any previously cached results.
    $errors = $this->readinessValidationManager
      ->run()
      ->getResults(SystemManager::REQUIREMENT_ERROR);
    if (empty($errors)) {
      $form['actions'] = $this
        ->actions();
    }
    return $form;
  }

  /**
   * Builds the form actions.
   *
   * @return mixed[][]
   *   The form's actions elements.
   */
  protected function actions() : array {
    $actions = [
      '#type' => 'actions',
    ];
    if ($this->updater
      ->hasActiveUpdate()) {
      $this
        ->messenger()
        ->addError($this
        ->t('Another Composer update process is currently active'));
      $actions['delete'] = [
        '#type' => 'submit',
        '#value' => $this
          ->t('Delete existing update'),
        '#submit' => [
          '::deleteExistingUpdate',
        ],
      ];
    }
    else {
      $actions['submit'] = [
        '#type' => 'submit',
        '#value' => $this
          ->t('Update'),
      ];
    }
    return $actions;
  }

  /**
   * Submit function to delete an existing in-progress update.
   */
  public function deleteExistingUpdate() : void {
    $this->updater
      ->clean();
    $this
      ->messenger()
      ->addMessage($this
      ->t("Staged update deleted"));
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $batch = (new BatchBuilder())
      ->setTitle($this
      ->t('Downloading updates'))
      ->setInitMessage($this
      ->t('Preparing to download updates'))
      ->addOperation([
      BatchProcessor::class,
      'begin',
    ], [
      $form_state
        ->getValue('update_version'),
    ])
      ->addOperation([
      BatchProcessor::class,
      'stage',
    ])
      ->setFinishCallback([
      BatchProcessor::class,
      'finishStage',
    ])
      ->toArray();
    batch_set($batch);
  }

}

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 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.
UpdaterForm::$readinessValidationManager protected property The readiness validation manager service.
UpdaterForm::$state protected property The state service.
UpdaterForm::$updater protected property The updater service.
UpdaterForm::actions protected function Builds the form actions.
UpdaterForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
UpdaterForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
UpdaterForm::deleteExistingUpdate public function Submit function to delete an existing in-progress update.
UpdaterForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
UpdaterForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
UpdaterForm::__construct public function Constructs a new UpdaterForm object.
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.