You are here

class StaticGeneratorForm in Tome 8

Contains a form for initializing a static build.

@internal

Hierarchy

Expanded class hierarchy of StaticGeneratorForm

1 string reference to 'StaticGeneratorForm'
tome_static.routing.yml in modules/tome_static/tome_static.routing.yml
modules/tome_static/tome_static.routing.yml

File

modules/tome_static/src/Form/StaticGeneratorForm.php, line 22

Namespace

Drupal\tome_static\Form
View source
class StaticGeneratorForm extends FormBase {
  use StaticUITrait;

  /**
   * The static generator.
   *
   * @var \Drupal\tome_static\StaticGeneratorInterface
   */
  protected $static;

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

  /**
   * The request preparer.
   *
   * @var \Drupal\tome_static\RequestPreparer
   */
  protected $requestPreparer;

  /**
   * StaticGeneratorForm constructor.
   *
   * @param \Drupal\tome_static\StaticGeneratorInterface $static
   *   The static generator.
   * @param \Drupal\Core\State\StateInterface $state
   *   The state system.
   * @param \Drupal\tome_static\RequestPreparer $request_preparer
   *   The request preparer.
   */
  public function __construct(StaticGeneratorInterface $static, StateInterface $state, RequestPreparer $request_preparer) {
    $this->static = $static;
    $this->state = $state;
    $this->requestPreparer = $request_preparer;
  }

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

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['description'] = [
      '#markup' => '<p>' . $this
        ->t('Submitting this form will initiate a build of all uncached static pages site using Tome. Existing files in the static export directory (@dir) will be overridden.', [
        '@dir' => $this->static
          ->getStaticDirectory(),
      ]) . '</p>',
    ];
    $form['base_url'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Base URL'),
      '#default_value' => $this->state
        ->get(StaticGeneratorInterface::STATE_KEY_URL, 'http://127.0.0.1'),
      '#required' => TRUE,
      '#size' => 30,
      '#description' => $this
        ->t('The absolute URL used for generating static pages. This should match the domain on the site where the static site will be deployed.'),
    ];
    $warnings = $this
      ->getWarnings();
    if ($this->state
      ->get(StaticGeneratorInterface::STATE_KEY_BUILDING, FALSE)) {
      $warnings[] = $this
        ->t('Another user may be running a static build, proceed only if the last build failed unexpectedly.');
    }
    if (!empty($warnings)) {
      $form['warnings'] = [
        '#type' => 'container',
        'title' => [
          '#markup' => '<strong>' . $this
            ->t('Build warnings') . '</strong>',
        ],
        'list' => [
          '#theme' => 'item_list',
          '#items' => [],
        ],
      ];
      foreach ($warnings as $warning) {
        $form['warnings']['list']['#items'][] = [
          '#markup' => $warning,
        ];
      }
    }
    $form['actions'] = [
      '#type' => 'actions',
    ];
    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Submit'),
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    if (!UrlHelper::isValid($form_state
      ->getValue('base_url'), TRUE)) {
      $form_state
        ->setError($form['base_url'], $this
        ->t('The provided URL is not valid.'));
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $this->state
      ->set(StaticGeneratorInterface::STATE_KEY_BUILDING, TRUE);
    $base_url = $form_state
      ->getValue('base_url');
    $this->state
      ->set(StaticGeneratorInterface::STATE_KEY_URL, $base_url);
    $this->static
      ->cleanupStaticDirectory();
    $this->static
      ->prepareStaticDirectory();
    $original_params = TomeStaticHelper::setBaseUrl($this
      ->getRequest(), $base_url);
    $paths = $this->static
      ->getPaths();
    TomeStaticHelper::restoreBaseUrl($this
      ->getRequest(), $original_params);
    $this
      ->setBatch($paths, $base_url);
  }

  /**
   * Exports all remaining paths at the end of a previous batch.
   *
   * @param string $base_url
   *   The base URL.
   * @param array $context
   *   The batch context.
   */
  public function batchInvokePaths($base_url, array &$context) {
    if (!empty($context['results']['invoke_paths'])) {
      $context['results']['old_paths'] = isset($context['results']['old_paths']) ? $context['results']['old_paths'] : [];
      $context['results']['invoke_paths'] = array_diff($context['results']['invoke_paths'], $context['results']['old_paths']);
      $context['results']['old_paths'] = array_merge($context['results']['invoke_paths'], $context['results']['old_paths']);
      $invoke_paths = $this->static
        ->exportPaths($context['results']['invoke_paths']);
      if (!empty($invoke_paths)) {
        $this
          ->setBatch($invoke_paths, $base_url);
      }
    }
  }

