You are here

class SimplesitemapVariantsForm in Simple XML sitemap 8.3

Class SimplesitemapVariantsForm @package Drupal\simple_sitemap\Form

Hierarchy

Expanded class hierarchy of SimplesitemapVariantsForm

1 string reference to 'SimplesitemapVariantsForm'
simple_sitemap.routing.yml in ./simple_sitemap.routing.yml
simple_sitemap.routing.yml

File

src/Form/SimplesitemapVariantsForm.php, line 12

Namespace

Drupal\simple_sitemap\Form
View source
class SimplesitemapVariantsForm extends SimplesitemapFormBase {

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['simple_sitemap_variants'] = [
      '#title' => $this
        ->t('Sitemap variants'),
      '#type' => 'fieldset',
      '#markup' => '<div class="description">' . $this
        ->t('Define sitemap variants. A sitemap variant is a sitemap instance of a certain type (specific sitemap generator and URL generators) accessible under a certain URL.<br>Each variant can have its own entity bundle settings (to be defined on bundle edit pages).') . '</div>',
      '#prefix' => FormHelper::getDonationText(),
    ];
    $form['simple_sitemap_variants']['variants'] = [
      '#type' => 'textarea',
      '#title' => $this
        ->t('Variants'),
      '#default_value' => $this
        ->variantsToString($this->generator
        ->getSitemapManager()
        ->getSitemapVariants(NULL, TRUE)),
      '#description' => $this
        ->t("Please specify sitemap variants, one per line. <strong>Caution: </strong>Removing variants here will delete their bundle settings, custom links and corresponding sitemap instances.<br><br>A variant definition consists of the variant name (used as the variant's path), the sitemap type it belongs to (optional) and the variant label (optional). These three values have to be separated by the | pipe | symbol.<br><br><strong>Examples:</strong><br><em>default | default_hreflang | Default</em> -> variant of the <em>default_hreflang</em> sitemap type and <em>Default</em> as label; accessible under <em>/default/sitemap.xml</em><br><em>test</em> -> variant of the <em>@default_sitemap_type</em> sitemap type and <em>test</em> as label; accessible under <em>/test/sitemap.xml</em><br><br><strong>Available sitemap types:</strong>", [
        '@default_sitemap_type' => SimplesitemapManager::DEFAULT_SITEMAP_TYPE,
      ]),
    ];
    foreach ($this->generator
      ->getSitemapManager()
      ->getSitemapTypes() as $sitemap_type => $definition) {
      $form['simple_sitemap_variants']['variants']['#description'] .= '<br>' . '<em>' . $sitemap_type . '</em>' . (!empty($definition['description']) ? ': ' . $definition['description'] : '');
    }
    $this->formHelper
      ->displayRegenerateNow($form['simple_sitemap_custom']);
    return parent::buildForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   *
   * @todo Show multiple errors at once.
   * @todo Allow numeric variant names, but bear in mind that they are stored as integer array keys due to how php arrays work.
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    $line = 0;
    $sitemap_types = $this->generator
      ->getSitemapManager()
      ->getSitemapTypes();
    foreach ($this
      ->stringToVariants($form_state
      ->getValue('variants')) as $variant_name => $variant_definition) {
      $placeholders = [
        '@line' => ++$line,
        '@name' => $variant_name,
        '@type' => isset($variant_definition['type']) ? $variant_definition['type'] : '',
        '@label' => isset($variant_definition['label']) ? $variant_definition['label'] : '',
      ];
      if (trim($variant_name) === '') {
        $form_state
          ->setErrorByName('', $this
          ->t("<strong>Line @line</strong>: The variant name cannot be empty.", $placeholders));
      }
      if (!preg_match('/^[\\w\\-_]+$/', $variant_name)) {
        $form_state
          ->setErrorByName('', $this
          ->t("<strong>Line @line</strong>: The variant name <em>@name</em> can only include alphanumeric characters, dashes and underscores.", $placeholders));
      }
      if (is_numeric($variant_name)) {
        $form_state
          ->setErrorByName('', $this
          ->t("<strong>Line @line</strong>: The variant name cannot be numeric.", $placeholders));
      }
      if (!isset($sitemap_types[$variant_definition['type']])) {
        $form_state
          ->setErrorByName('', $this
          ->t("<strong>Line @line</strong>: The variant <em>@name</em> is of a sitemap type <em>@type</em> that does not exist.", $placeholders));
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $manager = $this->generator
      ->getSitemapManager();
    $new_variants = $this
      ->stringToVariants($form_state
      ->getValue('variants'));
    $remove_variants = array_values(array_diff(array_keys($manager
      ->getSitemapVariants(NULL, FALSE)), array_keys($new_variants)));
    $manager
      ->removeSitemapVariants($remove_variants);
    $weight = 0;
    foreach ($new_variants as $variant_name => $variant_definition) {
      $manager
        ->addSitemapVariant($variant_name, $variant_definition + [
        'weight' => $weight,
      ]);
      $weight++;
    }
    parent::submitForm($form, $form_state);

    // Regenerate sitemaps according to user setting.
    if ($form_state
      ->getValue('simple_sitemap_regenerate_now')) {
      $this->generator
        ->setVariants(TRUE)
        ->rebuildQueue()
        ->generateSitemap();
    }
  }

  /**
   * @param $variant_string
   * @return array
   */
  protected function stringToVariants($variant_string) {

    // Unify newline characters and explode into array.
    $variants_string_lines = explode("\n", str_replace("\r\n", "\n", $variant_string));

    // Remove empty values and whitespaces from array.
    $variants_string_lines = array_filter(array_map('trim', $variants_string_lines));
    $variants = [];
    foreach ($variants_string_lines as $i => &$line) {
      $variant_settings = explode('|', $line);
      $name = strtolower(trim($variant_settings[0]));
      $variants[$name]['type'] = !empty($variant_settings[1]) ? trim($variant_settings[1]) : SimplesitemapManager::DEFAULT_SITEMAP_TYPE;
      $variants[$name]['label'] = !empty($variant_settings[2]) ? trim($variant_settings[2]) : $name;
    }
    return $variants;
  }

  /**
   * @param array $variants
   * @return string
   */
  protected function variantsToString(array $variants) {
    $variants_string = '';
    foreach ($variants as $variant_name => $variant_definition) {
      $variants_string .= $variant_name . ' | ' . $variant_definition['type'] . ' | ' . $variant_definition['label'] . "\r\n";
    }
    return $variants_string;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ConfigFormBaseTrait::config protected function Retrieves a configuration object.
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::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.
SimplesitemapFormBase::$formHelper protected property
SimplesitemapFormBase::$generator protected property
SimplesitemapFormBase::create public static function Instantiates a new instance of this class. Overrides ConfigFormBase::create 4
SimplesitemapFormBase::getEditableConfigNames protected function Gets the configuration names that will be editable. Overrides ConfigFormBaseTrait::getEditableConfigNames
SimplesitemapFormBase::__construct public function SimplesitemapFormBase constructor. Overrides ConfigFormBase::__construct 4
SimplesitemapVariantsForm::buildForm public function Form constructor. Overrides ConfigFormBase::buildForm
SimplesitemapVariantsForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
SimplesitemapVariantsForm::stringToVariants protected function
SimplesitemapVariantsForm::submitForm public function Form submission handler. Overrides ConfigFormBase::submitForm
SimplesitemapVariantsForm::validateForm public function @todo Show multiple errors at once. @todo Allow numeric variant names, but bear in mind that they are stored as integer array keys due to how php arrays work. Overrides FormBase::validateForm
SimplesitemapVariantsForm::variantsToString protected function
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.