You are here

class DeploymentForm in Build Hooks 3.x

Same name and namespace in other branches
  1. 8.2 src/Form/DeploymentForm.php \Drupal\build_hooks\Form\DeploymentForm

Defines a form for triggering deployments.

Hierarchy

Expanded class hierarchy of DeploymentForm

1 string reference to 'DeploymentForm'
build_hooks.routing.yml in ./build_hooks.routing.yml
build_hooks.routing.yml

File

src/Form/DeploymentForm.php, line 22

Namespace

Drupal\build_hooks\Form
View source
class DeploymentForm extends FormBase {

  /**
   * Drupal\build_hooks\TriggerInterface definition.
   *
   * @var \Drupal\build_hooks\TriggerInterface
   */
  protected $buildHooksTrigger;

  /**
   * Drupal\build_hooks\DeployLogger definition.
   *
   * @var \Drupal\build_hooks\DeployLogger
   */
  protected $buildHooksDeploylogger;

  /**
   * Drupal\Core\Render\Renderer definition.
   *
   * @var \Drupal\Core\Render\Renderer
   */
  protected $renderer;

  /**
   * Drupal\Core\Datetime\DateFormatter definition.
   *
   * @var \Drupal\Core\Datetime\DateFormatter
   */
  protected $dateFormatter;

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

  /**
   * Constructs a new DeploymentForm object.
   */
  public function __construct(TriggerInterface $build_hooks_trigger, DeployLogger $build_hooks_deploylogger, Renderer $renderer, DateFormatter $dateFormatter, EntityTypeManagerInterface $entityTypeManager) {
    $this->buildHooksTrigger = $build_hooks_trigger;
    $this->buildHooksDeploylogger = $build_hooks_deploylogger;
    $this->renderer = $renderer;
    $this->dateFormatter = $dateFormatter;
    $this->entityTypeManager = $entityTypeManager;
  }

  /**
   * Create.
   *
   * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
   *   The container.
   *
   * @return \Drupal\build_hooks\Form\DeploymentForm
   *   The deployment form.
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('build_hooks.trigger'), $container
      ->get('build_hooks.deploylogger'), $container
      ->get('renderer'), $container
      ->get('date.formatter'), $container
      ->get('entity_type.manager'));
  }

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, FrontendEnvironment $frontend_environment = NULL) {

    // @todo render this with some theme hook instead of html tags.
    $form['display'] = [
      '#markup' => '<h2>' . $this
        ->t('@envName Environment', [
        '@envName' => $frontend_environment
          ->label(),
      ]) . '</h2>',
    ];
    $form['environment_link'] = [
      '#markup' => $this
        ->t('Frontend @environmentName site url: @link', [
        '@link' => Link::fromTextAndUrl($frontend_environment
          ->getUrl(), Url::fromUri($frontend_environment
          ->getUrl(), [
          'attributes' => [
            'target' => '_blank',
          ],
        ]))
          ->toString(),
        '@environmentName' => $frontend_environment
          ->label(),
      ]),
    ];

    // When was the last deployment?
    $last_deployment_timestamp = $this->buildHooksDeploylogger
      ->getLastDeployTimeForEnvironment($frontend_environment);
    if ($last_deployment_timestamp) {
      $last_deployment_timestamp_formatted = $this->dateFormatter
        ->format($last_deployment_timestamp, 'long');
      $form['last_deployment'] = [
        '#markup' => '<p>' . $this
          ->t('Last deployment triggered on: <strong>@date</strong>', [
          '@date' => $last_deployment_timestamp_formatted,
        ]) . '</p>',
      ];
    }
    $form['changelog'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Changelog'),
      '#description' => $this
        ->t("This is a summary of the changes since the previous deployment to the <strong>%name</strong> environment:", [
        '%name' => $frontend_environment
          ->label(),
      ]) . '</p>',
      '#open' => TRUE,
    ];

    // Have we logged any changes since last deployment?
    if ($this->buildHooksDeploylogger
      ->getNumberOfItemsSinceLastDeploymentForEnvironment($frontend_environment) > 0) {
      try {
        $form['changelog']['log'] = $this
          ->getChangelogView($frontend_environment);
      } catch (\Exception $e) {
        $this
          ->messenger()
          ->addWarning($this
          ->t('Could not preview the deployment. Check configuration.'));
      }
    }
    else {
      $form['changelog']['#description'] = '<p>' . $this
        ->t('No changes recorded since the last deployment for this environment. If needed you can still trigger a deployment using this page.') . '</p>';
    }

    // Add the entity to the form:
    $form['frontend_environment'] = [
      '#type' => 'value',
      '#value' => $frontend_environment,
    ];

    // Plugins have a possibility to return additional elements for this form:

    /** @var \Drupal\build_hooks\Plugin\FrontendEnvironmentBase $plugin */
    $plugin = $frontend_environment
      ->getPlugin();
    $additionalFormElements = $plugin
      ->getAdditionalDeployFormElements($form_state);

    // If they do, merge their form elements into the form:
    if (!empty($additionalFormElements)) {
      $form = NestedArray::mergeDeep($form, $additionalFormElements);
    }
    $form['submit'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Start a new deployment to the @environment environment', [
        '@environment' => $frontend_environment
          ->label(),
      ]),
    ];
    return $form;
  }

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

    // Get the environment entity:

    /** @var \Drupal\build_hooks\Entity\FrontendEnvironment $frontend_environment */
    $frontend_environment = $form_state
      ->getValue('frontend_environment');
    $this->buildHooksTrigger
      ->triggerBuildHookForEnvironment($frontend_environment);
  }

  /**
   * Use the included view to render the changelog.
   *
   * @param \Drupal\build_hooks\Entity\FrontendEnvironmentInterface $environment
   *   Environment.
   *
   * @return array
   *   Render array.
   */
  private function getChangelogView(FrontendEnvironmentInterface $environment) {

    /** @var \Drupal\build_hooks\DeploymentStorageHandlerInterface $deployment_storage */
    $deployment_storage = $this->entityTypeManager
      ->getStorage('build_hooks_deployment');
    $deployment = $deployment_storage
      ->getOrCreateNextDeploymentForEnvironment($environment);
    return $this->entityTypeManager
      ->getViewBuilder('build_hooks_deployment')
      ->view($deployment);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property
DependencySerializationTrait::$_serviceIds protected property
DependencySerializationTrait::__sleep public function 2
DependencySerializationTrait::__wakeup public function 2
DeploymentForm::$buildHooksDeploylogger protected property Drupal\build_hooks\DeployLogger definition.
DeploymentForm::$buildHooksTrigger protected property Drupal\build_hooks\TriggerInterface definition.
DeploymentForm::$dateFormatter protected property Drupal\Core\Datetime\DateFormatter definition.
DeploymentForm::$entityTypeManager protected property Entity type manager.
DeploymentForm::$renderer protected property Drupal\Core\Render\Renderer definition.
DeploymentForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
DeploymentForm::create public static function Create. Overrides FormBase::create
DeploymentForm::getChangelogView private function Use the included view to render the changelog.
DeploymentForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
DeploymentForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
DeploymentForm::__construct public function Constructs a new DeploymentForm object.
FormBase::$configFactory protected property The config factory. 3
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. 3
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.
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 72
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. 27
MessengerTrait::messenger public function Gets the messenger. 27
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. 4
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.