You are here

abstract class MetaNameBase in Metatag 8

Each meta tag will extend this base.

Hierarchy

Expanded class hierarchy of MetaNameBase

136 files declare their use of MetaNameBase
AbstractTag.php in metatag_dc_advanced/src/Plugin/metatag/Tag/AbstractTag.php
AccessRights.php in metatag_dc_advanced/src/Plugin/metatag/Tag/AccessRights.php
AccrualMethod.php in metatag_dc_advanced/src/Plugin/metatag/Tag/AccrualMethod.php
AccrualPeriodicity.php in metatag_dc_advanced/src/Plugin/metatag/Tag/AccrualPeriodicity.php
AccrualPolicy.php in metatag_dc_advanced/src/Plugin/metatag/Tag/AccrualPolicy.php

... See full list

1 string reference to 'MetaNameBase'
GenerateTagCommand::interact in src/Command/GenerateTagCommand.php

File

src/Plugin/metatag/Tag/MetaNameBase.php, line 13

Namespace

Drupal\metatag\Plugin\metatag\Tag
View source
abstract class MetaNameBase extends PluginBase {
  use StringTranslationTrait;

  /**
   * Machine name of the meta tag plugin.
   *
   * @var string
   */
  protected $id;

  /**
   * Official metatag name.
   *
   * @var string
   */
  protected $name;

  /**
   * The title of the plugin.
   *
   * @var \Drupal\Core\Annotation\Translation
   *
   * @ingroup plugin_translatable
   */
  protected $label;

  /**
   * A longer explanation of what the field is for.
   *
   * @var \Drupal\Core\Annotation\Translation
   *
   * @ingroup plugin_translatable
   */
  protected $description;

  /**
   * The category this meta tag fits in.
   *
   * @var string
   */
  protected $group;

  /**
   * Type of the value being stored.
   *
   * @var string
   */
  protected $type;

  /**
   * True if URL must use HTTPS.
   *
   * @var bool
   */
  protected $secure;

  /**
   * True if more than one is allowed.
   *
   * @var bool
   */
  protected $multiple;

  /**
   * True if the tag should use a text area.
   *
   * @var bool
   */
  protected $long;

  /**
   * True if the URL value(s) must be absolute.
   *
   * @var bool
   */
  protected $absoluteUrl;

  /**
   * Retrieves the currently active request object.
   *
   * @var \Symfony\Component\HttpFoundation\Request
   */
  protected $request;

  /**
   * The value of the metatag in this instance.
   *
   * @var mixed
   */
  protected $value;

  /**
   * The attribute this tag uses for the name.
   *
   * @var string
   */
  protected $nameAttribute = 'name';

