Move all files to 2017/

This commit is contained in:
Oliver Davies 2025-09-29 22:25:17 +01:00
parent ac7370f67f
commit 2875863330
15717 changed files with 0 additions and 0 deletions

View file

@ -0,0 +1,8 @@
name: Link test base field
description: Tests link field as an optional base field
type: module
core: 8.x
hidden: true
dependencies:
- drupal:link
- drupal:entity_test

View file

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

View file

@ -0,0 +1,10 @@
name: 'Link test views'
type: module
description: 'Provides default views for views link tests.'
package: Testing
version: VERSION
core: 8.x
dependencies:
- drupal:node
- drupal:views
- drupal:link

View file

@ -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

View file

@ -0,0 +1,756 @@
<?php
namespace Drupal\Tests\link\Functional;
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\node\NodeInterface;
use Drupal\Tests\BrowserTestBase;
use Drupal\field\Entity\FieldStorageConfig;
/**
* Tests link field widgets and formatters.
*
* @group link
*/
class LinkFieldTest extends BrowserTestBase {
/**
* Modules to enable.
*
* @var array
*/
public static $modules = [
'entity_test',
'link',
'node',
'link_test_base_field',
];
/**
* 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.
*/
public function testURLValidation() {
$field_name = mb_strtolower($this->randomMachineName());
// Create a field with settings to validate.
$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' => [
'title' => DRUPAL_DISABLED,
'link_type' => LinkItemInterface::LINK_GENERIC,
],
]);
$this->field->save();
entity_get_form_display('entity_test', 'entity_test', 'default')
->setComponent($field_name, [
'type' => 'link_default',
'settings' => [
'placeholder_url' => 'http://example.com',
],
])
->save();
entity_get_display('entity_test', 'entity_test', 'full')
->setComponent($field_name, [
'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();
$restricted_node = $this->drupalCreateNode(['status' => NodeInterface::NOT_PUBLISHED]);
// Define some valid URLs (keys are the entered values, values are the
// strings displayed to the user).
$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 = [
'/entity_test/add' => '/entity_test/add',
'/a/path/alias' => '/a/path/alias',
// Front page, with query string and fragment.
'/' => '&lt;front&gt;',
'/?example=llama' => '&lt;front&gt;?example=llama',
'/#example' => '&lt;front&gt;#example',
// Trailing spaces should be ignored.
'/ ' => '&lt;front&gt;',
'/path with spaces ' => '/path with spaces',
// @todo '<front>' is valid input for BC reasons, may be removed by
// https://www.drupal.org/node/2421941
'<front>' => '&lt;front&gt;',
'<front>#example' => '&lt;front&gt;#example',
'<front>?example=llama' => '&lt;front&gt;?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:node/' . $restricted_node->id() => '- Restricted access - (' . $restricted_node->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 = [
// Invalid protocol
'invalid://not-a-valid-protocol' => $validation_error_1,
// Missing host name
'http://' => $validation_error_1,
];
$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);
$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 = [
"{$field_name}[0][uri]" => $uri,
];
$this->drupalPostForm('entity_test/add', $edit, t('Save'));
preg_match('|entity_test/manage/(\d+)|', $this->getUrl(), $match);
$id = $match[1];
$this->assertText(t('entity_test @id has been created.', ['@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 = [
"{$field_name}[0][uri]" => $invalid_value,
];
$this->drupalPostForm('entity_test/add', $edit, t('Save'));
$this->assertText(t($error_message, ['@link_path' => $invalid_value]));
}
}
/**
* Tests the link title settings of a link field.
*/
public function testLinkTitle() {
$field_name = mb_strtolower($this->randomMachineName());
// Create a field with settings to validate.
$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' => [
'title' => DRUPAL_OPTIONAL,
'link_type' => LinkItemInterface::LINK_GENERIC,
],
]);
$this->field->save();
entity_get_form_display('entity_test', 'entity_test', 'default')
->setComponent($field_name, [
'type' => 'link_default',
'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, [
'type' => 'link',
'label' => 'hidden',
])
->save();
// Verify that the link text field works according to the field 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();
// 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_OPTIONAL) {
// Verify that the URL is required, if the link text is non-empty.
$edit = [
"{$field_name}[0][title]" => 'Example',
];
$this->drupalPostForm(NULL, $edit, t('Save'));
$this->assertText(t('The URL field is required when the @title field is specified.', ['@title' => t('Link text')]));
}
if ($title_setting === DRUPAL_REQUIRED) {
// Verify that the link text is required, if the URL is non-empty.
$edit = [
"{$field_name}[0][uri]" => 'http://www.example.com',
];
$this->drupalPostForm(NULL, $edit, t('Save'));
$this->assertText(t('@title field is required if there is @uri input.', ['@title' => t('Link text'), '@uri' => t('URL')]));
// Verify that the link text is not required, if the URL is empty.
$edit = [
"{$field_name}[0][uri]" => '',
];
$this->drupalPostForm(NULL, $edit, t('Save'));
$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 = [
"{$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.', ['@name' => t('Link text')]));
}
}
}
// Verify that a link without link text is rendered using the URL as text.
$value = 'http://www.example.com/';
$edit = [
"{$field_name}[0][uri]" => $value,
"{$field_name}[0][title]" => '',
];
$this->drupalPostForm(NULL, $edit, t('Save'));
preg_match('|entity_test/manage/(\d+)|', $this->getUrl(), $match);
$id = $match[1];
$this->assertText(t('entity_test @id has been created.', ['@id' => $id]));
$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 = [
"{$field_name}[0][title]" => $title,
];
$this->drupalPostForm("entity_test/manage/$id/edit", $edit, t('Save'));
$this->assertText(t('entity_test @id has been updated.', ['@id' => $id]));
$output = $this->renderTestEntity($id);
$expected_link = (string) \Drupal::l($title, Url::fromUri($value));
$this->assertContains($expected_link, $output);
}
/**
* Tests the default 'link' formatter.
*/
public function testLinkFormatter() {
$field_name = mb_strtolower($this->randomMachineName());
// Create a field with settings to validate.
$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' => [
'title' => DRUPAL_OPTIONAL,
'link_type' => LinkItemInterface::LINK_GENERIC,
],
])->save();
entity_get_form_display('entity_test', 'entity_test', 'default')
->setComponent($field_name, [
'type' => 'link_default',
])
->save();
$display_options = [
'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 = [
"{$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->getUrl(), $match);
$id = $match[1];
$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 = [
'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'] = [$setting => $new_value];
}
else {
$display_options['settings'] = $new_value;
}
entity_get_display('entity_test', 'entity_test', 'full')
->setComponent($field_name, $display_options)
->save();
$output = $this->renderTestEntity($id);
switch ($setting) {
case 'trim_length':
$url = $url1;
$title = isset($new_value) ? Unicode::truncate($title1, $new_value, FALSE, TRUE) : $title1;
$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->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->assertContains('<a href="' . Html::escape($url) . '">' . Html::escape($title) . '</a>', $output);
break;
case 'rel':
$rel = isset($new_value) ? ' rel="' . $new_value . '"' : '';
$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->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->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->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->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;
}
}
}
}
/**
* 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.
*/
public function testLinkSeparateFormatter() {
$field_name = mb_strtolower($this->randomMachineName());
// Create a field with settings to validate.
$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' => [
'title' => DRUPAL_OPTIONAL,
'link_type' => LinkItemInterface::LINK_GENERIC,
],
])->save();
$display_options = [
'type' => 'link_separate',
'label' => 'hidden',
];
entity_get_form_display('entity_test', 'entity_test', 'default')
->setComponent($field_name, [
'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 = [
"{$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->getUrl(), $match);
$id = $match[1];
$this->assertText(t('entity_test @id has been created.', ['@id' => $id]));
// Verify that the link is output according to the formatter settings.
$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'] = [$setting => $new_value];
entity_get_display('entity_test', 'entity_test', 'full')
->setComponent($field_name, $display_options)
->save();
$output = $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->assertContains($expected, $output);
$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->assertContains($expected, $output);
$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->assertContains($expected, $output);
break;
case 'rel':
$rel = isset($new_value) ? ' rel="' . $new_value . '"' : '';
$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->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;
}
}
}
}
/**
* Test '#link_type' property exists on 'link_default' widget.
*
* Make sure the 'link_default' widget exposes a '#link_type' property on
* its element. Modules can use it to understand if a text form element is
* a link and also which LinkItemInterface::LINK_* is (EXTERNAL, GENERIC,
* INTERNAL).
*/
public function testLinkTypeOnLinkWidget() {
$link_type = LinkItemInterface::LINK_EXTERNAL;
$field_name = mb_strtolower($this->randomMachineName());
// Create a field with settings to validate.
$this->fieldStorage = FieldStorageConfig::create([
'field_name' => $field_name,
'entity_type' => 'entity_test',
'type' => 'link',
'cardinality' => 1,
]);
$this->fieldStorage->save();
FieldConfig::create([
'field_storage' => $this->fieldStorage,
'label' => 'Read more about this entity',
'bundle' => 'entity_test',
'settings' => [
'title' => DRUPAL_OPTIONAL,
'link_type' => $link_type,
],
])->save();
$this->container->get('entity.manager')
->getStorage('entity_form_display')
->load('entity_test.entity_test.default')
->setComponent($field_name, [
'type' => 'link_default',
])
->save();
$form = \Drupal::service('entity.form_builder')->getForm(EntityTest::create());
$this->assertEqual($form[$field_name]['widget'][0]['uri']['#link_type'], $link_type);
}
/**
* Tests editing a link to a non-node entity.
*/
public function testEditNonNodeEntityLink() {
$entity_type_manager = \Drupal::entityTypeManager();
$entity_test_storage = $entity_type_manager->getStorage('entity_test');
// Create a field with settings to validate.
$this->fieldStorage = FieldStorageConfig::create([
'field_name' => 'field_link',
'entity_type' => 'entity_test',
'type' => 'link',
'cardinality' => 1,
]);
$this->fieldStorage->save();
FieldConfig::create([
'field_storage' => $this->fieldStorage,
'label' => 'Read more about this entity',
'bundle' => 'entity_test',
'settings' => [
'title' => DRUPAL_OPTIONAL,
],
])->save();
$entity_type_manager
->getStorage('entity_form_display')
->load('entity_test.entity_test.default')
->setComponent('field_link', [
'type' => 'link_default',
])
->save();
// Create a node and a test entity to have a possibly valid reference for
// both. Create another test entity that references the first test entity.
$entity_test_link = $entity_test_storage->create(['name' => 'correct link target']);
$entity_test_link->save();
$node = $this->drupalCreateNode(['wrong link target']);
$correct_link = 'entity:entity_test/' . $entity_test_link->id();
$entity_test = $entity_test_storage->create([
'name' => 'correct link target',
'field_link' => $correct_link,
]);
$entity_test->save();
// Edit the entity and save it, verify the correct link is kept and not
// changed to point to a node. Currently, widget does not support non-node
// autocomplete and therefore must show the link unaltered.
$this->drupalGet($entity_test->toUrl('edit-form'));
$this->assertSession()->fieldValueEquals('field_link[0][uri]', $correct_link);
$this->drupalPostForm(NULL, [], 'Save');
$entity_test_storage->resetCache();
$entity_test = $entity_test_storage->load($entity_test->id());
$this->assertEquals($correct_link, $entity_test->get('field_link')->uri);
}
/**
* Renders a test_entity and returns the output.
*
* @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.
*
* @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([$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);
$output = (string) $output;
$this->verbose($output);
return $output;
}
}

View file

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

View file

@ -0,0 +1,98 @@
<?php
namespace Drupal\Tests\link\Functional\Views;
use Drupal\field\Entity\FieldConfig;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\Tests\views\Functional\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($import_test_views = TRUE) {
parent::setUp($import_test_views);
ViewTestData::createTestViews(get_class($this), ['link_test_views']);
// Create Basic page node type.
$this->drupalCreateContentType([
'type' => 'page',
'name' => 'Basic page',
]);
// Create a field.
FieldStorageConfig::create([
'field_name' => $this->fieldName,
'type' => 'link',
'entity_type' => 'node',
'cardinality' => 1,
])->save();
FieldConfig::create([
'field_name' => $this->fieldName,
'entity_type' => 'node',
'bundle' => 'page',
'label' => 'link field',
])->save();
}
public function testLinkViewsTokens() {
// 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 = ['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: .");
}
}
}

View file

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

View 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 = ['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', ['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', ['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);
}
}

View file

@ -0,0 +1,18 @@
<?php
namespace Drupal\Tests\link\Kernel\Plugin\migrate\cckfield\d7;
/**
* @group link
* @group legacy
*/
class LinkCckDeprecationTest extends LinkCckTest {
/**
* @expectedDeprecation Deprecated in Drupal 8.6.0, to be removed before Drupal 9.0.0. Use alterFieldInstanceMigration() instead. See https://www.drupal.org/node/2944598.
*/
public function testAlterFieldInstanceMigration($method = 'processFieldInstance') {
parent::testAlterFieldInstanceMigration($method);
}
}

