Update core 8.3.0

This commit is contained in:
Rob Davies 2017-04-13 15:53:35 +01:00
parent da7a7918f8
commit cd7a898e66
6144 changed files with 132297 additions and 87747 deletions

View file

@ -15,11 +15,11 @@ function link_help($route_name, RouteMatchInterface $route_match) {
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 .= '<p>' . t('The Link module allows you to create fields that contain internal or external URLs and optional link text. See the <a href=":field">Field module help</a> and the <a href=":field_ui">Field UI help</a> pages for general information on fields and how to create and manage them. For more information, see the <a href=":link_documentation">online documentation for the Link module</a>.', [':field' => \Drupal::url('help.page', ['name' => 'field']), ':field_ui' => (\Drupal::moduleHandler()->moduleExists('field_ui')) ? \Drupal::url('help.page', ['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 .= '<dd>' . t('The <em>settings</em> and the <em>display</em> of the link field can be configured separately. See the <a href=":field_ui">Field UI help</a> for more information on how to manage fields and their display.', [':field_ui' => (\Drupal::moduleHandler()->moduleExists('field_ui')) ? \Drupal::url('help.page', ['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>';
@ -39,11 +39,11 @@ function link_help($route_name, RouteMatchInterface $route_match) {
* Implements hook_theme().
*/
function link_theme() {
return array(
'link_formatter_link_separate' => array(
'variables' => array('title' => NULL, 'url_title' => NULL, 'url' => NULL),
),
);
return [
'link_formatter_link_separate' => [
'variables' => ['title' => NULL, 'url_title' => NULL, 'url' => NULL],
],
];
}
/**

View file

@ -78,13 +78,13 @@ class LinkFormatter extends FormatterBase implements ContainerFactoryPluginInter
* {@inheritdoc}
*/
public static function defaultSettings() {
return array(
return [
'trim_length' => '80',
'url_only' => '',
'url_plain' => '',
'rel' => '',
'target' => '',
) + parent::defaultSettings();
] + parent::defaultSettings();
}
/**
@ -93,43 +93,43 @@ class LinkFormatter extends FormatterBase implements ContainerFactoryPluginInter
public function settingsForm(array $form, FormStateInterface $form_state) {
$elements = parent::settingsForm($form, $form_state);
$elements['trim_length'] = array(
$elements['trim_length'] = [
'#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(
];
$elements['url_only'] = [
'#type' => 'checkbox',
'#title' => t('URL only'),
'#default_value' => $this->getSetting('url_only'),
'#access' => $this->getPluginId() == 'link',
);
$elements['url_plain'] = array(
];
$elements['url_plain'] = [
'#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(
'#states' => [
'visible' => [
':input[name*="url_only"]' => ['checked' => TRUE],
],
],
];
$elements['rel'] = [
'#type' => 'checkbox',
'#title' => t('Add rel="nofollow" to links'),
'#return_value' => 'nofollow',
'#default_value' => $this->getSetting('rel'),
);
$elements['target'] = array(
];
$elements['target'] = [
'#type' => 'checkbox',
'#title' => t('Open link in new window'),
'#return_value' => '_blank',
'#default_value' => $this->getSetting('target'),
);
];
return $elements;
}
@ -138,12 +138,12 @@ class LinkFormatter extends FormatterBase implements ContainerFactoryPluginInter
* {@inheritdoc}
*/
public function settingsSummary() {
$summary = array();
$summary = [];
$settings = $this->getSettings();
if (!empty($settings['trim_length'])) {
$summary[] = t('Link text trimmed to @limit characters', array('@limit' => $settings['trim_length']));
$summary[] = t('Link text trimmed to @limit characters', ['@limit' => $settings['trim_length']]);
}
else {
$summary[] = t('Link text not trimmed');
@ -157,7 +157,7 @@ class LinkFormatter extends FormatterBase implements ContainerFactoryPluginInter
}
}
if (!empty($settings['rel'])) {
$summary[] = t('Add rel="@rel"', array('@rel' => $settings['rel']));
$summary[] = t('Add rel="@rel"', ['@rel' => $settings['rel']]);
}
if (!empty($settings['target'])) {
$summary[] = t('Open link in new window');
@ -170,7 +170,7 @@ class LinkFormatter extends FormatterBase implements ContainerFactoryPluginInter
* {@inheritdoc}
*/
public function viewElements(FieldItemListInterface $items, $langcode) {
$element = array();
$element = [];
$entity = $items->getEntity();
$settings = $this->getSettings();
@ -193,9 +193,9 @@ class LinkFormatter extends FormatterBase implements ContainerFactoryPluginInter
}
if (!empty($settings['url_only']) && !empty($settings['url_plain'])) {
$element[$delta] = array(
$element[$delta] = [
'#plain_text' => $link_title,
);
];
if (!empty($item->_attributes)) {
// Piggyback on the metadata attributes, which will be placed in the
@ -204,19 +204,19 @@ class LinkFormatter extends FormatterBase implements ContainerFactoryPluginInter
// @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);
$item->_attributes += ['content' => $content];
}
}
else {
$element[$delta] = array(
$element[$delta] = [
'#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' => []];
$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.

View file

@ -26,18 +26,18 @@ class LinkSeparateFormatter extends LinkFormatter {
* {@inheritdoc}
*/
public static function defaultSettings() {
return array(
return [
'trim_length' => 80,
'rel' => '',
'target' => '',
) + parent::defaultSettings();
] + parent::defaultSettings();
}
/**
* {@inheritdoc}
*/
public function viewElements(FieldItemListInterface $items, $langcode) {
$element = array();
$element = [];
$entity = $items->getEntity();
$settings = $this->getSettings();
@ -67,12 +67,12 @@ class LinkSeparateFormatter extends LinkFormatter {
$url_title = Unicode::truncate($url_title, $settings['trim_length'], FALSE, TRUE);
}
$element[$delta] = array(
$element[$delta] = [
'#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.

View file

@ -30,10 +30,10 @@ class LinkItem extends FieldItemBase implements LinkItemInterface {
* {@inheritdoc}
*/
public static function defaultFieldSettings() {
return array(
return [
'title' => DRUPAL_OPTIONAL,
'link_type' => LinkItemInterface::LINK_GENERIC
) + parent::defaultFieldSettings();
] + parent::defaultFieldSettings();
}
/**
@ -56,58 +56,58 @@ class LinkItem extends FieldItemBase implements LinkItemInterface {
* {@inheritdoc}
*/
public static function schema(FieldStorageDefinitionInterface $field_definition) {
return array(
'columns' => array(
'uri' => array(
return [
'columns' => [
'uri' => [
'description' => 'The URI of the link.',
'type' => 'varchar',
'length' => 2048,
),
'title' => array(
],
'title' => [
'description' => 'The link text.',
'type' => 'varchar',
'length' => 255,
),
'options' => array(
],
'options' => [
'description' => 'Serialized array of options for the link.',
'type' => 'blob',
'size' => 'big',
'serialize' => TRUE,
),
),
'indexes' => array(
'uri' => array(array('uri', 30)),
),
);
],
],
'indexes' => [
'uri' => [['uri', 30]],
],
];
}
/**
* {@inheritdoc}
*/
public function fieldSettingsForm(array $form, FormStateInterface $form_state) {
$element = array();
$element = [];
$element['link_type'] = array(
$element['link_type'] = [
'#type' => 'radios',
'#title' => t('Allowed link type'),
'#default_value' => $this->getSetting('link_type'),
'#options' => array(
'#options' => [
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(
$element['title'] = [
'#type' => 'radios',
'#title' => t('Allow link text'),
'#default_value' => $this->getSetting('title'),
'#options' => array(
'#options' => [
DRUPAL_DISABLED => t('Disabled'),
DRUPAL_OPTIONAL => t('Optional'),
DRUPAL_REQUIRED => t('Required'),
),
);
],
];
return $element;
}
@ -119,7 +119,7 @@ class LinkItem extends FieldItemBase implements LinkItemInterface {
$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');
$tlds = ['com', 'net', 'gov', 'org', 'edu', 'biz', 'info'];
// Set random length for the domain name.
$domain_length = mt_rand(7, 15);

View file

@ -27,10 +27,10 @@ class LinkWidget extends WidgetBase {
* {@inheritdoc}
*/
public static function defaultSettings() {
return array(
return [
'placeholder_url' => '',
'placeholder_title' => '',
) + parent::defaultSettings();
] + parent::defaultSettings();
}
/**
@ -74,7 +74,7 @@ class LinkWidget extends WidgetBase {
// 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));
$displayable_string = EntityAutocomplete::getEntityLabels([$entity]);
}
}
@ -153,7 +153,7 @@ class LinkWidget extends WidgetBase {
$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'])));
$form_state->setError($element['title'], t('@name field is required.', ['@name' => $element['title']['#title']]));
}
}
@ -164,7 +164,7 @@ class LinkWidget extends WidgetBase {
/** @var \Drupal\link\LinkItemInterface $item */
$item = $items[$delta];
$element['uri'] = array(
$element['uri'] = [
'#type' => 'url',
'#title' => $this->t('URL'),
'#placeholder' => $this->getSetting('placeholder_url'),
@ -172,10 +172,10 @@ class LinkWidget extends WidgetBase {
// 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')),
'#element_validate' => [[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.
@ -193,44 +193,45 @@ class LinkWidget extends WidgetBase {
}
// If the field is configured to allow only internal links, add a useful
// element prefix.
// element prefix and description.
if (!$this->supportsExternalLinks()) {
$element['uri']['#field_prefix'] = rtrim(\Drupal::url('<front>', array(), array('absolute' => TRUE)), '/');
$element['uri']['#field_prefix'] = rtrim(\Drupal::url('<front>', [], ['absolute' => TRUE]), '/');
$element['uri']['#description'] = $this->t('This must be an internal path such as %add-node. You can also start typing the title of a piece of content to select it. Enter %front to link to the front page.', ['%add-node' => '/node/add', '%front' => '<front>']);
}
// 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'));
$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.', ['%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['uri']['#description'] = $this->t('This must be an external URL such as %url.', ['%url' => 'http://example.com']);
}
$element['title'] = array(
$element['title'] = [
'#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');
$element['#element_validate'][] = [get_called_class(), 'validateTitleElement'];
}
// Exposing the attributes array in the widget is left for alternate and more
// advanced field widgets.
$element['attributes'] = array(
$element['attributes'] = [
'#type' => 'value',
'#tree' => TRUE,
'#value' => !empty($items[$delta]->options['attributes']) ? $items[$delta]->options['attributes'] : array(),
'#attributes' => array('class' => array('link-field-widget-attributes')),
);
'#value' => !empty($items[$delta]->options['attributes']) ? $items[$delta]->options['attributes'] : [],
'#attributes' => ['class' => ['link-field-widget-attributes']],
];
// If cardinality is 1, ensure a proper label is output for the field.
if ($this->fieldDefinition->getFieldStorageDefinition()->getCardinality() == 1) {
@ -241,9 +242,9 @@ class LinkWidget extends WidgetBase {
}
// Otherwise wrap everything in a details element.
else {
$element += array(
$element += [
'#type' => 'fieldset',
);
];
}
}
@ -280,23 +281,23 @@ class LinkWidget extends WidgetBase {
public function settingsForm(array $form, FormStateInterface $form_state) {
$elements = parent::settingsForm($form, $form_state);
$elements['placeholder_url'] = array(
$elements['placeholder_url'] = [
'#type' => 'textfield',
'#title' => $this->t('Placeholder for URL'),
'#default_value' => $this->getSetting('placeholder_url'),
'#description' => $this->t('Text that will be shown inside the field until a value is entered. This hint is usually a sample value or a brief description of the expected format.'),
);
$elements['placeholder_title'] = array(
];
$elements['placeholder_title'] = [
'#type' => 'textfield',
'#title' => $this->t('Placeholder for link text'),
'#default_value' => $this->getSetting('placeholder_title'),
'#description' => $this->t('Text that will be shown inside the field until a value is entered. This hint is usually a sample value or a brief description of the expected format.'),
'#states' => array(
'invisible' => array(
':input[name="instance[settings][title]"]' => array('value' => DRUPAL_DISABLED),
),
),
);
'#states' => [
'invisible' => [
':input[name="instance[settings][title]"]' => ['value' => DRUPAL_DISABLED],
],
],
];
return $elements;
}
@ -305,7 +306,7 @@ class LinkWidget extends WidgetBase {
* {@inheritdoc}
*/
public function settingsSummary() {
$summary = array();
$summary = [];
$placeholder_title = $this->getSetting('placeholder_title');
$placeholder_url = $this->getSetting('placeholder_url');
@ -314,10 +315,10 @@ class LinkWidget extends WidgetBase {
}
else {
if (!empty($placeholder_title)) {
$summary[] = $this->t('Title placeholder: @placeholder_title', array('@placeholder_title' => $placeholder_title));
$summary[] = $this->t('Title placeholder: @placeholder_title', ['@placeholder_title' => $placeholder_title]);
}
if (!empty($placeholder_url)) {
$summary[] = $this->t('URL placeholder: @placeholder_url', array('@placeholder_url' => $placeholder_url));
$summary[] = $this->t('URL placeholder: @placeholder_url', ['@placeholder_url' => $placeholder_url]);
}
}

View file

@ -6,20 +6,12 @@ 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;
use Symfony\Component\Validator\ConstraintValidator;
/**
* Validates the LinkAccess constraint.
*/
class LinkAccessConstraintValidator implements ConstraintValidatorInterface, ContainerInjectionInterface {
/**
* Stores the validator's state during validation.
*
* @var \Symfony\Component\Validator\ExecutionContextInterface
*/
protected $context;
class LinkAccessConstraintValidator extends ConstraintValidator implements ContainerInjectionInterface {
/**
* Proxy for the current user account.
@ -47,13 +39,6 @@ class LinkAccessConstraintValidator implements ConstraintValidatorInterface, Con
);
}
/**
* {@inheritdoc}
*/
public function initialize(ExecutionContextInterface $context) {
$this->context = $context;
}
/**
* {@inheritdoc}
*/
@ -70,7 +55,7 @@ class LinkAccessConstraintValidator implements ConstraintValidatorInterface, Con
// 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));
$this->context->addViolation($constraint->message, ['@uri' => $value->uri]);
}
}
}

View file

@ -4,27 +4,12 @@ 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;
use Symfony\Component\Validator\ConstraintValidator;
/**
* 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;
}
class LinkExternalProtocolsConstraintValidator extends ConstraintValidator {
/**
* {@inheritdoc}
@ -41,7 +26,7 @@ class LinkExternalProtocolsConstraintValidator implements ConstraintValidatorInt
}
// 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));
$this->context->addViolation($constraint->message, ['@uri' => $value->uri]);
}
}
}

View file

@ -6,27 +6,12 @@ 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;
use Symfony\Component\Validator\ConstraintValidator;
/**
* 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;
}
class LinkNotExistingInternalConstraintValidator extends ConstraintValidator {
/**
* {@inheritdoc}
@ -59,7 +44,7 @@ class LinkNotExistingInternalConstraintValidator implements ConstraintValidatorI
$allowed = FALSE;
}
if (!$allowed) {
$this->context->addViolation($constraint->message, array('@uri' => $value->uri));
$this->context->addViolation($constraint->message, ['@uri' => $value->uri]);
}
}
}

View file

@ -2,10 +2,7 @@
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.
@ -15,64 +12,8 @@ use Symfony\Component\Validator\ExecutionContextInterface;
* label = @Translation("Link data valid for link type.", context = "Validation"),
* )
*/
class LinkTypeConstraint extends Constraint implements ConstraintValidatorInterface {
class LinkTypeConstraint extends Constraint {
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));
}
}
}
}

View file

@ -0,0 +1,51 @@
<?php
namespace Drupal\link\Plugin\Validation\Constraint;
use Drupal\link\LinkItemInterface;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
/**
* Constraint validator for links receiving data allowed by its settings.
*/
class LinkTypeConstraintValidator extends ConstraintValidator {
/**
* {@inheritdoc}
*/
public function validate($value, Constraint $constraint) {
if (isset($value)) {
$uri_is_valid = TRUE;
/** @var $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($constraint->message, ['@uri' => $link_item->uri]);
}
}
}
}

View file

@ -40,27 +40,27 @@ class LinkViewsTokensTest extends ViewTestBase {
*/
protected function setUp() {
parent::setUp();
ViewTestData::createTestViews(get_class($this), array('link_test_views'));
ViewTestData::createTestViews(get_class($this), ['link_test_views']);
// Create Basic page node type.
$this->drupalCreateContentType(array(
$this->drupalCreateContentType([
'type' => 'page',
'name' => 'Basic page'
));
]);
// Create a field.
FieldStorageConfig::create(array(
FieldStorageConfig::create([
'field_name' => $this->fieldName,
'type' => 'link',
'entity_type' => 'node',
'cardinality' => 1,
))->save();
FieldConfig::create(array(
])->save();
FieldConfig::create([
'field_name' => $this->fieldName,
'entity_type' => 'node',
'bundle' => 'page',
'label' => 'link field',
))->save();
])->save();
}
@ -72,7 +72,7 @@ class LinkViewsTokensTest extends ViewTestBase {
// Add nodes with the URI's and titles.
foreach ($uris as $uri => $title) {
$values = array('type' => 'page');
$values = ['type' => 'page'];
$values[$this->fieldName][] = ['uri' => $uri, 'title' => $title, 'options' => ['attributes' => ['class' => 'test-link-class']]];
$this->drupalCreateNode($values);
}

View file

@ -1,6 +1,6 @@
<?php
namespace Drupal\link\Tests;
namespace Drupal\Tests\link\Functional;
use Drupal\Component\Utility\Html;
use Drupal\Component\Utility\Unicode;
@ -8,7 +8,7 @@ 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\Tests\BrowserTestBase;
use Drupal\field\Entity\FieldStorageConfig;
/**
@ -16,7 +16,7 @@ use Drupal\field\Entity\FieldStorageConfig;
*
* @group link
*/
class LinkFieldTest extends WebTestBase {
class LinkFieldTest extends BrowserTestBase {
/**
* Modules to enable.
@ -52,36 +52,36 @@ class LinkFieldTest extends WebTestBase {
/**
* Tests link field URL validation.
*/
function testURLValidation() {
public function testURLValidation() {
$field_name = Unicode::strtolower($this->randomMachineName());
// Create a field with settings to validate.
$this->fieldStorage = FieldStorageConfig::create(array(
$this->fieldStorage = FieldStorageConfig::create([
'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(
'settings' => [
'title' => DRUPAL_DISABLED,
'link_type' => LinkItemInterface::LINK_GENERIC,
),
],
]);
$this->field->save();
entity_get_form_display('entity_test', 'entity_test', 'default')
->setComponent($field_name, array(
->setComponent($field_name, [
'type' => 'link_default',
'settings' => array(
'settings' => [
'placeholder_url' => 'http://example.com',
),
))
],
])
->save();
entity_get_display('entity_test', 'entity_test', 'full')
->setComponent($field_name, array(
->setComponent($field_name, [
'type' => 'link',
))
])
->save();
// Display creation form.
@ -103,14 +103,14 @@ class LinkFieldTest extends WebTestBase {
// Define some valid URLs (keys are the entered values, values are the
// strings displayed to the user).
$valid_external_entries = array(
$valid_external_entries = [
'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(
];
$valid_internal_entries = [
'/entity_test/add' => '/entity_test/add',
'/a/path/alias' => '/a/path/alias',
@ -137,24 +137,24 @@ class LinkFieldTest extends WebTestBase {
'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_external_entries = [
// Invalid protocol
'invalid://not-a-valid-protocol' => $validation_error_1,
// Missing host name
'http://' => $validation_error_1,
);
$invalid_internal_entries = array(
];
$invalid_internal_entries = [
'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);
@ -191,13 +191,13 @@ class LinkFieldTest extends WebTestBase {
*/
protected function assertValidEntries($field_name, array $valid_entries) {
foreach ($valid_entries as $uri => $string) {
$edit = array(
$edit = [
"{$field_name}[0][uri]" => $uri,
);
];
$this->drupalPostForm('entity_test/add', $edit, t('Save'));
preg_match('|entity_test/manage/(\d+)|', $this->url, $match);
preg_match('|entity_test/manage/(\d+)|', $this->getUrl(), $match);
$id = $match[1];
$this->assertText(t('entity_test @id has been created.', array('@id' => $id)));
$this->assertText(t('entity_test @id has been created.', ['@id' => $id]));
$this->assertRaw($string);
}
}
@ -212,54 +212,54 @@ class LinkFieldTest extends WebTestBase {
*/
protected function assertInvalidEntries($field_name, array $invalid_entries) {
foreach ($invalid_entries as $invalid_value => $error_message) {
$edit = array(
$edit = [
"{$field_name}[0][uri]" => $invalid_value,
);
];
$this->drupalPostForm('entity_test/add', $edit, t('Save'));
$this->assertText(t($error_message, array('@link_path' => $invalid_value)));
$this->assertText(t($error_message, ['@link_path' => $invalid_value]));
}
}
/**
* Tests the link title settings of a link field.
*/
function testLinkTitle() {
public function testLinkTitle() {
$field_name = Unicode::strtolower($this->randomMachineName());
// Create a field with settings to validate.
$this->fieldStorage = FieldStorageConfig::create(array(
$this->fieldStorage = FieldStorageConfig::create([
'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(
'settings' => [
'title' => DRUPAL_OPTIONAL,
'link_type' => LinkItemInterface::LINK_GENERIC,
),
],
]);
$this->field->save();
entity_get_form_display('entity_test', 'entity_test', 'default')
->setComponent($field_name, array(
->setComponent($field_name, [
'type' => 'link_default',
'settings' => array(
'settings' => [
'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(
->setComponent($field_name, [
'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) {
foreach ([DRUPAL_DISABLED, DRUPAL_REQUIRED, DRUPAL_OPTIONAL] as $title_setting) {
// Update the link title field setting.
$this->field->setSetting('title', $title_setting);
$this->field->save();
@ -281,90 +281,90 @@ class LinkFieldTest extends WebTestBase {
$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(
$edit = [
"{$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'))));
$this->assertText(t('@name field is required.', ['@name' => t('Link text')]));
// Verify that the link text is not required, if the URL is empty.
$edit = array(
$edit = [
"{$field_name}[0][uri]" => '',
);
];
$this->drupalPostForm(NULL, $edit, t('Save'));
$this->assertNoText(t('@name field is required.', array('@name' => t('Link text'))));
$this->assertNoText(t('@name field is required.', ['@name' => t('Link text')]));
// Verify that a URL and link text meets requirements.
$this->drupalGet('entity_test/add');
$edit = array(
$edit = [
"{$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'))));
$this->assertNoText(t('@name field is required.', ['@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(
$edit = [
"{$field_name}[0][uri]" => $value,
"{$field_name}[0][title]" => '',
);
];
$this->drupalPostForm(NULL, $edit, t('Save'));
preg_match('|entity_test/manage/(\d+)|', $this->url, $match);
preg_match('|entity_test/manage/(\d+)|', $this->getUrl(), $match);
$id = $match[1];
$this->assertText(t('entity_test @id has been created.', array('@id' => $id)));
$this->assertText(t('entity_test @id has been created.', ['@id' => $id]));
$this->renderTestEntity($id);
$expected_link = \Drupal::l($value, Url::fromUri($value));
$this->assertRaw($expected_link);
$output = $this->renderTestEntity($id);
$expected_link = (string) \Drupal::l($value, Url::fromUri($value));
$this->assertContains($expected_link, $output);
// Verify that a link with text is rendered using the link text.
$title = $this->randomMachineName();
$edit = array(
$edit = [
"{$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->assertText(t('entity_test @id has been updated.', ['@id' => $id]));
$this->renderTestEntity($id);
$expected_link = \Drupal::l($title, Url::fromUri($value));
$this->assertRaw($expected_link);
$output = $this->renderTestEntity($id);
$expected_link = (string) \Drupal::l($title, Url::fromUri($value));
$this->assertContains($expected_link, $output);
}
/**
* Tests the default 'link' formatter.
*/
function testLinkFormatter() {
public function testLinkFormatter() {
$field_name = Unicode::strtolower($this->randomMachineName());
// Create a field with settings to validate.
$this->fieldStorage = FieldStorageConfig::create(array(
$this->fieldStorage = FieldStorageConfig::create([
'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(
'settings' => [
'title' => DRUPAL_OPTIONAL,
'link_type' => LinkItemInterface::LINK_GENERIC,
),
],
])->save();
entity_get_form_display('entity_test', 'entity_test', 'default')
->setComponent($field_name, array(
->setComponent($field_name, [
'type' => 'link_default',
))
])
->save();
$display_options = array(
$display_options = [
'type' => 'link',
'label' => 'hidden',
);
];
entity_get_display('entity_test', 'entity_test', 'full')
->setComponent($field_name, $display_options)
->save();
@ -383,7 +383,7 @@ class LinkFieldTest extends WebTestBase {
// 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(
$edit = [
"{$field_name}[0][uri]" => $url1,
// Note that $title1 is not submitted.
"{$field_name}[0][title]" => '',
@ -391,35 +391,35 @@ class LinkFieldTest extends WebTestBase {
"{$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);
preg_match('|entity_test/manage/(\d+)|', $this->getUrl(), $match);
$id = $match[1];
$this->assertText(t('entity_test @id has been created.', array('@id' => $id)));
$this->assertText(t('entity_test @id has been created.', ['@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),
),
);
$options = [
'trim_length' => [NULL, 6],
'rel' => [NULL, 'nofollow'],
'target' => [NULL, '_blank'],
'url_only' => [
['url_only' => FALSE],
['url_only' => FALSE, 'url_plain' => TRUE],
['url_only' => TRUE],
['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);
$display_options['settings'] = [$setting => $new_value];
}
else {
$display_options['settings'] = $new_value;
@ -428,56 +428,56 @@ class LinkFieldTest extends WebTestBase {
->setComponent($field_name, $display_options)
->save();
$this->renderTestEntity($id);
$output = $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>');
$this->assertContains('<a href="' . Html::escape($url) . '">' . Html::escape($title) . '</a>', $output);
$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>');
$this->assertContains('<a href="' . Html::escape($url) . '">' . Html::escape($title) . '</a>', $output);
$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>');
$this->assertContains('<a href="' . Html::escape($url) . '">' . Html::escape($title) . '</a>', $output);
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>');
$this->assertContains('<a href="' . Html::escape($url1) . '"' . $rel . '>' . Html::escape($title1) . '</a>', $output);
$this->assertContains('<a href="' . Html::escape($url2) . '"' . $rel . '>' . Html::escape($title2) . '</a>', $output);
$this->assertContains('<a href="' . Html::escape($url3) . '"' . $rel . '>' . Html::escape($title3) . '</a>', $output);
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>');
$this->assertContains('<a href="' . Html::escape($url1) . '"' . $target . '>' . Html::escape($title1) . '</a>', $output);
$this->assertContains('<a href="' . Html::escape($url2) . '"' . $target . '>' . Html::escape($title2) . '</a>', $output);
$this->assertContains('<a href="' . Html::escape($url3) . '"' . $target . '>' . Html::escape($title3) . '</a>', $output);
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>');
$this->assertContains('<a href="' . Html::escape($url1) . '">' . Html::escape($title1) . '</a>', $output);
$this->assertContains('<a href="' . Html::escape($url2) . '">' . Html::escape($title2) . '</a>', $output);
$this->assertContains('<a href="' . Html::escape($url3) . '">' . Html::escape($title3) . '</a>', $output);
}
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>');
$this->assertContains('<a href="' . Html::escape($url1) . '">' . Html::escape($url1) . '</a>', $output);
$this->assertContains('<a href="' . Html::escape($url2) . '">' . Html::escape($url2) . '</a>', $output);
$this->assertContains('<a href="' . Html::escape($url3) . '">' . Html::escape($url3) . '</a>', $output);
}
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);
$this->assertNotContains('<a href="' . Html::escape($url1) . '">' . Html::escape($url1) . '</a>', $output);
$this->assertNotContains('<a href="' . Html::escape($url2) . '">' . Html::escape($url2) . '</a>', $output);
$this->assertNotContains('<a href="' . Html::escape($url3) . '">' . Html::escape($url3) . '</a>', $output);
$this->assertContains(Html::escape($url1), $output);
$this->assertContains(Html::escape($url2), $output);
$this->assertContains(Html::escape($url3), $output);
}
}
break;
@ -492,32 +492,32 @@ class LinkFieldTest extends WebTestBase {
* This test is mostly the same as testLinkFormatter(), but they cannot be
* merged, since they involve different configuration and output.
*/
function testLinkSeparateFormatter() {
public function testLinkSeparateFormatter() {
$field_name = Unicode::strtolower($this->randomMachineName());
// Create a field with settings to validate.
$this->fieldStorage = FieldStorageConfig::create(array(
$this->fieldStorage = FieldStorageConfig::create([
'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(
'settings' => [
'title' => DRUPAL_OPTIONAL,
'link_type' => LinkItemInterface::LINK_GENERIC,
),
],
])->save();
$display_options = array(
$display_options = [
'type' => 'link_separate',
'label' => 'hidden',
);
];
entity_get_form_display('entity_test', 'entity_test', 'default')
->setComponent($field_name, array(
->setComponent($field_name, [
'type' => 'link_default',
))
])
->save();
entity_get_display('entity_test', 'entity_test', 'full')
->setComponent($field_name, $display_options)
@ -536,33 +536,33 @@ class LinkFieldTest extends WebTestBase {
// 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(
$edit = [
"{$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);
preg_match('|entity_test/manage/(\d+)|', $this->getUrl(), $match);
$id = $match[1];
$this->assertText(t('entity_test @id has been created.', array('@id' => $id)));
$this->assertText(t('entity_test @id has been created.', ['@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'),
);
$options = [
'trim_length' => [NULL, 6],
'rel' => [NULL, 'nofollow'],
'target' => [NULL, '_blank'],
];
foreach ($options as $setting => $values) {
foreach ($values as $new_value) {
// Update the field formatter settings.
$display_options['settings'] = array($setting => $new_value);
$display_options['settings'] = [$setting => $new_value];
entity_get_display('entity_test', 'entity_test', 'full')
->setComponent($field_name, $display_options)
->save();
$this->renderTestEntity($id);
$output = $this->renderTestEntity($id);
switch ($setting) {
case 'trim_length':
$url = $url1;
@ -570,7 +570,7 @@ class LinkFieldTest extends WebTestBase {
$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);
$this->assertContains($expected, $output);
$url = $url2;
$url_title = isset($new_value) ? Unicode::truncate($url, $new_value, FALSE, TRUE) : $url;
@ -579,7 +579,7 @@ class LinkFieldTest extends WebTestBase {
$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);
$this->assertContains($expected, $output);
$url = $url3;
$url_title = isset($new_value) ? Unicode::truncate($url, $new_value, FALSE, TRUE) : $url;
@ -588,21 +588,21 @@ class LinkFieldTest extends WebTestBase {
$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);
$this->assertContains($expected, $output);
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>');
$this->assertContains('<div class="link-url"><a href="' . Html::escape($url1) . '"' . $rel . '>' . Html::escape($url1) . '</a></div>', $output);
$this->assertContains('<div class="link-url"><a href="' . Html::escape($url2) . '"' . $rel . '>' . Html::escape($url2) . '</a></div>', $output);
$this->assertContains('<div class="link-url"><a href="' . Html::escape($url3) . '"' . $rel . '>' . Html::escape($url3) . '</a></div>', $output);
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>');
$this->assertContains('<div class="link-url"><a href="' . Html::escape($url1) . '"' . $target . '>' . Html::escape($url1) . '</a></div>', $output);
$this->assertContains('<div class="link-url"><a href="' . Html::escape($url2) . '"' . $target . '>' . Html::escape($url2) . '</a></div>', $output);
$this->assertContains('<div class="link-url"><a href="' . Html::escape($url3) . '"' . $target . '>' . Html::escape($url3) . '</a></div>', $output);
break;
}
}
@ -610,7 +610,7 @@ class LinkFieldTest extends WebTestBase {
}
/**
* Renders a test_entity and sets the output in the internal browser.
* Renders a test_entity and returns the output.
*
* @param int $id
* The test_entity ID to render.
@ -619,17 +619,21 @@ class LinkFieldTest extends WebTestBase {
* @param bool $reset
* (optional) Whether to reset the entity_test storage cache. Defaults to
* TRUE to simplify testing.
*
* @return string
* The rendered HTML output.
*/
protected function renderTestEntity($id, $view_mode = 'full', $reset = TRUE) {
if ($reset) {
$this->container->get('entity.manager')->getStorage('entity_test')->resetCache(array($id));
$this->container->get('entity.manager')->getStorage('entity_test')->resetCache([$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);
$output = (string) $output;
$this->verbose($output);
return $output;
}
}

View file

@ -1,18 +1,18 @@
<?php
namespace Drupal\link\Tests;
namespace Drupal\Tests\link\Functional;
use Drupal\Component\Utility\Unicode;
use Drupal\field_ui\Tests\FieldUiTestTrait;
use Drupal\link\LinkItemInterface;
use Drupal\simpletest\WebTestBase;
use Drupal\Tests\BrowserTestBase;
/**
* Tests link field UI functionality.
*
* @group link
*/
class LinkFieldUITest extends WebTestBase {
class LinkFieldUITest extends BrowserTestBase {
use FieldUiTestTrait;
@ -44,7 +44,7 @@ class LinkFieldUITest extends WebTestBase {
/**
* Tests the link field UI.
*/
function testFieldUI() {
public function testFieldUI() {
// Add a content type.
$type = $this->drupalCreateContentType();
$type_path = 'admin/structure/types/manage/' . $type->id();
@ -60,7 +60,7 @@ class LinkFieldUITest extends WebTestBase {
// 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)));
$this->assertText(t('Link text trimmed to @limit characters', ['@limit' => 80]));
// Test the help text displays when the link field allows both internal and
// external links.
@ -81,7 +81,7 @@ class LinkFieldUITest extends WebTestBase {
$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);
$this->fieldUIAddNewField($type_path, $field_name, $label, 'link', [], $field_edit);
// Test the help text displays when link allows only external links.
$this->drupalLogin($this->drupalCreateUser(['create ' . $type->id() . ' content']));

View file

@ -24,7 +24,7 @@ class LinkItemTest extends FieldKernelTestBase {
*
* @var array
*/
public static $modules = array('link');
public static $modules = ['link'];
protected function setUp() {
parent::setUp();
@ -78,7 +78,7 @@ class LinkItemTest extends FieldKernelTestBase {
$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));
$entity->field_test->first()->get('options')->set('attributes', ['class' => $class]);
$this->assertEquals([
'query' => $parsed_url['query'],
'attributes' => [
@ -118,7 +118,7 @@ class LinkItemTest extends FieldKernelTestBase {
$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));
$entity->field_test->first()->get('options')->set('attributes', ['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);

View file

@ -5,6 +5,7 @@ namespace Drupal\Tests\link\Unit\Plugin\Validation\Constraint;
use Drupal\link\Plugin\Validation\Constraint\LinkAccessConstraint;
use Drupal\link\Plugin\Validation\Constraint\LinkAccessConstraintValidator;
use Drupal\Tests\UnitTestCase;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
/**
* Tests the LinkAccessConstraintValidator validator.
@ -29,7 +30,7 @@ class LinkAccessConstraintValidatorTest extends UnitTestCase {
* @dataProvider providerValidate
*/
public function testValidate($value, $user, $valid) {
$context = $this->getMock('Symfony\Component\Validator\ExecutionContextInterface');
$context = $this->getMock(ExecutionContextInterface::class);
if ($valid) {
$context->expects($this->never())

View file

@ -7,6 +7,7 @@ use Drupal\Core\Url;
use Drupal\link\Plugin\Validation\Constraint\LinkExternalProtocolsConstraint;
use Drupal\link\Plugin\Validation\Constraint\LinkExternalProtocolsConstraintValidator;
use Drupal\Tests\UnitTestCase;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
/**
* @coversDefaultClass \Drupal\link\Plugin\Validation\Constraint\LinkExternalProtocolsConstraintValidator
@ -19,7 +20,7 @@ class LinkExternalProtocolsConstraintValidatorTest extends UnitTestCase {
* @dataProvider providerValidate
*/
public function testValidate($value, $valid) {
$context = $this->getMock('Symfony\Component\Validator\ExecutionContextInterface');
$context = $this->getMock(ExecutionContextInterface::class);
if ($valid) {
$context->expects($this->never())
@ -77,7 +78,7 @@ class LinkExternalProtocolsConstraintValidatorTest extends UnitTestCase {
->method('getUrl')
->willThrowException(new \InvalidArgumentException());
$context = $this->getMock('Symfony\Component\Validator\ExecutionContextInterface');
$context = $this->getMock(ExecutionContextInterface::class);
$context->expects($this->never())
->method('addViolation');
@ -97,7 +98,7 @@ class LinkExternalProtocolsConstraintValidatorTest extends UnitTestCase {
->method('getUrl')
->willReturn(Url::fromRoute('example.test'));
$context = $this->getMock('Symfony\Component\Validator\ExecutionContextInterface');
$context = $this->getMock(ExecutionContextInterface::class);
$context->expects($this->never())
->method('addViolation');

View file

@ -7,6 +7,7 @@ use Drupal\link\Plugin\Validation\Constraint\LinkNotExistingInternalConstraint;
use Drupal\link\Plugin\Validation\Constraint\LinkNotExistingInternalConstraintValidator;
use Drupal\Tests\UnitTestCase;
use Symfony\Component\Routing\Exception\RouteNotFoundException;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
/**
* @coversDefaultClass \Drupal\link\Plugin\Validation\Constraint\LinkNotExistingInternalConstraintValidator
@ -19,7 +20,7 @@ class LinkNotExistingInternalConstraintValidatorTest extends UnitTestCase {
* @dataProvider providerValidate
*/
public function testValidate($value, $valid) {
$context = $this->getMock('Symfony\Component\Validator\ExecutionContextInterface');
$context = $this->getMock(ExecutionContextInterface::class);
if ($valid) {
$context->expects($this->never())
@ -94,7 +95,7 @@ class LinkNotExistingInternalConstraintValidatorTest extends UnitTestCase {
->method('getUrl')
->willThrowException(new \InvalidArgumentException());
$context = $this->getMock('Symfony\Component\Validator\ExecutionContextInterface');
$context = $this->getMock(ExecutionContextInterface::class);
$context->expects($this->never())
->method('addViolation');