You are here

class SimpleSitemapDisplayExtender in Simple XML sitemap (Views integration) 8

Simple XML Sitemap display extender plugin.

Plugin annotation


@ViewsDisplayExtender(
  id = "simple_sitemap_display_extender",
  title = @Translation("Simple XML Sitemap"),
  help = @Translation("Simple XML Sitemap settings for this view."),
  no_ui = FALSE
)

Hierarchy

Expanded class hierarchy of SimpleSitemapDisplayExtender

1 file declares its use of SimpleSitemapDisplayExtender
SimpleSitemapViews.php in src/SimpleSitemapViews.php
Contains simple_sitemap_views service.

File

src/Plugin/views/display_extender/SimpleSitemapDisplayExtender.php, line 30
Contains Simple XML Sitemap display extender.

Namespace

Drupal\simple_sitemap_views\Plugin\views\display_extender
View source
class SimpleSitemapDisplayExtender extends DisplayExtenderPluginBase {

  /**
   * Simple XML Sitemap form helper.
   *
   * @var \Drupal\simple_sitemap\Form\FormHelper
   */
  protected $formHelper;

  /**
   * Constructs the plugin.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param \Drupal\simple_sitemap\Form\FormHelper $form_helper
   *   Simple XML Sitemap form helper.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, FormHelper $form_helper) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->formHelper = $form_helper;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static($configuration, $plugin_id, $plugin_definition, $container
      ->get('simple_sitemap.form_helper'));
  }

  /**
   * {@inheritdoc}
   */
  public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL) {
    parent::init($view, $display, $options);
    if (!$this
      ->hasSitemapSettings()) {
      $this->options = [];
    }
  }

  /**
   * {@inheritdoc}
   */
  protected function defineOptions() {
    $options = parent::defineOptions();
    $options['index'] = [
      'default' => 0,
    ];
    $options['priority'] = [
      'default' => 0.5,
    ];
    $options['changefreq'] = [
      'default' => '',
    ];
    $options['arguments'] = [
      'default' => [],
    ];
    $options['max_links'] = [
      'default' => 100,
    ];
    return $options;
  }

  /**
   * {@inheritdoc}
   */
  public function buildOptionsForm(&$form, FormStateInterface $form_state) {
    if ($this
      ->hasSitemapSettings() && $form_state
      ->get('section') == 'simple_sitemap') {
      $form['#title'] .= $this
        ->t('Simple XML Sitemap settings for this display');
      $settings = $this
        ->getSitemapSettings();

      // The index section.
      $form['index'] = [
        '#prefix' => '<div class="simple-sitemap-views-index">',
        '#suffix' => '</div>',
      ];

      // Add a checkbox for JS users, which will have behavior attached to it
      // so it can replace the button.
      $form['index']['index'] = [
        '#type' => 'checkbox',
        '#title' => $this
          ->t('Index this display'),
        '#default_value' => $settings['index'],
      ];

      // Then add the button itself.
      $form['index']['index_button'] = [
        '#limit_validation_errors' => [],
        '#type' => 'submit',
        '#value' => $this
          ->t('Index this display'),
        '#submit' => [
          [
            $this,
            'displaySitemapSettingsForm',
          ],
        ],
      ];

      // Show the whole form only if indexing is checked.
      if ($this->options['index']) {

        // Main settings fieldset.
        $form['main'] = [
          '#type' => 'fieldset',
          '#title' => $this
            ->t('Main settings'),
        ];

        // The sitemap priority.
        $form['main']['priority'] = [
          '#type' => 'select',
          '#title' => $this
            ->t('Priority'),
          '#description' => $this
            ->t('The priority displays will have in the eyes of search engine bots.'),
          '#default_value' => $settings['priority'],
          '#options' => $this->formHelper
            ->getPrioritySelectValues(),
        ];

        // The sitemap change frequency.
        $form['main']['changefreq'] = [
          '#type' => 'select',
          '#title' => $this
            ->t('Change frequency'),
          '#description' => $this
            ->t('The frequency with which this display changes. Search engine bots may take this as an indication of how often to index it.'),
          '#default_value' => $settings['changefreq'],
          '#options' => $this->formHelper
            ->getChangefreqSelectValues(),
        ];

        // Argument settings fieldset.
        $form['arguments'] = [
          '#type' => 'fieldset',
          '#title' => $this
            ->t('Argument settings'),
        ];

        // Get view arguments options.
        if ($arguments_options = $this
          ->getArgumentsOptions()) {

          // Indexed arguments element.
          $form['arguments']['arguments'] = [
            '#type' => 'checkboxes',
            '#title' => $this
              ->t('Indexed arguments'),
            '#options' => $arguments_options,
            '#default_value' => $settings['arguments'],
            '#attributes' => [
              'class' => [
                'indexed-arguments',
              ],
            ],
          ];

          // Max links with arguments.
          $form['arguments']['max_links'] = [
            '#type' => 'number',
            '#title' => $this
              ->t('Maximum links in a sitemap'),
            '#description' => $this
              ->t('The maximum number of links with different argument values ​​for this display, which will be included in the sitemap. If left blank, all links will be included in the sitemap. Use with caution, since a large number of argument values ​​can lead to a significant increase in the number of links in the sitemap.'),
            '#default_value' => $settings['max_links'],
            '#min' => 1,
          ];
        }
        else {
          $form['arguments']['#description'] = $this
            ->t('This display has no arguments.');
        }
      }

      // Attaching script to form.
      $form['#attached']['library'][] = 'simple_sitemap_views/views_ui.admin';
    }
  }

  /**
   * {@inheritdoc}
   */
  public function validateOptionsForm(&$form, FormStateInterface $form_state) {
    if ($this
      ->hasSitemapSettings() && $form_state
      ->get('section') == 'simple_sitemap') {

      // Validate indexed arguments.
      $arguments = $form_state
        ->getValue('arguments', []);
      $errors = $this
        ->validateIndexedArguments($arguments);
      foreach ($errors as $message) {
        $form_state
          ->setError($form['arguments']['arguments'], $message);
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitOptionsForm(&$form, FormStateInterface $form_state) {
    if ($this
      ->hasSitemapSettings() && $form_state
      ->get('section') == 'simple_sitemap') {
      $values = $form_state
        ->cleanValues()
        ->getValues();
      $values['arguments'] = isset($values['arguments']) ? array_filter($values['arguments']) : [];

      // Save sitemap settings.
      foreach ($values as $key => $value) {
        if (isset($this->options[$key])) {
          $this->options[$key] = $value;
        }
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public function validate() {
    $errors = parent::validate();

    // Validate the argument options relative to the
    // current state of the view argument handlers.
    if ($this
      ->hasSitemapSettings()) {
      $settings = $this
        ->getSitemapSettings();
      $result = $this
        ->validateIndexedArguments($settings['arguments']);
      $errors = array_merge($errors, $result);
    }
    return $errors;
  }

  /**
   * {@inheritdoc}
   */
  public function optionsSummary(&$categories, &$options) {
    if ($this
      ->hasSitemapSettings()) {
      $categories['simple_sitemap'] = [
        'title' => $this
          ->t('Simple XML Sitemap'),
        'column' => 'second',
      ];
      $options['simple_sitemap'] = [
        'category' => 'simple_sitemap',
        'title' => $this
          ->t('Status'),
        'value' => $this
          ->isIndexingEnabled() ? $this
          ->t('Included in sitemap') : $this
          ->t('Excluded from sitemap'),
      ];
    }
  }

  /**
   * Displays the sitemap settings form.
   *
   * @param array $form
   *   The form structure.
   * @param FormStateInterface $form_state
   *   Current form state.
   */
  public function displaySitemapSettingsForm(array $form, FormStateInterface $form_state) {

    // Update index option.
    $this->options['index'] = empty($this->options['index']);

    // Rebuild settings form.

    /** @var \Drupal\views_ui\ViewUI $view */
    $view = $form_state
      ->get('view');
    $display_handler = $view
      ->getExecutable()->display_handler;
    $extender_options = $display_handler
      ->getOption('display_extenders');
    if (isset($extender_options[$this->pluginId])) {
      $extender_options[$this->pluginId] = $this->options;
      $display_handler
        ->setOption('display_extenders', $extender_options);
    }
    $view
      ->cacheSet();
    $form_state
      ->set('rerender', TRUE);
    $form_state
      ->setRebuild();
  }

  /**
   * Get sitemap settings configuration for this display.
   *
   * @return array
   *   The sitemap settings.
   */
  public function getSitemapSettings() {
    return $this->options;
  }

  /**
   * Identify whether or not the current display has sitemap settings.
   *
   * @return bool
   *   Has sitemap settings (TRUE) or not (FALSE).
   */
  public function hasSitemapSettings() {
    return $this->displayHandler instanceof DisplayRouterInterface;
  }

  /**
   * Identify whether or not the current display indexing is enabled.
   *
   * @return bool
   *   Indexing is enabled (TRUE) or not (FALSE).
   */
  public function isIndexingEnabled() {
    $settings = $this
      ->getSitemapSettings();
    return !empty($settings['index']);
  }

  /**
   * Returns available view arguments options.
   *
   * @return array
   *   View arguments labels keyed by argument ID.
   */
  protected function getArgumentsOptions() {
    $arguments_options = [];

    // Get view argument handlers.
    $arguments = $this->displayHandler
      ->getHandlers('argument');

    /** @var \Drupal\views\Plugin\views\argument\ArgumentPluginBase $argument */
    foreach ($arguments as $id => $argument) {
      $arguments_options[$id] = $argument
        ->adminLabel();
    }
    return $arguments_options;
  }

  /**
   * Validate indexed arguments.
   *
   * @param array $indexed_arguments
   *   Indexed arguments array.
   *
   * @return array
   *   An array of error strings. This will be empty if there are no validation
   *   errors.
   */
  protected function validateIndexedArguments(array $indexed_arguments) {
    $arguments = $this->displayHandler
      ->getHandlers('argument');
    $arguments = array_fill_keys(array_keys($arguments), 0);
    $arguments = array_merge($arguments, $indexed_arguments);
    reset($arguments);
    $errors = [];
    while (($argument = current($arguments)) !== FALSE) {
      $next_argument = next($arguments);
      if (empty($argument) && !empty($next_argument)) {
        $errors[] = $this
          ->t('To enable indexing of an argument, you must enable indexing of all previous arguments.');
        break;
      }
    }
    return $errors;
  }

}

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
DisplayExtenderPluginBase::defaultableSections public function Static member function to list which sections are defaultable and what items each section contains. 1
DisplayExtenderPluginBase::defineOptionsAlter public function Provide a form to edit options for this plugin.
DisplayExtenderPluginBase::preExecute public function Set up any variables on the view prior to execution. 1
DisplayExtenderPluginBase::query public function Inject anything into the query that the display_extender handler needs. Overrides PluginBase::query 1
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$definition public property Plugins's definition
PluginBase::$displayHandler public property The display object this plugin is for.
PluginBase::$options public property Options for this plugin will be held here.
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::$renderer protected property Stores the render API renderer. 3
PluginBase::$usesOptions protected property Denotes whether the plugin has an additional options form. 8
PluginBase::$view public property The top object of a view. 1
PluginBase::calculateDependencies public function Calculates dependencies for the configured plugin. Overrides DependentPluginInterface::calculateDependencies 14
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::destroy public function Clears a plugin. Overrides ViewsPluginInterface::destroy 2
PluginBase::doFilterByDefinedOptions protected function Do the work to filter out stored options depending on the defined options.
PluginBase::filterByDefinedOptions public function Filter out stored options depending on the defined options. Overrides ViewsPluginInterface::filterByDefinedOptions
PluginBase::getAvailableGlobalTokens public function Returns an array of available token replacements. Overrides ViewsPluginInterface::getAvailableGlobalTokens
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 3
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::getProvider public function Returns the plugin provider. Overrides ViewsPluginInterface::getProvider
PluginBase::getRenderer protected function Returns the render API renderer. 1
PluginBase::globalTokenForm public function Adds elements for available core tokens to a form. Overrides ViewsPluginInterface::globalTokenForm
PluginBase::globalTokenReplace public function Returns a string with any core tokens replaced. Overrides ViewsPluginInterface::globalTokenReplace
PluginBase::INCLUDE_ENTITY constant Include entity row languages when listing languages.
PluginBase::INCLUDE_NEGOTIATED constant Include negotiated languages when listing languages.
PluginBase::isConfigurable public function Determines if the plugin is configurable.
PluginBase::listLanguages protected function Makes an array of languages, optionally including special languages.
PluginBase::pluginTitle public function Return the human readable name of the display. Overrides ViewsPluginInterface::pluginTitle
PluginBase::preRenderAddFieldsetMarkup public static function Moves form elements into fieldsets for presentation purposes. Overrides ViewsPluginInterface::preRenderAddFieldsetMarkup
PluginBase::preRenderFlattenData public static function Flattens the structure of form elements. Overrides ViewsPluginInterface::preRenderFlattenData
PluginBase::queryLanguageSubstitutions public static function Returns substitutions for Views queries for languages.
PluginBase::setOptionDefaults protected function Fills up the options of the plugin with defaults.
PluginBase::summaryTitle public function Returns the summary of the settings in the display. Overrides ViewsPluginInterface::summaryTitle 6
PluginBase::themeFunctions public function Provide a full list of possible theme templates used by this style. Overrides ViewsPluginInterface::themeFunctions 1
PluginBase::trustedCallbacks public static function Lists the trusted callbacks provided by the implementing class. Overrides TrustedCallbackInterface::trustedCallbacks 6
PluginBase::unpackOptions public function Unpack options over our existing defaults, drilling down into arrays so that defaults don't get totally blown away. Overrides ViewsPluginInterface::unpackOptions
PluginBase::usesOptions public function Returns the usesOptions property. Overrides ViewsPluginInterface::usesOptions 8
PluginBase::viewsTokenReplace protected function Replaces Views' tokens in a given string. The resulting string will be sanitized with Xss::filterAdmin. 1
PluginBase::VIEWS_QUERY_LANGUAGE_SITE_DEFAULT constant Query string to indicate the site default language.
SimpleSitemapDisplayExtender::$formHelper protected property Simple XML Sitemap form helper.
SimpleSitemapDisplayExtender::buildOptionsForm public function Provide a form to edit options for this plugin. Overrides DisplayExtenderPluginBase::buildOptionsForm
SimpleSitemapDisplayExtender::create public static function Creates an instance of the plugin. Overrides PluginBase::create
SimpleSitemapDisplayExtender::defineOptions protected function Information about options for all kinds of purposes will be held here. Overrides PluginBase::defineOptions
SimpleSitemapDisplayExtender::displaySitemapSettingsForm public function Displays the sitemap settings form.
SimpleSitemapDisplayExtender::getArgumentsOptions protected function Returns available view arguments options.
SimpleSitemapDisplayExtender::getSitemapSettings public function Get sitemap settings configuration for this display.
SimpleSitemapDisplayExtender::hasSitemapSettings public function Identify whether or not the current display has sitemap settings.
SimpleSitemapDisplayExtender::init public function Initialize the plugin. Overrides PluginBase::init
SimpleSitemapDisplayExtender::isIndexingEnabled public function Identify whether or not the current display indexing is enabled.
SimpleSitemapDisplayExtender::optionsSummary public function Provide the default summary for options in the views UI. Overrides DisplayExtenderPluginBase::optionsSummary
SimpleSitemapDisplayExtender::submitOptionsForm public function Handle any special handling on the validate form. Overrides DisplayExtenderPluginBase::submitOptionsForm
SimpleSitemapDisplayExtender::validate public function Validate that the plugin is correct and can be saved. Overrides PluginBase::validate
SimpleSitemapDisplayExtender::validateIndexedArguments protected function Validate indexed arguments.
SimpleSitemapDisplayExtender::validateOptionsForm public function Validate the options form. Overrides DisplayExtenderPluginBase::validateOptionsForm
SimpleSitemapDisplayExtender::__construct public function Constructs the plugin. Overrides PluginBase::__construct
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.
TrustedCallbackInterface::THROW_EXCEPTION constant Untrusted callbacks throw exceptions.
TrustedCallbackInterface::TRIGGER_SILENCED_DEPRECATION constant Untrusted callbacks trigger silenced E_USER_DEPRECATION errors.
TrustedCallbackInterface::TRIGGER_WARNING constant Untrusted callbacks trigger E_USER_WARNING errors.