View file

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

View file

@ -0,0 +1,18 @@
<?php
namespace Drupal\Tests\link\Kernel\Plugin\migrate\field\d7;
/**
* @group legacy
* @group link
*/
class LinkFieldLegacyTest extends LinkFieldTest {
/**
* @expectedDeprecation Deprecated in Drupal 8.6.0, to be removed before Drupal 9.0.0. Use alterFieldInstanceMigration() instead. See https://www.drupal.org/node/2944598.
*/
public function testAlterFieldInstanceMigration($method = 'processFieldInstance') {
parent::testAlterFieldInstanceMigration($method);
}
}

View file

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

View file

@ -0,0 +1,96 @@
<?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;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
/**
* Tests the LinkAccessConstraintValidator validator.
*
* @coversDefaultClass \Drupal\link\Plugin\Validation\Constraint\LinkAccessConstraintValidator
* @group validation
*/
class LinkAccessConstraintValidatorTest extends UnitTestCase {
/**
* Tests the \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(ExecutionContextInterface::class);
if ($valid) {
$context->expects($this->never())
->method('addViolation');
}
else {
$context->expects($this->once())
->method('addViolation');
}
$constraint = new LinkAccessConstraint();
$validate = new LinkAccessConstraintValidator($user);
$validate->initialize($context);
$validate->validate($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;
}
}

View file

@ -0,0 +1,112 @@
<?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;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
/**
* @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(ExecutionContextInterface::class);
if ($valid) {
$context->expects($this->never())
->method('addViolation');
}
else {
$context->expects($this->once())
->method('addViolation');
}
// Setup some more allowed protocols.
UrlHelper::setAllowedProtocols(['http', 'https', 'magnet']);
$constraint = new LinkExternalProtocolsConstraint();
$validator = new LinkExternalProtocolsConstraintValidator();
$validator->initialize($context);
$validator->validate($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(ExecutionContextInterface::class);
$context->expects($this->never())
->method('addViolation');
$constraint = new LinkExternalProtocolsConstraint();
$validator = new LinkExternalProtocolsConstraintValidator();
$validator->initialize($context);
$validator->validate($link, $constraint);
}
/**
* @covers ::validate
*/
public function testValidateIgnoresInternalUrls() {
$link = $this->getMock('Drupal\link\LinkItemInterface');
$link->expects($this->any())
->method('getUrl')
->willReturn(Url::fromRoute('example.test'));
$context = $this->getMock(ExecutionContextInterface::class);
$context->expects($this->never())
->method('addViolation');
$constraint = new LinkExternalProtocolsConstraint();
$validator = new LinkExternalProtocolsConstraintValidator();
$validator->initialize($context);
$validator->validate($link, $constraint);
}
}

