first commit

This commit is contained in:
2024-07-15 12:33:27 +02:00
commit ce50ae282b
22084 changed files with 2623791 additions and 0 deletions

View File

@@ -0,0 +1,9 @@
/*
* DO NOT EDIT THIS FILE.
* See the following change record for more information,
* https://www.drupal.org/node/3084859
* @preserve
*/
.field-icon-link {
background-image: url("data:image/svg+xml,%3csvg height='38' viewBox='0 0 38 38' width='38' xmlns='http://www.w3.org/2000/svg'%3e%3cpath d='m25.84 2.37c-1.972.311-3.605 1.099-5.162 2.493-1.157 1.035-3.04 2.995-3.221 3.353a1.34 1.34 0 0 0 -.018 1.252c.193.415.819.997 1.219 1.133.798.272 1.01.143 2.997-1.818.891-.88 1.734-1.688 1.873-1.796.678-.523 1.686-.971 2.555-1.135.663-.125 2.055-.089 2.622.068 1.75.484 3.119 1.611 3.911 3.219.493.999.595 1.459.593 2.673-.002 1.102-.093 1.593-.444 2.395-.437.998-.716 1.326-3.528 4.137-1.468 1.467-2.844 2.795-3.058 2.951-1.167.846-2.819 1.293-4.162 1.126a6.606 6.606 0 0 1 -2.194-.674c-.836-.445-1.081-.654-2.231-1.909-.385-.42-.706-.585-1.139-.584-.431.001-.898.215-1.313.604-.579.541-.721 1.135-.423 1.773.157.339.916 1.282 1.378 1.712a9.753 9.753 0 0 0 3.617 2.108c.98.314 1.471.395 2.613.432.91.03 1.195.015 1.842-.096a9.098 9.098 0 0 0 2.767-.918c1.263-.639 1.688-1.007 4.862-4.201 2.382-2.397 2.954-3.006 3.28-3.496 1.732-2.599 2.122-5.727 1.075-8.622-1.126-3.113-3.765-5.388-7.049-6.079-.818-.172-2.484-.224-3.262-.101m-10.64 10.783c-1.249.2-2.102.463-3.071.946-1.308.651-1.648.941-4.727 4.012-1.669 1.666-2.97 3.018-3.178 3.302-.899 1.23-1.444 2.426-1.758 3.857-.168.763-.233 2.364-.128 3.113.583 4.136 3.564 7.335 7.605 8.161 2.581.528 5.344-.096 7.537-1.7.261-.191 1.234-1.1 2.162-2.02 1.865-1.851 2.043-2.083 2.047-2.677.003-.427-.133-.719-.538-1.163-.35-.383-.785-.62-1.212-.661-.581-.056-.836.131-2.744 2.013-1.74 1.715-2.089 2.001-2.908 2.379-.895.414-1.338.502-2.507.499-.947-.002-1.096-.018-1.592-.171-.737-.227-1.185-.431-1.713-.783-1.1-.731-1.953-1.812-2.37-3.006-.489-1.401-.452-3.071.097-4.364.449-1.056.614-1.252 3.451-4.107 1.466-1.475 2.829-2.809 3.03-2.964 1.652-1.284 3.976-1.616 5.891-.842 1.036.419 1.703.931 2.81 2.16.537.595 1.024.749 1.675.527.388-.132.966-.601 1.17-.951.338-.576.258-1.146-.258-1.835-1.526-2.036-3.759-3.341-6.333-3.703-.425-.06-2.108-.075-2.438-.022' fill='%2355565b'/%3e%3c/svg%3e");
}

View File

@@ -0,0 +1,3 @@
.field-icon-link {
background-image: url(../../../misc/icons/55565b/link.svg);
}

12
core/modules/link/link.info.yml Executable file
View File

@@ -0,0 +1,12 @@
name: Link
type: module
description: 'Provides a field type for internal and external URLs.'
package: Field types
# version: VERSION
dependencies:
- drupal:field
# Information added by Drupal.org packaging script on 2024-07-04
version: '10.3.1'
project: 'drupal'
datestamp: 1720094222

View File

@@ -0,0 +1,7 @@
drupal.link-icon:
version: VERSION
css:
theme:
css/link.icon.theme.css: {}
dependencies:
- field_ui/drupal.field_ui.manage_fields

77
core/modules/link/link.module Executable file
View File

@@ -0,0 +1,77 @@
<?php
/**
* @file
* Defines simple link field types.
*/
use Drupal\Core\Field\FieldTypeCategoryManagerInterface;
use Drupal\Core\Link;
use Drupal\Core\Url;
use Drupal\Core\Routing\RouteMatchInterface;
/**
* Implements hook_help().
*/
function link_help($route_name, RouteMatchInterface $route_match) {
switch ($route_name) {
case 'help.page.link':
$output = '';
$output .= '<h2>' . t('About') . '</h2>';
$output .= '<p>' . t('The Link module allows you to create fields that contain internal or external URLs and optional link text. See the <a href=":field">Field module help</a> and the <a href=":field_ui">Field UI help</a> pages for general information on fields and how to create and manage them. For more information, see the <a href=":link_documentation">online documentation for the Link module</a>.', [':field' => Url::fromRoute('help.page', ['name' => 'field'])->toString(), ':field_ui' => (\Drupal::moduleHandler()->moduleExists('field_ui')) ? Url::fromRoute('help.page', ['name' => 'field_ui'])->toString() : '#', ':link_documentation' => 'https://www.drupal.org/documentation/modules/link']) . '</p>';
$output .= '<h2>' . t('Uses') . '</h2>';
$output .= '<dl>';
$output .= '<dt>' . t('Managing and displaying link fields') . '</dt>';
$output .= '<dd>' . t('The <em>settings</em> and the <em>display</em> of the link field can be configured separately. See the <a href=":field_ui">Field UI help</a> for more information on how to manage fields and their display.', [':field_ui' => (\Drupal::moduleHandler()->moduleExists('field_ui')) ? Url::fromRoute('help.page', ['name' => 'field_ui'])->toString() : '#']) . '</dd>';
$output .= '<dt>' . t('Setting the allowed link type') . '</dt>';
$output .= '<dd>' . t('In the field settings you can define the allowed link type to be <em>internal links only</em>, <em>external links only</em>, or <em>both internal and external links</em>. <em>Internal links only</em> and <em>both internal and external links</em> options enable an autocomplete widget for internal links, so a user does not have to copy or remember a URL.') . '</dd>';
$output .= '<dt>' . t('Adding link text') . '</dt>';
$output .= '<dd>' . t('In the field settings you can define additional link text to be <em>optional</em> or <em>required</em> in any link field.') . '</dd>';
$output .= '<dt>' . t('Displaying link text') . '</dt>';
$output .= '<dd>' . t('If link text has been submitted for a URL, then by default this link text is displayed as a link to the URL. If you want to display both the link text <em>and</em> the URL, choose the appropriate link format from the drop-down menu in the <em>Manage display</em> page. If you only want to display the URL even if link text has been submitted, choose <em>Link</em> as the format, and then change its <em>Format settings</em> to display <em>URL only</em>.') . '</dd>';
$output .= '<dt>' . t('Adding attributes to links') . '</dt>';
$output .= '<dd>' . t('You can add attributes to links, by changing the <em>Format settings</em> in the <em>Manage display</em> page. Adding <em>rel="nofollow"</em> notifies search engines that links should not be followed.') . '</dd>';
$output .= '<dt>' . t('Validating URLs') . '</dt>';
$output .= '<dd>' . t('All links are validated after a link field is filled in. They can include anchors or query strings.') . '</dd>';
$output .= '</dl>';
return $output;
}
}
/**
* Implements hook_theme().
*/
function link_theme() {
return [
'link_formatter_link_separate' => [
'variables' => ['title' => NULL, 'url_title' => NULL, 'url' => NULL],
],
];
}
/**
* Prepares variables for separated link field templates.
*
* This template outputs a separate title and link.
*
* Default template: link-formatter-link-separate.html.twig.
*
* @param array $variables
* An associative array containing:
* - title: (optional) A descriptive or alternate title for the link, which
* may be different than the actual link text.
* - url_title: The anchor text for the link.
* - url: A \Drupal\Core\Url object.
*/
function template_preprocess_link_formatter_link_separate(&$variables) {
$variables['link'] = Link::fromTextAndUrl($variables['url_title'], $variables['url'])->toString();
}
/**
* Implements hook_field_type_category_info_alter().
*/
function link_field_type_category_info_alter(&$definitions) {
// The `link` field type belongs in the `general` category, so the libraries
// need to be attached using an alter hook.
$definitions[FieldTypeCategoryManagerInterface::FALLBACK_CATEGORY]['libraries'][] = 'link/drupal.link-icon';
}

View File

@@ -0,0 +1,5 @@
finished:
6:
link: link
7:
link: link

View File

@@ -0,0 +1,54 @@
<?php
namespace Drupal\link;
use Drupal\Core\Field\FieldItemInterface;
/**
* Defines an interface for the link field item.
*/
interface LinkItemInterface extends FieldItemInterface {
/**
* Specifies whether the field supports only internal URLs.
*/
const LINK_INTERNAL = 0x01;
/**
* Specifies whether the field supports only external URLs.
*/
const LINK_EXTERNAL = 0x10;
/**
* Specifies whether the field supports both internal and external URLs.
*/
const LINK_GENERIC = 0x11;
/**
* Determines if a link is external.
*
* @return bool
* TRUE if the link is external, FALSE otherwise.
*/
public function isExternal();
/**
* Gets the URL object.
*
* @return \Drupal\Core\Url
* Returns a Url object.
*
* @throws \InvalidArgumentException
* Thrown when there is a problem with field data.
*/
public function getUrl();
/**
* Gets the link title.
*
* @return string|null
* Returns the link title.
*/
public function getTitle(): ?string;
}

View File

@@ -0,0 +1,263 @@
<?php
namespace Drupal\link\Plugin\Field\FieldFormatter;
use Drupal\Component\Utility\Unicode;
use Drupal\Core\Field\Attribute\FieldFormatter;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FormatterBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Path\PathValidatorInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Core\Url;
use Drupal\link\LinkItemInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Plugin implementation of the 'link' formatter.
*/
#[FieldFormatter(
id: 'link',
label: new TranslatableMarkup('Link'),
field_types: [
'link',
],
)]
class LinkFormatter extends FormatterBase {
/**
* The path validator service.
*
* @var \Drupal\Core\Path\PathValidatorInterface
*/
protected $pathValidator;
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$plugin_id,
$plugin_definition,
$configuration['field_definition'],
$configuration['settings'],
$configuration['label'],
$configuration['view_mode'],
$configuration['third_party_settings'],
$container->get('path.validator')
);
}
/**
* Constructs a new LinkFormatter.
*
* @param string $plugin_id
* The plugin_id for the formatter.
* @param mixed $plugin_definition
* The plugin implementation definition.
* @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
* The definition of the field to which the formatter is associated.
* @param array $settings
* The formatter settings.
* @param string $label
* The formatter label display setting.
* @param string $view_mode
* The view mode.
* @param array $third_party_settings
* Third party settings.
* @param \Drupal\Core\Path\PathValidatorInterface $path_validator
* The path validator service.
*/
public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, $label, $view_mode, array $third_party_settings, PathValidatorInterface $path_validator) {
parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $label, $view_mode, $third_party_settings);
$this->pathValidator = $path_validator;
}
/**
* {@inheritdoc}
*/
public static function defaultSettings() {
return [
'trim_length' => '80',
'url_only' => '',
'url_plain' => '',
'rel' => '',
'target' => '',
] + parent::defaultSettings();
}
/**
* {@inheritdoc}
*/
public function settingsForm(array $form, FormStateInterface $form_state) {
$elements = parent::settingsForm($form, $form_state);
$elements['trim_length'] = [
'#type' => 'number',
'#title' => $this->t('Trim link text length'),
'#field_suffix' => $this->t('characters'),
'#default_value' => $this->getSetting('trim_length'),
'#min' => 1,
'#description' => $this->t('Leave blank to allow unlimited link text lengths.'),
];
$elements['url_only'] = [
'#type' => 'checkbox',
'#title' => $this->t('URL only'),
'#default_value' => $this->getSetting('url_only'),
'#access' => $this->getPluginId() == 'link',
];
$elements['url_plain'] = [
'#type' => 'checkbox',
'#title' => $this->t('Show URL as plain text'),
'#default_value' => $this->getSetting('url_plain'),
'#access' => $this->getPluginId() == 'link',
'#states' => [
'visible' => [
':input[name*="url_only"]' => ['checked' => TRUE],
],
],
];
$elements['rel'] = [
'#type' => 'checkbox',
'#title' => $this->t('Add rel="nofollow" to links'),
'#return_value' => 'nofollow',
'#default_value' => $this->getSetting('rel'),
];
$elements['target'] = [
'#type' => 'checkbox',
'#title' => $this->t('Open link in new window'),
'#return_value' => '_blank',
'#default_value' => $this->getSetting('target'),
];
return $elements;
}
/**
* {@inheritdoc}
*/
public function settingsSummary() {
$summary = [];
$settings = $this->getSettings();
if (!empty($settings['trim_length'])) {
$summary[] = $this->t('Link text trimmed to @limit characters', ['@limit' => $settings['trim_length']]);
}
else {
$summary[] = $this->t('Link text not trimmed');
}
if ($this->getPluginId() == 'link' && !empty($settings['url_only'])) {
if (!empty($settings['url_plain'])) {
$summary[] = $this->t('Show URL only as plain-text');
}
else {
$summary[] = $this->t('Show URL only');
}
}
if (!empty($settings['rel'])) {
$summary[] = $this->t('Add rel="@rel"', ['@rel' => $settings['rel']]);
}
if (!empty($settings['target'])) {
$summary[] = $this->t('Open link in new window');
}
return $summary;
}
/**
* {@inheritdoc}
*/
public function viewElements(FieldItemListInterface $items, $langcode) {
$element = [];
$entity = $items->getEntity();
$settings = $this->getSettings();
foreach ($items as $delta => $item) {
// By default use the full URL as the link text.
$url = $this->buildUrl($item);
$link_title = $url->toString();
// If the title field value is available, use it for the link text.
if (empty($settings['url_only']) && !empty($item->title)) {
// Unsanitized token replacement here because the entire link title
// gets auto-escaped during link generation in
// \Drupal\Core\Utility\LinkGenerator::generate().
$link_title = \Drupal::token()->replace($item->title, [$entity->getEntityTypeId() => $entity], ['clear' => TRUE]);
}
// Trim the link text to the desired length.
if (!empty($settings['trim_length'])) {
$link_title = Unicode::truncate($link_title, $settings['trim_length'], FALSE, TRUE);
}
if (!empty($settings['url_only']) && !empty($settings['url_plain'])) {
$element[$delta] = [
'#plain_text' => $link_title,
];
if (!empty($item->_attributes)) {
// Piggyback on the metadata attributes, which will be placed in the
// field template wrapper, and set the URL value in a content
// attribute.
$content = str_replace('internal:/', '', $item->uri);
$item->_attributes += ['content' => $content];
}
}
else {
// Skip the #options to prevent duplications of query parameters.
$element[$delta] = [
'#type' => 'link',
'#title' => $link_title,
'#url' => $url,
];
if (!empty($item->_attributes)) {
$element[$delta]['#attributes'] = $item->_attributes;
// Unset field item attributes since they have been included in the
// formatter output and should not be rendered in the field template.
unset($item->_attributes);
}
}
}
return $element;
}
/**
* Builds the \Drupal\Core\Url object for a link field item.
*
* @param \Drupal\link\LinkItemInterface $item
* The link field item being rendered.
*
* @return \Drupal\Core\Url
* A Url object.
*/
protected function buildUrl(LinkItemInterface $item) {
try {
$url = $item->getUrl();
}
catch (\InvalidArgumentException $e) {
// @todo Add logging here in https://www.drupal.org/project/drupal/issues/3348020
$url = Url::fromRoute('<none>');
}
$settings = $this->getSettings();
$options = $item->options;
$options += $url->getOptions();
// Add optional 'rel' attribute to link options.
if (!empty($settings['rel'])) {
$options['attributes']['rel'] = $settings['rel'];
}
// Add optional 'target' attribute to link options.
if (!empty($settings['target'])) {
$options['attributes']['target'] = $settings['target'];
}
$url->setOptions($options);
return $url;
}
}

