You are here

class MetatagDisplayExtender in Metatag 8

Metatag display extender plugin.

Plugin annotation


@ViewsDisplayExtender(
  id = "metatag_display_extender",
  title = @Translation("Metatag display extender"),
  help = @Translation("Metatag settings for this view."),
  no_ui = FALSE
)

Hierarchy

Expanded class hierarchy of MetatagDisplayExtender

2 files declare their use of MetatagDisplayExtender
MetatagViewsCacheWrapper.php in metatag_views/src/MetatagViewsCacheWrapper.php
metatag_views.module in metatag_views/metatag_views.module
Contains hook implementations for the metatag_views module.

File

metatag_views/src/Plugin/views/display_extender/MetatagDisplayExtender.php, line 24

Namespace

Drupal\metatag_views\Plugin\views\display_extender
View source
class MetatagDisplayExtender extends DisplayExtenderPluginBase {
  use StringTranslationTrait;

  /**
   * The metatag manager.
   *
   * @var \Drupal\metatag\MetatagManagerInterface
   */
  protected $metatagManager;

  /**
   * The plugin manager for metatag tags.
   *
   * @var \Drupal\metatag\MetatagTagPluginManager
   */
  protected $metatagTagManager;

  /**
   * The first row tokens on the style plugin.
   *
   * @var array
   */
  protected static $firstRowTokens;

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {

    /** @var \Drupal\metatag_views\Plugin\views\display_extender\MetatagDisplayExtender */
    $instance = parent::create($container, $configuration, $plugin_id, $plugin_definition);
    $instance->metatagTagManager = $container
      ->get('plugin.manager.metatag.tag');
    $instance->metatagManager = $container
      ->get('metatag.manager');
    return $instance;
  }
  protected function defineOptions() {
    $options = parent::defineOptions();
    $options['metatags'] = [
      'default' => [],
    ];
    $options['tokenize'] = [
      'default' => FALSE,
    ];
    return $options;
  }

  /**
   * Provide a form to edit options for this plugin.
   */
  public function buildOptionsForm(&$form, FormStateInterface $form_state) {
    if ($form_state
      ->get('section') == 'metatags') {
      $form['#title'] .= $this
        ->t('The meta tags for this display');
      $metatags = $this
        ->getMetatags(TRUE);

      // Build/inject the Metatag form.
      $form['metatags'] = $this->metatagManager
        ->form($metatags, $form, [
        'view',
      ]);
      $this
        ->tokenForm($form['metatags'], $form_state);
    }
  }

  /**
   * Validate the options form.
   */
  public function validateOptionsForm(&$form, FormStateInterface $form_state) {
  }

  /**
   * Handle any special handling on the validate form.
   */
  public function submitOptionsForm(&$form, FormStateInterface $form_state) {
    if ($form_state
      ->get('section') == 'metatags') {

      // Process submitted metatag values and remove empty tags.
      $tag_values = [];
      $metatags = $form_state
        ->cleanValues()
        ->getValues();
      $this->options['tokenize'] = $metatags['tokenize'] ?? FALSE;
      unset($metatags['tokenize']);
      foreach ($metatags as $tag_id => $tag_value) {

        // Some plugins need to process form input before storing it.
        // Hence, we set it and then get it.
        $tag = $this->metatagTagManager
          ->createInstance($tag_id);
        $tag
          ->setValue($tag_value);
        if (!empty($tag
          ->value())) {
          $tag_values[$tag_id] = $tag
            ->value();
        }
      }
      $this->options['metatags'] = $tag_values;
    }
  }

