ExternalHreflang.php in External Hreflang 8
File
src/Plugin/metatag/Tag/ExternalHreflang.php
View source
<?php
namespace Drupal\external_hreflang\Plugin\metatag\Tag;
use Drupal\Core\Form\FormStateInterface;
use Drupal\metatag\Plugin\metatag\Tag\LinkRelBase;
class ExternalHreflang extends LinkRelBase {
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;
}
public function name() {
return 'hreflang';
}
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;
}
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]');
}
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'],
]));
}
}
public static function getHrefLangsArrayFromString(string $value = '') {
$hreflangs = [];
if (empty($value)) {
return $hreflangs;
}
$value = str_replace("\r\n", PHP_EOL, $value);
$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;
}
}