View File

@@ -0,0 +1,90 @@
<?php
namespace Drupal\link\Plugin\Field\FieldFormatter;
use Drupal\Component\Utility\Unicode;
use Drupal\Core\Field\Attribute\FieldFormatter;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
/**
* Plugin implementation of the 'link_separate' formatter.
*
* @todo https://www.drupal.org/node/1829202 Merge into 'link' formatter once
* there is a #type like 'item' that can render a compound label and content
* outside of a form context.
*/
#[FieldFormatter(
id: 'link_separate',
label: new TranslatableMarkup('Separate link text and URL'),
field_types: [
'link',
],
)]
class LinkSeparateFormatter extends LinkFormatter {
/**
* {@inheritdoc}
*/
public static function defaultSettings() {
return [
'trim_length' => 80,
'rel' => '',
'target' => '',
] + parent::defaultSettings();
}
/**
* {@inheritdoc}
*/
public function viewElements(FieldItemListInterface $items, $langcode) {
$element = [];
$entity = $items->getEntity();
$settings = $this->getSettings();
foreach ($items as $delta => $item) {
// By default use the full URL as the link text.
$url = $this->buildUrl($item);
$link_title = $url->toString();
// If the link text field value is available, use it for the text.
if (empty($settings['url_only']) && !empty($item->title)) {
// Unsanitized token replacement here because the entire link title
// gets auto-escaped during link generation in
// \Drupal\Core\Utility\LinkGenerator::generate().
$link_title = \Drupal::token()->replace($item->title, [$entity->getEntityTypeId() => $entity], ['clear' => TRUE]);
}
// The link_separate formatter has two titles; the link text (as in the
// field values) and the URL itself. If there is no link text value,
// $link_title defaults to the URL, so it needs to be unset.
// The URL version may need to be trimmed as well.
if (empty($item->title)) {
$link_title = NULL;
}
$url_title = $url->toString();
if (!empty($settings['trim_length'])) {
$link_title = $link_title !== NULL ? Unicode::truncate($link_title, $settings['trim_length'], FALSE, TRUE) : NULL;
$url_title = Unicode::truncate($url_title, $settings['trim_length'], FALSE, TRUE);
}
$element[$delta] = [
'#theme' => 'link_formatter_link_separate',
'#title' => $link_title,
'#url_title' => $url_title,
'#url' => $url,
];
if (!empty($item->_attributes)) {
// Set our attributes on the <a> element that is being built.
$url->setOption('attributes', $item->_attributes);
// Unset field item attributes since they have been included in the
// formatter output and should not be rendered in the field template.
unset($item->_attributes);
}
}
return $element;
}
}

View File

@@ -0,0 +1,207 @@
<?php
namespace Drupal\link\Plugin\Field\FieldType;
use Drupal\Component\Utility\Random;
use Drupal\Core\Field\Attribute\FieldType;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemBase;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Core\TypedData\DataDefinition;
use Drupal\Core\TypedData\MapDataDefinition;
use Drupal\Core\Url;
use Drupal\link\LinkItemInterface;
/**
* Plugin implementation of the 'link' field type.
*/
#[FieldType(
id: "link",
label: new TranslatableMarkup("Link"),
description: new TranslatableMarkup("Stores a URL string, optional varchar link text, and optional blob of attributes to assemble a link."),
default_widget: "link_default",
default_formatter: "link",
constraints: [
"LinkType" => [],
"LinkAccess" => [],
"LinkExternalProtocols" => [],
"LinkNotExistingInternal" => [],
]
)]
class LinkItem extends FieldItemBase implements LinkItemInterface {
/**
* {@inheritdoc}
*/
public static function defaultFieldSettings() {
return [
'title' => DRUPAL_OPTIONAL,
'link_type' => LinkItemInterface::LINK_GENERIC,
] + parent::defaultFieldSettings();
}
/**
* {@inheritdoc}
*/
public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
$properties['uri'] = DataDefinition::create('uri')
->setLabel(new TranslatableMarkup('URI'));
$properties['title'] = DataDefinition::create('string')
->setLabel(new TranslatableMarkup('Link text'));
$properties['options'] = MapDataDefinition::create()
->setLabel(new TranslatableMarkup('Options'));
return $properties;
}
/**
* {@inheritdoc}
*/
public static function schema(FieldStorageDefinitionInterface $field_definition) {
return [
'columns' => [
'uri' => [
'description' => 'The URI of the link.',
'type' => 'varchar',
'length' => 2048,
],
'title' => [
'description' => 'The link text.',
'type' => 'varchar',
'length' => 255,
],
'options' => [
'description' => 'Serialized array of options for the link.',
'type' => 'blob',
'size' => 'big',
'serialize' => TRUE,
],
],
'indexes' => [
'uri' => [['uri', 30]],
],
];
}
/**
* {@inheritdoc}
*/
public function fieldSettingsForm(array $form, FormStateInterface $form_state) {
$element = [];
$element['link_type'] = [
'#type' => 'radios',
'#title' => $this->t('Allowed link type'),
'#default_value' => $this->getSetting('link_type'),
'#options' => [
static::LINK_INTERNAL => $this->t('Internal links only'),
static::LINK_EXTERNAL => $this->t('External links only'),
static::LINK_GENERIC => $this->t('Both internal and external links'),
],
];
$element['title'] = [
'#type' => 'radios',
'#title' => $this->t('Allow link text'),
'#default_value' => $this->getSetting('title'),
'#options' => [
DRUPAL_DISABLED => $this->t('Disabled'),
DRUPAL_OPTIONAL => $this->t('Optional'),
DRUPAL_REQUIRED => $this->t('Required'),
],
];
return $element;
}
/**
* {@inheritdoc}
*/
public static function generateSampleValue(FieldDefinitionInterface $field_definition) {
$random = new Random();
if ($field_definition->getItemDefinition()->getSetting('link_type') & LinkItemInterface::LINK_EXTERNAL) {
// Set of possible top-level domains.
$tlds = ['com', 'net', 'gov', 'org', 'edu', 'biz', 'info'];
// Set random length for the domain name.
$domain_length = mt_rand(7, 15);
switch ($field_definition->getSetting('title')) {
case DRUPAL_DISABLED:
$values['title'] = '';
break;
case DRUPAL_REQUIRED:
$values['title'] = $random->sentences(4);
break;
case DRUPAL_OPTIONAL:
// In case of optional title, randomize its generation.
$values['title'] = mt_rand(0, 1) ? $random->sentences(4) : '';
break;
}
$values['uri'] = 'https://www.' . $random->word($domain_length) . '.' . $tlds[mt_rand(0, (count($tlds) - 1))];
}
else {
$values['uri'] = 'base:' . $random->name(mt_rand(1, 64));
}
return $values;
}
/**
* {@inheritdoc}
*/
public function isEmpty() {
$value = $this->get('uri')->getValue();
return $value === NULL || $value === '';
}
/**
* {@inheritdoc}
*/
public function isExternal() {
return $this->getUrl()->isExternal();
}
/**
* {@inheritdoc}
*/
public static function mainPropertyName() {
return 'uri';
}
/**
* {@inheritdoc}
*/
public function getUrl() {
return Url::fromUri($this->uri, (array) $this->options);
}
/**
* {@inheritdoc}
*/
public function getTitle(): ?string {
return $this->title ?: NULL;
}
/**
* {@inheritdoc}
*/
public function setValue($values, $notify = TRUE) {
// Treat the values as property value of the main property, if no array is
// given.
if (isset($values) && !is_array($values)) {
$values = [static::mainPropertyName() => $values];
}
if (isset($values)) {
$values += [
'options' => [],
];
}
parent::setValue($values, $notify);
}
}

View File