  /**
   * Verbatim copy of TokenizeAreaPluginBase::tokenForm().
   */
  public function tokenForm(&$form, FormStateInterface $form_state) {
    $form['tokenize'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Use replacement tokens from the first row'),
      '#default_value' => $this->options['tokenize'],
    ];

    // Get a list of the available fields and arguments for token replacement.
    $options = [];
    $optgroup_arguments = (string) t('Arguments');
    $optgroup_fields = (string) t('Fields');
    foreach ($this->view->display_handler
      ->getHandlers('field') as $field => $handler) {
      $options[$optgroup_fields]["{{ {$field} }}"] = $handler
        ->adminLabel();
    }
    foreach ($this->view->display_handler
      ->getHandlers('argument') as $arg => $handler) {
      $options[$optgroup_arguments]["{{ arguments.{$arg} }}"] = $this
        ->t('@argument title', [
        '@argument' => $handler
          ->adminLabel(),
      ]);
      $options[$optgroup_arguments]["{{ raw_arguments.{$arg} }}"] = $this
        ->t('@argument input', [
        '@argument' => $handler
          ->adminLabel(),
      ]);
    }
    if (!empty($options)) {
      $form['tokens'] = [
        '#type' => 'details',
        '#title' => $this
          ->t('Replacement patterns'),
        '#open' => TRUE,
        '#id' => 'edit-options-token-help',
        '#states' => [
          'visible' => [
            ':input[name="options[tokenize]"]' => [
              'checked' => TRUE,
            ],
          ],
        ],
      ];
      $form['tokens']['help'] = [
        '#markup' => '<p>' . $this
          ->t('The following tokens are available. You may use Twig syntax in this field.') . '</p>',
      ];
      foreach (array_keys($options) as $type) {
        if (!empty($options[$type])) {
          $items = [];
          foreach ($options[$type] as $key => $value) {
            $items[] = $key . ' == ' . $value;
          }
          $form['tokens'][$type]['tokens'] = [
            '#theme' => 'item_list',
            '#items' => $items,
          ];
        }
      }
    }
    $this
      ->globalTokenForm($form, $form_state);
  }

  /**
   * Set up any variables on the view prior to execution.
   */
  public function preExecute() {
  }

  /**
   * Inject anything into the query that the display_extender handler needs.
   */
  public function query() {
  }

  /**
   * Provide the default summary for options in the views UI.
   *
   * This output is returned as an array.
   */
  public function optionsSummary(&$categories, &$options) {
    $categories['metatags'] = [
      'title' => $this
        ->t('Meta tags'),
      'column' => 'second',
    ];
    $options['metatags'] = [
      'category' => 'metatags',
      'title' => $this
        ->t('Meta tags'),
      'value' => $this
        ->hasMetatags() ? $this
        ->t('Overridden') : $this
        ->t('Using defaults'),
    ];
  }

  /**
   * Lists defaultable sections and items contained in each section.
   */
  public function defaultableSections(&$sections, $section = NULL) {
  }

  /**
   * Identify whether or not the current display has custom meta tags defined.
   *
   * @return bool
   *   Whether or not the view has overridden metatags.
   */
  protected function hasMetatags() {
    $metatags = $this
      ->getMetatags();
    return !empty($metatags);
  }

  /**
   * Get the Metatag configuration for this display.
   *
   * @param bool $raw
   *   TRUE to suppress tokenization.
   *
   * @return array
   *   The meta tag values.
   */
  public function getMetatags($raw = FALSE) {
    $view = $this->view;
    $metatags = [];
    if (!empty($this->options['metatags'])) {
      $metatags = $this->options['metatags'];
    }
    if ($this->options['tokenize'] && !$raw) {
      if (self::$firstRowTokens) {
        self::setFirstRowTokensOnStylePlugin($view, self::$firstRowTokens);
      }

      // This is copied from TokenizeAreaPluginBase::tokenizeValue().
      $style = $view
        ->getStyle();
      foreach ($metatags as $key => $metatag) {
        $metatag = $style
          ->tokenizeValue($metatag, 0);
        $metatags[$key] = $this
          ->globalTokenReplace($metatag);
      }
    }
    return $metatags;
  }

  /**
   * Sets the meta tags for the given view.
   *
   * @param array $metatags
   *   Metatag arrays as suitable for storage.
   */
  public function setMetatags(array $metatags) {
    $this->options['metatags'] = $metatags;
  }

  /**
   * Store first row tokens on the class.
   *
   * metatag_views_metatag_route_entity() loads the View fresh, to avoid
   * rebuilding and re-rendering it, preserve the first row tokens.
   */
  public function setFirstRowTokens(array $first_row_tokens) {
    self::$firstRowTokens = $first_row_tokens;
  }

