DomainSourceToken.php in Domain Access 8
File
domain_source/src/DomainSourceToken.php
View source
<?php
namespace Drupal\domain_source;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Render\BubbleableMetadata;
use Drupal\Core\StringTranslation\StringTranslationTrait;
class DomainSourceToken {
use StringTranslationTrait;
protected $configFactory;
public function __construct(ConfigFactoryInterface $config_factory) {
$this->configFactory = $config_factory;
}
public function getTokenInfo() {
$info['tokens']['node']['canonical-source-domain-url'] = [
'name' => $this
->t('Canonical Source Domain URL'),
'description' => $this
->t("The canonical URL from the source domain for this node."),
'type' => 'node',
];
return $info;
}
public function getTokens($type, $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata) {
$replacements = [];
switch ($type) {
case 'node':
foreach ($tokens as $name => $original) {
if ($name !== 'canonical-source-domain-url') {
continue;
}
if (!empty($data['node'])) {
$node = $data['node'];
$original = $tokens['canonical-source-domain-url'];
if (in_array('canonical', $this
->getExcludedRoutes()) && $node
->hasField('field_domain_source') && !$node->field_domain_source
->isEmpty()) {
$sourceDomain = $node->field_domain_source->entity;
$url = $node
->toUrl('canonical')
->toString();
$replacements[$original] = $sourceDomain
->buildUrl($url);
$bubbleable_metadata
->addCacheableDependency($sourceDomain);
}
else {
$replacements[$original] = $node
->toUrl('canonical')
->setAbsolute()
->toString();
}
}
}
break;
}
return $replacements;
}
public function getExcludedRoutes() {
if (!isset($this->excludedRoutes)) {
$config = $this->configFactory
->get('domain_source.settings');
$routes = $config
->get('exclude_routes');
if (is_array($routes)) {
$this->excludedRoutes = array_flip($routes);
}
else {
$this->excludedRoutes = [];
}
}
return $this->excludedRoutes;
}
}