@@ -0,0 +1,462 @@
<?php
namespace Drupal\link\Plugin\Field\FieldWidget;
use Drupal\Core\Field\Attribute\FieldWidget;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Core\Url;
use Drupal\Core\Entity\Element\EntityAutocomplete;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\link\LinkItemInterface;
use Symfony\Component\Validator\ConstraintViolation;
use Symfony\Component\Validator\ConstraintViolationListInterface;
/**
* Plugin implementation of the 'link' widget.
*/
#[FieldWidget(
id: 'link_default',
label: new TranslatableMarkup('Link'),
field_types: ['link'],
)]
class LinkWidget extends WidgetBase {
/**
* {@inheritdoc}
*/
public static function defaultSettings() {
return [
'placeholder_url' => '',
'placeholder_title' => '',
] + parent::defaultSettings();
}
/**
* Gets the URI without the 'internal:' or 'entity:' scheme.
*
* The following two forms of URIs are transformed:
* - 'entity:' URIs: to entity autocomplete ("label (entity id)") strings;
* - 'internal:' URIs: the scheme is stripped.
*
* This method is the inverse of ::getUserEnteredStringAsUri().
*
* @param string $uri
* The URI to get the displayable string for.
*
* @return string
*
* @see static::getUserEnteredStringAsUri()
*/
protected static function getUriAsDisplayableString($uri) {
$scheme = parse_url($uri, PHP_URL_SCHEME);
// By default, the displayable string is the URI.
$displayable_string = $uri;
// A different displayable string may be chosen in case of the 'internal:'
// or 'entity:' built-in schemes.
if ($scheme === 'internal') {
$uri_reference = explode(':', $uri, 2)[1];
// @todo '<front>' is valid input for BC reasons, may be removed by
// https://www.drupal.org/node/2421941
$path = parse_url($uri, PHP_URL_PATH);
if ($path === '/') {
$uri_reference = '<front>' . substr($uri_reference, 1);
}
$displayable_string = $uri_reference;
}
elseif ($scheme === 'entity') {
[$entity_type, $entity_id] = explode('/', substr($uri, 7), 2);
// Show the 'entity:' URI as the entity autocomplete would.
// @todo Support entity types other than 'node'. Will be fixed in
// https://www.drupal.org/node/2423093.
if ($entity_type == 'node' && $entity = \Drupal::entityTypeManager()->getStorage($entity_type)->load($entity_id)) {
$displayable_string = EntityAutocomplete::getEntityLabels([$entity]);
}
}
elseif ($scheme === 'route') {
$displayable_string = ltrim($displayable_string, 'route:');
}
return $displayable_string;
}
/**
* Gets the user-entered string as a URI.
*
* The following two forms of input are mapped to URIs:
* - entity autocomplete ("label (entity id)") strings: to 'entity:' URIs;
* - strings without a detectable scheme: to 'internal:' URIs.
*
* This method is the inverse of ::getUriAsDisplayableString().
*
* @param string $string
* The user-entered string.
*
* @return string
* The URI, if a non-empty $uri was passed.
*
* @see static::getUriAsDisplayableString()
*/
protected static function getUserEnteredStringAsUri($string) {
// By default, assume the entered string is a URI.
$uri = trim($string);
// Detect entity autocomplete string, map to 'entity:' URI.
$entity_id = EntityAutocomplete::extractEntityIdFromAutocompleteInput($string);
if ($entity_id !== NULL) {
// @todo Support entity types other than 'node'. Will be fixed in
// https://www.drupal.org/node/2423093.
$uri = 'entity:node/' . $entity_id;
}
// Support linking to nothing.
elseif (in_array($string, ['<nolink>', '<none>', '<button>'], TRUE)) {
$uri = 'route:' . $string;
}
// Detect a schemeless string, map to 'internal:' URI.
elseif (!empty($string) && parse_url($string, PHP_URL_SCHEME) === NULL) {
// @todo '<front>' is valid input for BC reasons, may be removed by
// https://www.drupal.org/node/2421941
// - '<front>' -> '/'
// - '<front>#foo' -> '/#foo'
if (str_starts_with($string, '<front>')) {
$string = '/' . substr($string, strlen('<front>'));
}
$uri = 'internal:' . $string;
}
return $uri;
}
/**
* Form element validation handler for the 'uri' element.
*
* Disallows saving inaccessible or untrusted URLs.
*/
public static function validateUriElement($element, FormStateInterface $form_state, $form) {
$uri = static::getUserEnteredStringAsUri($element['#value']);
$form_state->setValueForElement($element, $uri);
// If getUserEnteredStringAsUri() mapped the entered value to an 'internal:'
// URI , ensure the raw value begins with '/', '?' or '#'.
// @todo '<front>' is valid input for BC reasons, may be removed by
// https://www.drupal.org/node/2421941
if (parse_url($uri, PHP_URL_SCHEME) === 'internal' && !in_array($element['#value'][0], ['/', '?', '#'], TRUE) && !str_starts_with($element['#value'], '<front>')) {
$form_state->setError($element, new TranslatableMarkup('Manually entered paths should start with one of the following characters: / ? #'));
return;
}
}
/**
* Form element validation handler for the 'title' element.
*
* Conditionally requires the link title if a URL value was filled in.
*/
public static function validateTitleElement(&$element, FormStateInterface $form_state, $form) {
if ($element['uri']['#value'] !== '' && $element['title']['#value'] === '') {
// We expect the field name placeholder value to be wrapped in $this->t() here,
// so it won't be escaped again as it's already marked safe.
$form_state->setError($element['title'], new TranslatableMarkup('@title field is required if there is @uri input.', ['@title' => $element['title']['#title'], '@uri' => $element['uri']['#title']]));
}
}
/**
* Form element validation handler for the 'title' element.
*
* Requires the URL value if a link title was filled in.
*/
public static function validateTitleNoLink(&$element, FormStateInterface $form_state, $form) {
if ($element['uri']['#value'] === '' && $element['title']['#value'] !== '') {
$form_state->setError($element['uri'], new TranslatableMarkup('The @uri field is required when the @title field is specified.', ['@title' => $element['title']['#title'], '@uri' => $element['uri']['#title']]));
}
}
/**
* {@inheritdoc}
*/
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
/** @var \Drupal\link\LinkItemInterface $item */
$item = $items[$delta];
$display_uri = NULL;
if (!$item->isEmpty()) {
try {
// The current field value could have been entered by a different user.
// However, if it is inaccessible to the current user, do not display it
// to them.
if (\Drupal::currentUser()->hasPermission('link to any page') || $item->getUrl()->access()) {
$display_uri = static::getUriAsDisplayableString($item->uri);
}
}
catch (\InvalidArgumentException $e) {
// If $item->uri is invalid, show value as is, so the user can see what
// to edit.
// @todo Add logging here in https://www.drupal.org/project/drupal/issues/3348020
$display_uri = $item->uri;
}
}
$element['uri'] = [
'#type' => 'url',
'#title' => $this->t('URL'),
'#placeholder' => $this->getSetting('placeholder_url'),
'#default_value' => $display_uri,
'#element_validate' => [[static::class, 'validateUriElement']],
'#maxlength' => 2048,
'#required' => $element['#required'],
'#link_type' => $this->getFieldSetting('link_type'),
];
// If the field is configured to support internal links, it cannot use the
// 'url' form element and we have to do the validation ourselves.
if ($this->supportsInternalLinks()) {
$element['uri']['#type'] = 'entity_autocomplete';
// @todo The user should be able to select an entity type. Will be fixed
// in https://www.drupal.org/node/2423093.
$element['uri']['#target_type'] = 'node';
// Disable autocompletion when the first character is '/', '#' or '?'.
$element['uri']['#attributes']['data-autocomplete-first-character-blacklist'] = '/#?';
// The link widget is doing its own processing in
// static::getUriAsDisplayableString().
$element['uri']['#process_default_value'] = FALSE;
}
// If the field is configured to allow only internal links, add a useful
// element prefix and description.
if (!$this->supportsExternalLinks()) {
$element['uri']['#field_prefix'] = rtrim(Url::fromRoute('<front>', [], ['absolute' => TRUE])->toString(), '/');
$element['uri']['#description'] = $this->t('This must be an internal path such as %add-node. You can also start typing the title of a piece of content to select it. Enter %front to link to the front page. Enter %nolink to display link text only. Enter %button to display keyboard-accessible link text only.', ['%add-node' => '/node/add', '%front' => '<front>', '%nolink' => '<nolink>', '%button' => '<button>']);
}
// If the field is configured to allow both internal and external links,
// show a useful description.
elseif ($this->supportsExternalLinks() && $this->supportsInternalLinks()) {
$element['uri']['#description'] = $this->t('Start typing the title of a piece of content to select it. You can also enter an internal path such as %add-node or an external URL such as %url. Enter %front to link to the front page. Enter %nolink to display link text only. Enter %button to display keyboard-accessible link text only.', ['%front' => '<front>', '%add-node' => '/node/add', '%url' => 'https://example.com', '%nolink' => '<nolink>', '%button' => '<button>']);
}
// If the field is configured to allow only external links, show a useful
// description.
elseif ($this->supportsExternalLinks() && !$this->supportsInternalLinks()) {
$element['uri']['#description'] = $this->t('This must be an external URL such as %url.', ['%url' => 'https://example.com']);
}
// Make uri required on the front-end when title filled-in.
if (!$this->isDefaultValueWidget($form_state) && $this->getFieldSetting('title') !== DRUPAL_DISABLED && !$element['uri']['#required']) {
$parents = $element['#field_parents'];
$parents[] = $this->fieldDefinition->getName();
$selector = $root = array_shift($parents);
if ($parents) {
$selector = $root . '[' . implode('][', $parents) . ']';
}
$element['uri']['#states']['required'] = [
':input[name="' . $selector . '[' . $delta . '][title]"]' => ['filled' => TRUE],
];
}
$element['title'] = [
'#type' => 'textfield',
'#title' => $this->t('Link text'),
'#placeholder' => $this->getSetting('placeholder_title'),
'#default_value' => $items[$delta]->title ?? NULL,
'#maxlength' => 255,
'#access' => $this->getFieldSetting('title') != DRUPAL_DISABLED,
'#required' => $this->getFieldSetting('title') === DRUPAL_REQUIRED && $element['#required'],
];
// Post-process the title field to make it conditionally required if URL is
// non-empty. Omit the validation on the field edit form, since the field
// settings cannot be saved otherwise.
//
// Validate that title field is filled out (regardless of uri) when it is a
// required field.
if (!$this->isDefaultValueWidget($form_state) && $this->getFieldSetting('title') === DRUPAL_REQUIRED) {
$element['#element_validate'][] = [static::class, 'validateTitleElement'];
$element['#element_validate'][] = [static::class, 'validateTitleNoLink'];
if (!$element['title']['#required']) {
// Make title required on the front-end when URI filled-in.
$parents = $element['#field_parents'];
$parents[] = $this->fieldDefinition->getName();
$selector = $root = array_shift($parents);
if ($parents) {
$selector = $root . '[' . implode('][', $parents) . ']';
}
$element['title']['#states']['required'] = [
':input[name="' . $selector . '[' . $delta . '][uri]"]' => ['filled' => TRUE],
];
}
}
// Ensure that a URI is always entered when an optional title field is
// submitted.
if (!$this->isDefaultValueWidget($form_state) && $this->getFieldSetting('title') == DRUPAL_OPTIONAL) {
$element['#element_validate'][] = [static::class, 'validateTitleNoLink'];
}
// Exposing the attributes array in the widget is left for alternate and more
// advanced field widgets.
$element['attributes'] = [
'#type' => 'value',
'#tree' => TRUE,
'#value' => !empty($items[$delta]->options['attributes']) ? $items[$delta]->options['attributes'] : [],
'#attributes' => ['class' => ['link-field-widget-attributes']],
];
// If cardinality is 1, ensure a proper label is output for the field.
if ($this->fieldDefinition->getFieldStorageDefinition()->getCardinality() == 1) {
// If the link title is disabled, use the field definition label as the
// title of the 'uri' element.
if ($this->getFieldSetting('title') == DRUPAL_DISABLED) {
$element['uri']['#title'] = $element['#title'];
// By default the field description is added to the title field. Since
// the title field is disabled, we add the description, if given, to the
// uri element instead.
if (!empty($element['#description'])) {
if (empty($element['uri']['#description'])) {
$element['uri']['#description'] = $element['#description'];
}
else {
// If we have the description of the type of field together with
// the user provided description, we want to make a distinction
// between "core help text" and "user entered help text". To make
// this distinction more clear, we put them in an unordered list.
$element['uri']['#description'] = [
'#theme' => 'item_list',
'#items' => [
// Assume the user-specified description has the most relevance,
// so place it first.
$element['#description'],
$element['uri']['#description'],
],
];
}
}
}
// Otherwise wrap everything in a details element.
else {
$element += [
'#type' => 'fieldset',
];
}
}
return $element;
}
/**
* Indicates enabled support for link to routes.
*
* @return bool
* Returns TRUE if the LinkItem field is configured to support links to
* routes, otherwise FALSE.
*/
protected function supportsInternalLinks() {
$link_type = $this->getFieldSetting('link_type');
return (bool) ($link_type & LinkItemInterface::LINK_INTERNAL);
}
/**
* Indicates enabled support for link to external URLs.
*
* @return bool
* Returns TRUE if the LinkItem field is configured to support links to
* external URLs, otherwise FALSE.
*/
protected function supportsExternalLinks() {
$link_type = $this->getFieldSetting('link_type');
return (bool) ($link_type & LinkItemInterface::LINK_EXTERNAL);
}
/**
* {@inheritdoc}
*/
public function settingsForm(array $form, FormStateInterface $form_state) {
$elements = parent::settingsForm($form, $form_state);
$elements['placeholder_url'] = [
'#type' => 'textfield',
'#title' => $this->t('Placeholder for URL'),
'#default_value' => $this->getSetting('placeholder_url'),
'#description' => $this->t('Text that will be shown inside the field until a value is entered. This hint is usually a sample value or a brief description of the expected format.'),
];
$elements['placeholder_title'] = [
'#type' => 'textfield',
'#title' => $this->t('Placeholder for link text'),
'#default_value' => $this->getSetting('placeholder_title'),
'#description' => $this->t('Text that will be shown inside the field until a value is entered. This hint is usually a sample value or a brief description of the expected format.'),
'#states' => [
'invisible' => [
':input[name="instance[settings][title]"]' => ['value' => DRUPAL_DISABLED],
],
],
];
return $elements;
}
/**
* {@inheritdoc}
*/
public function settingsSummary() {
$summary = [];
$placeholder_title = $this->getSetting('placeholder_title');
$placeholder_url = $this->getSetting('placeholder_url');
if (empty($placeholder_title) && empty($placeholder_url)) {
$summary[] = $this->t('No placeholders');
}
else {
if (!empty($placeholder_title)) {
$summary[] = $this->t('Title placeholder: @placeholder_title', ['@placeholder_title' => $placeholder_title]);
}
if (!empty($placeholder_url)) {
$summary[] = $this->t('URL placeholder: @placeholder_url', ['@placeholder_url' => $placeholder_url]);
}
}
return $summary;
}
/**
* {@inheritdoc}
*/
public function massageFormValues(array $values, array $form, FormStateInterface $form_state) {
foreach ($values as &$value) {
$value['uri'] = static::getUserEnteredStringAsUri($value['uri']);
$value += ['options' => []];
}
return $values;
}
/**
* {@inheritdoc}
*
* Override the '%uri' message parameter, to ensure that 'internal:' URIs
* show a validation error message that doesn't mention that scheme.
*/
public function flagErrors(FieldItemListInterface $items, ConstraintViolationListInterface $violations, array $form, FormStateInterface $form_state) {
/** @var \Symfony\Component\Validator\ConstraintViolationInterface $violation */
foreach ($violations as $offset => $violation) {
$parameters = $violation->getParameters();
if (isset($parameters['@uri'])) {
$parameters['@uri'] = static::getUriAsDisplayableString($parameters['@uri']);
$violations->set($offset, new ConstraintViolation(
$this->t($violation->getMessageTemplate(), $parameters),
$violation->getMessageTemplate(),
$parameters,
$violation->getRoot(),
$violation->getPropertyPath(),
$violation->getInvalidValue(),
$violation->getPlural(),
$violation->getCode()
));
}
}
parent::flagErrors($items, $violations, $form, $form_state);
}
}

View File

@@ -0,0 +1,20 @@
<?php
namespace Drupal\link\Plugin\Validation\Constraint;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Core\Validation\Attribute\Constraint;
use Symfony\Component\Validator\Constraint as SymfonyConstraint;
/**
* Defines an access validation constraint for links.
*/
#[Constraint(
id: 'LinkAccess',
label: new TranslatableMarkup('Link URI can be accessed by the user.', [], ['context' => 'Validation'])
)]
class LinkAccessConstraint extends SymfonyConstraint {
public $message = "The path '@uri' is inaccessible.";
}

View File

