You are here

class ExternalHreflang in External Hreflang 8

A new hreflang tag will be made available for each language.

The meta tag's values will be based upon this annotation.

Plugin annotation


@MetatagTag(
  id = "hreflang_external",
  label = @Translation("External Hreflang"),
  description = @Translation("This plugin will be cloned from these settings for each enabled language."),
  name = "hreflang_external",
  group = "advanced",
  weight = 10,
  type = "string",
  secure = FALSE,
  multiple = TRUE
)

Hierarchy

Expanded class hierarchy of ExternalHreflang

1 file declares its use of ExternalHreflang
external_hreflang.module in ./external_hreflang.module
Module file.

File

src/Plugin/metatag/Tag/ExternalHreflang.php, line 25

Namespace

Drupal\external_hreflang\Plugin\metatag\Tag
View source
class ExternalHreflang extends LinkRelBase {

  /**
   * {@inheritdoc}
   */
  public function output() {
    $elements = [];
    try {
      $value = $this
        ->value() ?? '';
      $hreflangs = self::getHrefLangsArrayFromString($value);
    } catch (\Exception $e) {
      \Drupal::logger('ExternalHreflang')
        ->warning($this
        ->t('Invalid value found in hreflang_external metatag.'));
    }
    foreach ($hreflangs ?? [] as $hreflang => $link) {
      $element = [];
      $element['#tag'] = 'link';
      $element['#attributes'] = [
        'rel' => 'alternate',
        'hreflang' => $hreflang,
        'href' => $link,
      ];
      $elements[] = $element;
    }
    return $elements;
  }

  /**
   * {@inheritdoc}
   */
  public function name() {
    return 'hreflang';
  }

  /**
   * {@inheritdoc}
   */
  public function form(array $element = []) {
    $form = [
      '#type' => 'textarea',
      '#title' => $this
        ->label(),
      '#default_value' => $this
        ->value(),
      '#required' => isset($element['#required']) ? $element['#required'] : FALSE,
      '#description' => $this
        ->description(),
      '#element_validate' => [
        [
          get_class($this),
          'validateTag',
        ],
      ],
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function description() {
    return $this
      ->t('Enter one link per hreflang, each separated by pipe (|) for code and url. Example: en-us|https://us.site.com/en[current-page:url:relative:en]');
  }

  /**
   * {@inheritdoc}
   */
  public static function validateTag(array &$element, FormStateInterface $form_state) {
    $value = $form_state
      ->getValue($element['#parents']) ?? '';
    try {
      self::getHrefLangsArrayFromString($value);
    } catch (\Exception $e) {
      $form_state
        ->setError($element, t('Invalid value in @name', [
        '@name' => $element['#title'],
      ]));
    }
  }

  /**
   * Convert string data from metatag to href langs array.
   *
   * @param string $value
   *   Value.
   *
   * @return array
   *   Array of Href Langs.
   *
   * @throws \Exception
   */
  public static function getHrefLangsArrayFromString(string $value = '') {
    $hreflangs = [];

    // Do nothing if empty.
    if (empty($value)) {
      return $hreflangs;
    }

    // Ensure we always have PHP_EOL as line separator.
    $value = str_replace("\r\n", PHP_EOL, $value);

    // Explode lines to get one array item per link.
    $value = array_filter(explode(PHP_EOL, $value));
    if (!is_array($value) || count($value) == 0) {
      throw new \Exception('Invalid value');
    }
    foreach ($value as $hreflang) {
      $hreflang = array_filter(explode('|', $hreflang));
      if (count($hreflang) !== 2) {
        throw new \Exception('Invalid value');
      }
      $hreflangs[$hreflang[0]] = $hreflang[1];
    }
    return $hreflangs;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ExternalHreflang::description public function The meta tag's description. Overrides MetaNameBase::description
ExternalHreflang::form public function Generate a form element for this meta tag. Overrides MetaNameBase::form
ExternalHreflang::getHrefLangsArrayFromString public static function Convert string data from metatag to href langs array.
ExternalHreflang::name public function The meta tag's machine name. Overrides MetaNameBase::name
ExternalHreflang::output public function Generate the HTML tag output for a meta tag. Overrides LinkRelBase::output
ExternalHreflang::validateTag public static function Validates the metatag data. Overrides MetaNameBase::validateTag
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::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::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::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.