  /**
   * Exports a path using Tome.
   *
   * @param string $path
   *   The path to export.
   * @param string $base_url
   *   The base URL.
   * @param array $context
   *   The batch context.
   */
  public function exportPath($path, $base_url, array &$context) {
    $original_params = TomeStaticHelper::setBaseUrl($this
      ->getRequest(), $base_url);
    $this->requestPreparer
      ->prepareForRequest();
    try {
      $invoke_paths = $this->static
        ->requestPath($path);
    } catch (\Exception $e) {
      $context['results']['errors'][] = $this
        ->formatPathException($path, $e);
      $invoke_paths = [];
    }
    TomeStaticHelper::restoreBaseUrl($this
      ->getRequest(), $original_params);
    $context['results']['invoke_paths'] = isset($context['results']['invoke_paths']) ? $context['results']['invoke_paths'] : [];
    $context['results']['invoke_paths'] = array_merge($context['results']['invoke_paths'], $invoke_paths);
  }

  /**
   * Batch finished callback after all paths and assets have been exported.
   *
   * @param bool $success
   *   Whether or not the batch was successful.
   * @param mixed $results
   *   Batch results set with context.
   */
  public function finishCallback($success, $results) {
    $this->state
      ->set(StaticGeneratorInterface::STATE_KEY_BUILDING, FALSE);
    $this
      ->messenger()
      ->deleteAll();
    if (!$success) {
      $this
        ->messenger()
        ->addError($this
        ->t('Static build failed - consult the error log for more details.'));
      return;
    }
    if (!empty($results['errors'])) {
      foreach ($results['errors'] as $error) {
        $this
          ->messenger()
          ->addError($error);
      }
    }
    $this
      ->messenger()
      ->addStatus($this
      ->t('Static build complete! To download the build, <a href=":download">click here.</a>', [
      '@dir' => $this->static
        ->getStaticDirectory(),
      ':download' => Url::fromRoute('tome_static.download_page')
        ->toString(),
    ]));
  }

  /**
   * Sets a new batch.
   *
   * @param array $paths
   *   An array of paths to invoke.
   * @param string $base_url
   *   The base URL.
   */
  protected function setBatch(array $paths, $base_url) {
    $batch_builder = (new BatchBuilder())
      ->setTitle($this
      ->t('Generating static HTML...'))
      ->setFinishCallback([
      $this,
      'finishCallback',
    ]);
    $paths = $this->static
      ->exportPaths($paths);
    foreach ($paths as $path) {
      $batch_builder
        ->addOperation([
        $this,
        'exportPath',
      ], [
        $path,
        $base_url,
      ]);
    }
    $batch_builder
      ->addOperation([
      $this,
      'batchInvokePaths',
    ], [
      $base_url,
    ]);
    batch_set($batch_builder
      ->toArray());
  }

}

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.
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.
StaticGeneratorForm::$requestPreparer protected property The request preparer.
StaticGeneratorForm::$state protected property The state system.
StaticGeneratorForm::$static protected property The static generator.
StaticGeneratorForm::batchInvokePaths public function Exports all remaining paths at the end of a previous batch.
StaticGeneratorForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
StaticGeneratorForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
StaticGeneratorForm::exportPath public function Exports a path using Tome.
StaticGeneratorForm::finishCallback public function Batch finished callback after all paths and assets have been exported.
StaticGeneratorForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
StaticGeneratorForm::setBatch protected function Sets a new batch.
StaticGeneratorForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
StaticGeneratorForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
StaticGeneratorForm::__construct public function StaticGeneratorForm constructor.
StaticUITrait::formatPathException protected function Formats an exception caught when requesting a path.
StaticUITrait::getWarnings protected function Collects warnings to help users correct issues in rendered HTML.
StaticUITrait::t abstract protected function Translates a string to the current language or to a given language.
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
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.