@@ -0,0 +1,67 @@
<?php
namespace Drupal\link\Plugin\Validation\Constraint;
use Drupal\Core\Session\AccountProxyInterface;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
/**
* Validates the LinkAccess constraint.
*/
class LinkAccessConstraintValidator extends ConstraintValidator implements ContainerInjectionInterface {
/**
* Proxy for the current user account.
*
* @var \Drupal\Core\Session\AccountProxyInterface
*/
// phpcs:ignore Drupal.NamingConventions.ValidVariableName.LowerCamelName
protected $current_user;
/**
* Constructs an instance of the LinkAccessConstraintValidator class.
*
* @param \Drupal\Core\Session\AccountProxyInterface $current_user
* The current user account.
*/
public function __construct(AccountProxyInterface $current_user) {
$this->current_user = $current_user;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('current_user')
);
}
/**
* {@inheritdoc}
*
* phpcs:ignore Drupal.Commenting.FunctionComment.VoidReturn
* @return void
*/
public function validate($value, Constraint $constraint) {
if (isset($value)) {
try {
$url = $value->getUrl();
}
// If the URL is malformed this constraint cannot check access.
catch (\InvalidArgumentException $e) {
return;
}
// Disallow URLs if the current user doesn't have the 'link to any page'
// permission nor can access this URI.
$allowed = $this->current_user->hasPermission('link to any page') || $url->access();
if (!$allowed) {
$this->context->addViolation($constraint->message, ['@uri' => $value->uri]);
}
}
}
}

View File

@@ -0,0 +1,20 @@
<?php
namespace Drupal\link\Plugin\Validation\Constraint;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Core\Validation\Attribute\Constraint;
use Symfony\Component\Validator\Constraint as SymfonyConstraint;
/**
* Defines a protocol validation constraint for links to external URLs.
*/
#[Constraint(
id: 'LinkExternalProtocols',
label: new TranslatableMarkup('No dangerous external protocols', [], ['context' => 'Validation'])
)]
class LinkExternalProtocolsConstraint extends SymfonyConstraint {
public $message = "The path '@uri' is invalid.";
}

View File

@@ -0,0 +1,37 @@
<?php
namespace Drupal\link\Plugin\Validation\Constraint;
use Drupal\Component\Utility\UrlHelper;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
/**
* Validates the LinkExternalProtocols constraint.
*/
class LinkExternalProtocolsConstraintValidator extends ConstraintValidator {
/**
* {@inheritdoc}
*
* phpcs:ignore Drupal.Commenting.FunctionComment.VoidReturn
* @return void
*/
public function validate($value, Constraint $constraint) {
if (isset($value)) {
try {
/** @var \Drupal\Core\Url $url */
$url = $value->getUrl();
}
// If the URL is malformed this constraint cannot check further.
catch (\InvalidArgumentException $e) {
return;
}
// Disallow external URLs using untrusted protocols.
if ($url->isExternal() && !in_array(parse_url($url->getUri(), PHP_URL_SCHEME), UrlHelper::getAllowedProtocols())) {
$this->context->addViolation($constraint->message, ['@uri' => $value->uri]);
}
}
}
}

View File

@@ -0,0 +1,20 @@
<?php
namespace Drupal\link\Plugin\Validation\Constraint;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Core\Validation\Attribute\Constraint;
use Symfony\Component\Validator\Constraint as SymfonyConstraint;
/**
* Defines a protocol validation constraint for links to broken internal URLs.
*/
#[Constraint(
id: 'LinkNotExistingInternal',
label: new TranslatableMarkup('No broken internal links', [], ['context' => 'Validation'])
)]
class LinkNotExistingInternalConstraint extends SymfonyConstraint {
public $message = "The path '@uri' is invalid.";
}

View File

@@ -0,0 +1,56 @@
<?php
namespace Drupal\link\Plugin\Validation\Constraint;
use Symfony\Component\Routing\Exception\InvalidParameterException;
use Symfony\Component\Routing\Exception\MissingMandatoryParametersException;
use Symfony\Component\Routing\Exception\RouteNotFoundException;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
/**
* Validates the LinkNotExistingInternal constraint.
*/
class LinkNotExistingInternalConstraintValidator extends ConstraintValidator {
/**
* {@inheritdoc}
*
* phpcs:ignore Drupal.Commenting.FunctionComment.VoidReturn
* @return void
*/
public function validate($value, Constraint $constraint) {
if (isset($value)) {
try {
/** @var \Drupal\Core\Url $url */
$url = $value->getUrl();
}
// If the URL is malformed this constraint cannot check further.
catch (\InvalidArgumentException $e) {
return;
}
if ($url->isRouted()) {
$allowed = TRUE;
try {
$url->toString(TRUE);
}
// The following exceptions are all possible during URL generation, and
// should be considered as disallowed URLs.
catch (RouteNotFoundException $e) {
$allowed = FALSE;
}
catch (InvalidParameterException $e) {
$allowed = FALSE;
}
catch (MissingMandatoryParametersException $e) {
$allowed = FALSE;
}
if (!$allowed) {
$this->context->addViolation($constraint->message, ['@uri' => $value->uri]);
}
}
}
}
}

View File

@@ -0,0 +1,20 @@
<?php
namespace Drupal\link\Plugin\Validation\Constraint;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Core\Validation\Attribute\Constraint;
use Symfony\Component\Validator\Constraint as SymfonyConstraint;
/**
* Validation constraint for links receiving data allowed by its settings.
*/
#[Constraint(
id: 'LinkType',
label: new TranslatableMarkup('Link data valid for link type.', [], ['context' => 'Validation'])
)]
class LinkTypeConstraint extends SymfonyConstraint {
public $message = "The path '@uri' is invalid.";
}

View File

@@ -0,0 +1,51 @@
<?php
namespace Drupal\link\Plugin\Validation\Constraint;
use Drupal\link\LinkItemInterface;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
/**
* Constraint validator for links receiving data allowed by its settings.
*/
class LinkTypeConstraintValidator extends ConstraintValidator {
/**
* {@inheritdoc}
*/
public function validate($value, Constraint $constraint) {
if (isset($value)) {
$uri_is_valid = TRUE;
/** @var \Drupal\link\LinkItemInterface $link_item */
$link_item = $value;
$link_type = $link_item->getFieldDefinition()->getSetting('link_type');
// Try to resolve the given URI to a URL. It may fail if it's schemeless.
try {
$url = $link_item->getUrl();
}
catch (\InvalidArgumentException $e) {
$uri_is_valid = FALSE;
}
// If the link field doesn't support both internal and external links,
// check whether the URL (a resolved URI) is in fact violating either
// restriction.
if ($uri_is_valid && $link_type !== LinkItemInterface::LINK_GENERIC) {
if (!($link_type & LinkItemInterface::LINK_EXTERNAL) && $url->isExternal()) {
$uri_is_valid = FALSE;
}
if (!($link_type & LinkItemInterface::LINK_INTERNAL) && !$url->isExternal()) {
$uri_is_valid = FALSE;
}
}
if (!$uri_is_valid) {
$this->context->addViolation($constraint->message, ['@uri' => $link_item->uri]);
}
}
}
}

View File

@@ -0,0 +1,49 @@
<?php
namespace Drupal\link\Plugin\migrate\field\d6;
use Drupal\migrate\Plugin\MigrationInterface;
use Drupal\migrate_drupal\Attribute\MigrateField;
use Drupal\migrate_drupal\Plugin\migrate\field\FieldPluginBase;
#[MigrateField(
id: 'link',
core: [6],
type_map: [
'link' => 'link',
],
source_module: 'link',
destination_module: 'link',
)]
class LinkField extends FieldPluginBase {
/**
* {@inheritdoc}
*/
public function getFieldFormatterMap() {
// See d6_field_formatter_settings.yml and FieldPluginBase
// alterFieldFormatterMigration().
return [
'default' => 'link',
'plain' => 'link',
'absolute' => 'link',
'title_plain' => 'link',
'url' => 'link',
'short' => 'link',
'label' => 'link',
'separate' => 'link_separate',
];
}
/**
* {@inheritdoc}
*/
public function defineValueProcessPipeline(MigrationInterface $migration, $field_name, $data) {
$process = [
'plugin' => 'field_link',
'source' => $field_name,
];
$migration->mergeProcessOfProperty($field_name, $process);
}
}

View File

@@ -0,0 +1,71 @@
<?php
namespace Drupal\link\Plugin\migrate\field\d7;
use Drupal\link\Plugin\migrate\field\d6\LinkField as D6LinkField;
use Drupal\migrate\Plugin\MigrationInterface;
use Drupal\migrate_drupal\Attribute\MigrateField;
/**
* MigrateField Plugin for Drupal 7 link fields.
*
* This plugin provides the exact same functionality as the Drupal 6 "link"
* plugin with the exception that the plugin ID "link_field" is used in the
* field type map.
*/
#[MigrateField(
id: 'link_field',
core: [7],
type_map: [
'link_field' => 'link',
],
source_module: 'link',
destination_module: 'link',
)]
class LinkField extends D6LinkField {
/**
* {@inheritdoc}
*/
public function getFieldFormatterMap() {
return [
'link_default' => 'link',
'link_title_plain' => 'link',
'link_host' => 'link',
'link_url' => 'link',
'link_plain' => 'link',
'link_absolute' => 'link',
'link_domain' => 'link',
'link_no_protocol' => 'link',
'link_short' => 'link',
'link_label' => 'link',
'link_separate' => 'link_separate',
];
}
/**
* {@inheritdoc}
*/
public function getFieldWidgetMap() {
// By default, use the plugin ID for the widget types.
return ['link_field' => 'link_default'];
}
/**
* {@inheritdoc}
*/
public function alterFieldInstanceMigration(MigrationInterface $migration) {
$process = [
'plugin' => 'static_map',
'source' => 'settings/title',
'bypass' => TRUE,
'map' => [
'disabled' => DRUPAL_DISABLED,
'optional' => DRUPAL_OPTIONAL,
'required' => DRUPAL_REQUIRED,
],
];
$migration->mergeProcessOfProperty('settings/title', $process);
}
}

View File

@@ -0,0 +1,146 @@
<?php
namespace Drupal\link\Plugin\migrate\process;
use Drupal\migrate\Attribute\MigrateProcess;
use Drupal\migrate\Plugin\MigrationInterface;
use Drupal\migrate\MigrateExecutableInterface;
use Drupal\migrate\ProcessPluginBase;
use Drupal\migrate\Row;
/**
* Transform a pre-Drupal 8 formatted link for use in Drupal 8.
*
* Previous to Drupal 8, URLs didn't need to have a URI scheme assigned. The
* contrib link module would auto-prefix the URL with a URI scheme. A link in
* Drupal 8 has more validation and external links must include the URI scheme.
* All external URIs need to be converted to use a URI scheme.
*
* Available configuration keys
* - uri_scheme: (optional) The URI scheme prefix to use for URLs without a
* scheme. Defaults to 'http://', which was the default in Drupal 6 and
* Drupal 7.
*
* Examples:
*
* Consider a link field migration, where you want to use https:// as the
* prefix:
*
* @code
* process:
* field_link:
* plugin: field_link
* uri_scheme: 'https://'
* source: field_link
* @endcode
*/
#[MigrateProcess('field_link')]
class FieldLink extends ProcessPluginBase {
/**
* {@inheritdoc}
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition, MigrationInterface $migration) {
$configuration += ['uri_scheme' => 'http://'];
parent::__construct($configuration, $plugin_id, $plugin_definition);
}
/**
* Turn a Drupal 6/7 URI into a Drupal 8-compatible format.
*
* @param string $uri
* The 'url' value from Drupal 6/7.
*
* @return string
* The Drupal 8-compatible URI.
*
* @see \Drupal\link\Plugin\Field\FieldWidget\LinkWidget::getUserEnteredStringAsUri()
*/
protected function canonicalizeUri($uri) {
// If the path starts with 2 slashes then it is always considered an
// external URL without an explicit protocol part.
// @todo Remove this when https://www.drupal.org/node/2744729 lands.
if (str_starts_with($uri, '//')) {
return $this->configuration['uri_scheme'] . ltrim($uri, '/');
}
// If we already have a scheme, we're fine.
if (parse_url($uri, PHP_URL_SCHEME)) {
return $uri;
}
// Empty URI and non-links are allowed.
if (empty($uri) || in_array($uri, ['<nolink>', '<none>'])) {
return 'route:<nolink>';
}
// Remove the <front> component of the URL.
if (str_starts_with($uri, '<front>')) {
$uri = substr($uri, strlen('<front>'));
}
else {
// List of unicode-encoded characters that were allowed in URLs,
// according to link module in Drupal 7. Every character between &#x00BF;
// and &#x00FF; (except × &#x00D7; and ÷ &#x00F7;) with the addition of
// &#x0152;, &#x0153; and &#x0178;.
// @see https://git.drupalcode.org/project/link/blob/7.x-1.5-beta2/link.module#L1382
// cSpell:disable-next-line
$link_i_chars = '¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿŒœŸ';
// Pattern specific to internal links.
$internal_pattern = "/^(?:[a-z0-9" . $link_i_chars . "_\-+\[\] ]+)";
$directories = "(?:\/[a-z0-9" . $link_i_chars . "_\-\.~+%=&,$'#!():;*@\[\]]*)*";
// Yes, four backslashes == a single backslash.
$query = "(?:\/?\?([?a-z0-9" . $link_i_chars . "+_|\-\.~\/\\\\%=&,$'():;*@\[\]{} ]*))";
$anchor = "(?:#[a-z0-9" . $link_i_chars . "_\-\.~+%=&,$'():;*@\[\]\/\?]*)";
// The rest of the path for a standard URL.
$end = $directories . '?' . $query . '?' . $anchor . '?$/i';
if (!preg_match($internal_pattern . $end, $uri)) {
$link_domains = '[a-z][a-z0-9-]{1,62}';
// Starting a parenthesis group with (?: means that it is grouped, but is not captured
$authentication = "(?:(?:(?:[\w\.\-\+!$&'\(\)*\+,;=" . $link_i_chars . "]|%[0-9a-f]{2})+(?::(?:[\w" . $link_i_chars . "\.\-\+%!$&'\(\)*\+,;=]|%[0-9a-f]{2})*)?)?@)";
$domain = '(?:(?:[a-z0-9' . $link_i_chars . ']([a-z0-9' . $link_i_chars . '\-_\[\]])*)(\.(([a-z0-9' . $link_i_chars . '\-_\[\]])+\.)*(' . $link_domains . '|[a-z]{2}))?)';
$ipv4 = '(?:[0-9]{1,3}(\.[0-9]{1,3}){3})';
$ipv6 = '(?:[0-9a-fA-F]{1,4}(\:[0-9a-fA-F]{1,4}){7})';
$port = '(?::([0-9]{1,5}))';
// Pattern specific to external links.
$external_pattern = '/^' . $authentication . '?(' . $domain . '|' . $ipv4 . '|' . $ipv6 . ' |localhost)' . $port . '?';
if (preg_match($external_pattern . $end, $uri)) {
return $this->configuration['uri_scheme'] . $uri;
}
}
}
// Add the internal: scheme and ensure a leading slash.
return 'internal:/' . ltrim($uri, '/');
}
/**
* {@inheritdoc}
*/
public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {
$attributes = unserialize($value['attributes']);
// Drupal 6/7 link attributes might be double serialized.
if (!is_array($attributes)) {
$attributes = unserialize($attributes);
}
// In rare cases Drupal 6/7 link attributes are triple serialized. To avoid
// further problems with them we set them to an empty array in this case.
if (!is_array($attributes)) {
$attributes = [];
}
// Massage the values into the correct form for the link.
$route['uri'] = $this->canonicalizeUri($value['url']);
$route['options']['attributes'] = $attributes;
$route['title'] = $value['title'];
return $route;
}
}

