You are here

class UpdateForm in Workspace 8

The form to update the current workspace with its upstream.

Hierarchy

Expanded class hierarchy of UpdateForm

1 string reference to 'UpdateForm'
workspace.routing.yml in ./workspace.routing.yml
workspace.routing.yml

File

src/Form/UpdateForm.php, line 23

Namespace

Drupal\workspace\Form
View source
class UpdateForm extends ConfirmFormBase {

  /**
   * The workspace manager.
   *
   * @var \Drupal\multiversion\Workspace\WorkspaceManagerInterface
   */
  protected $workspaceManager;

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

  /**
   * The replicator manager.
   *
   * @var \Drupal\workspace\ReplicatorInterface
   */
  protected $replicatorManager;

  /**
   * The renderer service.
   *
   * @var \Drupal\Core\Render\RendererInterface
   */
  protected $renderer;

  /**
   * The injected service to track conflicts during replication.
   *
   * @var \Drupal\multiversion\Workspace\ConflictTrackerInterface
   */
  protected $conflictTracker;

  /**
   * Inject services needed by the form.
   *
   * @param \Drupal\multiversion\Workspace\WorkspaceManagerInterface $workspace_manager
   *   The workspace manager.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   * @param \Drupal\workspace\ReplicatorInterface $replicator_manager
   *   The replicator manager.
   * @param \Drupal\Core\Render\RendererInterface $renderer
   *   The renderer service.
   * @param \Drupal\multiversion\Workspace\ConflictTrackerInterface $conflict_tracker
   *   The conflict tracking service.
   */
  public function __construct(WorkspaceManagerInterface $workspace_manager, EntityTypeManagerInterface $entity_type_manager, ReplicatorInterface $replicator_manager, RendererInterface $renderer, ConflictTrackerInterface $conflict_tracker) {
    $this->workspaceManager = $workspace_manager;
    $this->entityTypeManager = $entity_type_manager;
    $this->replicatorManager = $replicator_manager;
    $this->renderer = $renderer;
    $this->conflictTracker = $conflict_tracker;
  }

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

  /**
   * Get the current active workspace's pointer.
   *
   * @return \Drupal\workspace\WorkspacePointerInterface
   *   The active workspace.
   *
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   */
  protected function getActive() {

    /** @var \Drupal\multiversion\Entity\WorkspaceInterface $workspace */
    $workspace = $this->workspaceManager
      ->getActiveWorkspace();

    /** @var \Drupal\workspace\WorkspacePointerInterface[] $pointers */
    $pointers = $this->entityTypeManager
      ->getStorage('workspace_pointer')
      ->loadByProperties([
      'workspace_pointer' => $workspace
        ->id(),
    ]);
    return reset($pointers);
  }

  /**
   * Returns the upstream for the given workspace.
   *
   * @return \Drupal\multiversion\Entity\WorkspaceInterface
   *   The upstream workspace.
   */
  protected function getUpstream() {
    $workspace = $this->workspaceManager
      ->getActiveWorkspace();
    if (isset($workspace->upstream)) {
      return $workspace->upstream->entity;
    }
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form = parent::buildForm($form, $form_state);
    $form['actions']['submit']['#ajax'] = [
      'callback' => [
        $this,
        'update',
      ],
      'event' => 'mousedown',
      'prevent' => 'click',
      'progress' => [
        'type' => 'throbber',
        'message' => 'Updating',
      ],
    ];
    if (!$this
      ->getUpstream()) {
      unset($form['actions']['submit']);
    }
    unset($form['actions']['cancel']);
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function getQuestion() {
    return $this
      ->t('Queue an update of @workspace', [
      '@workspace' => $this
        ->getActive()
        ->label(),
    ]);
  }

  /**
   * {@inheritdoc}
   */
  public function getCancelUrl() {
    return new Url('system.admin');
  }

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

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $upstream = $this
      ->getUpstream();
    $active = $this
      ->getActive();
    try {

      // Derive a replication task from the Workspace we are acting on.
      $task = $this->replicatorManager
        ->getTask($active
        ->getWorkspace(), 'pull_replication_settings');
      $response = $this->replicatorManager
        ->update($upstream, $active, $task);
      if ($response instanceof ReplicationLogInterface && $response
        ->get('ok')->value == TRUE) {

        // Notify the user if there are now conflicts.
        $conflicts = $this->conflictTracker
          ->useWorkspace($active
          ->getWorkspace())
          ->getAll();
        if ($conflicts) {
          drupal_set_message($this
            ->t('%workspace has been updated with content from %upstream, but there are <a href=":link">@count conflict(s) with the %target workspace</a>.', [
            '%upstream' => $upstream
              ->label(),
            '%workspace' => $active
              ->label(),
            ':link' => Url::fromRoute('entity.workspace.conflicts', [
              'workspace' => $active
                ->getWorkspace()
                ->id(),
            ])
              ->toString(),
            '@count' => count($conflicts),
            '%target' => $upstream
              ->label(),
          ]), 'error');
        }
        else {
          drupal_set_message($this
            ->t('An update of %workspace has been queued with content from %upstream.', [
            '%upstream' => $upstream
              ->label(),
            '%workspace' => $active
              ->label(),
          ]));
          if (\Drupal::moduleHandler()
            ->moduleExists('deploy')) {
            $input = $form_state
              ->getUserInput();
            if (!isset($input['_drupal_ajax'])) {
              $form_state
                ->setRedirect('entity.replication.collection');
            }
          }
        }
      }
      else {
        drupal_set_message($this
          ->t('Error updating %workspace from %upstream.', [
          '%upstream' => $upstream
            ->label(),
          '%workspace' => $active
            ->label(),
        ]), 'error');
      }
    } catch (\Exception $e) {
      watchdog_exception('Workspace', $e);
      drupal_set_message($e
        ->getMessage(), 'error');
    }
  }

