You are here

class GatsbyAdminForm in Gatsby Live Preview & Incremental Builds 2.0.x

Same name and namespace in other branches
  1. 8 src/Form/GatsbyAdminForm.php \Drupal\gatsby\Form\GatsbyAdminForm

Defines a config form to store Gatsby configuration.

Hierarchy

Expanded class hierarchy of GatsbyAdminForm

1 file declares its use of GatsbyAdminForm
GatsbyInstantPreviewAdminForm.php in modules/gatsby_instantpreview/src/Form/GatsbyInstantPreviewAdminForm.php
1 string reference to 'GatsbyAdminForm'
gatsby.routing.yml in ./gatsby.routing.yml
gatsby.routing.yml

File

src/Form/GatsbyAdminForm.php, line 17

Namespace

Drupal\gatsby\Form
View source
class GatsbyAdminForm extends ConfigFormBase {

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

  /**
   * Drupal\Core\Extension\ModuleHandlerInterface definition.
   *
   * @var \Drupal\Core\Extension\ModuleHandlerInterface
   */
  protected $moduleHandler;

  /**
   * Drupal\gatsby\PathMapping definition.
   *
   * @var \Drupal\gatsby\PathMapping
   */
  protected $pathMapping;

  /**
   * Class constructor.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entityTypeManager
   *   The entity type manager.
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $moduleHandler
   *   The module handler.
   * @param \Drupal\gatsby\PathMapping $pathMapping
   *   The path mapping.
   */
  public function __construct(EntityTypeManagerInterface $entityTypeManager, ModuleHandlerInterface $moduleHandler, PathMapping $pathMapping) {
    $this->entityTypeManager = $entityTypeManager;
    $this->moduleHandler = $moduleHandler;
    $this->pathMapping = $pathMapping;
  }

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

  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames() {
    return [
      'gatsby.settings',
    ];
  }

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $config = $this
      ->config('gatsby.settings');
    $form['site_settings'] = [
      '#type' => 'fieldset',
      '#title' => $this
        ->t('Site settings'),
      '#desription' => $this
        ->t('In a Gatsby Cloud account these details may be found on the "Site Settings" section of the dashboard.'),
    ];
    $form['site_settings']['server_url'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Gatsby Server URL'),
      '#description' => $this
        ->t('The URL to the Gatsby server (with port number if needed). Separate multiple values with a comma.<br />For Gatsby Cloud accounts this will be a URL in the format https://example12345.gatsbyjs.io.'),
      '#default_value' => $config
        ->get('server_url'),
      '#required' => TRUE,
      '#maxlength' => 250,
      '#weight' => 0,
    ];
    $form['site_settings']['preview_callback_url'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Preview Webhook URL(s)'),
      '#description' => $this
        ->t('The URL to the Gatsby preview build webhook (if running locally, it\'s "localhost:8000/__refresh"). Separate multiple values with a comma.'),
      '#default_value' => $config
        ->get('preview_callback_url'),
      '#required' => TRUE,
      '#maxlength' => 250,
      '#weight' => 0,
    ];
    $form['site_settings']['incrementalbuild_url'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t("Build Webhook URL(s)"),
      '#description' => $this
        ->t('The Callback URL to trigger the Gatsby Build. Multiple build server URLS can be separated by commas. Note: Incremental builds are currently only supported with JSON:API and gatsby-source-drupal.'),
      '#default_value' => $config
        ->get('incrementalbuild_url'),
      '#maxlength' => 250,
      '#weight' => 1,
    ];
    $form['content_advanced'] = [
      '#type' => 'fieldset',
      '#title' => $this
        ->t('Content / path mapping'),
    ];
    $form['content_advanced']['path_mapping'] = [
      '#type' => 'textarea',
      '#title' => $this
        ->t('Preview Server Path Mapping'),
      '#description' => $this
        ->t('If you do any path manipulation in your Gatsby site you may need to map the preview iframe and preview button to this correct path. For instance, you may have a /home path in Drupal that maps to / on your Gatsby site. Enter the Drupal path on the left (starting with a "/") and the Gatsby path on the right (starting with a "/") separated by a "|" character. For example: "/home|/". Enter one path mapping per line.'),
      '#default_value' => $config
        ->get('path_mapping'),
    ];
    $form['data_selection'] = [
      '#type' => 'fieldset',
      '#title' => $this
        ->t('Data selection'),
    ];
    $form['data_selection']['build_published'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Only trigger builds for published content'),
      '#description' => $this
        ->t('Depending on your content workflow, you may only want builds to be triggered for published content. By checking this box only published content will trigger a build. This means additional entities such as Media or Files will not trigger a rebuild until the content it\'s attached to is published. The downside is that this will only allow content entities to trigger a rebuild.'),
      '#default_value' => $config
        ->get('build_published') !== NULL ? $config
        ->get('build_published') : TRUE,
      '#weight' => 2,
    ];
    $form['data_selection']['preview_entity_types'] = [
      '#type' => 'checkboxes',
      '#options' => $this
        ->getContentEntityTypes(),
      '#default_value' => $config
        ->get('preview_entity_types') ?: [],
      '#title' => $this
        ->t('Entity types to send to Gatsby Preview and Build Server'),
      '#description' => $this
        ->t('What entities should be sent to the Gatsby Preview and Build Server?'),
      '#weight' => 10,
    ];
    $form['advanced'] = [
      '#type' => 'fieldset',
      '#title' => $this
        ->t('Advanced settings'),
    ];
    $form['advanced']['log_json'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Create log messages of JSON objects sent to the Gatsby preview server'),
      '#description' => $this
        ->t('By checking this box, log messages will be created every time a POST request is sent to the Gatsby preview server. Useful for debugging the JSON object data that gets sent to Gatsby.<br /><strong>Note: this may have security implications, esure that only trusted users can access the logged messages. Should not be used on a production environment.</strong.'),
      '#default_value' => $config
        ->get('log_json'),
      '#weight' => 3,
    ];
    return parent::buildForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    parent::validateForm($form, $form_state);
    $this
      ->validateCsvUrl('server_url', $this
      ->t('Invalid Gatsby preview server URL.'), $form_state);
    $this
      ->validateCsvUrl('preview_callback_url', $this
      ->t('Invalid Gatsby preview callback URL.'), $form_state);
    $path_mapping = $form_state
      ->getValue('path_mapping');
    try {
      $map = PathMapping::parsePathMapping($path_mapping);
      if (strlen(trim($path_mapping)) > 0 && count($map) === 0) {

        // Unable to parse anything meaningful from the path mapping.
        $form_state
          ->setErrorByName('path_mapping', $this
          ->t('Invalid preview server path mapping.'));
      }
    } catch (\Error $e) {

      // Parsing the path mapping caused a PHP Error.
      $form_state
        ->setErrorByName('path_mapping', $this
        ->t('Invalid preview server path mapping.'));
    }
    $incremental_build_url = $form_state
      ->getValue('incrementalbuild_url');
    if (strlen($incremental_build_url) > 0 and !filter_var($incremental_build_url, FILTER_VALIDATE_URL)) {
      $form_state
        ->setErrorByName('incrementalbuild_url', $this
        ->t('Invalid incremental build URL.'));
    }
  }

  /**
   * Validates a URL that may be multi-value via commas.
   *
   * @param string $field_name
   *   Field name.
   * @param \Drupal\Core\StringTranslation\TranslatableMarkup $error
   *   Error message to show if invalid.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   Form state.
   */
  protected function validateCsvUrl(string $field_name, TranslatableMarkup $error, FormStateInterface $form_state) : void {
    $urls = array_map('trim', explode(',', $form_state
      ->getValue($field_name)));
    foreach ($urls as $url) {
      if (strlen($url) > 0 and !filter_var($url, FILTER_VALIDATE_URL)) {
        $form_state
          ->setErrorByName($field_name, $error);
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    parent::submitForm($form, $form_state);
    $this
      ->config('gatsby.settings')
      ->set('server_url', $form_state
      ->getValue('server_url'))
      ->set('preview_callback_url', $form_state
      ->getValue('preview_callback_url'))
      ->set('incrementalbuild_url', $form_state
      ->getValue('incrementalbuild_url'))
      ->set('build_published', $form_state
      ->getValue('build_published'))
      ->set('preview_entity_types', array_values(array_filter($form_state
      ->getValue('preview_entity_types'))))
      ->set('path_mapping', $form_state
      ->getValue('path_mapping'))
      ->set('log_json', $form_state
      ->getValue('log_json'))
      ->save();
  }

  /**
   * Gets a list of all the defined content entities in the system.
   *
   * @return array
   *   An array of content entities definitions.
   */
  private function getContentEntityTypes() {
    $content_entity_types = [];
    $allEntityTypes = $this->entityTypeManager
      ->getDefinitions();
    foreach ($allEntityTypes as $entity_type_id => $entity_type) {

      // Add all content entity types but not the gatsby log entity provided
      // by the gatsby_fastbuilds module (if it exists).
      if ($entity_type instanceof ContentEntityTypeInterface && $entity_type_id !== 'gatsby_log_entity') {
        $content_entity_types[$entity_type_id] = $entity_type
          ->getLabel();
      }
    }
    return $content_entity_types;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ConfigFormBaseTrait::config protected function Retrieves a configuration object.
DependencySerializationTrait::$_entityStorages protected property
DependencySerializationTrait::$_serviceIds protected property
DependencySerializationTrait::__sleep public function 2
DependencySerializationTrait::__wakeup public function 2
FormBase::$configFactory protected property The config factory. 3
FormBase::$requestStack protected property The request stack. 1
FormBase::$routeMatch protected property The route match.
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.
GatsbyAdminForm::$entityTypeManager protected property Drupal\Core\Entity\EntityTypeManagerInterface definition.
GatsbyAdminForm::$moduleHandler protected property Drupal\Core\Extension\ModuleHandlerInterface definition.
GatsbyAdminForm::$pathMapping protected property Drupal\gatsby\PathMapping definition.
GatsbyAdminForm::buildForm public function Form constructor. Overrides ConfigFormBase::buildForm 1
GatsbyAdminForm::create public static function Instantiates a new instance of this class. Overrides ConfigFormBase::create
GatsbyAdminForm::getContentEntityTypes private function Gets a list of all the defined content entities in the system.
GatsbyAdminForm::getEditableConfigNames protected function Gets the configuration names that will be editable. Overrides ConfigFormBaseTrait::getEditableConfigNames
GatsbyAdminForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
GatsbyAdminForm::submitForm public function Form submission handler. Overrides ConfigFormBase::submitForm 1
GatsbyAdminForm::validateCsvUrl protected function Validates a URL that may be multi-value via commas.
GatsbyAdminForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
GatsbyAdminForm::__construct public function Class constructor. Overrides ConfigFormBase::__construct
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.