View File

@@ -0,0 +1,20 @@
{#
/**
* @file
* Default theme implementation of a link with separate title and URL elements.
*
* Available variables:
* - link: The link that has already been formatted by l().
* - title: (optional) A descriptive or alternate title for the link, which may
* be different than the actual link text.
*
* @see template_preprocess()
* @see template_preprocess_link_formatter_link_separate()
*
* @ingroup themeable
*/
#}
{% apply spaceless %}
{{ title }}
{{ link }}
{% endapply %}

View File

@@ -0,0 +1,12 @@
name: Link test base field
description: Tests link field as an optional base field
type: module
hidden: true
dependencies:
- drupal:link
- drupal:entity_test
# Information added by Drupal.org packaging script on 2024-07-04
version: '10.3.1'
project: 'drupal'
datestamp: 1720094222

View File

@@ -0,0 +1,35 @@
<?php
/**
* @file
* Contains main module functions.
*/
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\link\LinkItemInterface;
/**
* Implements hook_entity_base_field_info().
*/
function link_test_base_field_entity_base_field_info(EntityTypeInterface $entity_type) {
$fields = [];
if ($entity_type->id() === 'entity_test') {
$fields['links'] = BaseFieldDefinition::create('link')
->setLabel(t('Links'))
->setRevisionable(TRUE)
->setCardinality(FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED)
->setDescription(t('Add links to the entity.'))
->setRequired(FALSE)
->setSettings([
'link_type' => LinkItemInterface::LINK_GENERIC,
'title' => DRUPAL_REQUIRED,
])
->setDisplayOptions('form', [
'type' => 'link_default',
'weight' => 49,
]);
}
return $fields;
}

View File

@@ -0,0 +1,14 @@
name: 'Link test views'
type: module
description: 'Provides default views for views link tests.'
package: Testing
# version: VERSION
dependencies:
- drupal:node
- drupal:views
- drupal:link
# Information added by Drupal.org packaging script on 2024-07-04
version: '10.3.1'
project: 'drupal'
datestamp: 1720094222

View File

@@ -0,0 +1,205 @@
langcode: en
status: true
dependencies:
config:
- field.storage.node.field_link
module:
- link
- node
- user
id: test_link_tokens
label: link
module: views
description: ''
tag: ''
base_table: node_field_data
base_field: nid
display:
default:
display_plugin: default
id: default
display_title: Default
position: 0
display_options:
access:
type: perm
options:
perm: 'access content'
cache:
type: tag
options: { }
query:
type: views_query
options:
disable_sql_rewrite: false
distinct: false
replica: false
query_comment: ''
query_tags: { }
exposed_form:
type: basic
options:
submit_button: Apply
reset_button: false
reset_button_label: Reset
exposed_sorts_label: 'Sort by'
expose_sort_order: true
sort_asc_label: Asc
sort_desc_label: Desc
pager:
type: full
options:
items_per_page: 10
offset: 0
id: 0
total_pages: null
expose:
items_per_page: false
items_per_page_label: 'Items per page'
items_per_page_options: '5, 10, 25, 50'
items_per_page_options_all: false
items_per_page_options_all_label: '- All -'
offset: false
offset_label: Offset
tags:
previous: ' previous'
next: 'next '
first: '« first'
last: 'last »'
quantity: 9
style:
type: default
row:
type: fields
options:
default_field_elements: true
inline: { }
separator: ''
hide_empty: false
fields:
field_link:
id: field_link
table: node__field_link
field: field_link
relationship: none
group_type: group
admin_label: ''
label: ''
exclude: false
alter:
alter_text: true
text: "Formatted: {{ field_link }}<br />\nRaw uri: {{ field_link__uri }}<br />\nRaw title: {{ field_link__title }}<br />\nRaw options: {{ field_link__options }}."
make_link: false
path: '{{ field_link__uri }}'
absolute: false
external: false
replace_spaces: false
path_case: none
trim_whitespace: false
alt: ''
rel: ''
link_class: ''
prefix: ''
suffix: ''
target: ''
nl2br: false
max_length: 0
word_boundary: true
ellipsis: true
more_link: false
more_link_text: ''
more_link_path: ''
strip_tags: false
trim: false
preserve_tags: ''
html: false
element_type: ''
element_class: ''
element_label_type: ''
element_label_class: ''
element_label_colon: false
element_wrapper_type: ''
element_wrapper_class: ''
element_default_classes: true
empty: ''
hide_empty: false
empty_zero: false
hide_alter_empty: true
click_sort_column: uri
type: link
settings:
trim_length: 80
url_only: false
url_plain: false
rel: '0'
target: '0'
group_column: ''
group_columns: { }
group_rows: true
delta_limit: 0
delta_offset: 0
delta_reversed: false
delta_first_last: false
multi_type: separator
separator: ', '
field_api_classes: false
plugin_id: field
filters:
status:
value: '1'
table: node_field_data
field: status
plugin_id: boolean
entity_type: node
entity_field: status
id: status
expose:
operator: ''
group: 1
sorts:
created:
id: created
table: node_field_data
field: created
order: DESC
entity_type: node
entity_field: created
plugin_id: date
relationship: none
group_type: group
admin_label: ''
exposed: false
expose:
label: ''
granularity: second
title: link
header: { }
footer: { }
empty: { }
relationships: { }
arguments: { }
display_extenders: { }
cache_metadata:
contexts:
- 'languages:language_content'
- 'languages:language_interface'
- url.query_args
- 'user.node_grants:view'
- user.permissions
cacheable: false
page_1:
display_plugin: page
id: page_1
display_title: Page
position: 1
display_options:
display_extenders: { }
path: test_link_tokens
cache_metadata:
contexts:
- 'languages:language_content'
- 'languages:language_interface'
- url.query_args
- 'user.node_grants:view'
- user.permissions
cacheable: false

View File

@@ -0,0 +1,14 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\link\Functional;
use Drupal\Tests\system\Functional\Module\GenericModuleTestBase;
/**
* Generic module test for link.
*
* @group link
*/
class GenericTest extends GenericModuleTestBase {}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,259 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\link\Functional;
use Drupal\Core\Url;
use Drupal\Component\Utility\Html;
use Drupal\Core\Entity\Entity\EntityFormDisplay;
use Drupal\link\LinkItemInterface;
use Drupal\Tests\BrowserTestBase;
use Drupal\Tests\field_ui\Traits\FieldUiTestTrait;
/**
* Tests link field UI functionality.
*
* @group link
*/
class LinkFieldUITest extends BrowserTestBase {
use FieldUiTestTrait;
/**
* Modules to enable.
*
* @var array
*/
protected static $modules = ['node', 'link', 'field_ui', 'block'];
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* A user that can edit content types.
*
* @var \Drupal\user\UserInterface
*/
protected $adminUser;
/**
* A user that should see the help texts.
*
* @var \Drupal\user\Entity\User
*/
protected $helpTextUser;
/**
* The content type to add fields to.
*
* @var \Drupal\node\Entity\NodeType
*/
protected $contentType;
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$this->contentType = $this->drupalCreateContentType();
$this->adminUser = $this->drupalCreateUser([
'administer content types',
'administer node fields',
'administer node display',
]);
$this->helpTextUser = $this->drupalCreateUser([
'create ' . $this->contentType->id() . ' content',
]);
$this->drupalPlaceBlock('system_breadcrumb_block');
}
/**
* Tests the link field UI.
*/
public function testFieldUI(): void {
foreach ($this->providerTestFieldUI() as $item) {
[$cardinality, $link_type, $title, $label, $field_name, $default_uri] = $item;
$this->runFieldUIItem($cardinality, $link_type, $title, $label, $field_name, $default_uri);
}
}
/**
* Provides test data for ::testFieldUI().
*/
protected function providerTestFieldUI() {
// There are many combinations of field settings: where the description
// should show: variation on internal, external, both; cardinality (where
// the fieldset is hidden or used); and link text shown (required or
// optional) or disabled. There are two descriptions: field and URL help
// text.
$cardinalities = [1, 2];
$title_settings = [
DRUPAL_DISABLED,
DRUPAL_OPTIONAL,
];
$link_types = [
LinkItemInterface::LINK_EXTERNAL => 'https://example.com',
LinkItemInterface::LINK_GENERIC => '',
LinkItemInterface::LINK_INTERNAL => '<front>',
];
// Test all variations of link types on all cardinalities.
foreach ($cardinalities as $cardinality) {
foreach ($link_types as $link_type => $default_uri) {
// Now, test this with both the title enabled and disabled.
foreach ($title_settings as $title_setting) {
// Test both empty and non-empty labels.
foreach ([TRUE, FALSE] as $label_provided) {
// Generate a unique machine name for the field so it can be
// identified in the test.
$id = implode('_', [
'link',
$cardinality,
$link_type,
$title_setting,
(int) $label_provided,
]);
// Use a unique label that contains some HTML.
$label = '<img src="https://example.com">' . $id;
yield [
$cardinality,
$link_type,
$title_setting,
$label_provided ? $label : '',
$id,
$default_uri,
];
}
}
}
}
}
/**
* Tests one link field UI item.
*
* @param int $cardinality
* The field cardinality.
* @param int $link_type
* Determine if the link is external, internal or both.
* @param int $title
* Determine if the field will display the link text field.
* @param string $label
* The field label.
* @param string $field_name
* The unique machine name for the field.
* @param string $default_uri
* The default URI value.
*/
public function runFieldUIItem($cardinality, $link_type, $title, $label, $field_name, $default_uri) {
$this->drupalLogin($this->adminUser);
$type_path = 'admin/structure/types/manage/' . $this->contentType->id();
// Add a link field to the newly-created type.
$description = 'link field description';
$field_edit = [
'description' => $description,
'settings[link_type]' => (int) $link_type,
];
if (!empty($default_uri)) {
$field_edit['set_default_value'] = '1';
$field_edit['default_value_input[field_' . $field_name . '][0][uri]'] = $default_uri;
$field_edit['default_value_input[field_' . $field_name . '][0][title]'] = 'Default title';
}
$storage_edit = [
'cardinality_number' => $cardinality,
];
$this->fieldUIAddNewField($type_path, $field_name, $label, 'link', $storage_edit, $field_edit);
// Load the formatter page to check that the settings summary does not
// generate warnings.
// @todo Mess with the formatter settings a bit here.
$this->drupalGet("$type_path/display");
$this->assertSession()->pageTextContains('Link text trimmed to 80 characters');
// Make the fields visible in the form display.
$form_display_id = implode('.', ['node', $this->contentType->id(), 'default']);
$form_display = EntityFormDisplay::load($form_display_id);
$form_display->setComponent($field_name, ['region' => 'content']);
$form_display->save();
// Log in a user that is allowed to create this content type, see if
// the user can see the expected help text.
$this->drupalLogin($this->helpTextUser);
$add_path = 'node/add/' . $this->contentType->id();
$this->drupalGet($add_path);
$expected_help_texts = [
LinkItemInterface::LINK_EXTERNAL => 'This must be an external URL such as <em class="placeholder">https://example.com</em>.',
LinkItemInterface::LINK_GENERIC => 'You can also enter an internal path such as <em class="placeholder">/node/add</em> or an external URL such as <em class="placeholder">https://example.com</em>. Enter <em class="placeholder">&lt;front&gt;</em> to link to the front page. Enter <em class="placeholder">&lt;nolink&gt;</em> to display link text only',
LinkItemInterface::LINK_INTERNAL => rtrim(Url::fromRoute('<front>', [], ['absolute' => TRUE])->toString(), '/'),
];
// Check that the help texts we assume should be there, is there.
$this->assertFieldContainsRawText($field_name, $expected_help_texts[$link_type]);
if ($link_type === LinkItemInterface::LINK_INTERNAL) {
// Internal links have no "system" description. Test that none
// of the other help texts show here.
$this->assertNoFieldContainsRawText($field_name, $expected_help_texts[LinkItemInterface::LINK_EXTERNAL]);
$this->assertNoFieldContainsRawText($field_name, $expected_help_texts[LinkItemInterface::LINK_GENERIC]);
}
// Also assert that the description we made is here, no matter what the
// cardinality or link setting.
if (!empty($label)) {
$this->assertFieldContainsRawText($field_name, $label);
}
// Test the default field value is used as expected.
$this->assertSession()->fieldValueEquals('field_' . $field_name . '[0][uri]', $default_uri);
}
/**
* Checks that given field contains the given raw text.
*
* @param string $field_name
* The name of the field to check.
* @param string $text
* The text to check.
*
* @internal
*/
protected function assertFieldContainsRawText(string $field_name, string $text): void {
$this->assertTrue((bool) preg_match('/' . preg_quote($text, '/') . '/ui', $this->getFieldHtml($field_name)));
}
/**
* Checks that given field does not contain the given raw text.
*
* @param string $field_name
* The name of the field to check.
* @param string $text
* The text to check.
*
* @internal
*/
protected function assertNoFieldContainsRawText(string $field_name, string $text): void {
$this->assertFalse((bool) preg_match('/' . preg_quote($text, '/') . '/ui', $this->getFieldHtml($field_name)));
}
/**
* Returns the raw HTML for the given field.
*
* @param $field_name
* The name of the field for which to return the HTML.
*
* @return string
* The raw HTML.
*/
protected function getFieldHtml($field_name) {
$css_id = Html::cleanCssIdentifier('edit-field-' . $field_name . '-wrapper');
return $this->xpath('//*[@id=:id]', [':id' => $css_id])[0]->getHtml();
}
}

