You are here

class ReplicationActionForm in Deploy - Content Staging 8

ReplicationActionForm class.

Hierarchy

Expanded class hierarchy of ReplicationActionForm

File

src/Form/ReplicationActionForm.php, line 21

Namespace

Drupal\deploy\Form
View source
class ReplicationActionForm extends FormBase {

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

  /**
   * A source object.
   *
   * @var \Drupal\workspace\WorkspacePointerInterface
   */
  protected $source = NULL;

  /**
   * A target object.
   *
   * @var \Drupal\workspace\WorkspacePointerInterface
   */
  protected $target = NULL;

  /**
   * The Entity Type Plug-in Manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * The Workspace Plug-in Manager.
   *
   * @var \Drupal\multiversion\Workspace\WorkspaceManagerInterface
   */
  protected $workspaceManager;

  /**
   * Constructs a ContentEntityForm object.
   *
   * @param \Drupal\multiversion\Workspace\ConflictTrackerInterface $conflict_tracker
   *   The conflict tracking service.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type plug-in manager.
   * @param \Drupal\multiversion\Workspace\WorkspaceManagerInterface $workspace_manager
   *   The workspace manager.
   */
  public function __construct(ConflictTrackerInterface $conflict_tracker, EntityTypeManagerInterface $entity_type_manager, WorkspaceManagerInterface $workspace_manager) {
    $this->conflictTracker = $conflict_tracker;
    $this->entityTypeManager = $entity_type_manager;
    $this->workspaceManager = $workspace_manager;
  }

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

  /**
   * Implements buildForm().
   *
   * {@inheritDoc}.
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $entity = $this
      ->getEntity($form_state);
    $form['#weight'] = 9999;
    $form['replication_id'] = [
      '#type' => 'hidden',
      '#value' => $entity
        ->id(),
    ];

    // Allow the user to not abort on conflicts.
    if ($default_source = $this
      ->getDefaultSource($form_state)) {
      $source_workspace = $default_source
        ->getWorkspace();
    }
    if ($default_target = $this
      ->getDefaultTarget($form_state)) {
      $target_workspace = $default_target
        ->getWorkspace();
    }
    $conflicts = $this->conflictTracker
      ->useWorkspace($source_workspace)
      ->getAll();
    if ($conflicts) {
      $form['message'] = $this
        ->generateMessageRenderArray('error', $this
        ->t('There are <a href=":link">@count conflict(s) with the :target workspace</a>. Pushing changes to :target may result in unexpected behavior or data loss, and cannot be undone. Please proceed with caution.', [
        '@count' => count($conflicts),
        ':link' => Url::fromRoute('entity.workspace.conflicts', [
          'workspace' => $source_workspace
            ->id(),
        ])
          ->toString(),
        ':target' => $this
          ->getDefaultTarget($form_state)
          ->label(),
      ]));
      $form['is_aborted_on_conflict'] = [
        '#type' => 'radios',
        '#title' => $this
          ->t('Abort if there are conflicts?'),
        '#default_value' => 'true',
        '#options' => [
          'true' => $this
            ->t('Yes, if conflicts are found do not replicate to upstream.'),
          'false' => $this
            ->t('No, go ahead and push any conflicts to the upstream.'),
        ],
        '#weight' => 0,
      ];
    }
    else {
      $form['message'] = $this
        ->generateMessageRenderArray('status', 'There are no conflicts.');
    }
    if ($source_workspace && !$source_workspace
      ->isPublished() && $target_workspace && !$target_workspace
      ->isPublished()) {
      $message = $this
        ->t('This deployment cannot be re-deployed because both source workspace (%source) and target workspace (%target) have been archived.', [
        '%source' => $source_workspace
          ->label(),
        '%target' => $target_workspace
          ->label(),
      ]);
    }
    elseif (!$default_source || $source_workspace && !$source_workspace
      ->isPublished()) {
      $message = $this
        ->t('This deployment cannot be re-deployed because the source workspace %source has been archived.', [
        '%source' => $source_workspace ? '(' . $source_workspace
          ->label() . ')' : '',
      ]);
    }
    elseif (!$default_target || $target_workspace && !$target_workspace
      ->isPublished()) {
      $message = $this
        ->t('This deployment cannot be re-deployed because the target workspace %target has been archived.', [
        '%target' => $target_workspace ? '(' . $target_workspace
          ->label() . ')' : '',
      ]);
    }
    elseif ($entity
      ->getArchiveSource()) {
      $message = $this
        ->t('This deployment cannot be re-deployed because the source workspace %source has been marked to be archived.', [
        '%source' => $source_workspace ? '(' . $source_workspace
          ->label() . ')' : '',
      ]);
    }
    if (isset($message)) {
      $form['message'] = $this
        ->generateMessageRenderArray('warning', $message);
    }
    else {
      $form['submit'] = [
        '#type' => 'submit',
        '#value' => $entity
          ->get('replicated')->value ? $this
          ->t('Re-deploy') : $this
          ->t('Deploy'),
      ];
    }
    return $form;
  }

  /**
   * Implements getFormId().
   *
   * {@inheritDoc}.
   */
  public function getFormId() {
    return 'replication_action';
  }

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