  /**
   * {@inheritdoc}
   */
  public function __construct(array $configuration, $plugin_id, array $plugin_definition) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);

    // Set the properties from the annotation.
    // @todo Should we have setProperty() methods for each of these?
    $this->id = $plugin_definition['id'];
    $this->name = $plugin_definition['name'];
    $this->label = $plugin_definition['label'];
    $this->description = $plugin_definition['description'];
    $this->group = $plugin_definition['group'];
    $this->weight = $plugin_definition['weight'];
    $this->type = $plugin_definition['type'];
    $this->secure = $plugin_definition['secure'];
    $this->multiple = $plugin_definition['multiple'];
    $this->long = !empty($plugin_definition['long']);
    $this->absoluteUrl = !empty($plugin_definition['absolute_url']);
    $this->request = \Drupal::request();
  }

  /**
   * Obtain the meta tag's internal ID.
   *
   * @return string
   *   This meta tag's internal ID.
   */
  public function id() {
    return $this->id;
  }

  /**
   * This meta tag's label.
   *
   * @return string
   *   The label.
   */
  public function label() {
    return $this->label;
  }

  /**
   * The meta tag's description.
   *
   * @return bool
   *   This meta tag's description.
   */
  public function description() {
    return $this->description;
  }

  /**
   * The meta tag's machine name.
   *
   * @return string
   *   This meta tag's machine name.
   */
  public function name() {
    return $this->name;
  }

  /**
   * The meta tag group this meta tag belongs to.
   *
   * @return string
   *   The meta tag's group name.
   */
  public function group() {
    return $this->group;
  }

  /**
   * This meta tag's form field's weight.
   *
   * @return int|float
   *   The form API weight for this. May be any number supported by Form API.
   */
  public function weight() {
    return $this->weight;
  }

  /**
   * Obtain this meta tag's type.
   *
   * @return string
   *   This meta tag's type.
   */
  public function type() {
    return $this->type;
  }

  /**
   * Whether or not this meta tag must output secure (HTTPS) URLs.
   *
   * @return bool
   *   Whether or not this meta tag must output secure (HTTPS) URLs.
   */
  public function secure() {
    return $this->secure;
  }

  /**
   * Whether or not this meta tag supports multiple values.
   *
   * @return bool
   *   Whether or not this meta tag supports multiple values.
   */
  public function multiple() {
    return $this->multiple;
  }

  /**
   * Whether or not this meta tag should use a text area.
   *
   * @return bool
   *   Whether or not this meta tag should use a text area.
   */
  public function isLong() {
    return $this->long;
  }

  /**
   * Whether or not this meta tag must output required absolute URLs.
   *
   * @return bool
   *   Whether or not this meta tag must output required absolute URLs.
   */
  public function requiresAbsoluteUrl() {
    return $this->absoluteUrl;
  }

  /**
   * Whether or not this meta tag is active.
   *
   * @return bool
   *   Whether this meta tag has been enabled.
   */
  public function isActive() {
    return TRUE;
  }

  /**
   * Generate a form element for this meta tag.
   *
   * @param array $element
   *   The existing form element to attach to.
   *
   * @return array
   *   The completed form element.
   */
  public function form(array $element = []) {
    $form = [
      '#type' => $this
        ->isLong() ? 'textarea' : 'textfield',
      '#title' => $this
        ->label(),
      '#default_value' => $this
        ->value(),
      '#maxlength' => 1024,
      '#required' => isset($element['#required']) ? $element['#required'] : FALSE,
      '#description' => $this
        ->description(),
      '#element_validate' => [
        [
          get_class($this),
          'validateTag',
        ],
      ],
    ];

    // Optional handling for items that allow multiple values.
    if (!empty($this->multiple)) {
      $form['#description'] .= ' ' . $this
        ->t('Multiple values may be used, separated by a comma. Note: Tokens that return multiple values will be handled automatically.');
    }

    // Optional handling for images.
    if (!empty($this
      ->type()) && $this
      ->type() === 'image') {
      $form['#description'] .= ' ' . $this
        ->t('This will be able to extract the URL from an image field if the field is configured properly.');
    }
    if (!empty($this->absolute_url)) {
      $form['#description'] .= ' ' . $this
        ->t('Any relative or protocol-relative URLs will be converted to absolute URLs.');
    }

    // Optional handling for secure paths.
    if (!empty($this->secure)) {
      $form['#description'] .= ' ' . $this
        ->t('Any URLs which start with "http://" will be converted to "https://".');
    }
    return $form;
  }

  /**
   * Obtain the current meta tag's raw value.
   *
   * @return string
   *   The current raw meta tag value.
   */
  public function value() {
    return $this->value;
  }

  /**
   * Assign the current meta tag a value.
   *
   * @param string $value
   *   The value to assign this meta tag.
   */
  public function setValue($value) {
    $this->value = $value;
  }

  /**
   * Make the string presentable.
   *
   * @param string $value
   *   The raw string to process.
   *
   * @return string
   *   The meta tag value after processing.
   */
  private function tidy($value) {
    return trim($value);
  }

  /**
   * Generate the HTML tag output for a meta tag.
   *
   * @return array|string
   *   A render array or an empty string.
   */
  public function output() {
    if (empty($this->value)) {

      // If there is no value, we don't want a tag output.
      return $this
        ->multiple() ? [] : '';
    }

    // If this contains embedded image tags, extract the image URLs.
    if ($this
      ->type() === 'image') {
      $value = $this
        ->parseImageUrl($this->value);
    }
    else {
      $value = PlainTextOutput::renderFromHtml($this->value);
    }
    $values = $this
      ->multiple() ? explode(',', $value) : [
      $value,
    ];
    $elements = [];
    foreach ($values as $value) {
      $value = $this
        ->tidy($value);
      if ($this
        ->requiresAbsoluteUrl()) {

        // Relative URL.
        if (parse_url($value, PHP_URL_HOST) == NULL) {
          $value = $this->request
            ->getSchemeAndHttpHost() . $value;
        }
        elseif (substr($value, 0, 2) === '//') {
          $value = $this->request
            ->getScheme() . ':' . $value;
        }
      }

      // If tag must be secure, convert all http:// to https://.
      if ($this
        ->secure() && strpos($value, 'http://') !== FALSE) {
        $value = str_replace('http://', 'https://', $value);
      }
      $elements[] = [
        '#tag' => 'meta',
        '#attributes' => [
          $this->nameAttribute => $this->name,
          'content' => $value,
        ],
      ];
    }
    return $this
      ->multiple() ? $elements : reset($elements);
  }

  /**
   * Validates the metatag data.
   *
   * @param array $element
   *   The form element to process.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state.
   */
  public static function validateTag(array &$element, FormStateInterface $form_state) {

    // @todo If there is some common validation, put it here. Otherwise, make
    // it abstract?
  }

  /**
   * Extract any image URLs that might be found in a meta tag.
   *
   * @return string
   *   A comma separated list of any image URLs found in the meta tag's value,
   *   or the original string if no images were identified.
   */
  protected function parseImageUrl($value) {
    global $base_root;

    // If image tag src is relative (starts with /), convert to an absolute
    // link; ignore protocol-relative URLs.
    if (strpos($value, '<img src="/') !== FALSE && strpos($value, '<img src="//') === FALSE) {
      $value = str_replace('<img src="/', '<img src="' . $base_root . '/', $value);
    }
    if ($this
      ->multiple()) {

      // Split the string into an array, remove empty items.
      $values = array_filter(explode(',', $value));
    }
    else {
      $values = [
        $value,
      ];
    }

    // Check through the value(s) to see if there are any image tags.
    foreach ($values as $key => $val) {
      $matches = [];
      preg_match('/src="([^"]*)"/', $val, $matches);
      if (!empty($matches[1])) {
        $values[$key] = $matches[1];
      }
      else {
        $values[$key] = PlainTextOutput::renderFromHtml($val);
      }
    }

    // Make sure there aren't any blank items in the array.
    $values = array_filter($values);

    // Convert the array back into a comma-delimited string before sending it
    // back.
    return implode(',', $values);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
MetaNameBase::$absoluteUrl protected property True if the URL value(s) must be absolute.
MetaNameBase::$description protected property A longer explanation of what the field is for.
MetaNameBase::$group protected property The category this meta tag fits in.
MetaNameBase::$id protected property Machine name of the meta tag plugin.
MetaNameBase::$label protected property The title of the plugin.
MetaNameBase::$long protected property True if the tag should use a text area.
MetaNameBase::$multiple protected property True if more than one is allowed.
MetaNameBase::$name protected property Official metatag name. 1
MetaNameBase::$nameAttribute protected property The attribute this tag uses for the name. 3
MetaNameBase::$request protected property Retrieves the currently active request object.
MetaNameBase::$secure protected property True if URL must use HTTPS.
MetaNameBase::$type protected property Type of the value being stored.
MetaNameBase::$value protected property The value of the metatag in this instance.
MetaNameBase::description public function The meta tag's description.
MetaNameBase::form public function Generate a form element for this meta tag. 6
MetaNameBase::group public function The meta tag group this meta tag belongs to.
MetaNameBase::id public function Obtain the meta tag's internal ID.
MetaNameBase::isActive public function Whether or not this meta tag is active.
MetaNameBase::isLong public function Whether or not this meta tag should use a text area.
MetaNameBase::label public function This meta tag's label.
MetaNameBase::multiple public function Whether or not this meta tag supports multiple values.
MetaNameBase::name public function The meta tag's machine name. 1
MetaNameBase::output public function Generate the HTML tag output for a meta tag. 1
MetaNameBase::parseImageUrl protected function Extract any image URLs that might be found in a meta tag.
MetaNameBase::requiresAbsoluteUrl public function Whether or not this meta tag must output required absolute URLs.
MetaNameBase::secure public function Whether or not this meta tag must output secure (HTTPS) URLs.
MetaNameBase::setValue public function Assign the current meta tag a value. 1
MetaNameBase::tidy private function Make the string presentable.
MetaNameBase::type public function Obtain this meta tag's type.
MetaNameBase::validateTag public static function Validates the metatag data.
MetaNameBase::value public function Obtain the current meta tag's raw value.
MetaNameBase::weight public function This meta tag's form field's weight.
MetaNameBase::__construct public function Constructs a \Drupal\Component\Plugin\PluginBase object. Overrides PluginBase::__construct
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
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::isConfigurable public function Determines if the plugin is configurable.
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.