View file

@ -0,0 +1,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;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
/**
* @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(ExecutionContextInterface::class);
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(ExecutionContextInterface::class);
$context->expects($this->never())
->method('addViolation');
$constraint = new LinkNotExistingInternalConstraint();
$validator = new LinkNotExistingInternalConstraintValidator();
$validator->initialize($context);
$validator->validate($link, $constraint);
}
}

View file

@ -0,0 +1,61 @@
<?php
namespace Drupal\Tests\link\Unit\Plugin\migrate\cckfield;
use Drupal\migrate\Plugin\MigrationInterface;
use Drupal\Tests\UnitTestCase;
use Drupal\link\Plugin\migrate\cckfield\LinkField;
use Prophecy\Argument;
/**
* @coversDefaultClass \Drupal\link\Plugin\migrate\cckfield\LinkField
* @group link
* @group legacy
*/
class LinkCckTest extends UnitTestCase {
/**
* @var \Drupal\migrate_drupal\Plugin\MigrateCckFieldInterface
*/
protected $plugin;
/**
* @var \Drupal\migrate\Plugin\MigrationInterface
*/
protected $migration;
/**
* {@inheritdoc}
*/
protected function setUp() {
$this->plugin = new LinkField([], 'link', []);
$migration = $this->prophesize(MigrationInterface::class);
// The plugin's processCckFieldValues() method will call
// mergeProcessOfProperty() and return nothing. So, in order to examine the
// process pipeline created by the plugin, we need to ensure that
// getProcess() always returns the last input to mergeProcessOfProperty().
$migration->mergeProcessOfProperty(Argument::type('string'), Argument::type('array'))
->will(function ($arguments) use ($migration) {
$migration->getProcess()->willReturn($arguments[1]);
});
$this->migration = $migration->reveal();
}
/**
* @covers ::processCckFieldValues
* @expectedDeprecation LinkField is deprecated in Drupal 8.3.x and will be be removed before Drupal 9.0.x. Use \Drupal\link\Plugin\migrate\field\d6\LinkField instead.
*/
public function testProcessCckFieldValues() {
$this->plugin->processCckFieldValues($this->migration, 'somefieldname', []);
$expected = [
'plugin' => 'd6_cck_link',
'source' => 'somefieldname',
];
$this->assertSame($expected, $this->migration->getProcess());
}
}

