Move into nested docroot
This commit is contained in:
parent
83a0d3a149
commit
c8b70abde9
13405 changed files with 0 additions and 0 deletions
85
web/core/modules/link/config/schema/link.schema.yml
Normal file
85
web/core/modules/link/config/schema/link.schema.yml
Normal file
|
@ -0,0 +1,85 @@
|
|||
# Schema for the configuration files of the Link module.
|
||||
|
||||
field.formatter.settings.link:
|
||||
type: mapping
|
||||
label: 'Link format settings'
|
||||
mapping:
|
||||
trim_length:
|
||||
type: integer
|
||||
label: 'Trim link text length'
|
||||
url_only:
|
||||
type: boolean
|
||||
label: 'URL only'
|
||||
url_plain:
|
||||
type: boolean
|
||||
label: 'Show URL as plain text'
|
||||
rel:
|
||||
type: string
|
||||
label: 'Add rel="nofollow" to links'
|
||||
target:
|
||||
type: string
|
||||
label: 'Open link in new window'
|
||||
|
||||
field.formatter.settings.link_separate:
|
||||
type: field.formatter.settings.link
|
||||
label: 'Link format settings'
|
||||
|
||||
field.widget.settings.link_default:
|
||||
type: mapping
|
||||
label: 'Link format settings'
|
||||
mapping:
|
||||
placeholder_url:
|
||||
type: string
|
||||
label: 'Placeholder for URL'
|
||||
placeholder_title:
|
||||
type: label
|
||||
label: 'Placeholder for link text'
|
||||
|
||||
field.storage_settings.link:
|
||||
type: mapping
|
||||
label: 'Link settings'
|
||||
|
||||
field.field_settings.link:
|
||||
type: mapping
|
||||
label: 'Link settings'
|
||||
mapping:
|
||||
title:
|
||||
type: integer
|
||||
label: 'Allow link text'
|
||||
link_type:
|
||||
type: integer
|
||||
label: 'Allowed link type'
|
||||
|
||||
field.value.link:
|
||||
type: mapping
|
||||
label: 'Default value'
|
||||
mapping:
|
||||
title:
|
||||
type: label
|
||||
label: 'Link text'
|
||||
url:
|
||||
type: string
|
||||
label: 'URL'
|
||||
options:
|
||||
type: mapping
|
||||
label: 'Link options'
|
||||
mapping:
|
||||
query:
|
||||
type: sequence
|
||||
label: 'URL query key value pairs'
|
||||
sequence:
|
||||
type: string
|
||||
fragment:
|
||||
type: string
|
||||
label: 'URL fragment'
|
||||
absolute:
|
||||
type: boolean
|
||||
label: 'Is this URL absolute'
|
||||
https:
|
||||
type: boolean
|
||||
label: 'If the URL should use a secure protocol'
|
||||
attributes:
|
||||
type: sequence
|
||||
label: 'Link attributes'
|
||||
sequence:
|
||||
type: string
|
8
web/core/modules/link/link.info.yml
Normal file
8
web/core/modules/link/link.info.yml
Normal file
|
@ -0,0 +1,8 @@
|
|||
name: Link
|
||||
type: module
|
||||
description: 'Provides a simple link field type.'
|
||||
core: 8.x
|
||||
package: Field types
|
||||
version: VERSION
|
||||
dependencies:
|
||||
- field
|
65
web/core/modules/link/link.module
Normal file
65
web/core/modules/link/link.module
Normal file
|
@ -0,0 +1,65 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* @file
|
||||
* Defines simple link field types.
|
||||
*/
|
||||
|
||||
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 .= '<h3>' . t('About') . '</h3>';
|
||||
$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>.', array(':field' => \Drupal::url('help.page', array('name' => 'field')), ':field_ui' => (\Drupal::moduleHandler()->moduleExists('field_ui')) ? \Drupal::url('help.page', array('name' => 'field_ui')) : '#', ':link_documentation' => 'https://www.drupal.org/documentation/modules/link')) . '</p>';
|
||||
$output .= '<h3>' . t('Uses') . '</h3>';
|
||||
$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.', array(':field_ui' => (\Drupal::moduleHandler()->moduleExists('field_ui')) ? \Drupal::url('help.page', array('name' => 'field_ui')) : '#')) . '</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 array(
|
||||
'link_formatter_link_separate' => array(
|
||||
'variables' => array('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'] = \Drupal::l($variables['url_title'], $variables['url']);
|
||||
}
|
43
web/core/modules/link/src/LinkItemInterface.php
Normal file
43
web/core/modules/link/src/LinkItemInterface.php
Normal file
|
@ -0,0 +1,43 @@
|
|||
<?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.
|
||||
*/
|
||||
public function getUrl();
|
||||
|
||||
}
|
|
@ -0,0 +1,260 @@
|
|||
<?php
|
||||
|
||||
namespace Drupal\link\Plugin\Field\FieldFormatter;
|
||||
|
||||
use Drupal\Component\Utility\Unicode;
|
||||
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\Plugin\ContainerFactoryPluginInterface;
|
||||
use Drupal\Core\Url;
|
||||
use Drupal\link\LinkItemInterface;
|
||||
use Symfony\Component\DependencyInjection\ContainerInterface;
|
||||
|
||||
/**
|
||||
* Plugin implementation of the 'link' formatter.
|
||||
*
|
||||
* @FieldFormatter(
|
||||
* id = "link",
|
||||
* label = @Translation("Link"),
|
||||
* field_types = {
|
||||
* "link"
|
||||
* }
|
||||
* )
|
||||
*/
|
||||
class LinkFormatter extends FormatterBase implements ContainerFactoryPluginInterface {
|
||||
|
||||
/**
|
||||
* 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 array(
|
||||
'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'] = array(
|
||||
'#type' => 'number',
|
||||
'#title' => t('Trim link text length'),
|
||||
'#field_suffix' => t('characters'),
|
||||
'#default_value' => $this->getSetting('trim_length'),
|
||||
'#min' => 1,
|
||||
'#description' => t('Leave blank to allow unlimited link text lengths.'),
|
||||
);
|
||||
$elements['url_only'] = array(
|
||||
'#type' => 'checkbox',
|
||||
'#title' => t('URL only'),
|
||||
'#default_value' => $this->getSetting('url_only'),
|
||||
'#access' => $this->getPluginId() == 'link',
|
||||
);
|
||||
$elements['url_plain'] = array(
|
||||
'#type' => 'checkbox',
|
||||
'#title' => t('Show URL as plain text'),
|
||||
'#default_value' => $this->getSetting('url_plain'),
|
||||
'#access' => $this->getPluginId() == 'link',
|
||||
'#states' => array(
|
||||
'visible' => array(
|
||||
':input[name*="url_only"]' => array('checked' => TRUE),
|
||||
),
|
||||
),
|
||||
);
|
||||
$elements['rel'] = array(
|
||||
'#type' => 'checkbox',
|
||||
'#title' => t('Add rel="nofollow" to links'),
|
||||
'#return_value' => 'nofollow',
|
||||
'#default_value' => $this->getSetting('rel'),
|
||||
);
|
||||
$elements['target'] = array(
|
||||
'#type' => 'checkbox',
|
||||
'#title' => t('Open link in new window'),
|
||||
'#return_value' => '_blank',
|
||||
'#default_value' => $this->getSetting('target'),
|
||||
);
|
||||
|
||||
return $elements;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function settingsSummary() {
|
||||
$summary = array();
|
||||
|
||||
$settings = $this->getSettings();
|
||||
|
||||
if (!empty($settings['trim_length'])) {
|
||||
$summary[] = t('Link text trimmed to @limit characters', array('@limit' => $settings['trim_length']));
|
||||
}
|
||||
else {
|
||||
$summary[] = t('Link text not trimmed');
|
||||
}
|
||||
if ($this->getPluginId() == 'link' && !empty($settings['url_only'])) {
|
||||
if (!empty($settings['url_plain'])) {
|
||||
$summary[] = t('Show URL only as plain-text');
|
||||
}
|
||||
else {
|
||||
$summary[] = t('Show URL only');
|
||||
}
|
||||
}
|
||||
if (!empty($settings['rel'])) {
|
||||
$summary[] = t('Add rel="@rel"', array('@rel' => $settings['rel']));
|
||||
}
|
||||
if (!empty($settings['target'])) {
|
||||
$summary[] = t('Open link in new window');
|
||||
}
|
||||
|
||||
return $summary;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function viewElements(FieldItemListInterface $items, $langcode) {
|
||||
$element = array();
|
||||
$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] = array(
|
||||
'#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.
|
||||
// @todo Does RDF need a URL rather than an internal URI here?
|
||||
// @see \Drupal\Tests\rdf\Kernel\Field\LinkFieldRdfaTest.
|
||||
$content = str_replace('internal:/', '', $item->uri);
|
||||
$item->_attributes += array('content' => $content);
|
||||
}
|
||||
}
|
||||
else {
|
||||
$element[$delta] = array(
|
||||
'#type' => 'link',
|
||||
'#title' => $link_title,
|
||||
'#options' => $url->getOptions(),
|
||||
);
|
||||
$element[$delta]['#url'] = $url;
|
||||
|
||||
if (!empty($item->_attributes)) {
|
||||
$element[$delta]['#options'] += array ('attributes' => array());
|
||||
$element[$delta]['#options']['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) {
|
||||
$url = $item->getUrl() ?: 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;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,89 @@
|
|||
<?php
|
||||
|
||||
namespace Drupal\link\Plugin\Field\FieldFormatter;
|
||||
|
||||
use Drupal\Component\Utility\Unicode;
|
||||
use Drupal\Core\Field\FieldItemListInterface;
|
||||
|
||||
/**
|
||||
* 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 = @Translation("Separate link text and URL"),
|
||||
* field_types = {
|
||||
* "link"
|
||||
* }
|
||||
* )
|
||||
*/
|
||||
class LinkSeparateFormatter extends LinkFormatter {
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public static function defaultSettings() {
|
||||
return array(
|
||||
'trim_length' => 80,
|
||||
'rel' => '',
|
||||
'target' => '',
|
||||
) + parent::defaultSettings();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function viewElements(FieldItemListInterface $items, $langcode) {
|
||||
$element = array();
|
||||
$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 = Unicode::truncate($link_title, $settings['trim_length'], FALSE, TRUE);
|
||||
$url_title = Unicode::truncate($url_title, $settings['trim_length'], FALSE, TRUE);
|
||||
}
|
||||
|
||||
$element[$delta] = array(
|
||||
'#theme' => 'link_formatter_link_separate',
|
||||
'#title' => $link_title,
|
||||
'#url_title' => $url_title,
|
||||
'#url' => $url,
|
||||
);
|
||||
|
||||
if (!empty($item->_attributes)) {
|
||||
// Set our RDFa 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;
|
||||
}
|
||||
|
||||
}
|
199
web/core/modules/link/src/Plugin/Field/FieldType/LinkItem.php
Normal file
199
web/core/modules/link/src/Plugin/Field/FieldType/LinkItem.php
Normal file
|
@ -0,0 +1,199 @@
|
|||
<?php
|
||||
|
||||
namespace Drupal\link\Plugin\Field\FieldType;
|
||||
|
||||
use Drupal\Component\Utility\Random;
|
||||
use Drupal\Core\Field\FieldDefinitionInterface;
|
||||
use Drupal\Core\Field\FieldItemBase;
|
||||
use Drupal\Core\Field\FieldStorageDefinitionInterface;
|
||||
use Drupal\Core\Form\FormStateInterface;
|
||||
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 = @Translation("Link"),
|
||||
* description = @Translation("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 array(
|
||||
'title' => DRUPAL_OPTIONAL,
|
||||
'link_type' => LinkItemInterface::LINK_GENERIC
|
||||
) + parent::defaultFieldSettings();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
|
||||
$properties['uri'] = DataDefinition::create('uri')
|
||||
->setLabel(t('URI'));
|
||||
|
||||
$properties['title'] = DataDefinition::create('string')
|
||||
->setLabel(t('Link text'));
|
||||
|
||||
$properties['options'] = MapDataDefinition::create()
|
||||
->setLabel(t('Options'));
|
||||
|
||||
return $properties;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public static function schema(FieldStorageDefinitionInterface $field_definition) {
|
||||
return array(
|
||||
'columns' => array(
|
||||
'uri' => array(
|
||||
'description' => 'The URI of the link.',
|
||||
'type' => 'varchar',
|
||||
'length' => 2048,
|
||||
),
|
||||
'title' => array(
|
||||
'description' => 'The link text.',
|
||||
'type' => 'varchar',
|
||||
'length' => 255,
|
||||
),
|
||||
'options' => array(
|
||||
'description' => 'Serialized array of options for the link.',
|
||||
'type' => 'blob',
|
||||
'size' => 'big',
|
||||
'serialize' => TRUE,
|
||||
),
|
||||
),
|
||||
'indexes' => array(
|
||||
'uri' => array(array('uri', 30)),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function fieldSettingsForm(array $form, FormStateInterface $form_state) {
|
||||
$element = array();
|
||||
|
||||
$element['link_type'] = array(
|
||||
'#type' => 'radios',
|
||||
'#title' => t('Allowed link type'),
|
||||
'#default_value' => $this->getSetting('link_type'),
|
||||
'#options' => array(
|
||||
static::LINK_INTERNAL => t('Internal links only'),
|
||||
static::LINK_EXTERNAL => t('External links only'),
|
||||
static::LINK_GENERIC => t('Both internal and external links'),
|
||||
),
|
||||
);
|
||||
|
||||
$element['title'] = array(
|
||||
'#type' => 'radios',
|
||||
'#title' => t('Allow link text'),
|
||||
'#default_value' => $this->getSetting('title'),
|
||||
'#options' => array(
|
||||
DRUPAL_DISABLED => t('Disabled'),
|
||||
DRUPAL_OPTIONAL => t('Optional'),
|
||||
DRUPAL_REQUIRED => 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 = array('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'] = 'http://www.' . $random->word($domain_length) . '.' . $tlds[mt_rand(0, (sizeof($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 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' => [],
|
||||
];
|
||||
}
|
||||
// Unserialize the values.
|
||||
// @todo The storage controller should take care of this, see
|
||||
// SqlContentEntityStorage::loadFieldItems, see
|
||||
// https://www.drupal.org/node/2414835
|
||||
if (is_string($values['options'])) {
|
||||
$values['options'] = unserialize($values['options']);
|
||||
}
|
||||
parent::setValue($values, $notify);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,366 @@
|
|||
<?php
|
||||
|
||||
namespace Drupal\link\Plugin\Field\FieldWidget;
|
||||
|
||||
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 = @Translation("Link"),
|
||||
* field_types = {
|
||||
* "link"
|
||||
* }
|
||||
* )
|
||||
*/
|
||||
class LinkWidget extends WidgetBase {
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public static function defaultSettings() {
|
||||
return array(
|
||||
'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') {
|
||||
list($entity_type, $entity_id) = explode('/', substr($uri, 7), 2);
|
||||
// Show the 'entity:' URI as the entity autocomplete would.
|
||||
$entity_manager = \Drupal::entityManager();
|
||||
if ($entity_manager->getDefinition($entity_type, FALSE) && $entity = \Drupal::entityManager()->getStorage($entity_type)->load($entity_id)) {
|
||||
$displayable_string = EntityAutocomplete::getEntityLabels(array($entity));
|
||||
}
|
||||
}
|
||||
|
||||
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 an URI.
|
||||
$uri = $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;
|
||||
}
|
||||
// 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 (strpos($string, '<front>') === 0) {
|
||||
$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 a '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) && substr($element['#value'], 0, 7) !== '<front>') {
|
||||
$form_state->setError($element, t('Manually entered paths should start with /, ? or #.'));
|
||||
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'] === '') {
|
||||
$element['title']['#required'] = TRUE;
|
||||
// We expect the field name placeholder value to be wrapped in t() here,
|
||||
// so it won't be escaped again as it's already marked safe.
|
||||
$form_state->setError($element['title'], t('@name field is required.', array('@name' => $element['title']['#title'])));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
|
||||
/** @var \Drupal\link\LinkItemInterface $item */
|
||||
$item = $items[$delta];
|
||||
|
||||
$element['uri'] = array(
|
||||
'#type' => 'url',
|
||||
'#title' => $this->t('URL'),
|
||||
'#placeholder' => $this->getSetting('placeholder_url'),
|
||||
// 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.
|
||||
'#default_value' => (!$item->isEmpty() && (\Drupal::currentUser()->hasPermission('link to any page') || $item->getUrl()->access())) ? static::getUriAsDisplayableString($item->uri) : NULL,
|
||||
'#element_validate' => array(array(get_called_class(), 'validateUriElement')),
|
||||
'#maxlength' => 2048,
|
||||
'#required' => $element['#required'],
|
||||
);
|
||||
|
||||
// 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.
|
||||
if (!$this->supportsExternalLinks()) {
|
||||
$element['uri']['#field_prefix'] = rtrim(\Drupal::url('<front>', array(), array('absolute' => TRUE)), '/');
|
||||
}
|
||||
// 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.', array('%front' => '<front>', '%add-node' => '/node/add', '%url' => 'http://example.com'));
|
||||
}
|
||||
// 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.', array('%url' => 'http://example.com'));
|
||||
}
|
||||
|
||||
$element['title'] = array(
|
||||
'#type' => 'textfield',
|
||||
'#title' => $this->t('Link text'),
|
||||
'#placeholder' => $this->getSetting('placeholder_title'),
|
||||
'#default_value' => isset($items[$delta]->title) ? $items[$delta]->title : NULL,
|
||||
'#maxlength' => 255,
|
||||
'#access' => $this->getFieldSetting('title') != DRUPAL_DISABLED,
|
||||
);
|
||||
// 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.
|
||||
if (!$this->isDefaultValueWidget($form_state) && $this->getFieldSetting('title') == DRUPAL_REQUIRED) {
|
||||
$element['#element_validate'][] = array(get_called_class(), 'validateTitleElement');
|
||||
}
|
||||
|
||||
// Exposing the attributes array in the widget is left for alternate and more
|
||||
// advanced field widgets.
|
||||
$element['attributes'] = array(
|
||||
'#type' => 'value',
|
||||
'#tree' => TRUE,
|
||||
'#value' => !empty($items[$delta]->options['attributes']) ? $items[$delta]->options['attributes'] : array(),
|
||||
'#attributes' => array('class' => array('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'];
|
||||
}
|
||||
// Otherwise wrap everything in a details element.
|
||||
else {
|
||||
$element += array(
|
||||
'#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'] = array(
|
||||
'#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'] = array(
|
||||
'#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' => array(
|
||||
'invisible' => array(
|
||||
':input[name="instance[settings][title]"]' => array('value' => DRUPAL_DISABLED),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
return $elements;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function settingsSummary() {
|
||||
$summary = array();
|
||||
|
||||
$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', array('@placeholder_title' => $placeholder_title));
|
||||
}
|
||||
if (!empty($placeholder_url)) {
|
||||
$summary[] = $this->t('URL placeholder: @placeholder_url', array('@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);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,19 @@
|
|||
<?php
|
||||
|
||||
namespace Drupal\link\Plugin\Validation\Constraint;
|
||||
|
||||
use Symfony\Component\Validator\Constraint;
|
||||
|
||||
/**
|
||||
* Defines an access validation constraint for links.
|
||||
*
|
||||
* @Constraint(
|
||||
* id = "LinkAccess",
|
||||
* label = @Translation("Link URI can be accessed by the user.", context = "Validation"),
|
||||
* )
|
||||
*/
|
||||
class LinkAccessConstraint extends Constraint {
|
||||
|
||||
public $message = "The path '@uri' is inaccessible.";
|
||||
|
||||
}
|
|
@ -0,0 +1,78 @@
|
|||
<?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\ConstraintValidatorInterface;
|
||||
use Symfony\Component\Validator\ExecutionContextInterface;
|
||||
|
||||
/**
|
||||
* Validates the LinkAccess constraint.
|
||||
*/
|
||||
class LinkAccessConstraintValidator implements ConstraintValidatorInterface, ContainerInjectionInterface {
|
||||
|
||||
/**
|
||||
* Stores the validator's state during validation.
|
||||
*
|
||||
* @var \Symfony\Component\Validator\ExecutionContextInterface
|
||||
*/
|
||||
protected $context;
|
||||
|
||||
/**
|
||||
* Proxy for the current user account.
|
||||
*
|
||||
* @var \Drupal\Core\Session\AccountProxyInterface
|
||||
*/
|
||||
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}
|
||||
*/
|
||||
public function initialize(ExecutionContextInterface $context) {
|
||||
$this->context = $context;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
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, array('@uri' => $value->uri));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,19 @@
|
|||
<?php
|
||||
|
||||
namespace Drupal\link\Plugin\Validation\Constraint;
|
||||
|
||||
use Symfony\Component\Validator\Constraint;
|
||||
|
||||
/**
|
||||
* Defines a protocol validation constraint for links to external URLs.
|
||||
*
|
||||
* @Constraint(
|
||||
* id = "LinkExternalProtocols",
|
||||
* label = @Translation("No dangerous external protocols", context = "Validation"),
|
||||
* )
|
||||
*/
|
||||
class LinkExternalProtocolsConstraint extends Constraint {
|
||||
|
||||
public $message = "The path '@uri' is invalid.";
|
||||
|
||||
}
|
|
@ -0,0 +1,49 @@
|
|||
<?php
|
||||
|
||||
namespace Drupal\link\Plugin\Validation\Constraint;
|
||||
|
||||
use Drupal\Component\Utility\UrlHelper;
|
||||
use Symfony\Component\Validator\Constraint;
|
||||
use Symfony\Component\Validator\ConstraintValidatorInterface;
|
||||
use Symfony\Component\Validator\ExecutionContextInterface;
|
||||
|
||||
/**
|
||||
* Validates the LinkExternalProtocols constraint.
|
||||
*/
|
||||
class LinkExternalProtocolsConstraintValidator implements ConstraintValidatorInterface {
|
||||
|
||||
/**
|
||||
* Stores the validator's state during validation.
|
||||
*
|
||||
* @var \Symfony\Component\Validator\ExecutionContextInterface
|
||||
*/
|
||||
protected $context;
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function initialize(ExecutionContextInterface $context) {
|
||||
$this->context = $context;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
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, array('@uri' => $value->uri));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,19 @@
|
|||
<?php
|
||||
|
||||
namespace Drupal\link\Plugin\Validation\Constraint;
|
||||
|
||||
use Symfony\Component\Validator\Constraint;
|
||||
|
||||
/**
|
||||
* Defines a protocol validation constraint for links to broken internal URLs.
|
||||
*
|
||||
* @Constraint(
|
||||
* id = "LinkNotExistingInternal",
|
||||
* label = @Translation("No broken internal links", context = "Validation"),
|
||||
* )
|
||||
*/
|
||||
class LinkNotExistingInternalConstraint extends Constraint {
|
||||
|
||||
public $message = "The path '@uri' is invalid.";
|
||||
|
||||
}
|
|
@ -0,0 +1,68 @@
|
|||
<?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\ConstraintValidatorInterface;
|
||||
use Symfony\Component\Validator\ExecutionContextInterface;
|
||||
|
||||
/**
|
||||
* Validates the LinkNotExistingInternal constraint.
|
||||
*/
|
||||
class LinkNotExistingInternalConstraintValidator implements ConstraintValidatorInterface {
|
||||
|
||||
/**
|
||||
* Stores the validator's state during validation.
|
||||
*
|
||||
* @var \Symfony\Component\Validator\ExecutionContextInterface
|
||||
*/
|
||||
protected $context;
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function initialize(ExecutionContextInterface $context) {
|
||||
$this->context = $context;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
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();
|
||||
}
|
||||
// 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, array('@uri' => $value->uri));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,78 @@
|
|||
<?php
|
||||
|
||||
namespace Drupal\link\Plugin\Validation\Constraint;
|
||||
|
||||
use Drupal\link\LinkItemInterface;
|
||||
use Symfony\Component\Validator\Constraint;
|
||||
use Symfony\Component\Validator\ConstraintValidatorInterface;
|
||||
use Symfony\Component\Validator\ExecutionContextInterface;
|
||||
|
||||
/**
|
||||
* Validation constraint for links receiving data allowed by its settings.
|
||||
*
|
||||
* @Constraint(
|
||||
* id = "LinkType",
|
||||
* label = @Translation("Link data valid for link type.", context = "Validation"),
|
||||
* )
|
||||
*/
|
||||
class LinkTypeConstraint extends Constraint implements ConstraintValidatorInterface {
|
||||
|
||||
public $message = "The path '@uri' is invalid.";
|
||||
|
||||
/**
|
||||
* @var \Symfony\Component\Validator\ExecutionContextInterface
|
||||
*/
|
||||
protected $context;
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function initialize(ExecutionContextInterface $context) {
|
||||
$this->context = $context;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function validatedBy() {
|
||||
return get_class($this);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function validate($value, Constraint $constraint) {
|
||||
if (isset($value)) {
|
||||
$uri_is_valid = TRUE;
|
||||
|
||||
/** @var $link_item \Drupal\link\LinkItemInterface */
|
||||
$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($this->message, array('@uri' => $link_item->uri));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,48 @@
|
|||
<?php
|
||||
|
||||
namespace Drupal\link\Plugin\migrate\cckfield;
|
||||
|
||||
use Drupal\migrate\Plugin\MigrationInterface;
|
||||
use Drupal\migrate_drupal\Plugin\migrate\cckfield\CckFieldPluginBase;
|
||||
|
||||
/**
|
||||
* @MigrateCckField(
|
||||
* id = "link",
|
||||
* core = {6},
|
||||
* type_map = {
|
||||
* "link_field" = "link"
|
||||
* }
|
||||
* )
|
||||
*/
|
||||
class LinkField extends CckFieldPluginBase {
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function getFieldFormatterMap() {
|
||||
// See d6_field_formatter_settings.yml and CckFieldPluginBase
|
||||
// processFieldFormatter().
|
||||
return [
|
||||
'default' => 'link',
|
||||
'plain' => 'link',
|
||||
'absolute' => 'link',
|
||||
'title_plain' => 'link',
|
||||
'url' => 'link',
|
||||
'short' => 'link',
|
||||
'label' => 'link',
|
||||
'separate' => 'link_separate',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function processCckFieldValues(MigrationInterface $migration, $field_name, $data) {
|
||||
$process = [
|
||||
'plugin' => 'd6_cck_link',
|
||||
'source' => $field_name,
|
||||
];
|
||||
$migration->mergeProcessOfProperty($field_name, $process);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,48 @@
|
|||
<?php
|
||||
|
||||
namespace Drupal\link\Plugin\migrate\cckfield\d7;
|
||||
|
||||
use Drupal\link\Plugin\migrate\cckfield\LinkField as D6LinkField;
|
||||
use Drupal\migrate\Plugin\MigrationInterface;
|
||||
|
||||
/**
|
||||
* @MigrateCckField(
|
||||
* id = "link_field",
|
||||
* core = {7},
|
||||
* type_map = {
|
||||
* "link_field" = "link"
|
||||
* }
|
||||
* )
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
class LinkField extends D6LinkField {
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function getFieldWidgetMap() {
|
||||
// By default, use the plugin ID for the widget types.
|
||||
return ['link_field' => 'link_default'];
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function processFieldInstance(MigrationInterface $migration) {
|
||||
$process = [
|
||||
'plugin' => 'static_map',
|
||||
'source' => 'instance_settings/title',
|
||||
'bypass' => TRUE,
|
||||
'map' => [
|
||||
'disabled' => DRUPAL_DISABLED,
|
||||
'optional' => DRUPAL_OPTIONAL,
|
||||
'required' => DRUPAL_REQUIRED,
|
||||
],
|
||||
];
|
||||
$migration->mergeProcessOfProperty('settings/title', $process);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,86 @@
|
|||
<?php
|
||||
|
||||
namespace Drupal\link\Plugin\migrate\process\d6;
|
||||
|
||||
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
|
||||
use Drupal\migrate\Plugin\MigrationInterface;
|
||||
use Drupal\migrate\MigrateExecutableInterface;
|
||||
use Drupal\migrate\ProcessPluginBase;
|
||||
use Drupal\migrate\Row;
|
||||
use Symfony\Component\DependencyInjection\ContainerInterface;
|
||||
|
||||
/**
|
||||
* @MigrateProcessPlugin(
|
||||
* id = "d6_cck_link"
|
||||
* )
|
||||
*/
|
||||
class CckLink extends ProcessPluginBase implements ContainerFactoryPluginInterface {
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function __construct(array $configuration, $plugin_id, $plugin_definition, MigrationInterface $migration) {
|
||||
parent::__construct($configuration, $plugin_id, $plugin_definition);
|
||||
$this->migration = $migration;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition, MigrationInterface $migration = NULL) {
|
||||
return new static(
|
||||
$configuration,
|
||||
$plugin_id,
|
||||
$plugin_definition,
|
||||
$migration
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Turn a Drupal 6 URI into a Drupal 8-compatible format.
|
||||
*
|
||||
* @param string $uri
|
||||
* The 'url' value from Drupal 6.
|
||||
*
|
||||
* @return string
|
||||
* The Drupal 8-compatible URI.
|
||||
*
|
||||
* @see \Drupal\link\Plugin\Field\FieldWidget\LinkWidget::getUserEnteredStringAsUri()
|
||||
*/
|
||||
protected function canonicalizeUri($uri) {
|
||||
// If we already have a scheme, we're fine.
|
||||
if (empty($uri) || !is_null(parse_url($uri, PHP_URL_SCHEME))) {
|
||||
return $uri;
|
||||
}
|
||||
|
||||
// Remove the <front> component of the URL.
|
||||
if (strpos($uri, '<front>') === 0) {
|
||||
$uri = substr($uri, strlen('<front>'));
|
||||
}
|
||||
|
||||
// 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 link attributes might be double serialized.
|
||||
if (!is_array($attributes)) {
|
||||
$attributes = unserialize($attributes);
|
||||
}
|
||||
|
||||
if (!$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;
|
||||
}
|
||||
|
||||
}
|
635
web/core/modules/link/src/Tests/LinkFieldTest.php
Normal file
635
web/core/modules/link/src/Tests/LinkFieldTest.php
Normal file
|
@ -0,0 +1,635 @@
|
|||
<?php
|
||||
|
||||
namespace Drupal\link\Tests;
|
||||
|
||||
use Drupal\Component\Utility\Html;
|
||||
use Drupal\Component\Utility\Unicode;
|
||||
use Drupal\Core\Url;
|
||||
use Drupal\entity_test\Entity\EntityTest;
|
||||
use Drupal\field\Entity\FieldConfig;
|
||||
use Drupal\link\LinkItemInterface;
|
||||
use Drupal\simpletest\WebTestBase;
|
||||
use Drupal\field\Entity\FieldStorageConfig;
|
||||
|
||||
/**
|
||||
* Tests link field widgets and formatters.
|
||||
*
|
||||
* @group link
|
||||
*/
|
||||
class LinkFieldTest extends WebTestBase {
|
||||
|
||||
/**
|
||||
* Modules to enable.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $modules = ['entity_test', 'link', 'node'];
|
||||
|
||||
/**
|
||||
* A field to use in this test class.
|
||||
*
|
||||
* @var \Drupal\field\Entity\FieldStorageConfig
|
||||
*/
|
||||
protected $fieldStorage;
|
||||
|
||||
/**
|
||||
* The instance used in this test class.
|
||||
*
|
||||
* @var \Drupal\field\Entity\FieldConfig
|
||||
*/
|
||||
protected $field;
|
||||
|
||||
protected function setUp() {
|
||||
parent::setUp();
|
||||
|
||||
$this->drupalLogin($this->drupalCreateUser([
|
||||
'view test entity',
|
||||
'administer entity_test content',
|
||||
'link to any page',
|
||||
]));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests link field URL validation.
|
||||
*/
|
||||
function testURLValidation() {
|
||||
$field_name = Unicode::strtolower($this->randomMachineName());
|
||||
// Create a field with settings to validate.
|
||||
$this->fieldStorage = FieldStorageConfig::create(array(
|
||||
'field_name' => $field_name,
|
||||
'entity_type' => 'entity_test',
|
||||
'type' => 'link',
|
||||
));
|
||||
$this->fieldStorage->save();
|
||||
$this->field = FieldConfig::create([
|
||||
'field_storage' => $this->fieldStorage,
|
||||
'bundle' => 'entity_test',
|
||||
'settings' => array(
|
||||
'title' => DRUPAL_DISABLED,
|
||||
'link_type' => LinkItemInterface::LINK_GENERIC,
|
||||
),
|
||||
]);
|
||||
$this->field->save();
|
||||
entity_get_form_display('entity_test', 'entity_test', 'default')
|
||||
->setComponent($field_name, array(
|
||||
'type' => 'link_default',
|
||||
'settings' => array(
|
||||
'placeholder_url' => 'http://example.com',
|
||||
),
|
||||
))
|
||||
->save();
|
||||
entity_get_display('entity_test', 'entity_test', 'full')
|
||||
->setComponent($field_name, array(
|
||||
'type' => 'link',
|
||||
))
|
||||
->save();
|
||||
|
||||
// Display creation form.
|
||||
$this->drupalGet('entity_test/add');
|
||||
$this->assertFieldByName("{$field_name}[0][uri]", '', 'Link URL field is displayed');
|
||||
$this->assertRaw('placeholder="http://example.com"');
|
||||
|
||||
// Create a path alias.
|
||||
\Drupal::service('path.alias_storage')->save('/admin', '/a/path/alias');
|
||||
|
||||
// Create a node to test the link widget.
|
||||
$node = $this->drupalCreateNode();
|
||||
|
||||
// Create an entity with restricted view access.
|
||||
$entity_test_no_label_access = EntityTest::create([
|
||||
'name' => 'forbid_access',
|
||||
]);
|
||||
$entity_test_no_label_access->save();
|
||||
|
||||
// Define some valid URLs (keys are the entered values, values are the
|
||||
// strings displayed to the user).
|
||||
$valid_external_entries = array(
|
||||
'http://www.example.com/' => 'http://www.example.com/',
|
||||
// Strings within parenthesis without leading space char.
|
||||
'http://www.example.com/strings_(string_within_parenthesis)' => '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/numbers_(9999)',
|
||||
);
|
||||
$valid_internal_entries = array(
|
||||
'/entity_test/add' => '/entity_test/add',
|
||||
'/a/path/alias' => '/a/path/alias',
|
||||
|
||||
// Front page, with query string and fragment.
|
||||
'/' => '<front>',
|
||||
'/?example=llama' => '<front>?example=llama',
|
||||
'/#example' => '<front>#example',
|
||||
|
||||
// @todo '<front>' is valid input for BC reasons, may be removed by
|
||||
// https://www.drupal.org/node/2421941
|
||||
'<front>' => '<front>',
|
||||
'<front>#example' => '<front>#example',
|
||||
'<front>?example=llama' => '<front>?example=llama',
|
||||
|
||||
// Query string and fragment.
|
||||
'?example=llama' => '?example=llama',
|
||||
'#example' => '#example',
|
||||
|
||||
// Entity reference autocomplete value.
|
||||
$node->label() . ' (1)' => $node->label() . ' (1)',
|
||||
// Entity URI displayed as ER autocomplete value when displayed in a form.
|
||||
'entity:node/1' => $node->label() . ' (1)',
|
||||
// URI for an entity that exists, but is not accessible by the user.
|
||||
'entity:entity_test/' . $entity_test_no_label_access->id() => '- Restricted access - (' . $entity_test_no_label_access->id() . ')',
|
||||
// URI for an entity that doesn't exist, but with a valid ID.
|
||||
'entity:user/999999' => 'entity:user/999999',
|
||||
);
|
||||
|
||||
// Define some invalid URLs.
|
||||
$validation_error_1 = "The path '@link_path' is invalid.";
|
||||
$validation_error_2 = 'Manually entered paths should start with /, ? or #.';
|
||||
$validation_error_3 = "The path '@link_path' is inaccessible.";
|
||||
$invalid_external_entries = array(
|
||||
// Invalid protocol
|
||||
'invalid://not-a-valid-protocol' => $validation_error_1,
|
||||
// Missing host name
|
||||
'http://' => $validation_error_1,
|
||||
);
|
||||
$invalid_internal_entries = array(
|
||||
'no-leading-slash' => $validation_error_2,
|
||||
'entity:non_existing_entity_type/yar' => $validation_error_1,
|
||||
// URI for an entity that doesn't exist, with an invalid ID.
|
||||
'entity:user/invalid-parameter' => $validation_error_1,
|
||||
);
|
||||
|
||||
// Test external and internal URLs for 'link_type' = LinkItemInterface::LINK_GENERIC.
|
||||
$this->assertValidEntries($field_name, $valid_external_entries + $valid_internal_entries);
|
||||
$this->assertInvalidEntries($field_name, $invalid_external_entries + $invalid_internal_entries);
|
||||
|
||||
// Test external URLs for 'link_type' = LinkItemInterface::LINK_EXTERNAL.
|
||||
$this->field->setSetting('link_type', LinkItemInterface::LINK_EXTERNAL);
|
||||
$this->field->save();
|
||||
$this->assertValidEntries($field_name, $valid_external_entries);
|
||||
$this->assertInvalidEntries($field_name, $valid_internal_entries + $invalid_external_entries);
|
||||
|
||||
// Test external URLs for 'link_type' = LinkItemInterface::LINK_INTERNAL.
|
||||
$this->field->setSetting('link_type', LinkItemInterface::LINK_INTERNAL);
|
||||
$this->field->save();
|
||||
$this->assertValidEntries($field_name, $valid_internal_entries);
|
||||
$this->assertInvalidEntries($field_name, $valid_external_entries + $invalid_internal_entries);
|
||||
|
||||
// Ensure that users with 'link to any page', don't apply access checking.
|
||||
$this->drupalLogin($this->drupalCreateUser([
|
||||
'view test entity',
|
||||
'administer entity_test content',
|
||||
]));
|
||||
$this->assertValidEntries($field_name, ['/entity_test/add' => '/entity_test/add']);
|
||||
$this->assertInValidEntries($field_name, ['/admin' => $validation_error_3]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Asserts that valid URLs can be submitted.
|
||||
*
|
||||
* @param string $field_name
|
||||
* The field name.
|
||||
* @param array $valid_entries
|
||||
* An array of valid URL entries.
|
||||
*/
|
||||
protected function assertValidEntries($field_name, array $valid_entries) {
|
||||
foreach ($valid_entries as $uri => $string) {
|
||||
$edit = array(
|
||||
"{$field_name}[0][uri]" => $uri,
|
||||
);
|
||||
$this->drupalPostForm('entity_test/add', $edit, t('Save'));
|
||||
preg_match('|entity_test/manage/(\d+)|', $this->url, $match);
|
||||
$id = $match[1];
|
||||
$this->assertText(t('entity_test @id has been created.', array('@id' => $id)));
|
||||
$this->assertRaw($string);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Asserts that invalid URLs cannot be submitted.
|
||||
*
|
||||
* @param string $field_name
|
||||
* The field name.
|
||||
* @param array $invalid_entries
|
||||
* An array of invalid URL entries.
|
||||
*/
|
||||
protected function assertInvalidEntries($field_name, array $invalid_entries) {
|
||||
foreach ($invalid_entries as $invalid_value => $error_message) {
|
||||
$edit = array(
|
||||
"{$field_name}[0][uri]" => $invalid_value,
|
||||
);
|
||||
$this->drupalPostForm('entity_test/add', $edit, t('Save'));
|
||||
$this->assertText(t($error_message, array('@link_path' => $invalid_value)));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the link title settings of a link field.
|
||||
*/
|
||||
function testLinkTitle() {
|
||||
$field_name = Unicode::strtolower($this->randomMachineName());
|
||||
// Create a field with settings to validate.
|
||||
$this->fieldStorage = FieldStorageConfig::create(array(
|
||||
'field_name' => $field_name,
|
||||
'entity_type' => 'entity_test',
|
||||
'type' => 'link',
|
||||
));
|
||||
$this->fieldStorage->save();
|
||||
$this->field = FieldConfig::create([
|
||||
'field_storage' => $this->fieldStorage,
|
||||
'bundle' => 'entity_test',
|
||||
'label' => 'Read more about this entity',
|
||||
'settings' => array(
|
||||
'title' => DRUPAL_OPTIONAL,
|
||||
'link_type' => LinkItemInterface::LINK_GENERIC,
|
||||
),
|
||||
]);
|
||||
$this->field->save();
|
||||
entity_get_form_display('entity_test', 'entity_test', 'default')
|
||||
->setComponent($field_name, array(
|
||||
'type' => 'link_default',
|
||||
'settings' => array(
|
||||
'placeholder_url' => 'http://example.com',
|
||||
'placeholder_title' => 'Enter the text for this link',
|
||||
),
|
||||
))
|
||||
->save();
|
||||
entity_get_display('entity_test', 'entity_test', 'full')
|
||||
->setComponent($field_name, array(
|
||||
'type' => 'link',
|
||||
'label' => 'hidden',
|
||||
))
|
||||
->save();
|
||||
|
||||
// Verify that the link text field works according to the field setting.
|
||||
foreach (array(DRUPAL_DISABLED, DRUPAL_REQUIRED, DRUPAL_OPTIONAL) as $title_setting) {
|
||||
// Update the link title field setting.
|
||||
$this->field->setSetting('title', $title_setting);
|
||||
$this->field->save();
|
||||
|
||||
// Display creation form.
|
||||
$this->drupalGet('entity_test/add');
|
||||
// Assert label is shown.
|
||||
$this->assertText('Read more about this entity');
|
||||
$this->assertFieldByName("{$field_name}[0][uri]", '', 'URL field found.');
|
||||
$this->assertRaw('placeholder="http://example.com"');
|
||||
|
||||
if ($title_setting === DRUPAL_DISABLED) {
|
||||
$this->assertNoFieldByName("{$field_name}[0][title]", '', 'Link text field not found.');
|
||||
$this->assertNoRaw('placeholder="Enter the text for this link"');
|
||||
}
|
||||
else {
|
||||
$this->assertRaw('placeholder="Enter the text for this link"');
|
||||
|
||||
$this->assertFieldByName("{$field_name}[0][title]", '', 'Link text field found.');
|
||||
if ($title_setting === DRUPAL_REQUIRED) {
|
||||
// Verify that the link text is required, if the URL is non-empty.
|
||||
$edit = array(
|
||||
"{$field_name}[0][uri]" => 'http://www.example.com',
|
||||
);
|
||||
$this->drupalPostForm(NULL, $edit, t('Save'));
|
||||
$this->assertText(t('@name field is required.', array('@name' => t('Link text'))));
|
||||
|
||||
// Verify that the link text is not required, if the URL is empty.
|
||||
$edit = array(
|
||||
"{$field_name}[0][uri]" => '',
|
||||
);
|
||||
$this->drupalPostForm(NULL, $edit, t('Save'));
|
||||
$this->assertNoText(t('@name field is required.', array('@name' => t('Link text'))));
|
||||
|
||||
// Verify that a URL and link text meets requirements.
|
||||
$this->drupalGet('entity_test/add');
|
||||
$edit = array(
|
||||
"{$field_name}[0][uri]" => 'http://www.example.com',
|
||||
"{$field_name}[0][title]" => 'Example',
|
||||
);
|
||||
$this->drupalPostForm(NULL, $edit, t('Save'));
|
||||
$this->assertNoText(t('@name field is required.', array('@name' => t('Link text'))));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Verify that a link without link text is rendered using the URL as text.
|
||||
$value = 'http://www.example.com/';
|
||||
$edit = array(
|
||||
"{$field_name}[0][uri]" => $value,
|
||||
"{$field_name}[0][title]" => '',
|
||||
);
|
||||
$this->drupalPostForm(NULL, $edit, t('Save'));
|
||||
preg_match('|entity_test/manage/(\d+)|', $this->url, $match);
|
||||
$id = $match[1];
|
||||
$this->assertText(t('entity_test @id has been created.', array('@id' => $id)));
|
||||
|
||||
$this->renderTestEntity($id);
|
||||
$expected_link = \Drupal::l($value, Url::fromUri($value));
|
||||
$this->assertRaw($expected_link);
|
||||
|
||||
// Verify that a link with text is rendered using the link text.
|
||||
$title = $this->randomMachineName();
|
||||
$edit = array(
|
||||
"{$field_name}[0][title]" => $title,
|
||||
);
|
||||
$this->drupalPostForm("entity_test/manage/$id/edit", $edit, t('Save'));
|
||||
$this->assertText(t('entity_test @id has been updated.', array('@id' => $id)));
|
||||
|
||||
$this->renderTestEntity($id);
|
||||
$expected_link = \Drupal::l($title, Url::fromUri($value));
|
||||
$this->assertRaw($expected_link);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the default 'link' formatter.
|
||||
*/
|
||||
function testLinkFormatter() {
|
||||
$field_name = Unicode::strtolower($this->randomMachineName());
|
||||
// Create a field with settings to validate.
|
||||
$this->fieldStorage = FieldStorageConfig::create(array(
|
||||
'field_name' => $field_name,
|
||||
'entity_type' => 'entity_test',
|
||||
'type' => 'link',
|
||||
'cardinality' => 3,
|
||||
));
|
||||
$this->fieldStorage->save();
|
||||
FieldConfig::create([
|
||||
'field_storage' => $this->fieldStorage,
|
||||
'label' => 'Read more about this entity',
|
||||
'bundle' => 'entity_test',
|
||||
'settings' => array(
|
||||
'title' => DRUPAL_OPTIONAL,
|
||||
'link_type' => LinkItemInterface::LINK_GENERIC,
|
||||
),
|
||||
])->save();
|
||||
entity_get_form_display('entity_test', 'entity_test', 'default')
|
||||
->setComponent($field_name, array(
|
||||
'type' => 'link_default',
|
||||
))
|
||||
->save();
|
||||
$display_options = array(
|
||||
'type' => 'link',
|
||||
'label' => 'hidden',
|
||||
);
|
||||
entity_get_display('entity_test', 'entity_test', 'full')
|
||||
->setComponent($field_name, $display_options)
|
||||
->save();
|
||||
|
||||
// Create an entity with three link field values:
|
||||
// - The first field item uses a URL only.
|
||||
// - The second field item uses a URL and link text.
|
||||
// - The third field item uses a fragment-only URL with text.
|
||||
// For consistency in assertion code below, the URL is assigned to the title
|
||||
// variable for the first field.
|
||||
$this->drupalGet('entity_test/add');
|
||||
$url1 = 'http://www.example.com/content/articles/archive?author=John&year=2012#com';
|
||||
$url2 = 'http://www.example.org/content/articles/archive?author=John&year=2012#org';
|
||||
$url3 = '#net';
|
||||
$title1 = $url1;
|
||||
// Intentionally contains an ampersand that needs sanitization on output.
|
||||
$title2 = 'A very long & strange example title that could break the nice layout of the site';
|
||||
$title3 = 'Fragment only';
|
||||
$edit = array(
|
||||
"{$field_name}[0][uri]" => $url1,
|
||||
// Note that $title1 is not submitted.
|
||||
"{$field_name}[0][title]" => '',
|
||||
"{$field_name}[1][uri]" => $url2,
|
||||
"{$field_name}[1][title]" => $title2,
|
||||
"{$field_name}[2][uri]" => $url3,
|
||||
"{$field_name}[2][title]" => $title3,
|
||||
);
|
||||
// Assert label is shown.
|
||||
$this->assertText('Read more about this entity');
|
||||
$this->drupalPostForm(NULL, $edit, t('Save'));
|
||||
preg_match('|entity_test/manage/(\d+)|', $this->url, $match);
|
||||
$id = $match[1];
|
||||
$this->assertText(t('entity_test @id has been created.', array('@id' => $id)));
|
||||
|
||||
// Verify that the link is output according to the formatter settings.
|
||||
// Not using generatePermutations(), since that leads to 32 cases, which
|
||||
// would not test actual link field formatter functionality but rather
|
||||
// the link generator and options/attributes. Only 'url_plain' has a
|
||||
// dependency on 'url_only', so we have a total of ~10 cases.
|
||||
$options = array(
|
||||
'trim_length' => array(NULL, 6),
|
||||
'rel' => array(NULL, 'nofollow'),
|
||||
'target' => array(NULL, '_blank'),
|
||||
'url_only' => array(
|
||||
array('url_only' => FALSE),
|
||||
array('url_only' => FALSE, 'url_plain' => TRUE),
|
||||
array('url_only' => TRUE),
|
||||
array('url_only' => TRUE, 'url_plain' => TRUE),
|
||||
),
|
||||
);
|
||||
foreach ($options as $setting => $values) {
|
||||
foreach ($values as $new_value) {
|
||||
// Update the field formatter settings.
|
||||
if (!is_array($new_value)) {
|
||||
$display_options['settings'] = array($setting => $new_value);
|
||||
}
|
||||
else {
|
||||
$display_options['settings'] = $new_value;
|
||||
}
|
||||
entity_get_display('entity_test', 'entity_test', 'full')
|
||||
->setComponent($field_name, $display_options)
|
||||
->save();
|
||||
|
||||
$this->renderTestEntity($id);
|
||||
switch ($setting) {
|
||||
case 'trim_length':
|
||||
$url = $url1;
|
||||
$title = isset($new_value) ? Unicode::truncate($title1, $new_value, FALSE, TRUE) : $title1;
|
||||
$this->assertRaw('<a href="' . Html::escape($url) . '">' . Html::escape($title) . '</a>');
|
||||
|
||||
$url = $url2;
|
||||
$title = isset($new_value) ? Unicode::truncate($title2, $new_value, FALSE, TRUE) : $title2;
|
||||
$this->assertRaw('<a href="' . Html::escape($url) . '">' . Html::escape($title) . '</a>');
|
||||
|
||||
$url = $url3;
|
||||
$title = isset($new_value) ? Unicode::truncate($title3, $new_value, FALSE, TRUE) : $title3;
|
||||
$this->assertRaw('<a href="' . Html::escape($url) . '">' . Html::escape($title) . '</a>');
|
||||
break;
|
||||
|
||||
case 'rel':
|
||||
$rel = isset($new_value) ? ' rel="' . $new_value . '"' : '';
|
||||
$this->assertRaw('<a href="' . Html::escape($url1) . '"' . $rel . '>' . Html::escape($title1) . '</a>');
|
||||
$this->assertRaw('<a href="' . Html::escape($url2) . '"' . $rel . '>' . Html::escape($title2) . '</a>');
|
||||
$this->assertRaw('<a href="' . Html::escape($url3) . '"' . $rel . '>' . Html::escape($title3) . '</a>');
|
||||
break;
|
||||
|
||||
case 'target':
|
||||
$target = isset($new_value) ? ' target="' . $new_value . '"' : '';
|
||||
$this->assertRaw('<a href="' . Html::escape($url1) . '"' . $target . '>' . Html::escape($title1) . '</a>');
|
||||
$this->assertRaw('<a href="' . Html::escape($url2) . '"' . $target . '>' . Html::escape($title2) . '</a>');
|
||||
$this->assertRaw('<a href="' . Html::escape($url3) . '"' . $target . '>' . Html::escape($title3) . '</a>');
|
||||
break;
|
||||
|
||||
case 'url_only':
|
||||
// In this case, $new_value is an array.
|
||||
if (!$new_value['url_only']) {
|
||||
$this->assertRaw('<a href="' . Html::escape($url1) . '">' . Html::escape($title1) . '</a>');
|
||||
$this->assertRaw('<a href="' . Html::escape($url2) . '">' . Html::escape($title2) . '</a>');
|
||||
$this->assertRaw('<a href="' . Html::escape($url3) . '">' . Html::escape($title3) . '</a>');
|
||||
}
|
||||
else {
|
||||
if (empty($new_value['url_plain'])) {
|
||||
$this->assertRaw('<a href="' . Html::escape($url1) . '">' . Html::escape($url1) . '</a>');
|
||||
$this->assertRaw('<a href="' . Html::escape($url2) . '">' . Html::escape($url2) . '</a>');
|
||||
$this->assertRaw('<a href="' . Html::escape($url3) . '">' . Html::escape($url3) . '</a>');
|
||||
}
|
||||
else {
|
||||
$this->assertNoRaw('<a href="' . Html::escape($url1) . '">' . Html::escape($url1) . '</a>');
|
||||
$this->assertNoRaw('<a href="' . Html::escape($url2) . '">' . Html::escape($url2) . '</a>');
|
||||
$this->assertNoRaw('<a href="' . Html::escape($url3) . '">' . Html::escape($url3) . '</a>');
|
||||
$this->assertEscaped($url1);
|
||||
$this->assertEscaped($url2);
|
||||
$this->assertEscaped($url3);
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the 'link_separate' formatter.
|
||||
*
|
||||
* This test is mostly the same as testLinkFormatter(), but they cannot be
|
||||
* merged, since they involve different configuration and output.
|
||||
*/
|
||||
function testLinkSeparateFormatter() {
|
||||
$field_name = Unicode::strtolower($this->randomMachineName());
|
||||
// Create a field with settings to validate.
|
||||
$this->fieldStorage = FieldStorageConfig::create(array(
|
||||
'field_name' => $field_name,
|
||||
'entity_type' => 'entity_test',
|
||||
'type' => 'link',
|
||||
'cardinality' => 3,
|
||||
));
|
||||
$this->fieldStorage->save();
|
||||
FieldConfig::create([
|
||||
'field_storage' => $this->fieldStorage,
|
||||
'bundle' => 'entity_test',
|
||||
'settings' => array(
|
||||
'title' => DRUPAL_OPTIONAL,
|
||||
'link_type' => LinkItemInterface::LINK_GENERIC,
|
||||
),
|
||||
])->save();
|
||||
$display_options = array(
|
||||
'type' => 'link_separate',
|
||||
'label' => 'hidden',
|
||||
);
|
||||
entity_get_form_display('entity_test', 'entity_test', 'default')
|
||||
->setComponent($field_name, array(
|
||||
'type' => 'link_default',
|
||||
))
|
||||
->save();
|
||||
entity_get_display('entity_test', 'entity_test', 'full')
|
||||
->setComponent($field_name, $display_options)
|
||||
->save();
|
||||
|
||||
// Create an entity with three link field values:
|
||||
// - The first field item uses a URL only.
|
||||
// - The second field item uses a URL and link text.
|
||||
// - The third field item uses a fragment-only URL with text.
|
||||
// For consistency in assertion code below, the URL is assigned to the title
|
||||
// variable for the first field.
|
||||
$this->drupalGet('entity_test/add');
|
||||
$url1 = 'http://www.example.com/content/articles/archive?author=John&year=2012#com';
|
||||
$url2 = 'http://www.example.org/content/articles/archive?author=John&year=2012#org';
|
||||
$url3 = '#net';
|
||||
// Intentionally contains an ampersand that needs sanitization on output.
|
||||
$title2 = 'A very long & strange example title that could break the nice layout of the site';
|
||||
$title3 = 'Fragment only';
|
||||
$edit = array(
|
||||
"{$field_name}[0][uri]" => $url1,
|
||||
"{$field_name}[1][uri]" => $url2,
|
||||
"{$field_name}[1][title]" => $title2,
|
||||
"{$field_name}[2][uri]" => $url3,
|
||||
"{$field_name}[2][title]" => $title3,
|
||||
);
|
||||
$this->drupalPostForm(NULL, $edit, t('Save'));
|
||||
preg_match('|entity_test/manage/(\d+)|', $this->url, $match);
|
||||
$id = $match[1];
|
||||
$this->assertText(t('entity_test @id has been created.', array('@id' => $id)));
|
||||
|
||||
// Verify that the link is output according to the formatter settings.
|
||||
$options = array(
|
||||
'trim_length' => array(NULL, 6),
|
||||
'rel' => array(NULL, 'nofollow'),
|
||||
'target' => array(NULL, '_blank'),
|
||||
);
|
||||
foreach ($options as $setting => $values) {
|
||||
foreach ($values as $new_value) {
|
||||
// Update the field formatter settings.
|
||||
$display_options['settings'] = array($setting => $new_value);
|
||||
entity_get_display('entity_test', 'entity_test', 'full')
|
||||
->setComponent($field_name, $display_options)
|
||||
->save();
|
||||
|
||||
$this->renderTestEntity($id);
|
||||
switch ($setting) {
|
||||
case 'trim_length':
|
||||
$url = $url1;
|
||||
$url_title = isset($new_value) ? Unicode::truncate($url, $new_value, FALSE, TRUE) : $url;
|
||||
$expected = '<div class="link-item">';
|
||||
$expected .= '<div class="link-url"><a href="' . Html::escape($url) . '">' . Html::escape($url_title) . '</a></div>';
|
||||
$expected .= '</div>';
|
||||
$this->assertRaw($expected);
|
||||
|
||||
$url = $url2;
|
||||
$url_title = isset($new_value) ? Unicode::truncate($url, $new_value, FALSE, TRUE) : $url;
|
||||
$title = isset($new_value) ? Unicode::truncate($title2, $new_value, FALSE, TRUE) : $title2;
|
||||
$expected = '<div class="link-item">';
|
||||
$expected .= '<div class="link-title">' . Html::escape($title) . '</div>';
|
||||
$expected .= '<div class="link-url"><a href="' . Html::escape($url) . '">' . Html::escape($url_title) . '</a></div>';
|
||||
$expected .= '</div>';
|
||||
$this->assertRaw($expected);
|
||||
|
||||
$url = $url3;
|
||||
$url_title = isset($new_value) ? Unicode::truncate($url, $new_value, FALSE, TRUE) : $url;
|
||||
$title = isset($new_value) ? Unicode::truncate($title3, $new_value, FALSE, TRUE) : $title3;
|
||||
$expected = '<div class="link-item">';
|
||||
$expected .= '<div class="link-title">' . Html::escape($title) . '</div>';
|
||||
$expected .= '<div class="link-url"><a href="' . Html::escape($url) . '">' . Html::escape($url_title) . '</a></div>';
|
||||
$expected .= '</div>';
|
||||
$this->assertRaw($expected);
|
||||
break;
|
||||
|
||||
case 'rel':
|
||||
$rel = isset($new_value) ? ' rel="' . $new_value . '"' : '';
|
||||
$this->assertRaw('<div class="link-url"><a href="' . Html::escape($url1) . '"' . $rel . '>' . Html::escape($url1) . '</a></div>');
|
||||
$this->assertRaw('<div class="link-url"><a href="' . Html::escape($url2) . '"' . $rel . '>' . Html::escape($url2) . '</a></div>');
|
||||
$this->assertRaw('<div class="link-url"><a href="' . Html::escape($url3) . '"' . $rel . '>' . Html::escape($url3) . '</a></div>');
|
||||
break;
|
||||
|
||||
case 'target':
|
||||
$target = isset($new_value) ? ' target="' . $new_value . '"' : '';
|
||||
$this->assertRaw('<div class="link-url"><a href="' . Html::escape($url1) . '"' . $target . '>' . Html::escape($url1) . '</a></div>');
|
||||
$this->assertRaw('<div class="link-url"><a href="' . Html::escape($url2) . '"' . $target . '>' . Html::escape($url2) . '</a></div>');
|
||||
$this->assertRaw('<div class="link-url"><a href="' . Html::escape($url3) . '"' . $target . '>' . Html::escape($url3) . '</a></div>');
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders a test_entity and sets the output in the internal browser.
|
||||
*
|
||||
* @param int $id
|
||||
* The test_entity ID to render.
|
||||
* @param string $view_mode
|
||||
* (optional) The view mode to use for rendering.
|
||||
* @param bool $reset
|
||||
* (optional) Whether to reset the entity_test storage cache. Defaults to
|
||||
* TRUE to simplify testing.
|
||||
*/
|
||||
protected function renderTestEntity($id, $view_mode = 'full', $reset = TRUE) {
|
||||
if ($reset) {
|
||||
$this->container->get('entity.manager')->getStorage('entity_test')->resetCache(array($id));
|
||||
}
|
||||
$entity = EntityTest::load($id);
|
||||
$display = entity_get_display($entity->getEntityTypeId(), $entity->bundle(), $view_mode);
|
||||
$content = $display->build($entity);
|
||||
$output = \Drupal::service('renderer')->renderRoot($content);
|
||||
$this->setRawContent($output);
|
||||
$this->verbose($output);
|
||||
}
|
||||
|
||||
}
|
92
web/core/modules/link/src/Tests/LinkFieldUITest.php
Normal file
92
web/core/modules/link/src/Tests/LinkFieldUITest.php
Normal file
|
@ -0,0 +1,92 @@
|
|||
<?php
|
||||
|
||||
namespace Drupal\link\Tests;
|
||||
|
||||
use Drupal\Component\Utility\Unicode;
|
||||
use Drupal\field_ui\Tests\FieldUiTestTrait;
|
||||
use Drupal\link\LinkItemInterface;
|
||||
use Drupal\simpletest\WebTestBase;
|
||||
|
||||
/**
|
||||
* Tests link field UI functionality.
|
||||
*
|
||||
* @group link
|
||||
*/
|
||||
class LinkFieldUITest extends WebTestBase {
|
||||
|
||||
use FieldUiTestTrait;
|
||||
|
||||
/**
|
||||
* Modules to enable.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $modules = ['node', 'link', 'field_ui', 'block'];
|
||||
|
||||
/**
|
||||
* A user that can edit content types.
|
||||
*
|
||||
* @var \Drupal\user\UserInterface
|
||||
*/
|
||||
protected $adminUser;
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function setUp() {
|
||||
parent::setUp();
|
||||
|
||||
$this->adminUser = $this->drupalCreateUser(['administer content types', 'administer node fields', 'administer node display']);
|
||||
$this->drupalLogin($this->adminUser);
|
||||
$this->drupalPlaceBlock('system_breadcrumb_block');
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the link field UI.
|
||||
*/
|
||||
function testFieldUI() {
|
||||
// Add a content type.
|
||||
$type = $this->drupalCreateContentType();
|
||||
$type_path = 'admin/structure/types/manage/' . $type->id();
|
||||
$add_path = 'node/add/' . $type->id();
|
||||
|
||||
// Add a link field to the newly-created type. It defaults to allowing both
|
||||
// internal and external links.
|
||||
$label = $this->randomMachineName();
|
||||
$field_name = Unicode::strtolower($label);
|
||||
$this->fieldUIAddNewField($type_path, $field_name, $label, 'link');
|
||||
|
||||
// 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->assertText(t('Link text trimmed to @limit characters', array('@limit' => 80)));
|
||||
|
||||
// Test the help text displays when the link field allows both internal and
|
||||
// external links.
|
||||
$this->drupalLogin($this->drupalCreateUser(['create ' . $type->id() . ' content']));
|
||||
$this->drupalGet($add_path);
|
||||
$this->assertRaw('You can also enter an internal path such as <em class="placeholder">/node/add</em> or an external URL such as <em class="placeholder">http://example.com</em>.');
|
||||
|
||||
// Log in an admin to set up the next content type.
|
||||
$this->drupalLogin($this->adminUser);
|
||||
|
||||
// Add a different content type.
|
||||
$type = $this->drupalCreateContentType();
|
||||
$type_path = 'admin/structure/types/manage/' . $type->id();
|
||||
$add_path = 'node/add/' . $type->id();
|
||||
|
||||
// Add a link field to the newly-created type. Specify it must allow
|
||||
// external only links.
|
||||
$label = $this->randomMachineName();
|
||||
$field_name = Unicode::strtolower($label);
|
||||
$field_edit = ['settings[link_type]' => LinkItemInterface::LINK_EXTERNAL];
|
||||
$this->fieldUIAddNewField($type_path, $field_name, $label, 'link', array(), $field_edit);
|
||||
|
||||
// Test the help text displays when link allows only external links.
|
||||
$this->drupalLogin($this->drupalCreateUser(['create ' . $type->id() . ' content']));
|
||||
$this->drupalGet($add_path);
|
||||
$this->assertRaw('This must be an external URL such as <em class="placeholder">http://example.com</em>.');
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,98 @@
|
|||
<?php
|
||||
|
||||
namespace Drupal\link\Tests\Views;
|
||||
|
||||
use Drupal\field\Entity\FieldConfig;
|
||||
use Drupal\field\Entity\FieldStorageConfig;
|
||||
use Drupal\views\Tests\ViewTestBase;
|
||||
use Drupal\views\Tests\ViewTestData;
|
||||
|
||||
/**
|
||||
* Tests the views integration for link tokens.
|
||||
*
|
||||
* @group link
|
||||
*/
|
||||
class LinkViewsTokensTest extends ViewTestBase {
|
||||
|
||||
/**
|
||||
* Modules to enable.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $modules = ['link_test_views'];
|
||||
|
||||
/**
|
||||
* 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() {
|
||||
parent::setUp();
|
||||
ViewTestData::createTestViews(get_class($this), array('link_test_views'));
|
||||
|
||||
// Create Basic page node type.
|
||||
$this->drupalCreateContentType(array(
|
||||
'type' => 'page',
|
||||
'name' => 'Basic page'
|
||||
));
|
||||
|
||||
// Create a field.
|
||||
FieldStorageConfig::create(array(
|
||||
'field_name' => $this->fieldName,
|
||||
'type' => 'link',
|
||||
'entity_type' => 'node',
|
||||
'cardinality' => 1,
|
||||
))->save();
|
||||
FieldConfig::create(array(
|
||||
'field_name' => $this->fieldName,
|
||||
'entity_type' => 'node',
|
||||
'bundle' => 'page',
|
||||
'label' => 'link field',
|
||||
))->save();
|
||||
|
||||
}
|
||||
|
||||
public function testLinkViewsTokens() {
|
||||
// Array of URI's to test.
|
||||
$uris = [
|
||||
'http://www.drupal.org' => 'Drupal.org',
|
||||
];
|
||||
|
||||
// Add nodes with the URI's and titles.
|
||||
foreach ($uris as $uri => $title) {
|
||||
$values = array('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->assertRaw("Formated: <a href=\"$uri\" class=\"test-link-class\">$title</a>");
|
||||
|
||||
// Raw uri: {{ field_link__uri }}<br />
|
||||
$this->assertRaw("Raw uri: $uri");
|
||||
|
||||
// Raw title: {{ field_link__title }}<br />
|
||||
$this->assertRaw("Raw title: $title");
|
||||
|
||||
// Raw options: {{ field_link__options }}<br />
|
||||
// Options is an array and should return empty after token replace.
|
||||
$this->assertRaw("Raw options: .");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -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
|
||||
*/
|
||||
#}
|
||||
{% spaceless %}
|
||||
{{ title }}
|
||||
{{ link }}
|
||||
{% endspaceless %}
|
|
@ -0,0 +1,10 @@
|
|||
name: 'Link test views'
|
||||
type: module
|
||||
description: 'Provides default views for views link tests.'
|
||||
package: Testing
|
||||
version: VERSION
|
||||
core: 8.x
|
||||
dependencies:
|
||||
- node
|
||||
- views
|
||||
- link
|
|
@ -0,0 +1,206 @@
|
|||
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
|
||||
core: 8.x
|
||||
display:
|
||||
default:
|
||||
display_plugin: default
|
||||
id: default
|
||||
display_title: Master
|
||||
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: "Formated: {{ 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
|
177
web/core/modules/link/tests/src/Kernel/LinkItemTest.php
Normal file
177
web/core/modules/link/tests/src/Kernel/LinkItemTest.php
Normal file
|
@ -0,0 +1,177 @@
|
|||
<?php
|
||||
|
||||
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
|
||||
*/
|
||||
public static $modules = array('link');
|
||||
|
||||
protected function setUp() {
|
||||
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() {
|
||||
// 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', array('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->assertTrue($entity->field_test instanceof FieldItemListInterface, 'Field implements interface.');
|
||||
$this->assertTrue($entity->field_test[0] instanceof FieldItemInterface, 'Field item implements interface.');
|
||||
$this->assertEqual($entity->field_test->uri, $parsed_url['path']);
|
||||
$this->assertEqual($entity->field_test[0]->uri, $parsed_url['path']);
|
||||
$this->assertEqual($entity->field_test->title, $title);
|
||||
$this->assertEqual($entity->field_test[0]->title, $title);
|
||||
$this->assertEqual($entity->field_test->options['attributes']['class'], $class);
|
||||
$this->assertEqual($entity->field_test->options['query'], $parsed_url['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->assertEqual($entity->field_test->uri, $parsed_url['path']);
|
||||
$this->assertEqual($entity->field_test->options['attributes']['class'], $class);
|
||||
$this->assertEqual($entity->field_test->options['query'], $parsed_url['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', array('class' => $new_class));
|
||||
$this->assertEqual($entity->field_test->uri, $new_url);
|
||||
$this->assertEqual($entity->field_test->title, $new_title);
|
||||
$this->assertEqual($entity->field_test->options['attributes']['class'], $new_class);
|
||||
$this->assertNull($entity->field_test->options['query']);
|
||||
|
||||
// Read changed entity and assert changed values.
|
||||
$entity->save();
|
||||
$entity = EntityTest::load($id);
|
||||
$this->assertEqual($entity->field_test->uri, $new_url);
|
||||
$this->assertEqual($entity->field_test->title, $new_title);
|
||||
$this->assertEqual($entity->field_test->options['attributes']['class'], $new_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->assertEqual($entity->field_test->uri, 'internal:/node/add');
|
||||
$this->assertNull($entity->field_test->title);
|
||||
$this->assertIdentical($entity->field_test->options, []);
|
||||
|
||||
// Check that if set uri and serialize options then the default values are
|
||||
// properly initialized.
|
||||
$entity->field_test = [
|
||||
'uri' => 'internal:/node/add',
|
||||
'options' => serialize(['query' => NULL]),
|
||||
];
|
||||
$this->assertEqual($entity->field_test->uri, 'internal:/node/add');
|
||||
$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->assertEqual($entity->field_test->uri, 'internal:/node/add');
|
||||
$this->assertNull($entity->field_test->title);
|
||||
$this->assertIdentical($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);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,95 @@
|
|||
<?php
|
||||
|
||||
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;
|
||||
|
||||
/**
|
||||
* Tests the LinkAccessConstraintValidator validator.
|
||||
*
|
||||
* @coversDefaultClass \Drupal\link\Plugin\Validation\Constraint\LinkAccessConstraintValidator
|
||||
* @group validation
|
||||
*/
|
||||
class LinkAccessConstraintValidatorTest extends UnitTestCase {
|
||||
|
||||
/**
|
||||
* Tests the \Drupal\link\Plugin\Validation\Constraint\LinkAccessConstraintValidator::validate()
|
||||
* method.
|
||||
*
|
||||
* @param \Drupal\link\LinkItemInterface $value
|
||||
* The link item.
|
||||
* @param \Drupal\Core\Session\AccountProxyInterface $user
|
||||
* The user account.
|
||||
* @param bool $valid
|
||||
* A boolean indicating if the combination is expected to be valid.
|
||||
*
|
||||
* @covers ::validate
|
||||
* @dataProvider providerValidate
|
||||
*/
|
||||
public function testValidate($value, $user, $valid) {
|
||||
$context = $this->getMock('Symfony\Component\Validator\ExecutionContextInterface');
|
||||
|
||||
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($value, $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 function providerValidate() {
|
||||
$data = [];
|
||||
|
||||
$cases = [
|
||||
['may_link_any_page' => TRUE, 'url_access' => TRUE, 'valid' => TRUE],
|
||||
['may_link_any_page' => TRUE, 'url_access' => FALSE, 'valid' => TRUE],
|
||||
['may_link_any_page' => FALSE, 'url_access' => TRUE, 'valid' => TRUE],
|
||||
['may_link_any_page' => FALSE, 'url_access' => FALSE, 'valid' => FALSE],
|
||||
];
|
||||
|
||||
foreach ($cases as $case) {
|
||||
// Mock a Url object that returns a boolean indicating user access.
|
||||
$url = $this->getMockBuilder('Drupal\Core\Url')
|
||||
->disableOriginalConstructor()
|
||||
->getMock();
|
||||
$url->expects($this->once())
|
||||
->method('access')
|
||||
->willReturn($case['url_access']);
|
||||
// Mock a link object that returns the URL object.
|
||||
$link = $this->getMock('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->getMock('Drupal\Core\Session\AccountProxyInterface');
|
||||
$user->expects($this->any())
|
||||
->method('hasPermission')
|
||||
->with($this->equalTo('link to any page'))
|
||||
->willReturn($case['may_link_any_page']);
|
||||
|
||||
$data[] = [$link, $user, $case['valid']];
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,111 @@
|
|||
<?php
|
||||
|
||||
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;
|
||||
|
||||
/**
|
||||
* @coversDefaultClass \Drupal\link\Plugin\Validation\Constraint\LinkExternalProtocolsConstraintValidator
|
||||
* @group Link
|
||||
*/
|
||||
class LinkExternalProtocolsConstraintValidatorTest extends UnitTestCase {
|
||||
|
||||
/**
|
||||
* @covers ::validate
|
||||
* @dataProvider providerValidate
|
||||
*/
|
||||
public function testValidate($value, $valid) {
|
||||
$context = $this->getMock('Symfony\Component\Validator\ExecutionContextInterface');
|
||||
|
||||
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($value, $constraint);
|
||||
}
|
||||
|
||||
/**
|
||||
* Data provider for ::testValidate
|
||||
*/
|
||||
public function providerValidate() {
|
||||
$data = [];
|
||||
|
||||
// Test allowed protocols.
|
||||
$data[] = ['http://www.drupal.org', TRUE];
|
||||
$data[] = ['https://www.drupal.org', TRUE];
|
||||
$data[] = ['magnet:?xt=urn:sha1:YNCKHTQCWBTRNJIV4WNAE52SJUQCZO5C', TRUE];
|
||||
|
||||
// Invalid protocols.
|
||||
$data[] = ['ftp://ftp.funet.fi/pub/standards/RFC/rfc959.txt', FALSE];
|
||||
|
||||
foreach ($data as &$single_data) {
|
||||
$url = Url::fromUri($single_data[0]);
|
||||
$link = $this->getMock('Drupal\link\LinkItemInterface');
|
||||
$link->expects($this->any())
|
||||
->method('getUrl')
|
||||
->willReturn($url);
|
||||
$single_data[0] = $link;
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* @covers ::validate
|
||||
*
|
||||
* @see \Drupal\Core\Url::fromUri
|
||||
*/
|
||||
public function testValidateWithMalformedUri() {
|
||||
$link = $this->getMock('Drupal\link\LinkItemInterface');
|
||||
$link->expects($this->any())
|
||||
->method('getUrl')
|
||||
->willThrowException(new \InvalidArgumentException());
|
||||
|
||||
$context = $this->getMock('Symfony\Component\Validator\ExecutionContextInterface');
|
||||
$context->expects($this->never())
|
||||
->method('addViolation');
|
||||
|
||||
$constraint = new LinkExternalProtocolsConstraint();
|
||||
|
||||
$validator = new LinkExternalProtocolsConstraintValidator();
|
||||
$validator->initialize($context);
|
||||
$validator->validate($link, $constraint);
|
||||
}
|
||||
|
||||
/**
|
||||
* @covers ::validate
|
||||
*/
|
||||
public function testValidateIgnoresInternalUrls() {
|
||||
$link = $this->getMock('Drupal\link\LinkItemInterface');
|
||||
$link->expects($this->any())
|
||||
->method('getUrl')
|
||||
->willReturn(Url::fromRoute('example.test'));
|
||||
|
||||
$context = $this->getMock('Symfony\Component\Validator\ExecutionContextInterface');
|
||||
$context->expects($this->never())
|
||||
->method('addViolation');
|
||||
|
||||
$constraint = new LinkExternalProtocolsConstraint();
|
||||
|
||||
$validator = new LinkExternalProtocolsConstraintValidator();
|
||||
$validator->initialize($context);
|
||||
$validator->validate($link, $constraint);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,108 @@
|
|||
<?php
|
||||
|
||||
namespace Drupal\Tests\link\Unit\Plugin\Validation\Constraint;
|
||||
|
||||
use Drupal\Core\Url;
|
||||
use Drupal\link\Plugin\Validation\Constraint\LinkNotExistingInternalConstraint;
|
||||
use Drupal\link\Plugin\Validation\Constraint\LinkNotExistingInternalConstraintValidator;
|
||||
use Drupal\Tests\UnitTestCase;
|
||||
use Symfony\Component\Routing\Exception\RouteNotFoundException;
|
||||
|
||||
/**
|
||||
* @coversDefaultClass \Drupal\link\Plugin\Validation\Constraint\LinkNotExistingInternalConstraintValidator
|
||||
* @group Link
|
||||
*/
|
||||
class LinkNotExistingInternalConstraintValidatorTest extends UnitTestCase {
|
||||
|
||||
/**
|
||||
* @covers ::validate
|
||||
* @dataProvider providerValidate
|
||||
*/
|
||||
public function testValidate($value, $valid) {
|
||||
$context = $this->getMock('Symfony\Component\Validator\ExecutionContextInterface');
|
||||
|
||||
if ($valid) {
|
||||
$context->expects($this->never())
|
||||
->method('addViolation');
|
||||
}
|
||||
else {
|
||||
$context->expects($this->once())
|
||||
->method('addViolation');
|
||||
}
|
||||
|
||||
|
||||
$constraint = new LinkNotExistingInternalConstraint();
|
||||
|
||||
$validator = new LinkNotExistingInternalConstraintValidator();
|
||||
$validator->initialize($context);
|
||||
$validator->validate($value, $constraint);
|
||||
}
|
||||
|
||||
/**
|
||||
* Data provider for ::testValidate
|
||||
*/
|
||||
public function providerValidate() {
|
||||
$data = [];
|
||||
|
||||
// External URL
|
||||
$data[] = [Url::fromUri('https://www.drupal.org'), TRUE];
|
||||
|
||||
// Existing routed URL.
|
||||
$url = Url::fromRoute('example.existing_route');
|
||||
|
||||
$url_generator = $this->getMock('Drupal\Core\Routing\UrlGeneratorInterface');
|
||||
$url_generator->expects($this->any())
|
||||
->method('generateFromRoute')
|
||||
->with('example.existing_route', [], [])
|
||||
->willReturn('/example/existing');
|
||||
$url->setUrlGenerator($url_generator);
|
||||
|
||||
$data[] = [$url, TRUE];
|
||||
|
||||
// Not existing routed URL.
|
||||
$url = Url::fromRoute('example.not_existing_route');
|
||||
|
||||
$url_generator = $this->getMock('Drupal\Core\Routing\UrlGeneratorInterface');
|
||||
$url_generator->expects($this->any())
|
||||
->method('generateFromRoute')
|
||||
->with('example.not_existing_route', [], [])
|
||||
->willThrowException(new RouteNotFoundException());
|
||||
$url->setUrlGenerator($url_generator);
|
||||
|
||||
$data[] = [$url, FALSE];
|
||||
|
||||
foreach ($data as &$single_data) {
|
||||
$link = $this->getMock('Drupal\link\LinkItemInterface');
|
||||
$link->expects($this->any())
|
||||
->method('getUrl')
|
||||
->willReturn($single_data[0]);
|
||||
|
||||
$single_data[0] = $link;
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* @covers ::validate
|
||||
*
|
||||
* @see \Drupal\Core\Url::fromUri
|
||||
*/
|
||||
public function testValidateWithMalformedUri() {
|
||||
$link = $this->getMock('Drupal\link\LinkItemInterface');
|
||||
$link->expects($this->any())
|
||||
->method('getUrl')
|
||||
->willThrowException(new \InvalidArgumentException());
|
||||
|
||||
$context = $this->getMock('Symfony\Component\Validator\ExecutionContextInterface');
|
||||
$context->expects($this->never())
|
||||
->method('addViolation');
|
||||
|
||||
$constraint = new LinkNotExistingInternalConstraint();
|
||||
|
||||
$validator = new LinkNotExistingInternalConstraintValidator();
|
||||
$validator->initialize($context);
|
||||
$validator->validate($link, $constraint);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,56 @@
|
|||
<?php
|
||||
|
||||
namespace Drupal\Tests\link\Unit\Plugin\migrate\process\d6;
|
||||
|
||||
use Drupal\link\Plugin\migrate\process\d6\CckLink;
|
||||
use Drupal\Tests\UnitTestCase;
|
||||
|
||||
/**
|
||||
* @group Link
|
||||
*/
|
||||
class CckLinkTest extends UnitTestCase {
|
||||
|
||||
/**
|
||||
* Test the url transformations in the CckLink process plugin.
|
||||
*
|
||||
* @dataProvider canonicalizeUriDataProvider
|
||||
*/
|
||||
public function testCanonicalizeUri($url, $expected) {
|
||||
$link_plugin = new CckLink([], '', [], $this->getMock('\Drupal\migrate\Plugin\MigrationInterface'));
|
||||
$transformed = $link_plugin->transform([
|
||||
'url' => $url,
|
||||
'title' => '',
|
||||
'attributes' => serialize([]),
|
||||
], $this->getMock('\Drupal\migrate\MigrateExecutableInterface'), $this->getMockBuilder('\Drupal\migrate\Row')->disableOriginalConstructor()->getMock(), NULL);
|
||||
$this->assertEquals($expected, $transformed['uri']);
|
||||
}
|
||||
|
||||
/**
|
||||
* Data provider for testCanonicalizeUri.
|
||||
*/
|
||||
public 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',
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
}
|
Reference in a new issue