    // Pass the abort flag to the ReplicationManager using runtime-only state,
    // i.e. a static.
    // @see \Drupal\workspace\ReplicatorManager
    // @see \Drupal\workspace\Entity\Form\WorkspaceForm
    $is_aborted_on_conflict = !$form_state
      ->hasValue('is_aborted_on_conflict') || $form_state
      ->getValue('is_aborted_on_conflict') === 'true';
    drupal_static('workspace_is_aborted_on_conflict', $is_aborted_on_conflict);
    $entity = $this
      ->getEntity($form_state);

    /** @var \Drupal\replication\Entity\ReplicationLogInterface $response */
    $response = \Drupal::service('workspace.replicator_manager')
      ->replicate($entity
      ->get('source')->entity, $entity
      ->get('target')->entity);
    if ($response instanceof ReplicationLogInterface && $response
      ->get('ok')->value == TRUE) {
      $entity
        ->set('replicated', REQUEST_TIME)
        ->save();
      $this
        ->messenger()
        ->addMessage('Successful deployment.');
    }
    else {
      $this
        ->messenger()
        ->addError('Deployment error. Check recent log messages for more details.');
    }
  }

  /**
   * Returns the entity object itself or an EntityMalformedException if error.
   *
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   Form State values.
   *
   * @return \Drupal\workspace\Entity\Replication
   *   The expected parent class for $entity.
   *
   * @throws EntityMalformedException
   */
  protected function getEntity(FormStateInterface $form_state) {
    $args = $form_state
      ->getBuildInfo()['args'];

    /** @var \Drupal\workspace\Entity\Replication $entity */
    $entity = $args[0];
    if ($entity instanceof Replication) {
      return $entity;
    }
    throw new EntityMalformedException('Invalid Replication entity given.');
  }

  /**
   * Generate a message render array with the given text.
   *
   * @param string $type
   *   The type of message: status, warning, or error.
   * @param string $message
   *   The message to create with.
   *
   * @return array
   *   The render array for a status message.
   *
   * @see \Drupal\Core\Render\Element\StatusMessages
   */
  protected function generateMessageRenderArray($type, $message) {
    return [
      '#theme' => 'status_messages',
      '#message_list' => [
        $type => [
          Markup::create($message),
        ],
      ],
    ];
  }

  /**
   * Returns a source object.
   *
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   Form State values.
   *
   * @return mixed
   *   The source object itself.
   */
  protected function getDefaultSource(FormStateInterface $form_state) {
    if (!empty($this->source)) {
      return $this->source;
    }
    if (!empty($this
      ->getEntity($form_state)
      ->get('source')) && $this
      ->getEntity($form_state)
      ->get('source')->entity instanceof WorkspacePointerInterface) {
      return $this->source = $this
        ->getEntity($form_state)
        ->get('source')->entity;
    }
  }

  /**
   * Returns a target object.
   *
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   Form State values.
   *
   * @return mixed
   *   The target object itself.
   */
  protected function getDefaultTarget(FormStateInterface $form_state) {
    if (!empty($this->target)) {
      return $this->target;
    }
    if (!empty($this
      ->getEntity($form_state)
      ->get('target')) && $this
      ->getEntity($form_state)
      ->get('target')->entity instanceof WorkspacePointerInterface) {
      return $this->target = $this
        ->getEntity($form_state)
        ->get('target')->entity;
    }
  }

}

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.
ReplicationActionForm::$conflictTracker protected property The injected service to track conflicts during replication.
ReplicationActionForm::$entityTypeManager protected property The Entity Type Plug-in Manager.
ReplicationActionForm::$source protected property A source object.
ReplicationActionForm::$target protected property A target object.
ReplicationActionForm::$workspaceManager protected property The Workspace Plug-in Manager.
ReplicationActionForm::buildForm public function Implements buildForm(). Overrides FormInterface::buildForm
ReplicationActionForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
ReplicationActionForm::generateMessageRenderArray protected function Generate a message render array with the given text.
ReplicationActionForm::getDefaultSource protected function Returns a source object.
ReplicationActionForm::getDefaultTarget protected function Returns a target object.
ReplicationActionForm::getEntity protected function Returns the entity object itself or an EntityMalformedException if error.
ReplicationActionForm::getFormId public function Implements getFormId(). Overrides FormInterface::getFormId
ReplicationActionForm::submitForm public function Implements submitForm(). Overrides FormInterface::submitForm
ReplicationActionForm::__construct public function Constructs a ContentEntityForm object.
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.