View File

@@ -0,0 +1,103 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\link\Functional\Views;
use Drupal\field\Entity\FieldConfig;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\Tests\views\Functional\ViewTestBase;
/**
* Tests the views integration for link tokens.
*
* @group link
*/
class LinkViewsTokensTest extends ViewTestBase {
/**
* Modules to enable.
*
* @var array
*/
protected static $modules = ['link_test_views'];
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* Views used by this test.
*
* @var array
*/
public static $testViews = ['test_link_tokens'];
/**
* The field name used for the link field.
*
* @var string
*/
protected $fieldName = 'field_link';
/**
* {@inheritdoc}
*/
protected function setUp($import_test_views = TRUE, $modules = ['link_test_views']): void {
parent::setUp($import_test_views, $modules);
// Create Basic page node type.
$this->drupalCreateContentType([
'type' => 'page',
'name' => 'Basic page',
]);
// Create a field.
FieldStorageConfig::create([
'field_name' => $this->fieldName,
'type' => 'link',
'entity_type' => 'node',
'cardinality' => 1,
])->save();
FieldConfig::create([
'field_name' => $this->fieldName,
'entity_type' => 'node',
'bundle' => 'page',
'label' => 'link field',
])->save();
}
public function testLinkViewsTokens(): void {
// Array of URI's to test.
$uris = [
'http://www.example.com' => 'example.com',
];
// Add nodes with the URI's and titles.
foreach ($uris as $uri => $title) {
$values = ['type' => 'page'];
$values[$this->fieldName][] = ['uri' => $uri, 'title' => $title, 'options' => ['attributes' => ['class' => 'test-link-class']]];
$this->drupalCreateNode($values);
}
$this->drupalGet('test_link_tokens');
foreach ($uris as $uri => $title) {
// Formatted link: {{ field_link }}<br />
$this->assertSession()->responseContains("Formatted: <a href=\"$uri\" class=\"test-link-class\">$title</a>");
// Raw uri: {{ field_link__uri }}<br />
$this->assertSession()->responseContains("Raw uri: $uri");
// Raw title: {{ field_link__title }}<br />
$this->assertSession()->responseContains("Raw title: $title");
// Raw options: {{ field_link__options }}<br />
// Options is an array and should return empty after token replace.
$this->assertSession()->responseContains("Raw options: .");
}
}
}

View File

@@ -0,0 +1,80 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\link\FunctionalJavascript;
use Drupal\FunctionalJavascriptTests\WebDriverTestBase;
/**
* Tests link field form states functionality.
*
* @group link
*/
class LinkFieldFormStatesTest extends WebDriverTestBase {
/**
* {@inheritdoc}
*/
protected static $modules = [
'entity_test',
'link',
'node',
'link_test_base_field',
];
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$this->drupalLogin($this->drupalCreateUser([
'administer entity_test content',
]));
}
/**
* @dataProvider linkFieldFormStatesData
*/
public function testLinkFieldFormStates(string $uri, string $title): void {
$this->drupalGet('entity_test/add');
$session = $this->assertSession();
$session->elementNotExists('css', '#edit-links-0-uri[required]');
$session->elementNotExists('css', '#edit-links-0-title[required]');
$page = $this->getSession()->getPage();
if ($uri !== '') {
$page->fillField('links[0][uri]', $uri);
$session->elementNotExists('css', '#edit-links-0-uri[required]');
$session->elementExists('css', '#edit-links-0-title[required]');
}
else {
$page->fillField('links[0][title]', $title);
$session->elementExists('css', '#edit-links-0-uri[required]');
$session->elementNotExists('css', '#edit-links-0-title[required]');
}
}
/**
* Provides data for ::testLinkFieldJSFormStates.
*/
public static function linkFieldFormStatesData() {
return [
'Fill uri, keep title empty' => [
'https://example.com',
'',
],
'Fill title, keep uri empty' => [
'',
'https://example.com',
],
];
}
}

View File

@@ -0,0 +1,107 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\link\Kernel;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\field\Entity\FieldConfig;
use Drupal\link\LinkItemInterface;
use Drupal\entity_test\Entity\EntityTest;
use Drupal\Component\Utility\UrlHelper;
use Drupal\Tests\field\Kernel\FieldKernelTestBase;
/**
* Tests link field serialization.
*
* @group link
*/
class LinkItemSerializationTest extends FieldKernelTestBase {
/**
* {@inheritdoc}
*/
protected static $modules = ['link', 'serialization'];
/**
* The serializer service.
*
* @var \Symfony\Component\Serializer\SerializerInterface
*/
protected $serializer;
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$this->installEntitySchema('user');
$this->serializer = \Drupal::service('serializer');
// Create a generic, external, and internal link fields for validation.
FieldStorageConfig::create([
'entity_type' => 'entity_test',
'field_name' => 'field_test',
'type' => 'link',
])->save();
FieldConfig::create([
'entity_type' => 'entity_test',
'field_name' => 'field_test',
'bundle' => 'entity_test',
'settings' => ['link_type' => LinkItemInterface::LINK_GENERIC],
])->save();
}
/**
* Tests the serialization.
*/
public function testLinkSerialization(): void {
// Create entity.
$entity = EntityTest::create();
$url = 'https://www.drupal.org?test_param=test_value';
$parsed_url = UrlHelper::parse($url);
$title = $this->randomMachineName();
$class = $this->randomMachineName();
$entity->field_test->uri = $parsed_url['path'];
$entity->field_test->title = $title;
$entity->field_test->first()
->get('options')
->set('query', $parsed_url['query']);
$entity->field_test->first()
->get('options')
->set('attributes', ['class' => $class]);
$entity->save();
$serialized = $this->serializer->serialize($entity, 'json');
$deserialized = $this->serializer->deserialize($serialized, EntityTest::class, 'json');
$options_expected = [
'query' => $parsed_url['query'],
'attributes' => ['class' => $class],
];
$this->assertSame($options_expected, $deserialized->field_test->options);
}
/**
* Tests the deserialization.
*/
public function testLinkDeserialization(): void {
// Create entity.
$entity = EntityTest::create();
$url = 'https://www.drupal.org?test_param=test_value';
$parsed_url = UrlHelper::parse($url);
$title = $this->randomMachineName();
$entity->field_test->uri = $parsed_url['path'];
$entity->field_test->title = $title;
$entity->field_test->first()
->get('options')
->set('query', $parsed_url['query']);
$json = json_decode($this->serializer->serialize($entity, 'json'), TRUE);
$json['field_test'][0]['options'] = 'string data';
$serialized = json_encode($json);
$this->expectException(\LogicException::class);
$this->expectExceptionMessage('The generic FieldItemNormalizer cannot denormalize string values for "options" properties of the "field_test" field (field item class: Drupal\link\Plugin\Field\FieldType\LinkItem).');
$this->serializer->deserialize($serialized, EntityTest::class, 'json');
}
}

View File

@@ -0,0 +1,183 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\link\Kernel;
use Drupal\Component\Utility\UrlHelper;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FieldItemInterface;
use Drupal\Core\Url;
use Drupal\entity_test\Entity\EntityTest;
use Drupal\field\Entity\FieldConfig;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\Tests\field\Kernel\FieldKernelTestBase;
use Drupal\link\LinkItemInterface;
/**
* Tests the new entity API for the link field type.
*
* @group link
*/
class LinkItemTest extends FieldKernelTestBase {
/**
* Modules to enable.
*
* @var array
*/
protected static $modules = ['link'];
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
// Create a generic, external, and internal link fields for validation.
FieldStorageConfig::create([
'field_name' => 'field_test',
'entity_type' => 'entity_test',
'type' => 'link',
])->save();
FieldConfig::create([
'entity_type' => 'entity_test',
'field_name' => 'field_test',
'bundle' => 'entity_test',
'settings' => ['link_type' => LinkItemInterface::LINK_GENERIC],
])->save();
FieldStorageConfig::create([
'field_name' => 'field_test_external',
'entity_type' => 'entity_test',
'type' => 'link',
])->save();
FieldConfig::create([
'entity_type' => 'entity_test',
'field_name' => 'field_test_external',
'bundle' => 'entity_test',
'settings' => ['link_type' => LinkItemInterface::LINK_EXTERNAL],
])->save();
FieldStorageConfig::create([
'field_name' => 'field_test_internal',
'entity_type' => 'entity_test',
'type' => 'link',
])->save();
FieldConfig::create([
'entity_type' => 'entity_test',
'field_name' => 'field_test_internal',
'bundle' => 'entity_test',
'settings' => ['link_type' => LinkItemInterface::LINK_INTERNAL],
])->save();
}
/**
* Tests using entity fields of the link field type.
*/
public function testLinkItem(): void {
// Create entity.
$entity = EntityTest::create();
$url = 'https://www.drupal.org?test_param=test_value';
$parsed_url = UrlHelper::parse($url);
$title = $this->randomMachineName();
$class = $this->randomMachineName();
$entity->field_test->uri = $parsed_url['path'];
$entity->field_test->title = $title;
$entity->field_test->first()->get('options')->set('query', $parsed_url['query']);
$entity->field_test->first()->get('options')->set('attributes', ['class' => $class]);
$this->assertEquals([
'query' => $parsed_url['query'],
'attributes' => [
'class' => $class,
],
'external' => TRUE,
], $entity->field_test->first()->getUrl()->getOptions());
$entity->name->value = $this->randomMachineName();
$entity->save();
// Verify that the field value is changed.
$id = $entity->id();
$entity = EntityTest::load($id);
$this->assertInstanceOf(FieldItemListInterface::class, $entity->field_test);
$this->assertInstanceOf(FieldItemInterface::class, $entity->field_test[0]);
$this->assertEquals($parsed_url['path'], $entity->field_test->uri);
$this->assertEquals($parsed_url['path'], $entity->field_test[0]->uri);
$this->assertEquals($title, $entity->field_test->title);
$this->assertEquals($title, $entity->field_test[0]->title);
$this->assertEquals($title, $entity->field_test[0]->getTitle());
$this->assertEquals($class, $entity->field_test->options['attributes']['class']);
$this->assertEquals($parsed_url['query'], $entity->field_test->options['query']);
// Update only the entity name property to check if the link field data will
// remain intact.
$entity->name->value = $this->randomMachineName();
$entity->save();
$id = $entity->id();
$entity = EntityTest::load($id);
$this->assertEquals($parsed_url['path'], $entity->field_test->uri);
$this->assertEquals($class, $entity->field_test->options['attributes']['class']);
$this->assertEquals($parsed_url['query'], $entity->field_test->options['query']);
// Verify changing the field value.
$new_url = 'https://www.drupal.org';
$new_title = $this->randomMachineName();
$new_class = $this->randomMachineName();
$entity->field_test->uri = $new_url;
$entity->field_test->title = $new_title;
$entity->field_test->first()->get('options')->set('query', NULL);
$entity->field_test->first()->get('options')->set('attributes', ['class' => $new_class]);
$this->assertEquals($new_url, $entity->field_test->uri);
$this->assertEquals($new_title, $entity->field_test->title);
$this->assertEquals($new_class, $entity->field_test->options['attributes']['class']);
$this->assertNull($entity->field_test->options['query']);
// Read changed entity and assert changed values.
$entity->save();
$entity = EntityTest::load($id);
$this->assertEquals($new_url, $entity->field_test->uri);
$this->assertEquals($new_title, $entity->field_test->title);
$this->assertEquals($new_class, $entity->field_test->options['attributes']['class']);
// Check that if we only set uri the default values for title and options
// are also initialized.
$entity->field_test = ['uri' => 'internal:/node/add'];
$this->assertEquals('internal:/node/add', $entity->field_test->uri);
$this->assertNull($entity->field_test->title);
$this->assertSame([], $entity->field_test->options);
// Check that if we set uri and options then the default values are properly
// initialized.
$entity->field_test = [
'uri' => 'internal:/node/add',
'options' => ['query' => NULL],
];
$this->assertEquals('internal:/node/add', $entity->field_test->uri);
$this->assertNull($entity->field_test->title);
$this->assertNull($entity->field_test->options['query']);
// Check that if we set the direct value of link field it correctly set the
// uri and the default values of the field.
$entity->field_test = 'internal:/node/add';
$this->assertEquals('internal:/node/add', $entity->field_test->uri);
$this->assertNull($entity->field_test->title);
$this->assertSame([], $entity->field_test->options);
// Check that setting options to NULL does not trigger an error when
// calling getUrl();
$entity->field_test->options = NULL;
$this->assertInstanceOf(Url::class, $entity->field_test[0]->getUrl());
// Check that setting LinkItem value NULL doesn't generate any error or
// warning.
$entity->field_test[0] = NULL;
$this->assertNull($entity->field_test[0]->getValue());
// Test the generateSampleValue() method for generic, external, and internal
// link types.
$entity = EntityTest::create();
$entity->field_test->generateSampleItems();
$entity->field_test_external->generateSampleItems();
$entity->field_test_internal->generateSampleItems();
$this->entityValidateAndSave($entity);
}
}

