View source
<?php
namespace Drupal\views\Plugin\views\field;
use Drupal\Core\Access\AccessManagerInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\BubbleableMetadata;
use Drupal\Core\Routing\RedirectDestinationTrait;
use Drupal\views\ResultRow;
use Symfony\Component\DependencyInjection\ContainerInterface;
abstract class LinkBase extends FieldPluginBase {
use RedirectDestinationTrait;
protected $accessManager;
protected $currentUser;
public function __construct(array $configuration, $plugin_id, $plugin_definition, AccessManagerInterface $access_manager) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->accessManager = $access_manager;
}
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static($configuration, $plugin_id, $plugin_definition, $container
->get('access_manager'));
}
protected function currentUser() {
if (!$this->currentUser) {
$this->currentUser = \Drupal::currentUser();
}
return $this->currentUser;
}
protected function defineOptions() {
$options = parent::defineOptions();
$options['text'] = array(
'default' => $this
->getDefaultLabel(),
);
return $options;
}
public function buildOptionsForm(&$form, FormStateInterface $form_state) {
$form['text'] = [
'#type' => 'textfield',
'#title' => $this
->t('Text to display'),
'#default_value' => $this->options['text'],
];
parent::buildOptionsForm($form, $form_state);
$form['alter'] += [
'path' => [],
'query' => [],
'external' => [],
];
$form['alter']['path'] += [
'#access' => FALSE,
];
$form['alter']['query'] += [
'#access' => FALSE,
];
$form['alter']['external'] += [
'#access' => FALSE,
];
}
public function usesGroupBy() {
return FALSE;
}
public function query() {
$this
->addAdditionalFields();
}
public function render(ResultRow $row) {
$access = $this
->checkUrlAccess($row);
$build = [
'#markup' => $access
->isAllowed() ? $this
->renderLink($row) : '',
];
BubbleableMetadata::createFromObject($access)
->applyTo($build);
return $build;
}
protected function checkUrlAccess(ResultRow $row) {
$url = $this
->getUrlInfo($row);
return $this->accessManager
->checkNamedRoute($url
->getRouteName(), $url
->getRouteParameters(), $this
->currentUser(), TRUE);
}
protected abstract function getUrlInfo(ResultRow $row);
protected function renderLink(ResultRow $row) {
$this->options['alter']['make_link'] = TRUE;
$this->options['alter']['url'] = $this
->getUrlInfo($row);
$text = !empty($this->options['text']) ? $this
->sanitizeValue($this->options['text']) : $this
->getDefaultLabel();
$this
->addLangcode($row);
return $text;
}
protected function addLangcode(ResultRow $row) {
$entity = $this
->getEntity($row);
$langcode_key = $entity ? $entity
->getEntityType()
->getKey('langcode') : FALSE;
if ($langcode_key && isset($this->aliases[$langcode_key])) {
$this->options['alter']['language'] = $entity
->language();
}
}
protected function getDefaultLabel() {
return $this
->t('link');
}
}