  /**
   * Callback handler for the update form button.
   *
   * @param array $form
   *   The form array.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state data.
   *
   * @return \Drupal\Core\Ajax\AjaxResponse
   *   The AJAX response.
   */
  public function update(array $form, FormStateInterface $form_state) {
    $response = new AjaxResponse();
    $response
      ->addCommand(new CloseModalDialogCommand());
    if (\Drupal::moduleHandler()
      ->moduleExists('deploy')) {
      $response
        ->addCommand(new RedirectCommand(Url::fromRoute('entity.replication.collection')
        ->setAbsolute()
        ->toString()));
    }
    else {
      $status_messages = [
        '#type' => 'status_messages',
      ];
      $response
        ->addCommand(new PrependCommand('.region-highlighted', $this->renderer
        ->renderRoot($status_messages)));
    }
    return $response;
  }

  /**
   * {@inheritdoc}
   */
  public function getDescription() {
    if (!$this
      ->getUpstream()) {
      return $this
        ->t('%workspace has no upstream set.', [
        '%workspace' => $this
          ->getActive()
          ->label(),
      ]);
    }
    return $this
      ->t('Do you want to queue %workspace to be updated with changes from %upstream?', [
      '%upstream' => $this
        ->getUpstream()
        ->label(),
      '%workspace' => $this
        ->getActive()
        ->label(),
    ]);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ConfirmFormBase::getCancelText public function Returns a caption for the link which cancels the action. Overrides ConfirmFormInterface::getCancelText 1
ConfirmFormBase::getConfirmText public function Returns a caption for the button that confirms the action. Overrides ConfirmFormInterface::getConfirmText 20
ConfirmFormBase::getFormName public function Returns the internal name used to refer to the confirmation item. Overrides ConfirmFormInterface::getFormName
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.
UpdateForm::$conflictTracker protected property The injected service to track conflicts during replication.
UpdateForm::$entityTypeManager protected property The entity type manager.
UpdateForm::$renderer protected property The renderer service.
UpdateForm::$replicatorManager protected property The replicator manager.
UpdateForm::$workspaceManager protected property The workspace manager.
UpdateForm::buildForm public function Form constructor. Overrides ConfirmFormBase::buildForm
UpdateForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
UpdateForm::getActive protected function Get the current active workspace's pointer.
UpdateForm::getCancelUrl public function Returns the route to go to if the user cancels the action. Overrides ConfirmFormInterface::getCancelUrl
UpdateForm::getDescription public function Returns additional text to display as a description. Overrides ConfirmFormBase::getDescription
UpdateForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
UpdateForm::getQuestion public function Returns the question to ask the user. Overrides ConfirmFormInterface::getQuestion
UpdateForm::getUpstream protected function Returns the upstream for the given workspace.
UpdateForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
UpdateForm::update public function Callback handler for the update form button.
UpdateForm::__construct public function Inject services needed by the form.
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.