View File

@@ -0,0 +1,124 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\link\Kernel;
use Drupal\Tests\field\Kernel\FieldKernelTestBase;
/**
* Tests link field validation.
*
* @group link
*/
class LinkItemUrlValidationTest extends FieldKernelTestBase {
/**
* {@inheritdoc}
*/
protected static $modules = ['link'];
/**
* Tests link validation.
*/
public function testExternalLinkValidation(): void {
$definition = \Drupal::typedDataManager()
->createDataDefinition('field_item:link');
$link_item = \Drupal::typedDataManager()->create($definition);
$test_links = $this->getTestLinks();
foreach ($test_links as $data) {
[$value, $expected_violations] = $data;
$link_item->setValue($value);
$violations = $link_item->validate();
$expected_count = count($expected_violations);
$this->assertCount($expected_count, $violations, sprintf('Violation message count error for %s', $value));
if ($expected_count) {
$i = 0;
foreach ($expected_violations as $error_msg) {
// If the expected message contains a '%' add the current link value.
if (strpos($error_msg, '%')) {
$error_msg = sprintf($error_msg, $value);
}
$this->assertEquals($error_msg, $violations[$i++]->getMessage());
}
}
}
}
/**
* Builds an array of links to test.
*
* @return array
* The first element of the array is the link value to test. The second
* value is an array of expected violation messages.
*/
protected function getTestLinks() {
$violation_0 = "The path '%s' is invalid.";
$violation_1 = 'This value should be of the correct primitive type.';
return [
['invalid://not-a-valid-protocol', [$violation_0]],
['http://www.example.com/', []],
// Strings within parenthesis without leading space char.
['http://www.example.com/strings_(string_within_parenthesis)', []],
// Numbers within parenthesis without leading space char.
['http://www.example.com/numbers_(9999)', []],
['http://www.example.com/?name=ferret&color=purple', []],
['http://www.example.com/page?name=ferret&color=purple', []],
['http://www.example.com?a=&b[]=c&d[]=e&d[]=f&h==', []],
['http://www.example.com#colors', []],
// Use list of valid URLS from],
// https://cran.r-project.org/web/packages/rex/vignettes/url_parsing.html.
["http://foo.com/blah_blah", []],
["http://foo.com/blah_blah/", []],
["http://foo.com/blah_blah_(wikipedia)", []],
["http://foo.com/blah_blah_(wikipedia)_(again)", []],
["http://www.example.com/wpstyle/?p=364", []],
["https://www.example.com/foo/?bar=baz&inga=42&quux", []],
["http://✪df.ws/123", []],
["http://userid:password@example.com:8080", []],
["http://userid:password@example.com:8080/", []],
["http://userid@example.com", []],
["http://userid@example.com/", []],
["http://userid@example.com:8080", []],
["http://userid@example.com:8080/", []],
["http://userid:password@example.com", []],
["http://userid:password@example.com/", []],
["http://➡.ws/䨹", []],
["http://⌘.ws", []],
["http://⌘.ws/", []],
["http://foo.com/blah_(wikipedia)#cite-1", []],
["http://foo.com/blah_(wikipedia)_blah#cite-1", []],
// The following invalid URLs produce false positives.
["http://foo.com/unicode_(✪)_in_parens", []],
["http://foo.com/(something)?after=parens", []],
["http://☺.damowmow.com/", []],
["http://code.google.com/events/#&product=browser", []],
["http://j.mp", []],
["ftp://foo.bar/baz", []],
["http://foo.bar/?q=Test%20URL-encoded%20stuff", []],
["http://مثال.إختبار", []],
["http://例子.测试", []],
["http://-.~_!$&'()*+,;=:%40:80%2f::::::@example.com", []],
["http://1337.net", []],
["http://a.b-c.de", []],
["radar://1234", [$violation_0]],
["h://test", [$violation_0]],
["ftps://foo.bar/", [$violation_0]],
// Use invalid URLS from
// https://cran.r-project.org/web/packages/rex/vignettes/url_parsing.html.
['http://', [$violation_0, $violation_1]],
["http://?", [$violation_0, $violation_1]],
["http://??", [$violation_0, $violation_1]],
["http://??/", [$violation_0, $violation_1]],
["http://#", [$violation_0, $violation_1]],
["http://##", [$violation_0, $violation_1]],
["http://##/", [$violation_0, $violation_1]],
["//", [$violation_0, $violation_1]],
["///a", [$violation_0, $violation_1]],
["///", [$violation_0, $violation_1]],
["http:///a", [$violation_0, $violation_1]],
];
}
}

View File

@@ -0,0 +1,74 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\link\Kernel\Plugin\migrate\field\d7;
use Drupal\KernelTests\KernelTestBase;
use Drupal\migrate\Plugin\MigrationInterface;
use Drupal\link\Plugin\migrate\field\d7\LinkField;
use Prophecy\Argument;
/**
* @coversDefaultClass \Drupal\link\Plugin\migrate\field\d7\LinkField
* @group link
*/
class LinkFieldTest extends KernelTestBase {
/**
* {@inheritdoc}
*/
protected static $modules = ['system'];
/**
* @var \Drupal\migrate_drupal\Plugin\MigrateFieldInterface
*/
protected $plugin;
/**
* @var \Drupal\migrate\Plugin\MigrationInterface
*/
protected $migration;
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$this->plugin = new LinkField([], 'link', []);
$migration = $this->prophesize(MigrationInterface::class);
// The plugin's alterFieldInstanceMigration() method will call
// mergeProcessOfProperty() and return nothing. So, in order to examine the
// process pipeline created by the plugin, we need to ensure that
// getProcess() always returns the last input to mergeProcessOfProperty().
$migration->mergeProcessOfProperty(Argument::type('string'), Argument::type('array'))
->will(function ($arguments) use ($migration) {
$migration->getProcess()->willReturn($arguments[1]);
});
$this->migration = $migration->reveal();
}
/**
* @covers ::alterFieldInstanceMigration
*/
public function testAlterFieldInstanceMigration($method = 'alterFieldInstanceMigration'): void {
$this->plugin->$method($this->migration);
$expected = [
'plugin' => 'static_map',
'source' => 'settings/title',
'bypass' => TRUE,
'map' => [
'disabled' => DRUPAL_DISABLED,
'optional' => DRUPAL_OPTIONAL,
'required' => DRUPAL_REQUIRED,
],
];
$this->assertSame($expected, $this->migration->getProcess());
}
}

View File

@@ -0,0 +1,155 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\link\Unit;
use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemList;
use Drupal\Core\Field\FieldTypePluginManagerInterface;
use Drupal\Core\Path\PathValidatorInterface;
use Drupal\Core\Routing\UrlGenerator;
use Drupal\Core\Url;
use Drupal\link\LinkItemInterface;
use Drupal\link\Plugin\Field\FieldFormatter\LinkFormatter;
use Drupal\Tests\UnitTestCase;
/**
* Tests the Field Formatter for the link field type.
*
* @group link
*/
class LinkFormatterTest extends UnitTestCase {
/**
* Tests when LinkItem::getUrl with malformed URL renders empty link.
*
* LinkItem::getUrl will throw \InvalidArgumentException.
*/
public function testFormatterLinkItemUrlMalformed(): void {
$entity = $this->createMock(EntityInterface::class);
$linkItem = $this->createMock(LinkItemInterface::class);
$exception = new \InvalidArgumentException();
$linkItem->expects($this->any())
->method('getParent')
->willReturn($entity);
$linkItem->expects($this->once())
->method('getUrl')
->willThrowException($exception);
$linkItem->expects($this->any())
->method('__get')
->with('options')
->willReturn([]);
$fieldDefinition = $this->createMock(FieldDefinitionInterface::class);
$fieldList = new FieldItemList($fieldDefinition, '', $linkItem);
$fieldTypePluginManager = $this->createMock(FieldTypePluginManagerInterface::class);
$fieldTypePluginManager->expects($this->once())
->method('createFieldItem')
->willReturn($linkItem);
$urlGenerator = $this->createMock(UrlGenerator::class);
$urlGenerator->expects($this->once())
->method('generateFromRoute')
->with('<none>', [], [], FALSE)
->willReturn('http://example.com');
$container = new ContainerBuilder();
$container->set('plugin.manager.field.field_type', $fieldTypePluginManager);
$container->set('url_generator', $urlGenerator);
\Drupal::setContainer($container);
$fieldList->setValue([$linkItem]);
$pathValidator = $this->createMock(PathValidatorInterface::class);
$linkFormatter = new LinkFormatter('', [], $fieldDefinition, [], '', '', [], $pathValidator);
$elements = $linkFormatter->viewElements($fieldList, 'es');
$this->assertEquals('link', $elements[0]['#type']);
}
/**
* Tests when LinkItem::getUrl throws an unexpected exception.
*/
public function testFormatterLinkItemUrlUnexpectedException(): void {
$exception = new \Exception('Unexpected!!!');
$linkItem = $this->createMock(LinkItemInterface::class);
$entity = $this->createMock(EntityInterface::class);
$linkItem->expects($this->any())
->method('getParent')
->willReturn($entity);
$linkItem->expects($this->once())
->method('getUrl')
->willThrowException($exception);
$linkItem->expects($this->any())
->method('__get')
->with('options')
->willReturn([]);
$fieldDefinition = $this->createMock(FieldDefinitionInterface::class);
$fieldList = new FieldItemList($fieldDefinition, '', $linkItem);
$fieldTypePluginManager = $this->createMock(FieldTypePluginManagerInterface::class);
$fieldTypePluginManager->expects($this->once())
->method('createFieldItem')
->willReturn($linkItem);
$container = new ContainerBuilder();
$container->set('plugin.manager.field.field_type', $fieldTypePluginManager);
\Drupal::setContainer($container);
$fieldList->setValue([$linkItem]);
$pathValidator = $this->createMock(PathValidatorInterface::class);
$linkFormatter = new LinkFormatter('', [], $fieldDefinition, [], '', '', [], $pathValidator);
$this->expectException(\Exception::class);
$this->expectExceptionMessage('Unexpected!!!');
$linkFormatter->viewElements($fieldList, 'fr');
}
/**
* Tests when LinkItem::getUrl returns a functional URL.
*/
public function testFormatterLinkItem(): void {
$expectedUrl = Url::fromUri('route:<front>');
$linkItem = $this->createMock(LinkItemInterface::class);
$entity = $this->createMock(EntityInterface::class);
$linkItem->expects($this->any())
->method('getParent')
->willReturn($entity);
$linkItem->expects($this->once())
->method('getUrl')
->willReturn($expectedUrl);
$linkItem->expects($this->any())
->method('__get')
->with('options')
->willReturn([]);
$fieldDefinition = $this->createMock(FieldDefinitionInterface::class);
$fieldList = new FieldItemList($fieldDefinition, '', $linkItem);
$fieldTypePluginManager = $this->createMock(FieldTypePluginManagerInterface::class);
$fieldTypePluginManager->expects($this->once())
->method('createFieldItem')
->willReturn($linkItem);
$urlGenerator = $this->createMock(UrlGenerator::class);
$urlGenerator->expects($this->once())
->method('generateFromRoute')
->with('<front>', [], [], FALSE)
->willReturn('http://example.com');
$container = new ContainerBuilder();
$container->set('plugin.manager.field.field_type', $fieldTypePluginManager);
$container->set('url_generator', $urlGenerator);
\Drupal::setContainer($container);
$fieldList->setValue([$linkItem]);
$pathValidator = $this->createMock(PathValidatorInterface::class);
$linkFormatter = new LinkFormatter('', [], $fieldDefinition, [], '', '', [], $pathValidator);
$elements = $linkFormatter->viewElements($fieldList, 'zh');
$this->assertEquals([
[
'#type' => 'link',
'#title' => 'http://example.com',
'#url' => $expectedUrl,
],
], $elements);
}
}

View File

@@ -0,0 +1,86 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\link\Unit\Plugin\Validation\Constraint;
use Drupal\link\Plugin\Validation\Constraint\LinkAccessConstraint;
use Drupal\link\Plugin\Validation\Constraint\LinkAccessConstraintValidator;
use Drupal\Tests\UnitTestCase;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
/**
* Tests the LinkAccessConstraintValidator validator.
*
* @coversDefaultClass \Drupal\link\Plugin\Validation\Constraint\LinkAccessConstraintValidator
* @group validation
*/
class LinkAccessConstraintValidatorTest extends UnitTestCase {
/**
* Tests the access validation constraint for links.
*
* @covers ::validate
* @dataProvider providerValidate
*/
public function testValidate(bool $mayLinkAnyPage, bool $urlAccess, bool $valid): void {
// Mock a Url object that returns a boolean indicating user access.
$url = $this->getMockBuilder('Drupal\Core\Url')
->disableOriginalConstructor()
->getMock();
if ($mayLinkAnyPage) {
$url->expects($this->never())
->method('access');
}
else {
$url->expects($this->once())
->method('access')
->willReturn($urlAccess);
}
// Mock a link object that returns the URL object.
$link = $this->createMock('Drupal\link\LinkItemInterface');
$link->expects($this->any())
->method('getUrl')
->willReturn($url);
// Mock a user object that returns a boolean indicating user access to all
// links.
$user = $this->createMock('Drupal\Core\Session\AccountProxyInterface');
$user->expects($this->any())
->method('hasPermission')
->with($this->equalTo('link to any page'))
->willReturn($mayLinkAnyPage);
$context = $this->createMock(ExecutionContextInterface::class);
if ($valid) {
$context->expects($this->never())
->method('addViolation');
}
else {
$context->expects($this->once())
->method('addViolation');
}
$constraint = new LinkAccessConstraint();
$validate = new LinkAccessConstraintValidator($user);
$validate->initialize($context);
$validate->validate($link, $constraint);
}
/**
* Data provider for LinkAccessConstraintValidator::validate().
*
* @return array
* An array of tests, matching the parameter inputs for testValidate.
*
* @see \Drupal\Tests\link\LinkAccessConstraintValidatorTest::validate()
*/
public static function providerValidate(): \Generator {
yield [TRUE, TRUE, TRUE];
yield [TRUE, FALSE, TRUE];
yield [FALSE, TRUE, TRUE];
yield [FALSE, FALSE, FALSE];
}
}