View file

@ -0,0 +1,18 @@
<?php
namespace Drupal\Tests\link\Unit\Plugin\migrate\field\d6;
/**
* @group legacy
* @group link
*/
class LinkFieldLegacyTest extends LinkFieldTest {
/**
* @expectedDeprecation Deprecated in Drupal 8.6.0, to be removed before Drupal 9.0.0. Use defineValueProcessPipeline() instead. See https://www.drupal.org/node/2944598.
*/
public function testDefineValueProcessPipeline($method = 'processFieldValues') {
parent::testDefineValueProcessPipeline($method);
}
}

View file

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

View file

@ -0,0 +1,92 @@
<?php
namespace Drupal\Tests\link\Unit\Plugin\migrate\process;
use Drupal\link\Plugin\migrate\process\FieldLink;
use Drupal\migrate\MigrateExecutableInterface;
use Drupal\migrate\Plugin\MigrationInterface;
use Drupal\migrate\Row;
use Drupal\Tests\UnitTestCase;
/**
* @group Link
*/
class FieldLinkTest extends UnitTestCase {
/**
* Test the url transformations in the FieldLink process plugin.
*
* @dataProvider canonicalizeUriDataProvider
*/
public function testCanonicalizeUri($url, $expected, $configuration = []) {
$link_plugin = new FieldLink($configuration, '', [], $this->getMock(MigrationInterface::class));
$transformed = $link_plugin->transform([
'url' => $url,
'title' => '',
'attributes' => serialize([]),
], $this->getMock(MigrateExecutableInterface::class), $this->getMockBuilder(Row::class)->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',
],
'Absolute URL with protocol prefix' => [
'http://www.google.com',
'http://www.google.com',
],
'Absolute URL without protocol prefix' => [
'www.yahoo.com',
'http://www.yahoo.com',
],
'Absolute URL without protocol prefix nor www' => [
'yahoo.com',
'https://yahoo.com',
['uri_scheme' => 'https://'],
],
'Absolute URL with non-standard characters' => [
'http://www.ßÀÑÐ¥ƒå¢ë.com',
'http://www.ßÀÑÐ¥ƒå¢ë.com',
],
'Absolute URL with non-standard characters, without protocol prefix' => [
'www.ÐØÑ¢åþë.com',
'http://www.ÐØÑ¢åþë.com',
],
'Absolute URL with non-standard top level domain' => [
'http://www.example.xxx',
'http://www.example.xxx',
],
'Internal link with fragment' => [
'/node/10#top',
'internal:/node/10#top',
],
'External link with fragment' => [
'http://www.example.com/page#links',
'http://www.example.com/page#links',
],
];
}
}

View file

@ -0,0 +1,57 @@
<?php
namespace Drupal\Tests\link\Unit\Plugin\migrate\process\d6;
use Drupal\link\Plugin\migrate\process\d6\FieldLink;
use Drupal\Tests\UnitTestCase;
/**
* @group Link
* @group legacy
*/
class FieldLinkTest extends UnitTestCase {
/**
* Test the url transformations in the FieldLink process plugin.
*
* @dataProvider canonicalizeUriDataProvider
*/
public function testCanonicalizeUri($url, $expected) {
$link_plugin = new FieldLink([], '', [], $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',
],
];
}
}