  /**
   * Set the first row tokens on the style plugin.
   *
   * @param \Drupal\views\ViewExecutable $view
   *   The view.
   * @param array $first_row_tokens
   *   The first row tokens.
   */
  public static function setFirstRowTokensOnStylePlugin(ViewExecutable $view, array $first_row_tokens) {
    $style = $view
      ->getStyle();
    self::getFirstRowTokensReflection($style)
      ->setValue($style, [
      $first_row_tokens,
    ]);
  }

  /**
   * Get the first row tokens from the style plugin.
   *
   * @param \Drupal\views\ViewExecutable $view
   *   The view.
   * @return array
   *   The first row tokens.
   */
  public static function getFirstRowTokensFromStylePlugin(ViewExecutable $view) {
    $style = $view
      ->getStyle();
    return self::getFirstRowTokensReflection($style)
      ->getValue($style)[0] ?? [];
  }

  /**
   * @param \Drupal\views\Plugin\views\style\StylePluginBase $style
   *
   * @return \ReflectionProperty
   */
  protected static function getFirstRowTokensReflection(StylePluginBase $style) : \ReflectionProperty {
    $r = new \ReflectionObject($style);
    $p = $r
      ->getProperty('rowTokens');
    $p
      ->setAccessible(TRUE);
    return $p;
  }

}

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::defineOptionsAlter public function Provide a form to edit options for this plugin.
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
MetatagDisplayExtender::$firstRowTokens protected static property The first row tokens on the style plugin.
MetatagDisplayExtender::$metatagManager protected property The metatag manager.
MetatagDisplayExtender::$metatagTagManager protected property The plugin manager for metatag tags.
MetatagDisplayExtender::buildOptionsForm public function Provide a form to edit options for this plugin. Overrides DisplayExtenderPluginBase::buildOptionsForm
MetatagDisplayExtender::create public static function Creates an instance of the plugin. Overrides PluginBase::create
MetatagDisplayExtender::defaultableSections public function Lists defaultable sections and items contained in each section. Overrides DisplayExtenderPluginBase::defaultableSections
MetatagDisplayExtender::defineOptions protected function Information about options for all kinds of purposes will be held here. @code 'option_name' => array( Overrides PluginBase::defineOptions
MetatagDisplayExtender::getFirstRowTokensFromStylePlugin public static function Get the first row tokens from the style plugin.
MetatagDisplayExtender::getFirstRowTokensReflection protected static function
MetatagDisplayExtender::getMetatags public function Get the Metatag configuration for this display.
MetatagDisplayExtender::hasMetatags protected function Identify whether or not the current display has custom meta tags defined.
MetatagDisplayExtender::optionsSummary public function Provide the default summary for options in the views UI. Overrides DisplayExtenderPluginBase::optionsSummary
MetatagDisplayExtender::preExecute public function Set up any variables on the view prior to execution. Overrides DisplayExtenderPluginBase::preExecute
MetatagDisplayExtender::query public function Inject anything into the query that the display_extender handler needs. Overrides DisplayExtenderPluginBase::query
MetatagDisplayExtender::setFirstRowTokens public function Store first row tokens on the class.
MetatagDisplayExtender::setFirstRowTokensOnStylePlugin public static function Set the first row tokens on the style plugin.
MetatagDisplayExtender::setMetatags public function Sets the meta tags for the given view.
MetatagDisplayExtender::submitOptionsForm public function Handle any special handling on the validate form. Overrides DisplayExtenderPluginBase::submitOptionsForm
MetatagDisplayExtender::tokenForm public function Verbatim copy of TokenizeAreaPluginBase::tokenForm().
MetatagDisplayExtender::validateOptionsForm public function Validate the options form. Overrides DisplayExtenderPluginBase::validateOptionsForm
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::init public function Initialize the plugin. Overrides ViewsPluginInterface::init 8
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::validate public function Validate that the plugin is correct and can be saved. Overrides ViewsPluginInterface::validate 6
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.
PluginBase::__construct public function Constructs a PluginBase object. 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.