View source
<?php
namespace Drupal\formatter_suite\Plugin\Field\FieldFormatter;
use Drupal\Component\Render\FormattableMarkup;
use Drupal\Component\Utility\Xss;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Config\Config;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\Plugin\Field\FieldFormatter\EntityReferenceFormatterBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Utility\Token;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\formatter_suite\Branding;
class GeneralUserReferenceFormatter extends EntityReferenceFormatterBase {
protected $tokenTreeBuilder;
protected $tokenService;
protected $userSettings;
public function __construct($pluginId, $pluginDefinition, FieldDefinitionInterface $fieldDefinition, array $settings, $label, $viewMode, array $thirdPartySettings, Token $tokenService, $tokenTreeBuilder, Config $userSettings) {
parent::__construct($pluginId, $pluginDefinition, $fieldDefinition, $settings, $label, $viewMode, $thirdPartySettings);
$this->tokenService = $tokenService;
$this->tokenTreeBuilder = $tokenTreeBuilder;
$this->userSettings = $userSettings;
}
public static function create(ContainerInterface $container, array $configuration, $pluginId, $pluginDefinition) {
$tokenService = NULL;
try {
$tokenService = $container
->get('token');
} catch (\Exception $e) {
}
$tokenTreeBuilder = NULL;
try {
$tokenTreeBuilder = $container
->get('token.tree_builder');
} catch (\Exception $e) {
}
$userSettings = NULL;
try {
$userSettings = $container
->get('config.factory')
->get('user.settings');
} catch (\Exception $e) {
}
return new static($pluginId, $pluginDefinition, $configuration['field_definition'], $configuration['settings'], $configuration['label'], $configuration['view_mode'], $configuration['third_party_settings'], $tokenService, $tokenTreeBuilder, $userSettings);
}
protected static function getUserReferenceStyles() {
return [
'id' => t("User's ID"),
'email' => t("User's email address"),
'account' => t("User's account name"),
'account-id' => t("User's account name and ID"),
'account-email' => t("User's account name and email address"),
'account-display' => t("User's account and display names"),
'account-roles' => t("User's account name and roles"),
'account-last' => t("User's account name and last login date"),
'account-since' => t("User's account name and account creation date"),
'display' => t("User's display name"),
'display-id' => t("User's display name and ID"),
'display-email' => t("User's display name and email address"),
'display-account' => t("User's display and account names"),
'display-roles' => t("User's display name and roles"),
'display-last' => t("User's display name and last login date"),
'display-since' => t("User's display name and account creation date"),
'custom' => t('Custom'),
];
}
protected static function getUserReferenceTokenPatterns() {
$last = (string) t('Last login');
$since = (string) t('Since');
return [
'id' => '[user:uid]',
'email' => '[user:mail]',
'account' => '[user:account-name]',
'account-id' => '[user:account-name] ([user:uid])',
'account-email' => '[user:account-name] <[user:mail]>',
'account-display' => '[user:account-name] ([user:display-name])',
'account-roles' => '[user:account-name] ([user:roles])',
'account-last' => '[user:account-name] (' . $last . ' [user:last-login])',
'account-since' => '[user:account-name] (' . $since . ' [user:created])',
'display' => '[user:display-name]',
'display-id' => '[user:display-name] ([user:uid])',
'display-email' => '[user:display-name] <[user:mail]>',
'display-account' => '[user:display-name] ([user:account-name])',
'display-roles' => '[user:display-name] ([user:roles])',
'display-last' => '[user:display-name] (' . $last . ' [user:last-login])',
'display-since' => '[user:display-name] (' . $since . ' [user:created])',
];
}
protected static function getOpenLinkInValues() {
return [
'_self' => t('Open linked entity in the same tab/window'),
'_blank' => t('Open linked entity in a new tab/window'),
'download' => t('Download the linked entity'),
];
}
protected static function getLinkTopicValues() {
return [
'any' => t('- Unspecified -'),
'alternate' => t('Alternate form of this entity'),
'author' => t('Author information'),
'canonical' => t('Canonical (preferred) form of this entity'),
];
}
protected static function getListStyles() {
return [
'span' => t('Single line list'),
'ol' => t('Numbered list'),
'ul' => t('Bulleted list'),
'div' => t('Non-bulleted block list'),
];
}
public static function defaultSettings() {
return array_merge([
'userReferenceStyle' => 'display',
'titleCustomText' => '',
'classes' => '',
'showLink' => TRUE,
'openLinkIn' => '_self',
'linkTopic' => 'any',
'listStyle' => 'span',
'listSeparator' => ', ',
], parent::defaultSettings());
}
public function settingsSummary() {
$this
->sanitizeSettings();
$isMultiple = $this->fieldDefinition
->getFieldStorageDefinition()
->isMultiple();
$summary = [];
$styles = self::getUserReferenceStyles();
$style = $this
->getSetting('userReferenceStyle');
if (isset($styles[$style]) === TRUE) {
$summary[] = $styles[$style];
}
else {
$summary[] = $this
->t("Unknown style");
}
if ($this
->getSetting('showLink') === FALSE) {
$summary[] = $this
->t('No link');
}
else {
switch ($this
->getSetting('openLinkIn')) {
case '_self':
$summary[] = $this
->t('Open in current tab/window');
break;
case '_blank':
$summary[] = $this
->t('Open in new tab/window');
break;
case 'download':
$summary[] = $this
->t('Download');
break;
}
}
if ($isMultiple === TRUE) {
$listStyles = self::getListStyles();
$listStyle = $this
->getSetting('listStyle');
$listSeparator = $this
->getSetting('listSeparator');
$text = $listStyles[$listStyle];
if ($listStyle === 'span' && empty($listSeparator) === FALSE) {
$text .= $this
->t(', with separator');
}
$summary[] = $text;
}
return $summary;
}
protected function getDescription() {
$isMultiple = $this->fieldDefinition
->getFieldStorageDefinition()
->isMultiple();
if ($isMultiple === TRUE) {
return $this
->t("Format field values as links that show the user's ID, account or display name, email address, and other options. Multiple field values are shown as a list on one line, bulleted, numbered, or in blocks.");
}
return $this
->t("Format a field as a link that shows the user's ID, account or display name, email address, and other options.");
}
public function settingsForm(array $form, FormStateInterface $formState) {
$this
->sanitizeSettings();
$isMultiple = $this->fieldDefinition
->getFieldStorageDefinition()
->isMultiple();
$marker = rand();
$elements = parent::settingsForm($form, $formState);
$elements = Branding::addFieldFormatterBranding($elements);
$elements['#attached']['library'][] = 'formatter_suite/formatter_suite.fieldformatter';
$elements['description'] = [
'#type' => 'html_tag',
'#tag' => 'div',
'#value' => $this
->getDescription(),
'#weight' => -1000,
'#attributes' => [
'class' => [
'formatter_suite-settings-description',
],
],
];
$weight = 0;
$elements['userReferenceStyle'] = [
'#title' => $this
->t('Link title'),
'#type' => 'select',
'#options' => self::getUserReferenceStyles(),
'#default_value' => $this
->getSetting('userReferenceStyle'),
'#weight' => $weight++,
'#wrapper_attributes' => [
'class' => [
'formatter_suite-general-user-reference-style',
],
],
'#attributes' => [
'class' => [
'userReferenceStyle-' . $marker,
],
],
];
$tokenUi = '';
if ($this->tokenTreeBuilder !== NULL) {
try {
$tokenUi = $this->tokenTreeBuilder
->buildRenderable([
'user',
], [
'global_types' => FALSE,
'click_insert' => TRUE,
'show_restricted' => FALSE,
'show_nested' => TRUE,
]);
} catch (\Exception $e) {
}
}
$elements['titleCustomText'] = [
'#title' => $this
->t('Custom text'),
'#type' => 'textfield',
'#size' => 10,
'#default_value' => $this
->getSetting('titleCustomText'),
'#description' => $tokenUi,
'#weight' => $weight++,
'#wrapper_attributes' => [
'class' => [
'formatter_suite-general-user-reference-title-custom-text',
],
],
'#states' => [
'visible' => [
'.userReferenceStyle-' . $marker => [
'value' => 'custom',
],
],
],
];
$elements['sectionBreak1'] = [
'#markup' => '<div class="formatter_suite-section-break"></div>',
'#weight' => $weight++,
];
$elements['classes'] = [
'#title' => $this
->t('Custom classes'),
'#type' => 'textfield',
'#size' => 10,
'#default_value' => $this
->getSetting('classes'),
'#weight' => $weight++,
'#attributes' => [
'autocomplete' => 'off',
'autocapitalize' => 'none',
'spellcheck' => 'false',
'autocorrect' => 'off',
],
'#wrapper_attributes' => [
'class' => [
'formatter_suite-general-user-reference-classes',
],
],
];
$elements['sectionBreak2'] = [
'#markup' => '<div class="formatter_suite-section-break"></div>',
'#weight' => $weight++,
];
$elements['showLink'] = [
'#title' => $this
->t('Link to the entity'),
'#type' => 'checkbox',
'#default_value' => $this
->getSetting('showLink'),
'#weight' => $weight++,
'#wrapper_attributes' => [
'class' => [
'formatter_suite-general-user-reference-show-link',
],
],
'#attributes' => [
'class' => [
'showLink-' . $marker,
],
],
];
$elements['openLinkIn'] = [
'#title' => $this
->t('Use link to'),
'#type' => 'select',
'#options' => self::getOpenLinkInValues(),
'#default_value' => $this
->getSetting('openLinkIn'),
'#weight' => $weight++,
'#wrapper_attributes' => [
'class' => [
'formatter_suite-general-user-reference-open-link-in',
],
],
'#states' => [
'visible' => [
'.showLink-' . $marker => [
'checked' => TRUE,
],
],
],
];
$elements['linkTopic'] = [
'#title' => $this
->t('Annotate link as'),
'#type' => 'select',
'#options' => self::getLinkTopicValues(),
'#default_value' => $this
->getSetting('linkTopic'),
'#weight' => $weight++,
'#wrapper_attributes' => [
'class' => [
'formatter_suite-general-user-reference-link-topic',
],
],
'#states' => [
'visible' => [
'.showLink-' . $marker => [
'checked' => TRUE,
],
],
],
];
if ($isMultiple === TRUE) {
$elements['sectionBreak3'] = [
'#markup' => '<div class="formatter_suite-section-break"></div>',
'#weight' => $weight++,
];
$elements['listStyle'] = [
'#title' => $this
->t('List style'),
'#type' => 'select',
'#options' => self::getListStyles(),
'#default_value' => $this
->getSetting('listStyle'),
'#weight' => $weight++,
'#wrapper_attributes' => [
'class' => [
'formatter_suite-general-user-reference-list-style',
],
],
'#attributes' => [
'class' => [
'listStyle-' . $marker,
],
],
];
$elements['listSeparator'] = [
'#title' => $this
->t('Separator'),
'#type' => 'textfield',
'#size' => 10,
'#default_value' => $this
->getSetting('listSeparator'),
'#weight' => $weight++,
'#attributes' => [
'autocomplete' => 'off',
'autocapitalize' => 'none',
'spellcheck' => 'false',
'autocorrect' => 'off',
],
'#wrapper_attributes' => [
'class' => [
'formatter_suite-general-user-reference-list-separator',
],
],
'#states' => [
'visible' => [
'.listStyle-' . $marker => [
'value' => 'span',
],
],
],
];
}
return $elements;
}
protected function sanitizeSettings() {
$userReferenceStyle = $this
->getSetting('userReferenceStyle');
$showLink = $this
->getSetting('showLink');
$openLinkIn = $this
->getSetting('openLinkIn');
$linkTopic = $this
->getSetting('linkTopic');
$isMultiple = $this->fieldDefinition
->getFieldStorageDefinition()
->isMultiple();
$defaults = self::defaultSettings();
$userReferenceStyles = $this
->getUserReferenceStyles();
if (empty($userReferenceStyle) === TRUE || isset($userReferenceStyles[$userReferenceStyle]) === FALSE) {
$userReferenceStyle = $defaults['userReferenceStyle'];
$this
->setSetting('userReferenceStyle', $userReferenceStyle);
}
$openLinkInValues = self::getOpenLinkInValues();
if (empty($openLinkIn) === TRUE || isset($openLinkInValues[$openLinkIn]) === FALSE) {
$openLinkIn = $defaults['openLinkIn'];
$this
->setSetting('openLinkIn', $openLinkIn);
}
$linkTopicValues = self::getLinkTopicValues();
if (empty($linkTopic) === TRUE || isset($linkTopicValues[$linkTopic]) === FALSE) {
$linkTopic = $defaults['linkTopic'];
$this
->setSetting('linkTopic', $linkTopic);
}
$showLink = boolval($showLink);
$this
->setSetting('showLink', $showLink);
$listStyle = $this
->getSetting('listStyle');
$listStyles = self::getListStyles();
if ($isMultiple === TRUE) {
if (empty($listStyle) === TRUE || isset($listStyles[$listStyle]) === FALSE) {
$listStyle = $defaults['listStyle'];
$this
->setSetting('listStyle', $listStyle);
}
}
}
public static function isApplicable(FieldDefinitionInterface $def) {
$target = $def
->getFieldStorageDefinition()
->getSetting('target_type');
return $target === 'user';
}
protected function checkAccess(EntityInterface $entity) {
switch ($this
->getSetting('userReferenceStyle')) {
case 'id':
return AccessResult::allowed();
default:
return $entity
->access('view label', NULL, TRUE);
}
}
protected function replaceTokensForAnonymous(string $pattern) {
$pattern = mb_ereg_replace('\\[user:created.*\\]', (string) $this
->t('site creation'), $pattern);
$pattern = mb_ereg_replace('\\[user:last-login.*\\]', (string) $this
->t('never'), $pattern);
$pattern = mb_ereg_replace('\\[user:user_picture.*\\]', '', $pattern);
$pattern = mb_ereg_replace('\\[user:url.*\\]', '', $pattern);
return str_replace([
'[user:uid]',
'[user:account-name]',
'[user:display-name]',
'[user:name]',
'[user:mail]',
'[user:edit-url]',
'[user:cancel-url]',
'[user:one-time-login-url]',
], [
0,
'anonymous',
$this->userSettings
->get('anonymous'),
'anonymous',
$this
->t('None'),
'',
'',
'',
], $pattern);
}
public function viewElements(FieldItemListInterface $items, $langcode) {
$this
->sanitizeSettings();
$elements = [];
$entities = $this
->getEntitiesToView($items, $langcode);
if (empty($entities) === TRUE) {
return [];
}
$classes = $this
->getSetting('classes');
if (empty($classes) === TRUE) {
$classes = [];
}
else {
$classes = strip_tags($classes);
$classes = mb_ereg_replace('[^_a-zA-Z0-9- ]', '', $classes);
if ($classes === FALSE) {
$classes = [];
}
$classes = explode(' ', $classes);
}
$userReferenceStyle = $this
->getSetting('userReferenceStyle');
if ($userReferenceStyle === 'custom') {
$pattern = $this
->getSetting('titleCustomText');
if (empty($pattern) === TRUE) {
$pattern = '[user:uid]';
}
else {
$pattern = Xss::filterAdmin($this
->getSetting('titleCustomText'));
}
}
else {
$userReferencePatterns = self::getUserReferenceTokenPatterns();
$pattern = $userReferencePatterns[$userReferenceStyle];
}
foreach ($entities as $delta => &$entity) {
$url = NULL;
if ($entity
->isAnonymous() === FALSE) {
$url = $entity
->toUrl();
$urlOptions = $url
->getOptions();
}
$title = '';
if ($entity
->isAnonymous() === TRUE) {
$updatedPattern = $this
->replaceTokensForAnonymous($pattern);
}
else {
$updatedPattern = $pattern;
}
$title = $this->tokenService
->replace($updatedPattern, [
'user' => $entity,
], [
'langcode' => $langcode,
'clear' => TRUE,
]);
$title = new FormattableMarkup($title, []);
if ($this
->getSetting('showLink') === FALSE || $url === NULL) {
$elements[$delta] = [
'#type' => 'html_tag',
'#tag' => 'span',
'#value' => $title,
'#attributes' => [
'class' => $classes,
],
'#cache' => [
'tags' => $entity
->getCacheTags(),
],
];
}
else {
$rel = '';
$target = '';
$download = FALSE;
switch ($this
->getSetting('openLinkIn')) {
case '_self':
$target = '_self';
break;
case '_blank':
$target = '_blank';
break;
case 'download':
$download = TRUE;
break;
}
$topic = $this
->getSetting('linkTopic');
if ($topic !== 'any') {
$rel .= $topic;
}
if (empty($rel) === FALSE) {
$urlOptions['attributes']['rel'] = $rel;
}
if (empty($target) === FALSE) {
$urlOptions['attributes']['target'] = $target;
}
if ($download === TRUE) {
$urlOptions['attributes']['download'] = '';
}
$url
->setOptions($urlOptions);
$elements[$delta] = [
'#type' => 'link',
'#title' => $title,
'#options' => $url
->getOptions(),
'#url' => $url,
'#attributes' => [
'class' => $classes,
],
'#cache' => [
'tags' => $entity
->getCacheTags(),
],
];
if (empty($items[$delta]->_attributes) === FALSE) {
$elements[$delta]['#options'] += [
'attributes' => $items[$delta]->_attributes,
];
unset($items[$delta]->_attributes);
}
}
}
if (empty($elements) === TRUE) {
return [];
}
$isMultiple = $this->fieldDefinition
->getFieldStorageDefinition()
->isMultiple();
if ($isMultiple === TRUE) {
$elements['#theme'] = 'formatter_suite_field_list';
$elements['#list_style'] = $this
->getSetting('listStyle');
$listSeparator = Xss::filterAdmin($this
->getSetting('listSeparator'));
$elements['#list_separator'] = new FormattableMarkup($listSeparator, []);
}
return $elements;
}
}