View File

@@ -0,0 +1,111 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\link\Unit\Plugin\Validation\Constraint;
use Drupal\Component\Utility\UrlHelper;
use Drupal\Core\Url;
use Drupal\link\Plugin\Validation\Constraint\LinkExternalProtocolsConstraint;
use Drupal\link\Plugin\Validation\Constraint\LinkExternalProtocolsConstraintValidator;
use Drupal\Tests\UnitTestCase;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
/**
* @coversDefaultClass \Drupal\link\Plugin\Validation\Constraint\LinkExternalProtocolsConstraintValidator
* @group Link
*/
class LinkExternalProtocolsConstraintValidatorTest extends UnitTestCase {
/**
* @covers ::validate
* @dataProvider providerValidate
* @runInSeparateProcess
*/
public function testValidate($url, $valid): void {
$link = $this->createMock('Drupal\link\LinkItemInterface');
$link->expects($this->any())
->method('getUrl')
->willReturn(Url::fromUri($url));
$context = $this->createMock(ExecutionContextInterface::class);
if ($valid) {
$context->expects($this->never())
->method('addViolation');
}
else {
$context->expects($this->once())
->method('addViolation');
}
// Setup some more allowed protocols.
UrlHelper::setAllowedProtocols(['http', 'https', 'magnet']);
$constraint = new LinkExternalProtocolsConstraint();
$validator = new LinkExternalProtocolsConstraintValidator();
$validator->initialize($context);
$validator->validate($link, $constraint);
}
/**
* Data provider for ::testValidate.
*/
public static function providerValidate() {
$data = [];
// Test allowed protocols.
$data[] = ['http://www.example.com', TRUE];
$data[] = ['https://www.example.com', TRUE];
// cSpell:disable-next-line
$data[] = ['magnet:?xt=urn:sha1:YNCKHTQCWBTRNJIV4WNAE52SJUQCZO5C', TRUE];
// Invalid protocols.
$data[] = ['ftp://ftp.funet.fi/pub/standards/RFC/rfc959.txt', FALSE];
return $data;
}
/**
* @covers ::validate
*
* @see \Drupal\Core\Url::fromUri
*/
public function testValidateWithMalformedUri(): void {
$link = $this->createMock('Drupal\link\LinkItemInterface');
$link->expects($this->any())
->method('getUrl')
->willThrowException(new \InvalidArgumentException());
$context = $this->createMock(ExecutionContextInterface::class);
$context->expects($this->never())
->method('addViolation');
$constraint = new LinkExternalProtocolsConstraint();
$validator = new LinkExternalProtocolsConstraintValidator();
$validator->initialize($context);
$validator->validate($link, $constraint);
}
/**
* @covers ::validate
*/
public function testValidateIgnoresInternalUrls(): void {
$link = $this->createMock('Drupal\link\LinkItemInterface');
$link->expects($this->any())
->method('getUrl')
->willReturn(Url::fromRoute('example.test'));
$context = $this->createMock(ExecutionContextInterface::class);
$context->expects($this->never())
->method('addViolation');
$constraint = new LinkExternalProtocolsConstraint();
$validator = new LinkExternalProtocolsConstraintValidator();
$validator->initialize($context);
$validator->validate($link, $constraint);
}
}

View File

@@ -0,0 +1,118 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\link\Unit\Plugin\Validation\Constraint;
use Drupal\Core\Routing\UrlGeneratorInterface;
use Drupal\Core\Url;
use Drupal\link\LinkItemInterface;
use Drupal\link\Plugin\Validation\Constraint\LinkNotExistingInternalConstraint;
use Drupal\link\Plugin\Validation\Constraint\LinkNotExistingInternalConstraintValidator;
use Drupal\Tests\UnitTestCase;
use PHPUnit\Framework\MockObject\MockObject;
use Symfony\Component\Routing\Exception\RouteNotFoundException;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
/**
* @coversDefaultClass \Drupal\link\Plugin\Validation\Constraint\LinkNotExistingInternalConstraintValidator
* @group Link
*/
class LinkNotExistingInternalConstraintValidatorTest extends UnitTestCase {
/**
* @covers ::validate
*/
public function testValidateFromUri(): void {
$url = Url::fromUri('https://www.drupal.org');
$link = $this->createMock(LinkItemInterface::class);
$link->expects($this->any())
->method('getUrl')
->willReturn($url);
$context = $this->createMock(ExecutionContextInterface::class);
$context->expects($this->never())
->method('addViolation');
$this->validate($link, $context);
}
/**
* @covers ::validate
*/
public function testValidateFromRoute(): void {
$url = Url::fromRoute('example.existing_route');
$urlGenerator = $this->createMock(UrlGeneratorInterface::class);
$urlGenerator->expects($this->any())
->method('generateFromRoute')
->with('example.existing_route', [], [])
->willReturn('/example/existing');
$url->setUrlGenerator($urlGenerator);
$link = $this->createMock(LinkItemInterface::class);
$link->expects($this->any())
->method('getUrl')
->willReturn($url);
$context = $this->createMock(ExecutionContextInterface::class);
$context->expects($this->never())
->method('addViolation');
$this->validate($link, $context);
}
/**
* @covers ::validate
*/
public function testValidateFromNonExistingRoute(): void {
$url = Url::fromRoute('example.not_existing_route');
$urlGenerator = $this->createMock(UrlGeneratorInterface::class);
$urlGenerator->expects($this->any())
->method('generateFromRoute')
->with('example.not_existing_route', [], [])
->willReturn(new RouteNotFoundException());
$url->setUrlGenerator($urlGenerator);
$link = $this->createMock(LinkItemInterface::class);
$link->expects($this->any())
->method('getUrl')
->willReturn($url);
$context = $this->createMock(ExecutionContextInterface::class);
$context->expects($this->never())
->method('addViolation');
$this->validate($link, $context);
}
/**
* @covers ::validate
*
* @see \Drupal\Core\Url::fromUri
*/
public function testValidateWithMalformedUri(): void {
$link = $this->createMock(LinkItemInterface::class);
$link->expects($this->any())
->method('getUrl')
->willThrowException(new \InvalidArgumentException());
$context = $this->createMock(ExecutionContextInterface::class);
$context->expects($this->never())
->method('addViolation');
$this->validate($link, $context);
}
/**
* Validate the link.
*/
protected function validate(LinkItemInterface&MockObject $link, ExecutionContextInterface&MockObject $context): void {
$validator = new LinkNotExistingInternalConstraintValidator();
$validator->initialize($context);
$validator->validate($link, new LinkNotExistingInternalConstraint());
}
}

View File

@@ -0,0 +1,63 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\link\Unit\Plugin\migrate\field\d6;
use Drupal\migrate\Plugin\MigrationInterface;
use Drupal\Tests\UnitTestCase;
use Drupal\link\Plugin\migrate\field\d6\LinkField;
use Prophecy\Argument;
/**
* @coversDefaultClass \Drupal\link\Plugin\migrate\field\d6\LinkField
* @group link
*/
class LinkFieldTest extends UnitTestCase {
/**
* @var \Drupal\migrate_drupal\Plugin\MigrateFieldInterface
*/
protected $plugin;
/**
* @var \Drupal\migrate\Plugin\MigrationInterface
*/
protected $migration;
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$this->plugin = new LinkField([], 'link', []);
$migration = $this->prophesize(MigrationInterface::class);
// The plugin's defineValueProcessPipeline() method will call
// mergeProcessOfProperty() and return nothing. So, in order to examine the
// process pipeline created by the plugin, we need to ensure that
// getProcess() always returns the last input to mergeProcessOfProperty().
$migration->mergeProcessOfProperty(Argument::type('string'), Argument::type('array'))
->will(function ($arguments) use ($migration) {
$migration->getProcess()->willReturn($arguments[1]);
});
$this->migration = $migration->reveal();
}
/**
* @covers ::defineValueProcessPipeline
*/
public function testDefineValueProcessPipeline($method = 'defineValueProcessPipeline'): void {
$this->plugin->$method($this->migration, 'field_name', []);
$expected = [
'plugin' => 'field_link',
'source' => 'field_name',
];
$this->assertSame($expected, $this->migration->getProcess());
}
}

View File

@@ -0,0 +1,133 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\link\Unit\Plugin\migrate\process;
use Drupal\link\Plugin\migrate\process\FieldLink;
use Drupal\migrate\MigrateExecutableInterface;
use Drupal\migrate\Plugin\MigrationInterface;
use Drupal\migrate\Row;
use Drupal\Tests\UnitTestCase;
/**
* @group Link
*/
class FieldLinkTest extends UnitTestCase {
/**
* Tests the URL transformations in the FieldLink process plugin.
*
* @dataProvider canonicalizeUriDataProvider
*/
public function testCanonicalizeUri($url, $expected, $configuration = []): void {
$link_plugin = new FieldLink($configuration, '', [], $this->createMock(MigrationInterface::class));
$transformed = $link_plugin->transform([
'url' => $url,
'title' => '',
'attributes' => serialize([]),
], $this->createMock(MigrateExecutableInterface::class), $this->getMockBuilder(Row::class)->disableOriginalConstructor()->getMock(), NULL);
$this->assertEquals($expected, $transformed['uri']);
}
/**
* Data provider for testCanonicalizeUri.
*/
public static function canonicalizeUriDataProvider() {
return [
'Simple front-page' => [
'<front>',
'internal:/',
],
'Front page with query' => [
'<front>?query=1',
'internal:/?query=1',
],
'No leading forward slash' => [
'node/10',
'internal:/node/10',
],
'Leading forward slash' => [
'/node/10',
'internal:/node/10',
],
'Existing scheme' => [
'scheme:test',
'scheme:test',
],
'Absolute URL with protocol prefix' => [
'http://www.google.com',
'http://www.google.com',
],
'Absolute URL without protocol prefix' => [
'www.yahoo.com',
'http://www.yahoo.com',
],
'Absolute URL without protocol prefix nor www' => [
'yahoo.com',
'https://yahoo.com',
['uri_scheme' => 'https://'],
],
'Absolute URL without explicit protocol (protocol-relative)' => [
'//example.com',
'http://example.com',
],
'Absolute URL with non-standard characters' => [
'http://www.ßÀÑÐ¥ƒå¢ë.com',
'http://www.ßÀÑÐ¥ƒå¢ë.com',
],
'Absolute URL with non-standard characters, without protocol prefix' => [
'www.ÐØÑ¢åþë.com',
'http://www.ÐØÑ¢åþë.com',
],
'Absolute URL with non-standard top level domain' => [
'http://www.example.xxx',
'http://www.example.xxx',
],
'Internal link with fragment' => [
'/node/10#top',
'internal:/node/10#top',
],
'External link with fragment' => [
'http://www.example.com/page#links',
'http://www.example.com/page#links',
],
'empty' => [
'',
'route:<nolink>',
],
'No link' => [
'<nolink>',
'route:<nolink>',
],
'none' => [
'<none>',
'route:<nolink>',
],
];
}
/**
* Tests the attributes that are deeply serialized are discarded.
*/
public function testCanonicalizeUriSerialized(): void {
$link_plugin = new FieldLink([], '', [], $this->createMock(MigrationInterface::class));
$migrate_executable = $this->createMock(MigrateExecutableInterface::class);
$row = new Row();
$transformed = $link_plugin->transform([
'url' => '',
'title' => '',
'attributes' => serialize(serialize(['not too deep'])),
], $migrate_executable, $row, NULL);
$this->assertEquals(['not too deep'], $transformed['options']['attributes']);
$transformed = $link_plugin->transform([
'url' => '',
'title' => '',
'attributes' => serialize(serialize(serialize(['too deep']))),
], $migrate_executable, $row, NULL);
$this->assertEmpty($transformed['options']['attributes']);
}
}

View File

@@ -0,0 +1,10 @@
name: 'Link Test Theme'
type: theme
description: 'Theme for testing link module'
# version: VERSION
base theme: stark
# Information added by Drupal.org packaging script on 2024-07-04
version: '10.3.1'
project: 'drupal'
datestamp: 1720094222

View File

@@ -0,0 +1,22 @@
{#
/**
* @file
* Theme override of a link with separate title and URL elements.
*
* Available variables:
* - link: The link that has already been formatted by l().
* - title: (optional) A descriptive or alternate title for the link, which may
* be different than the actual link text.
*
* @see template_preprocess()
* @see template_preprocess_link_formatter_link_separate()
*/
#}
{% apply spaceless %}
<div class="link-item">
{% if title %}
<div class="link-title">{{ title }}</div>
{% endif %}
<div class="link-url">{{ link }}</div>
</div>
{% endapply %}