View source
<?php
namespace Drupal\freelinking\Plugin\freelinking;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Url;
use Drupal\freelinking\Plugin\FreelinkingPluginBase;
use Drupal\path_alias\AliasManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class PathAlias extends FreelinkingPluginBase implements ContainerFactoryPluginInterface {
protected $moduleHandler;
protected $aliasManager;
public function __construct(array $configuration, $plugin_id, $plugin_definition, ModuleHandlerInterface $moduleHandler, AliasManagerInterface $aliasManager) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->moduleHandler = $moduleHandler;
$this->aliasManager = $aliasManager;
}
public function getIndicator() {
return '/path|alias/i';
}
public function getTip() {
return $this
->t('Click to view a local node.');
}
public function defaultConfiguration() {
return parent::defaultConfiguration() + [
'settings' => [
'failover' => 'search',
],
];
}
public function settingsForm(array $form, FormStateInterface $form_state) {
$element['failover'] = [
'#type' => 'select',
'#title' => $this
->t('If path alias is not found'),
'#description' => $this
->t('What should freelinking do when the page is not found?'),
'#options' => [
'error' => $this
->t('Insert an error message'),
],
];
if ($this->moduleHandler
->moduleExists('search')) {
$element['failover']['#options']['search'] = $this
->t('Add link to search content');
}
return $element;
}
public function buildLink(array $target) {
$failover = $this
->getConfiguration()['settings']['failover'];
$alias = strpos('/', $target['dest']) === 0 ? $target['dest'] : '/' . $target['dest'];
$langcode = isset($target['language']) ? $target['language']
->getId() : NULL;
$path = $this->aliasManager
->getPathByAlias($alias, $langcode);
if ($path !== $alias) {
$link = [
'#type' => 'link',
'#title' => $target['text'],
'#url' => Url::fromUserInput($path, [
'language' => $target['language'],
]),
'#attributes' => [
'title' => isset($target['tooltip']) ? $target['tooltip'] : $this
->getTip(),
],
];
}
elseif ($failover === 'search' && $this->moduleHandler
->moduleExists('search')) {
$link = [
'#type' => 'link',
'#title' => $target['text'],
'#url' => Url::fromUserInput('/search', [
'query' => [
'keys' => $path,
],
'language' => $target['language'],
]),
'#attributes' => [
'title' => $this
->getTip(),
],
];
}
else {
$link = [
'#theme' => 'freelink_error',
'#plugin' => 'path_alias',
'#message' => $this
->t('path “%path” not found', [
'%path' => $path,
]),
];
}
return $link;
}
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static($configuration, $plugin_id, $plugin_definition, $container
->get('module_handler'), $container
->get('path_alias.manager'));
}
}