Initial Drupal 11 with DDEV setup
This commit is contained in:
@ -0,0 +1,7 @@
|
||||
name: Link test base field
|
||||
description: Tests link field as an optional base field
|
||||
type: module
|
||||
hidden: true
|
||||
dependencies:
|
||||
- drupal:link
|
||||
- drupal:entity_test
|
||||
@ -0,0 +1,33 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Drupal\link_test_base_field\Hook;
|
||||
|
||||
use Drupal\link\LinkItemInterface;
|
||||
use Drupal\Core\Field\FieldStorageDefinitionInterface;
|
||||
use Drupal\Core\Field\BaseFieldDefinition;
|
||||
use Drupal\Core\Entity\EntityTypeInterface;
|
||||
use Drupal\Core\Hook\Attribute\Hook;
|
||||
|
||||
/**
|
||||
* Hook implementations for link_test_base_field.
|
||||
*/
|
||||
class LinkTestBaseFieldHooks {
|
||||
|
||||
/**
|
||||
* Implements hook_entity_base_field_info().
|
||||
*/
|
||||
#[Hook('entity_base_field_info')]
|
||||
public function entityBaseFieldInfo(EntityTypeInterface $entity_type): array {
|
||||
$fields = [];
|
||||
if ($entity_type->id() === 'entity_test') {
|
||||
$fields['links'] = BaseFieldDefinition::create('link')->setLabel('Links')->setRevisionable(TRUE)->setCardinality(FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED)->setDescription('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;
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,9 @@
|
||||
name: 'Link test views'
|
||||
type: module
|
||||
description: 'Provides default views for views link tests.'
|
||||
package: Testing
|
||||
version: VERSION
|
||||
dependencies:
|
||||
- drupal:node
|
||||
- drupal:views
|
||||
- drupal:link
|
||||
@ -0,0 +1,205 @@
|
||||
langcode: en
|
||||
status: true
|
||||
dependencies:
|
||||
config:
|
||||
- field.storage.node.field_link
|
||||
module:
|
||||
- link
|
||||
- node
|
||||
- user
|
||||
id: test_link_tokens
|
||||
label: link
|
||||
module: views
|
||||
description: ''
|
||||
tag: ''
|
||||
base_table: node_field_data
|
||||
base_field: nid
|
||||
display:
|
||||
default:
|
||||
display_plugin: default
|
||||
id: default
|
||||
display_title: Default
|
||||
position: 0
|
||||
display_options:
|
||||
access:
|
||||
type: perm
|
||||
options:
|
||||
perm: 'access content'
|
||||
cache:
|
||||
type: tag
|
||||
options: { }
|
||||
query:
|
||||
type: views_query
|
||||
options:
|
||||
disable_sql_rewrite: false
|
||||
distinct: false
|
||||
replica: false
|
||||
query_comment: ''
|
||||
query_tags: { }
|
||||
exposed_form:
|
||||
type: basic
|
||||
options:
|
||||
submit_button: Apply
|
||||
reset_button: false
|
||||
reset_button_label: Reset
|
||||
exposed_sorts_label: 'Sort by'
|
||||
expose_sort_order: true
|
||||
sort_asc_label: Asc
|
||||
sort_desc_label: Desc
|
||||
pager:
|
||||
type: full
|
||||
options:
|
||||
items_per_page: 10
|
||||
offset: 0
|
||||
id: 0
|
||||
total_pages: null
|
||||
expose:
|
||||
items_per_page: false
|
||||
items_per_page_label: 'Items per page'
|
||||
items_per_page_options: '5, 10, 25, 50'
|
||||
items_per_page_options_all: false
|
||||
items_per_page_options_all_label: '- All -'
|
||||
offset: false
|
||||
offset_label: Offset
|
||||
tags:
|
||||
previous: '‹ previous'
|
||||
next: 'next ›'
|
||||
first: '« first'
|
||||
last: 'last »'
|
||||
quantity: 9
|
||||
style:
|
||||
type: default
|
||||
row:
|
||||
type: fields
|
||||
options:
|
||||
default_field_elements: true
|
||||
inline: { }
|
||||
separator: ''
|
||||
hide_empty: false
|
||||
fields:
|
||||
field_link:
|
||||
id: field_link
|
||||
table: node__field_link
|
||||
field: field_link
|
||||
relationship: none
|
||||
group_type: group
|
||||
admin_label: ''
|
||||
label: ''
|
||||
exclude: false
|
||||
alter:
|
||||
alter_text: true
|
||||
text: "Formatted: {{ field_link }}<br />\nRaw uri: {{ field_link__uri }}<br />\nRaw title: {{ field_link__title }}<br />\nRaw options: {{ field_link__options }}."
|
||||
make_link: false
|
||||
path: '{{ field_link__uri }}'
|
||||
absolute: false
|
||||
external: false
|
||||
replace_spaces: false
|
||||
path_case: none
|
||||
trim_whitespace: false
|
||||
alt: ''
|
||||
rel: ''
|
||||
link_class: ''
|
||||
prefix: ''
|
||||
suffix: ''
|
||||
target: ''
|
||||
nl2br: false
|
||||
max_length: 0
|
||||
word_boundary: true
|
||||
ellipsis: true
|
||||
more_link: false
|
||||
more_link_text: ''
|
||||
more_link_path: ''
|
||||
strip_tags: false
|
||||
trim: false
|
||||
preserve_tags: ''
|
||||
html: false
|
||||
element_type: ''
|
||||
element_class: ''
|
||||
element_label_type: ''
|
||||
element_label_class: ''
|
||||
element_label_colon: false
|
||||
element_wrapper_type: ''
|
||||
element_wrapper_class: ''
|
||||
element_default_classes: true
|
||||
empty: ''
|
||||
hide_empty: false
|
||||
empty_zero: false
|
||||
hide_alter_empty: true
|
||||
click_sort_column: uri
|
||||
type: link
|
||||
settings:
|
||||
trim_length: 80
|
||||
url_only: false
|
||||
url_plain: false
|
||||
rel: '0'
|
||||
target: '0'
|
||||
group_column: ''
|
||||
group_columns: { }
|
||||
group_rows: true
|
||||
delta_limit: 0
|
||||
delta_offset: 0
|
||||
delta_reversed: false
|
||||
delta_first_last: false
|
||||
multi_type: separator
|
||||
separator: ', '
|
||||
field_api_classes: false
|
||||
plugin_id: field
|
||||
filters:
|
||||
status:
|
||||
value: '1'
|
||||
table: node_field_data
|
||||
field: status
|
||||
plugin_id: boolean
|
||||
entity_type: node
|
||||
entity_field: status
|
||||
id: status
|
||||
expose:
|
||||
operator: ''
|
||||
group: 1
|
||||
sorts:
|
||||
created:
|
||||
id: created
|
||||
table: node_field_data
|
||||
field: created
|
||||
order: DESC
|
||||
entity_type: node
|
||||
entity_field: created
|
||||
plugin_id: date
|
||||
relationship: none
|
||||
group_type: group
|
||||
admin_label: ''
|
||||
exposed: false
|
||||
expose:
|
||||
label: ''
|
||||
granularity: second
|
||||
title: link
|
||||
header: { }
|
||||
footer: { }
|
||||
empty: { }
|
||||
relationships: { }
|
||||
arguments: { }
|
||||
display_extenders: { }
|
||||
cache_metadata:
|
||||
contexts:
|
||||
- 'languages:language_content'
|
||||
- 'languages:language_interface'
|
||||
- url.query_args
|
||||
- 'user.node_grants:view'
|
||||
- user.permissions
|
||||
cacheable: false
|
||||
page_1:
|
||||
display_plugin: page
|
||||
id: page_1
|
||||
display_title: Page
|
||||
position: 1
|
||||
display_options:
|
||||
display_extenders: { }
|
||||
path: test_link_tokens
|
||||
cache_metadata:
|
||||
contexts:
|
||||
- 'languages:language_content'
|
||||
- 'languages:language_interface'
|
||||
- url.query_args
|
||||
- 'user.node_grants:view'
|
||||
- user.permissions
|
||||
cacheable: false
|
||||
14
web/core/modules/link/tests/src/Functional/GenericTest.php
Normal file
14
web/core/modules/link/tests/src/Functional/GenericTest.php
Normal file
@ -0,0 +1,14 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Drupal\Tests\link\Functional;
|
||||
|
||||
use Drupal\Tests\system\Functional\Module\GenericModuleTestBase;
|
||||
|
||||
/**
|
||||
* Generic module test for link.
|
||||
*
|
||||
* @group link
|
||||
*/
|
||||
class GenericTest extends GenericModuleTestBase {}
|
||||
555
web/core/modules/link/tests/src/Functional/LinkFieldTest.php
Normal file
555
web/core/modules/link/tests/src/Functional/LinkFieldTest.php
Normal file
@ -0,0 +1,555 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Drupal\Tests\link\Functional;
|
||||
|
||||
use Drupal\Core\Link;
|
||||
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;
|
||||
use Drupal\Tests\Traits\Core\PathAliasTestTrait;
|
||||
|
||||
/**
|
||||
* Tests link field widgets and formatters.
|
||||
*
|
||||
* @group link
|
||||
* @group #slow
|
||||
*/
|
||||
class LinkFieldTest extends BrowserTestBase {
|
||||
|
||||
use PathAliasTestTrait;
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected static $modules = [
|
||||
'entity_test',
|
||||
'link',
|
||||
'node',
|
||||
];
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected $defaultTheme = 'link_test_theme';
|
||||
|
||||
/**
|
||||
* 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;
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function setUp(): void {
|
||||
parent::setUp();
|
||||
|
||||
$this->drupalLogin($this->drupalCreateUser([
|
||||
'view test entity',
|
||||
'administer entity_test content',
|
||||
'link to any page',
|
||||
]));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the functionality and rendering of the link field.
|
||||
*
|
||||
* This is being as one to avoid multiple Drupal install.
|
||||
*/
|
||||
public function testLinkField(): void {
|
||||
$this->doTestURLValidation();
|
||||
$this->doTestLinkTitle();
|
||||
$this->doTestEditNonNodeEntityLink();
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests link field URL validation.
|
||||
*/
|
||||
protected function doTestURLValidation(): void {
|
||||
$field_name = $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();
|
||||
/** @var \Drupal\Core\Entity\EntityDisplayRepositoryInterface $display_repository */
|
||||
$display_repository = \Drupal::service('entity_display.repository');
|
||||
$display_repository->getFormDisplay('entity_test', 'entity_test')
|
||||
->setComponent($field_name, [
|
||||
'type' => 'link_default',
|
||||
'settings' => [
|
||||
'placeholder_url' => 'http://example.com',
|
||||
],
|
||||
])
|
||||
->save();
|
||||
$display_repository->getViewDisplay('entity_test', 'entity_test', 'full')
|
||||
->setComponent($field_name, [
|
||||
'type' => 'link',
|
||||
])
|
||||
->save();
|
||||
|
||||
// Display creation form.
|
||||
$this->drupalGet('entity_test/add');
|
||||
$this->assertSession()->fieldValueEquals("{$field_name}[0][uri]", '');
|
||||
$this->assertSession()->responseContains('placeholder="http://example.com"');
|
||||
|
||||
// Create a path alias.
|
||||
$this->createPathAlias('/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.
|
||||
'/' => '<front>',
|
||||
'/?example=llama' => '<front>?example=llama',
|
||||
'/#example' => '<front>#example',
|
||||
|
||||
// Trailing spaces should be ignored.
|
||||
'/ ' => '<front>',
|
||||
'/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>' => '<front>',
|
||||
'<front>#example' => '<front>#example',
|
||||
'<front>?example=llama' => '<front>?example=llama',
|
||||
|
||||
// Text-only links.
|
||||
'<nolink>' => '<nolink>',
|
||||
'route:<nolink>' => '<nolink>',
|
||||
'<none>' => '<none>',
|
||||
'<button>' => '<button>',
|
||||
|
||||
// Query string and fragment.
|
||||
'?example=llama' => '?example=llama',
|
||||
'#example' => '#example',
|
||||
|
||||
// Complex query string. Similar to facet links.
|
||||
'?a[]=1&a[]=2' => '?a[]=1&a[]=2',
|
||||
'?b[0]=1&b[1]=2' => '?b[0]=1&b[1]=2',
|
||||
'?c[]=1&d=3&c[]=2' => '?c[]=1&d=3&c[]=2',
|
||||
'?e[f][g]=h' => '?e[f][g]=h',
|
||||
'?i[j[k]]=l' => '?i[j[k]]=l',
|
||||
'?x=1&x=2' => '?x=1&x=2',
|
||||
'?z[0]=1&z[0]=2' => '?z[0]=1&z[0]=2',
|
||||
|
||||
// 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 one of the following characters: / ? #';
|
||||
$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.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
protected function assertValidEntries(string $field_name, array $valid_entries): void {
|
||||
foreach ($valid_entries as $uri => $string) {
|
||||
$edit = [
|
||||
"{$field_name}[0][uri]" => $uri,
|
||||
];
|
||||
$this->drupalGet('entity_test/add');
|
||||
$this->submitForm($edit, 'Save');
|
||||
preg_match('|entity_test/manage/(\d+)|', $this->getUrl(), $match);
|
||||
$id = $match[1];
|
||||
$this->assertSession()->statusMessageContains('entity_test ' . $id . ' has been created.', 'status');
|
||||
$this->assertSession()->responseContains('"' . $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.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
protected function assertInvalidEntries(string $field_name, array $invalid_entries): void {
|
||||
foreach ($invalid_entries as $invalid_value => $error_message) {
|
||||
$edit = [
|
||||
"{$field_name}[0][uri]" => $invalid_value,
|
||||
];
|
||||
$this->drupalGet('entity_test/add');
|
||||
$this->submitForm($edit, 'Save');
|
||||
$this->assertSession()->responseContains(strtr($error_message, ['@link_path' => $invalid_value]));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the link title settings of a link field.
|
||||
*/
|
||||
protected function doTestLinkTitle(): void {
|
||||
$field_name = $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();
|
||||
/** @var \Drupal\Core\Entity\EntityDisplayRepositoryInterface $display_repository */
|
||||
$display_repository = \Drupal::service('entity_display.repository');
|
||||
$display_repository->getFormDisplay('entity_test', 'entity_test')
|
||||
->setComponent($field_name, [
|
||||
'type' => 'link_default',
|
||||
'settings' => [
|
||||
'placeholder_url' => 'http://example.com',
|
||||
'placeholder_title' => 'Enter the text for this link',
|
||||
],
|
||||
])
|
||||
->save();
|
||||
$display_repository->getViewDisplay('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->assertSession()->pageTextContains('Read more about this entity');
|
||||
$this->assertSession()->fieldValueEquals("{$field_name}[0][uri]", '');
|
||||
$this->assertSession()->responseContains('placeholder="http://example.com"');
|
||||
|
||||
if ($title_setting === DRUPAL_DISABLED) {
|
||||
$this->assertSession()->fieldNotExists("{$field_name}[0][title]");
|
||||
$this->assertSession()->responseNotContains('placeholder="Enter the text for this link"');
|
||||
}
|
||||
else {
|
||||
$this->assertSession()->responseContains('placeholder="Enter the text for this link"');
|
||||
|
||||
$this->assertSession()->fieldValueEquals("{$field_name}[0][title]", '');
|
||||
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->submitForm($edit, 'Save');
|
||||
$this->assertSession()->statusMessageContains('The URL field is required when the Link text field is specified.', 'error');
|
||||
}
|
||||
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->submitForm($edit, 'Save');
|
||||
$this->assertSession()->statusMessageContains('Link text field is required if there is URL input.', 'error');
|
||||
|
||||
// Verify that the link text is not required, if the URL is empty.
|
||||
$edit = [
|
||||
"{$field_name}[0][uri]" => '',
|
||||
];
|
||||
$this->submitForm($edit, 'Save');
|
||||
$this->assertSession()->statusMessageNotContains('Link text field is required.');
|
||||
|
||||
// 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->submitForm($edit, 'Save');
|
||||
$this->assertSession()->statusMessageNotContains('Link text field is required.');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 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->submitForm($edit, 'Save');
|
||||
preg_match('|entity_test/manage/(\d+)|', $this->getUrl(), $match);
|
||||
$id = $match[1];
|
||||
$this->assertSession()->statusMessageContains('entity_test ' . $id . ' has been created.', 'status');
|
||||
|
||||
$output = $this->renderTestEntity($id);
|
||||
$expected_link = (string) Link::fromTextAndUrl($value, Url::fromUri($value))->toString();
|
||||
$this->assertStringContainsString($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->drupalGet("entity_test/manage/{$id}/edit");
|
||||
$this->submitForm($edit, 'Save');
|
||||
$this->assertSession()->statusMessageContains('entity_test ' . $id . ' has been updated.', 'status');
|
||||
|
||||
$output = $this->renderTestEntity($id);
|
||||
$expected_link = (string) Link::fromTextAndUrl($title, Url::fromUri($value))->toString();
|
||||
$this->assertStringContainsString($expected_link, $output);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests editing a link to a non-node entity.
|
||||
*/
|
||||
protected function doTestEditNonNodeEntityLink(): void {
|
||||
|
||||
$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();
|
||||
|
||||
// Create a node with the same ID as the test entity to ensure that the link
|
||||
// doesn't match incorrectly.
|
||||
$this->drupalCreateNode(['title' => '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->submitForm([], '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): string {
|
||||
if ($reset) {
|
||||
$this->container->get('entity_type.manager')->getStorage('entity_test')->resetCache([$id]);
|
||||
}
|
||||
$entity = EntityTest::load($id);
|
||||
$display = \Drupal::service('entity_display.repository')
|
||||
->getViewDisplay($entity->getEntityTypeId(), $entity->bundle(), $view_mode);
|
||||
$content = $display->build($entity);
|
||||
$output = \Drupal::service('renderer')->renderRoot($content);
|
||||
return (string) $output;
|
||||
}
|
||||
|
||||
/**
|
||||
* Test link widget exception handled if link uri value is invalid.
|
||||
*/
|
||||
public function testLinkWidgetCaughtExceptionEditingInvalidUrl(): void {
|
||||
$field_name = $this->randomMachineName();
|
||||
$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' => 'Link',
|
||||
'bundle' => 'entity_test',
|
||||
'settings' => [
|
||||
'title' => DRUPAL_OPTIONAL,
|
||||
'link_type' => LinkItemInterface::LINK_GENERIC,
|
||||
],
|
||||
])->save();
|
||||
|
||||
$entityTypeManager = $this->container->get('entity_type.manager');
|
||||
$entityTypeManager
|
||||
->getStorage('entity_form_display')
|
||||
->load('entity_test.entity_test.default')
|
||||
->setComponent($field_name, [
|
||||
'type' => 'link_default',
|
||||
])
|
||||
->save();
|
||||
|
||||
$entityTypeManager
|
||||
->getStorage('entity_view_display')
|
||||
->create([
|
||||
'targetEntityType' => 'entity_test',
|
||||
'bundle' => 'entity_test',
|
||||
'mode' => 'full',
|
||||
'status' => TRUE,
|
||||
])
|
||||
->setComponent($field_name, [
|
||||
'type' => 'link',
|
||||
])
|
||||
->save();
|
||||
|
||||
// Entities can be saved without validation, for example via migration.
|
||||
// Link fields may contain invalid uris such as external URLs without
|
||||
// scheme.
|
||||
$invalidUri = 'www.example.com';
|
||||
$invalidLinkUrlEntity = $entityTypeManager
|
||||
->getStorage('entity_test')
|
||||
->create([
|
||||
'name' => 'Test entity with invalid link URL',
|
||||
$field_name => ['uri' => $invalidUri],
|
||||
]);
|
||||
$invalidLinkUrlEntity->save();
|
||||
|
||||
// If a user without 'link to any page' permission edits an entity, widget
|
||||
// checks access by converting uri to Url object, which will throw an
|
||||
// InvalidArgumentException if uri is invalid.
|
||||
$this->drupalLogin($this->drupalCreateUser([
|
||||
'view test entity',
|
||||
'administer entity_test content',
|
||||
]));
|
||||
$this->drupalGet("/entity_test/manage/{$invalidLinkUrlEntity->id()}/edit");
|
||||
$this->assertSession()->statusCodeEquals(200);
|
||||
$this->assertSession()->fieldValueEquals("{$field_name}[0][uri]", $invalidUri);
|
||||
}
|
||||
|
||||
}
|
||||
258
web/core/modules/link/tests/src/Functional/LinkFieldUITest.php
Normal file
258
web/core/modules/link/tests/src/Functional/LinkFieldUITest.php
Normal file
@ -0,0 +1,258 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Drupal\Tests\link\Functional;
|
||||
|
||||
use Drupal\Core\Url;
|
||||
use Drupal\Component\Utility\Html;
|
||||
use Drupal\Core\Entity\Entity\EntityFormDisplay;
|
||||
use Drupal\link\LinkItemInterface;
|
||||
use Drupal\Tests\BrowserTestBase;
|
||||
use Drupal\Tests\field_ui\Traits\FieldUiTestTrait;
|
||||
|
||||
/**
|
||||
* Tests link field UI functionality.
|
||||
*
|
||||
* @group link
|
||||
* @group #slow
|
||||
*/
|
||||
class LinkFieldUITest extends BrowserTestBase {
|
||||
|
||||
use FieldUiTestTrait;
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected static $modules = ['node', 'link', 'field_ui', 'block'];
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected $defaultTheme = 'stark';
|
||||
|
||||
/**
|
||||
* A user that can edit content types.
|
||||
*
|
||||
* @var \Drupal\user\UserInterface
|
||||
*/
|
||||
protected $adminUser;
|
||||
|
||||
/**
|
||||
* A user that should see the help texts.
|
||||
*
|
||||
* @var \Drupal\user\Entity\User
|
||||
*/
|
||||
protected $helpTextUser;
|
||||
|
||||
/**
|
||||
* The content type to add fields to.
|
||||
*
|
||||
* @var \Drupal\node\Entity\NodeType
|
||||
*/
|
||||
protected $contentType;
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function setUp(): void {
|
||||
parent::setUp();
|
||||
|
||||
$this->contentType = $this->drupalCreateContentType();
|
||||
$this->adminUser = $this->drupalCreateUser([
|
||||
'administer content types',
|
||||
'administer node fields',
|
||||
'administer node display',
|
||||
]);
|
||||
$this->helpTextUser = $this->drupalCreateUser([
|
||||
'create ' . $this->contentType->id() . ' content',
|
||||
]);
|
||||
$this->drupalPlaceBlock('system_breadcrumb_block');
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the link field UI.
|
||||
*/
|
||||
public function testFieldUI(): void {
|
||||
foreach ($this->providerTestFieldUI() as $item) {
|
||||
[$cardinality, $link_type, $title, $label, $field_name, $default_uri] = $item;
|
||||
$this->runFieldUIItem($cardinality, $link_type, $title, $label, $field_name, $default_uri);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Provides test data for ::testFieldUI().
|
||||
*/
|
||||
protected function providerTestFieldUI() {
|
||||
// There are many combinations of field settings: where the description
|
||||
// should show: variation on internal, external, both; cardinality (where
|
||||
// the fieldset is hidden or used); and link text shown (required or
|
||||
// optional) or disabled. There are two descriptions: field and URL help
|
||||
// text.
|
||||
$cardinalities = [1, 2];
|
||||
$title_settings = [
|
||||
DRUPAL_DISABLED,
|
||||
DRUPAL_OPTIONAL,
|
||||
];
|
||||
$link_types = [
|
||||
LinkItemInterface::LINK_EXTERNAL => 'https://example.com',
|
||||
LinkItemInterface::LINK_GENERIC => '',
|
||||
LinkItemInterface::LINK_INTERNAL => '<front>',
|
||||
];
|
||||
|
||||
// Test all variations of link types on all cardinalities.
|
||||
foreach ($cardinalities as $cardinality) {
|
||||
foreach ($link_types as $link_type => $default_uri) {
|
||||
// Now, test this with both the title enabled and disabled.
|
||||
foreach ($title_settings as $title_setting) {
|
||||
// Test both empty and non-empty labels.
|
||||
foreach ([TRUE, FALSE] as $label_provided) {
|
||||
// Generate a unique machine name for the field so it can be
|
||||
// identified in the test.
|
||||
$id = implode('_', [
|
||||
'link',
|
||||
$cardinality,
|
||||
$link_type,
|
||||
$title_setting,
|
||||
(int) $label_provided,
|
||||
]);
|
||||
|
||||
// Use a unique label that contains some HTML.
|
||||
$label = '<img src="https://example.com">' . $id;
|
||||
|
||||
yield [
|
||||
$cardinality,
|
||||
$link_type,
|
||||
$title_setting,
|
||||
$label_provided ? $label : '',
|
||||
$id,
|
||||
$default_uri,
|
||||
];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests one link field UI item.
|
||||
*
|
||||
* @param int $cardinality
|
||||
* The field cardinality.
|
||||
* @param int $link_type
|
||||
* Determine if the link is external, internal or both.
|
||||
* @param int $title
|
||||
* Determine if the field will display the link text field.
|
||||
* @param string $label
|
||||
* The field label.
|
||||
* @param string $field_name
|
||||
* The unique machine name for the field.
|
||||
* @param string $default_uri
|
||||
* The default URI value.
|
||||
*/
|
||||
public function runFieldUIItem($cardinality, $link_type, $title, $label, $field_name, $default_uri): void {
|
||||
$this->drupalLogin($this->adminUser);
|
||||
$type_path = 'admin/structure/types/manage/' . $this->contentType->id();
|
||||
|
||||
// Add a link field to the newly-created type.
|
||||
$description = 'link field description';
|
||||
$field_edit = [
|
||||
'description' => $description,
|
||||
'settings[link_type]' => (int) $link_type,
|
||||
];
|
||||
if (!empty($default_uri)) {
|
||||
$field_edit['set_default_value'] = '1';
|
||||
$field_edit['default_value_input[field_' . $field_name . '][0][uri]'] = $default_uri;
|
||||
$field_edit['default_value_input[field_' . $field_name . '][0][title]'] = 'Default title';
|
||||
}
|
||||
$storage_edit = [
|
||||
'cardinality_number' => $cardinality,
|
||||
];
|
||||
$this->fieldUIAddNewField($type_path, $field_name, $label, 'link', $storage_edit, $field_edit);
|
||||
|
||||
// Load the formatter page to check that the settings summary does not
|
||||
// generate warnings.
|
||||
// @todo Mess with the formatter settings a bit here.
|
||||
$this->drupalGet("$type_path/display");
|
||||
$this->assertSession()->pageTextContains('Link text trimmed to 80 characters');
|
||||
|
||||
// Make the fields visible in the form display.
|
||||
$form_display_id = implode('.', ['node', $this->contentType->id(), 'default']);
|
||||
$form_display = EntityFormDisplay::load($form_display_id);
|
||||
$form_display->setComponent($field_name, ['region' => 'content']);
|
||||
$form_display->save();
|
||||
|
||||
// Log in a user that is allowed to create this content type, see if
|
||||
// the user can see the expected help text.
|
||||
$this->drupalLogin($this->helpTextUser);
|
||||
|
||||
$add_path = 'node/add/' . $this->contentType->id();
|
||||
$this->drupalGet($add_path);
|
||||
|
||||
$expected_help_texts = [
|
||||
LinkItemInterface::LINK_EXTERNAL => 'This must be an external URL such as <em class="placeholder">https://example.com</em>.',
|
||||
LinkItemInterface::LINK_GENERIC => 'You can also enter an internal path such as <em class="placeholder">/node/add</em> or an external URL such as <em class="placeholder">https://example.com</em>. Enter <em class="placeholder"><front></em> to link to the front page. Enter <em class="placeholder"><nolink></em> to display link text only',
|
||||
LinkItemInterface::LINK_INTERNAL => rtrim(Url::fromRoute('<front>', [], ['absolute' => TRUE])->toString(), '/'),
|
||||
];
|
||||
|
||||
// Check that the help texts we assume should be there, is there.
|
||||
$this->assertFieldContainsRawText($field_name, $expected_help_texts[$link_type]);
|
||||
if ($link_type === LinkItemInterface::LINK_INTERNAL) {
|
||||
// Internal links have no "system" description. Test that none
|
||||
// of the other help texts show here.
|
||||
$this->assertNoFieldContainsRawText($field_name, $expected_help_texts[LinkItemInterface::LINK_EXTERNAL]);
|
||||
$this->assertNoFieldContainsRawText($field_name, $expected_help_texts[LinkItemInterface::LINK_GENERIC]);
|
||||
}
|
||||
// Also assert that the description we made is here, no matter what the
|
||||
// cardinality or link setting.
|
||||
if (!empty($label)) {
|
||||
$this->assertFieldContainsRawText($field_name, $label);
|
||||
}
|
||||
|
||||
// Test the default field value is used as expected.
|
||||
$this->assertSession()->fieldValueEquals('field_' . $field_name . '[0][uri]', $default_uri);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks that given field contains the given raw text.
|
||||
*
|
||||
* @param string $field_name
|
||||
* The name of the field to check.
|
||||
* @param string $text
|
||||
* The text to check.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
protected function assertFieldContainsRawText(string $field_name, string $text): void {
|
||||
$this->assertTrue((bool) preg_match('/' . preg_quote($text, '/') . '/ui', $this->getFieldHtml($field_name)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks that given field does not contain the given raw text.
|
||||
*
|
||||
* @param string $field_name
|
||||
* The name of the field to check.
|
||||
* @param string $text
|
||||
* The text to check.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
protected function assertNoFieldContainsRawText(string $field_name, string $text): void {
|
||||
$this->assertFalse((bool) preg_match('/' . preg_quote($text, '/') . '/ui', $this->getFieldHtml($field_name)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the raw HTML for the given field.
|
||||
*
|
||||
* @param string $field_name
|
||||
* The name of the field for which to return the HTML.
|
||||
*
|
||||
* @return string
|
||||
* The raw HTML.
|
||||
*/
|
||||
protected function getFieldHtml($field_name) {
|
||||
$css_id = Html::cleanCssIdentifier('edit-field-' . $field_name . '-wrapper');
|
||||
return $this->xpath('//*[@id=:id]', [':id' => $css_id])[0]->getHtml();
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,104 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Drupal\Tests\link\Functional\Views;
|
||||
|
||||
use Drupal\field\Entity\FieldConfig;
|
||||
use Drupal\field\Entity\FieldStorageConfig;
|
||||
use Drupal\Tests\views\Functional\ViewTestBase;
|
||||
|
||||
/**
|
||||
* Tests the views integration for link tokens.
|
||||
*
|
||||
* @group link
|
||||
*/
|
||||
class LinkViewsTokensTest extends ViewTestBase {
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected static $modules = ['link_test_views'];
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected $defaultTheme = 'stark';
|
||||
|
||||
/**
|
||||
* Views used by this test.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $testViews = ['test_link_tokens'];
|
||||
|
||||
/**
|
||||
* The field name used for the link field.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $fieldName = 'field_link';
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function setUp($import_test_views = TRUE, $modules = ['link_test_views']): void {
|
||||
parent::setUp($import_test_views, $modules);
|
||||
|
||||
// Create Basic page node type.
|
||||
$this->drupalCreateContentType([
|
||||
'type' => 'page',
|
||||
'name' => 'Basic page',
|
||||
]);
|
||||
|
||||
// Create a field.
|
||||
FieldStorageConfig::create([
|
||||
'field_name' => $this->fieldName,
|
||||
'type' => 'link',
|
||||
'entity_type' => 'node',
|
||||
'cardinality' => 1,
|
||||
])->save();
|
||||
FieldConfig::create([
|
||||
'field_name' => $this->fieldName,
|
||||
'entity_type' => 'node',
|
||||
'bundle' => 'page',
|
||||
'label' => 'link field',
|
||||
])->save();
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the link views tokens.
|
||||
*/
|
||||
public function testLinkViewsTokens(): void {
|
||||
// Array of URI's to test.
|
||||
$uris = [
|
||||
'http://www.example.com' => 'example.com',
|
||||
];
|
||||
|
||||
// Add nodes with the URI's and titles.
|
||||
foreach ($uris as $uri => $title) {
|
||||
$values = ['type' => 'page'];
|
||||
$values[$this->fieldName][] = ['uri' => $uri, 'title' => $title, 'options' => ['attributes' => ['class' => 'test-link-class']]];
|
||||
$this->drupalCreateNode($values);
|
||||
}
|
||||
|
||||
$this->drupalGet('test_link_tokens');
|
||||
|
||||
foreach ($uris as $uri => $title) {
|
||||
// Formatted link: {{ field_link }}<br />
|
||||
$this->assertSession()->responseContains("Formatted: <a href=\"$uri\" class=\"test-link-class\">$title</a>");
|
||||
|
||||
// Raw uri: {{ field_link__uri }}<br />
|
||||
$this->assertSession()->responseContains("Raw uri: $uri");
|
||||
|
||||
// Raw title: {{ field_link__title }}<br />
|
||||
$this->assertSession()->responseContains("Raw title: $title");
|
||||
|
||||
// Raw options: {{ field_link__options }}<br />
|
||||
// Options is an array and should return empty after token replace.
|
||||
$this->assertSession()->responseContains("Raw options: .");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,81 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Drupal\Tests\link\FunctionalJavascript;
|
||||
|
||||
use Drupal\FunctionalJavascriptTests\WebDriverTestBase;
|
||||
|
||||
/**
|
||||
* Tests link field form states functionality.
|
||||
*
|
||||
* @group link
|
||||
* @group #slow
|
||||
*/
|
||||
class LinkFieldFormStatesTest extends WebDriverTestBase {
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected static $modules = [
|
||||
'entity_test',
|
||||
'link',
|
||||
'node',
|
||||
'link_test_base_field',
|
||||
];
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected $defaultTheme = 'stark';
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function setUp(): void {
|
||||
parent::setUp();
|
||||
$this->drupalLogin($this->drupalCreateUser([
|
||||
'administer entity_test content',
|
||||
]));
|
||||
}
|
||||
|
||||
/**
|
||||
* @dataProvider linkFieldFormStatesData
|
||||
*/
|
||||
public function testLinkFieldFormStates(string $uri, string $title): void {
|
||||
$this->drupalGet('entity_test/add');
|
||||
$session = $this->assertSession();
|
||||
$session->elementNotExists('css', '#edit-links-0-uri[required]');
|
||||
$session->elementNotExists('css', '#edit-links-0-title[required]');
|
||||
|
||||
$page = $this->getSession()->getPage();
|
||||
|
||||
if ($uri !== '') {
|
||||
$page->fillField('links[0][uri]', $uri);
|
||||
$session->elementNotExists('css', '#edit-links-0-uri[required]');
|
||||
$session->elementExists('css', '#edit-links-0-title[required]');
|
||||
}
|
||||
else {
|
||||
$page->fillField('links[0][title]', $title);
|
||||
$session->elementExists('css', '#edit-links-0-uri[required]');
|
||||
$session->elementNotExists('css', '#edit-links-0-title[required]');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Provides data for ::testLinkFieldJSFormStates.
|
||||
*/
|
||||
public static function linkFieldFormStatesData() {
|
||||
return [
|
||||
'Fill uri, keep title empty' => [
|
||||
'https://example.com',
|
||||
'',
|
||||
],
|
||||
'Fill title, keep uri empty' => [
|
||||
'',
|
||||
'https://example.com',
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,66 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Drupal\Tests\link\Kernel;
|
||||
|
||||
use Drupal\entity_test\Entity\EntityTest;
|
||||
use Drupal\field\Entity\FieldConfig;
|
||||
use Drupal\link\LinkItemInterface;
|
||||
use Drupal\field\Entity\FieldStorageConfig;
|
||||
use Drupal\Tests\field\Kernel\FieldKernelTestBase;
|
||||
|
||||
/**
|
||||
* Tests link field widgets.
|
||||
*
|
||||
* @group link
|
||||
*/
|
||||
class LinkFieldWidgetTest extends FieldKernelTestBase {
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected static $modules = [
|
||||
'link',
|
||||
];
|
||||
|
||||
/**
|
||||
* Tests '#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(): void {
|
||||
$link_type = LinkItemInterface::LINK_EXTERNAL;
|
||||
$field_name = $this->randomMachineName();
|
||||
|
||||
// Create a field with settings to validate.
|
||||
$fieldStorage = FieldStorageConfig::create([
|
||||
'field_name' => $field_name,
|
||||
'entity_type' => 'entity_test',
|
||||
'type' => 'link',
|
||||
'cardinality' => 1,
|
||||
]);
|
||||
$fieldStorage->save();
|
||||
FieldConfig::create([
|
||||
'field_storage' => $fieldStorage,
|
||||
'label' => 'Read more about this entity',
|
||||
'bundle' => 'entity_test',
|
||||
'settings' => [
|
||||
'title' => DRUPAL_OPTIONAL,
|
||||
'link_type' => $link_type,
|
||||
],
|
||||
])->save();
|
||||
|
||||
\Drupal::service('entity_display.repository')
|
||||
->getFormDisplay('entity_test', 'entity_test')
|
||||
->setComponent($field_name, ['type' => 'link_default'])
|
||||
->save();
|
||||
|
||||
$form = \Drupal::service('entity.form_builder')->getForm(EntityTest::create());
|
||||
$this->assertEquals($link_type, $form[$field_name]['widget'][0]['uri']['#link_type']);
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,268 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Drupal\Tests\link\Kernel;
|
||||
|
||||
use Drupal\Tests\field\Kernel\FieldKernelTestBase;
|
||||
use Drupal\Tests\link\Traits\LinkInputValuesTraits;
|
||||
use Drupal\entity_test\Entity\EntityTest;
|
||||
use Drupal\field\Entity\FieldConfig;
|
||||
use Drupal\field\Entity\FieldStorageConfig;
|
||||
use Drupal\link\LinkItemInterface;
|
||||
|
||||
// cspell:ignore Fragm
|
||||
|
||||
/**
|
||||
* Tests the default 'link' field formatter.
|
||||
*
|
||||
* The formatter is tested with several forms of complex query parameters. And
|
||||
* each form is tested with different display settings.
|
||||
*
|
||||
* @group link
|
||||
*/
|
||||
class LinkFormatterDisplayTest extends FieldKernelTestBase {
|
||||
|
||||
use LinkInputValuesTraits;
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected static $modules = ['link'];
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function setUp(): void {
|
||||
parent::setUp();
|
||||
|
||||
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' => [
|
||||
'title' => DRUPAL_OPTIONAL,
|
||||
'link_type' => LinkItemInterface::LINK_GENERIC,
|
||||
],
|
||||
])->save();
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests that links are rendered correctly.
|
||||
*
|
||||
* Run tests without dataProvider to improve speed.
|
||||
*
|
||||
* @see \Drupal\Tests\link\Traits\LinkInputValuesTraits::getLinkInputValues()
|
||||
* @see self::getTestCases()
|
||||
*/
|
||||
public function testLinkFormatter(): void {
|
||||
// Create an entity with link field values provided.
|
||||
$entity = EntityTest::create();
|
||||
$entity->field_test->setValue($this->getLinkInputValues());
|
||||
|
||||
foreach ($this->getTestCases() as $case_name => $case_options) {
|
||||
[$display_settings, $expected_results] = array_values($case_options);
|
||||
$this->assertEquals(count($this->getLinkInputValues()), count($expected_results), "Each field delta have expected result. Case name: '$case_name'");
|
||||
|
||||
// Render link field with default 'link' formatter and custom
|
||||
// display settings. Hide field label.
|
||||
$render_array = $entity->field_test->view([
|
||||
'label' => 'hidden',
|
||||
'settings' => $display_settings,
|
||||
]);
|
||||
$output = (string) \Drupal::service('renderer')->renderRoot($render_array);
|
||||
// Convert each field delta value to separate array item.
|
||||
$field_deltas_display = explode("\n", trim($output));
|
||||
|
||||
// Check results.
|
||||
foreach ($expected_results as $delta => $expected_result) {
|
||||
$rendered_delta = trim($field_deltas_display[$delta]);
|
||||
$message = "Test case failed. Case name: '$case_name'. Delta: '$delta'. Uri: '{$this->getLinkInputValues()[$delta]['uri']}'";
|
||||
$this->assertEquals($expected_result, $rendered_delta, $message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function getTestCases(): \Generator {
|
||||
$default = [
|
||||
0 => '<div><a href="http://www.example.com/content/articles/archive?author=John&year=2012#com">http://www.example.com/content/articles/archive?author=John&year=2012#com</a></div>',
|
||||
1 => '<div><a href="http://www.example.org/content/articles/archive?author=John&year=2012#org">A very long & strange example title that could break the nice layout of the site</a></div>',
|
||||
2 => '<div><a href="#net">Fragment only</a></div>',
|
||||
3 => '<div><a href="?a%5B0%5D=1&a%5B1%5D=2">?a%5B0%5D=1&a%5B1%5D=2</a></div>',
|
||||
4 => '<div><a href="?b%5B0%5D=1&b%5B1%5D=2">?b%5B0%5D=1&b%5B1%5D=2</a></div>',
|
||||
16 => '<div><a href="?b%5B0%5D=9&b%5B1%5D=8">?b%5B0%5D=9&b%5B1%5D=8</a></div>',
|
||||
5 => '<div><a href="?c%5B0%5D=1&c%5B1%5D=2&d=3">?c%5B0%5D=1&c%5B1%5D=2&d=3</a></div>',
|
||||
6 => '<div><a href="?e%5Bf%5D%5Bg%5D=h">?e%5Bf%5D%5Bg%5D=h</a></div>',
|
||||
7 => '<div><a href="?i%5Bj%5Bk%5D=l">?i%5Bj%5Bk%5D=l</a></div>',
|
||||
8 => '<div><a href="?x=2">?x=2</a></div>',
|
||||
9 => '<div><a href="?z%5B0%5D=2">?z%5B0%5D=2</a></div>',
|
||||
10 => '<div><a href=""></a></div>',
|
||||
11 => '<div><a href="">Title, no link</a></div>',
|
||||
12 => '<div><span></span></div>',
|
||||
13 => '<div><span>Title, no link</span></div>',
|
||||
14 => '<div><button type="button"></button></div>',
|
||||
15 => '<div><button type="button">Title, button</button></div>',
|
||||
];
|
||||
|
||||
yield 'default settings' => [
|
||||
'display settings' => [],
|
||||
'expected_results' => $default,
|
||||
];
|
||||
|
||||
yield 'trim_length=null' => [
|
||||
'display_settings' => ['trim_length' => NULL],
|
||||
'expected_results' => $default,
|
||||
];
|
||||
|
||||
yield 'trim_length=6' => [
|
||||
'display settings' => ['trim_length' => 6],
|
||||
'expected_results' => [
|
||||
0 => '<div><a href="http://www.example.com/content/articles/archive?author=John&year=2012#com">http:…</a></div>',
|
||||
1 => '<div><a href="http://www.example.org/content/articles/archive?author=John&year=2012#org">A ver…</a></div>',
|
||||
2 => '<div><a href="#net">Fragm…</a></div>',
|
||||
3 => '<div><a href="?a%5B0%5D=1&a%5B1%5D=2">?a%5B…</a></div>',
|
||||
4 => '<div><a href="?b%5B0%5D=1&b%5B1%5D=2">?b%5B…</a></div>',
|
||||
16 => '<div><a href="?b%5B0%5D=9&b%5B1%5D=8">?b%5B…</a></div>',
|
||||
5 => '<div><a href="?c%5B0%5D=1&c%5B1%5D=2&d=3">?c%5B…</a></div>',
|
||||
6 => '<div><a href="?e%5Bf%5D%5Bg%5D=h">?e%5B…</a></div>',
|
||||
7 => '<div><a href="?i%5Bj%5Bk%5D=l">?i%5B…</a></div>',
|
||||
8 => '<div><a href="?x=2">?x=2</a></div>',
|
||||
9 => '<div><a href="?z%5B0%5D=2">?z%5B…</a></div>',
|
||||
10 => '<div><a href=""></a></div>',
|
||||
11 => '<div><a href="">Title…</a></div>',
|
||||
12 => '<div><span></span></div>',
|
||||
13 => '<div><span>Title…</span></div>',
|
||||
14 => '<div><button type="button"></button></div>',
|
||||
15 => '<div><button type="button">Title…</button></div>',
|
||||
],
|
||||
];
|
||||
|
||||
yield 'attribute rel=null' => [
|
||||
'display_settings' => ['rel' => NULL],
|
||||
'expected_results' => $default,
|
||||
];
|
||||
|
||||
yield 'attribute rel=nofollow' => [
|
||||
'display_settings' => ['rel' => 'nofollow'],
|
||||
'expected_results' => [
|
||||
0 => '<div><a href="http://www.example.com/content/articles/archive?author=John&year=2012#com" rel="nofollow">http://www.example.com/content/articles/archive?author=John&year=2012#com</a></div>',
|
||||
1 => '<div><a href="http://www.example.org/content/articles/archive?author=John&year=2012#org" rel="nofollow">A very long & strange example title that could break the nice layout of the site</a></div>',
|
||||
2 => '<div><a href="#net" rel="nofollow">Fragment only</a></div>',
|
||||
3 => '<div><a href="?a%5B0%5D=1&a%5B1%5D=2" rel="nofollow">?a%5B0%5D=1&a%5B1%5D=2</a></div>',
|
||||
4 => '<div><a href="?b%5B0%5D=1&b%5B1%5D=2" rel="nofollow">?b%5B0%5D=1&b%5B1%5D=2</a></div>',
|
||||
16 => '<div><a href="?b%5B0%5D=9&b%5B1%5D=8" rel="nofollow">?b%5B0%5D=9&b%5B1%5D=8</a></div>',
|
||||
5 => '<div><a href="?c%5B0%5D=1&c%5B1%5D=2&d=3" rel="nofollow">?c%5B0%5D=1&c%5B1%5D=2&d=3</a></div>',
|
||||
6 => '<div><a href="?e%5Bf%5D%5Bg%5D=h" rel="nofollow">?e%5Bf%5D%5Bg%5D=h</a></div>',
|
||||
7 => '<div><a href="?i%5Bj%5Bk%5D=l" rel="nofollow">?i%5Bj%5Bk%5D=l</a></div>',
|
||||
8 => '<div><a href="?x=2" rel="nofollow">?x=2</a></div>',
|
||||
9 => '<div><a href="?z%5B0%5D=2" rel="nofollow">?z%5B0%5D=2</a></div>',
|
||||
10 => '<div><a href="" rel="nofollow"></a></div>',
|
||||
11 => '<div><a href="" rel="nofollow">Title, no link</a></div>',
|
||||
12 => '<div><span rel="nofollow"></span></div>',
|
||||
13 => '<div><span rel="nofollow">Title, no link</span></div>',
|
||||
14 => '<div><button rel="nofollow" type="button"></button></div>',
|
||||
15 => '<div><button rel="nofollow" type="button">Title, button</button></div>',
|
||||
],
|
||||
];
|
||||
|
||||
yield 'attribute target=null' => [
|
||||
'display_settings' => ['target' => NULL],
|
||||
'expected_results' => $default,
|
||||
];
|
||||
|
||||
yield 'attribute target=_blank' => [
|
||||
'display_settings' => ['target' => '_blank'],
|
||||
'expected_results' => [
|
||||
0 => '<div><a href="http://www.example.com/content/articles/archive?author=John&year=2012#com" target="_blank">http://www.example.com/content/articles/archive?author=John&year=2012#com</a></div>',
|
||||
1 => '<div><a href="http://www.example.org/content/articles/archive?author=John&year=2012#org" target="_blank">A very long & strange example title that could break the nice layout of the site</a></div>',
|
||||
2 => '<div><a href="#net" target="_blank">Fragment only</a></div>',
|
||||
3 => '<div><a href="?a%5B0%5D=1&a%5B1%5D=2" target="_blank">?a%5B0%5D=1&a%5B1%5D=2</a></div>',
|
||||
4 => '<div><a href="?b%5B0%5D=1&b%5B1%5D=2" target="_blank">?b%5B0%5D=1&b%5B1%5D=2</a></div>',
|
||||
16 => '<div><a href="?b%5B0%5D=9&b%5B1%5D=8" target="_blank">?b%5B0%5D=9&b%5B1%5D=8</a></div>',
|
||||
5 => '<div><a href="?c%5B0%5D=1&c%5B1%5D=2&d=3" target="_blank">?c%5B0%5D=1&c%5B1%5D=2&d=3</a></div>',
|
||||
6 => '<div><a href="?e%5Bf%5D%5Bg%5D=h" target="_blank">?e%5Bf%5D%5Bg%5D=h</a></div>',
|
||||
7 => '<div><a href="?i%5Bj%5Bk%5D=l" target="_blank">?i%5Bj%5Bk%5D=l</a></div>',
|
||||
8 => '<div><a href="?x=2" target="_blank">?x=2</a></div>',
|
||||
9 => '<div><a href="?z%5B0%5D=2" target="_blank">?z%5B0%5D=2</a></div>',
|
||||
10 => '<div><a href="" target="_blank"></a></div>',
|
||||
11 => '<div><a href="" target="_blank">Title, no link</a></div>',
|
||||
12 => '<div><span target="_blank"></span></div>',
|
||||
13 => '<div><span target="_blank">Title, no link</span></div>',
|
||||
14 => '<div><button target="_blank" type="button"></button></div>',
|
||||
15 => '<div><button target="_blank" type="button">Title, button</button></div>',
|
||||
],
|
||||
];
|
||||
|
||||
yield 'url_only=false' => [
|
||||
'display_settings' => ['url_only' => FALSE],
|
||||
'expected_results' => $default,
|
||||
];
|
||||
|
||||
yield 'url_only=true' => [
|
||||
'display_settings' => ['url_only' => TRUE],
|
||||
'expected_results' => [
|
||||
0 => '<div><a href="http://www.example.com/content/articles/archive?author=John&year=2012#com">http://www.example.com/content/articles/archive?author=John&year=2012#com</a></div>',
|
||||
1 => '<div><a href="http://www.example.org/content/articles/archive?author=John&year=2012#org">http://www.example.org/content/articles/archive?author=John&year=2012#org</a></div>',
|
||||
2 => '<div><a href="#net">#net</a></div>',
|
||||
3 => '<div><a href="?a%5B0%5D=1&a%5B1%5D=2">?a%5B0%5D=1&a%5B1%5D=2</a></div>',
|
||||
4 => '<div><a href="?b%5B0%5D=1&b%5B1%5D=2">?b%5B0%5D=1&b%5B1%5D=2</a></div>',
|
||||
16 => '<div><a href="?b%5B0%5D=9&b%5B1%5D=8">?b%5B0%5D=9&b%5B1%5D=8</a></div>',
|
||||
5 => '<div><a href="?c%5B0%5D=1&c%5B1%5D=2&d=3">?c%5B0%5D=1&c%5B1%5D=2&d=3</a></div>',
|
||||
6 => '<div><a href="?e%5Bf%5D%5Bg%5D=h">?e%5Bf%5D%5Bg%5D=h</a></div>',
|
||||
7 => '<div><a href="?i%5Bj%5Bk%5D=l">?i%5Bj%5Bk%5D=l</a></div>',
|
||||
8 => '<div><a href="?x=2">?x=2</a></div>',
|
||||
9 => '<div><a href="?z%5B0%5D=2">?z%5B0%5D=2</a></div>',
|
||||
10 => '<div><a href=""></a></div>',
|
||||
11 => '<div><a href=""></a></div>',
|
||||
12 => '<div><span></span></div>',
|
||||
13 => '<div><span></span></div>',
|
||||
14 => '<div><button type="button"></button></div>',
|
||||
15 => '<div><button type="button"></button></div>',
|
||||
],
|
||||
];
|
||||
|
||||
yield 'url_only=false, url_plain=true' => [
|
||||
'display_settings' => [
|
||||
'url_only' => FALSE,
|
||||
'url_plain' => TRUE,
|
||||
],
|
||||
'expected_results' => $default,
|
||||
];
|
||||
|
||||
yield 'url_only=true, url_plain=true' => [
|
||||
'display_settings' => [
|
||||
'url_only' => TRUE,
|
||||
'url_plain' => TRUE,
|
||||
],
|
||||
'expected_results' => [
|
||||
0 => '<div>http://www.example.com/content/articles/archive?author=John&year=2012#com</div>',
|
||||
1 => '<div>http://www.example.org/content/articles/archive?author=John&year=2012#org</div>',
|
||||
2 => '<div>#net</div>',
|
||||
3 => '<div>?a%5B0%5D=1&a%5B1%5D=2</div>',
|
||||
4 => '<div>?b%5B0%5D=1&b%5B1%5D=2</div>',
|
||||
16 => '<div>?b%5B0%5D=9&b%5B1%5D=8</div>',
|
||||
5 => '<div>?c%5B0%5D=1&c%5B1%5D=2&d=3</div>',
|
||||
6 => '<div>?e%5Bf%5D%5Bg%5D=h</div>',
|
||||
7 => '<div>?i%5Bj%5Bk%5D=l</div>',
|
||||
8 => '<div>?x=2</div>',
|
||||
9 => '<div>?z%5B0%5D=2</div>',
|
||||
10 => '<div></div>',
|
||||
11 => '<div></div>',
|
||||
12 => '<div></div>',
|
||||
13 => '<div></div>',
|
||||
14 => '<div></div>',
|
||||
15 => '<div></div>',
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
}
|
||||
132
web/core/modules/link/tests/src/Kernel/LinkFormatterTest.php
Normal file
132
web/core/modules/link/tests/src/Kernel/LinkFormatterTest.php
Normal file
@ -0,0 +1,132 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Drupal\Tests\link\Kernel;
|
||||
|
||||
use Drupal\field\Entity\FieldConfig;
|
||||
use Drupal\field\Entity\FieldStorageConfig;
|
||||
use Drupal\KernelTests\Core\Entity\EntityKernelTestBase;
|
||||
use Drupal\user\Entity\Role;
|
||||
use Drupal\user\RoleInterface;
|
||||
|
||||
/**
|
||||
* Tests the Field Formatter for the link field type.
|
||||
*
|
||||
* @group link
|
||||
*/
|
||||
class LinkFormatterTest extends EntityKernelTestBase {
|
||||
|
||||
/**
|
||||
* Modules to enable.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected static $modules = ['link'];
|
||||
|
||||
/**
|
||||
* The entity type used in this test.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected string $entityType = 'entity_test';
|
||||
|
||||
/**
|
||||
* The bundle used in this test.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected string $bundle = 'entity_test';
|
||||
|
||||
/**
|
||||
* The name of the field used in this test.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected string $fieldName = 'field_test';
|
||||
|
||||
/**
|
||||
* The entity to be tested.
|
||||
*
|
||||
* @var \Drupal\Core\Entity\EntityInterface
|
||||
*/
|
||||
protected $entity;
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function setUp(): void {
|
||||
parent::setUp();
|
||||
|
||||
// Use Stark theme for testing markup output.
|
||||
\Drupal::service('theme_installer')->install(['stark']);
|
||||
$this->config('system.theme')->set('default', 'stark')->save();
|
||||
$this->installEntitySchema('entity_test');
|
||||
// Grant the 'view test entity' permission.
|
||||
$this->installConfig(['user']);
|
||||
Role::load(RoleInterface::ANONYMOUS_ID)
|
||||
->grantPermission('view test entity')
|
||||
->save();
|
||||
|
||||
FieldStorageConfig::create([
|
||||
'field_name' => $this->fieldName,
|
||||
'type' => 'link',
|
||||
'entity_type' => $this->entityType,
|
||||
'cardinality' => 1,
|
||||
])->save();
|
||||
|
||||
FieldConfig::create([
|
||||
'field_name' => $this->fieldName,
|
||||
'entity_type' => $this->entityType,
|
||||
'bundle' => $this->bundle,
|
||||
'label' => 'Field test',
|
||||
])->save();
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the link formatters.
|
||||
*
|
||||
* @param string $formatter
|
||||
* The name of the link formatter to test.
|
||||
*
|
||||
* @dataProvider providerLinkFormatter
|
||||
*/
|
||||
public function testLinkFormatter(string $formatter): void {
|
||||
$entity = $this->container->get('entity_type.manager')
|
||||
->getStorage($this->entityType)
|
||||
->create([
|
||||
'name' => $this->randomMachineName(),
|
||||
$this->fieldName => [
|
||||
'uri' => 'https://www.drupal.org/',
|
||||
'title' => 'Hello world',
|
||||
'options' => [
|
||||
'attributes' => [
|
||||
'class' => 'classy',
|
||||
'onmouseover' => 'alert(document.cookie)',
|
||||
],
|
||||
],
|
||||
],
|
||||
]);
|
||||
$entity->save();
|
||||
|
||||
$build = $entity->get($this->fieldName)->view(['type' => $formatter]);
|
||||
|
||||
$renderer = $this->container->get('renderer');
|
||||
$renderer->renderRoot($build[0]);
|
||||
|
||||
$output = (string) $build[0]['#markup'];
|
||||
$this->assertStringContainsString('<a href="https://www.drupal.org/" class="classy">', $output);
|
||||
$this->assertStringNotContainsString('onmouseover=', $output);
|
||||
}
|
||||
|
||||
/**
|
||||
* Data provider for ::testLinkFormatter.
|
||||
*/
|
||||
public static function providerLinkFormatter(): array {
|
||||
return [
|
||||
'default formatter' => ['link'],
|
||||
'separate link text and URL' => ['link_separate'],
|
||||
];
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,107 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Drupal\Tests\link\Kernel;
|
||||
|
||||
use Drupal\field\Entity\FieldStorageConfig;
|
||||
use Drupal\field\Entity\FieldConfig;
|
||||
use Drupal\link\LinkItemInterface;
|
||||
use Drupal\entity_test\Entity\EntityTest;
|
||||
use Drupal\Component\Utility\UrlHelper;
|
||||
use Drupal\Tests\field\Kernel\FieldKernelTestBase;
|
||||
|
||||
/**
|
||||
* Tests link field serialization.
|
||||
*
|
||||
* @group link
|
||||
*/
|
||||
class LinkItemSerializationTest extends FieldKernelTestBase {
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected static $modules = ['link', 'serialization'];
|
||||
|
||||
/**
|
||||
* The serializer service.
|
||||
*
|
||||
* @var \Symfony\Component\Serializer\SerializerInterface
|
||||
*/
|
||||
protected $serializer;
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function setUp(): void {
|
||||
parent::setUp();
|
||||
|
||||
$this->installEntitySchema('user');
|
||||
$this->serializer = \Drupal::service('serializer');
|
||||
|
||||
// Create a generic, external, and internal link fields for validation.
|
||||
FieldStorageConfig::create([
|
||||
'entity_type' => 'entity_test',
|
||||
'field_name' => 'field_test',
|
||||
'type' => 'link',
|
||||
])->save();
|
||||
|
||||
FieldConfig::create([
|
||||
'entity_type' => 'entity_test',
|
||||
'field_name' => 'field_test',
|
||||
'bundle' => 'entity_test',
|
||||
'settings' => ['link_type' => LinkItemInterface::LINK_GENERIC],
|
||||
])->save();
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the serialization.
|
||||
*/
|
||||
public function testLinkSerialization(): void {
|
||||
// Create entity.
|
||||
$entity = EntityTest::create();
|
||||
$url = 'https://www.drupal.org?test_param=test_value';
|
||||
$parsed_url = UrlHelper::parse($url);
|
||||
$title = $this->randomMachineName();
|
||||
$class = $this->randomMachineName();
|
||||
$entity->field_test->uri = $parsed_url['path'];
|
||||
$entity->field_test->title = $title;
|
||||
$entity->field_test->first()
|
||||
->get('options')
|
||||
->set('query', $parsed_url['query']);
|
||||
$entity->field_test->first()
|
||||
->get('options')
|
||||
->set('attributes', ['class' => $class]);
|
||||
$entity->save();
|
||||
$serialized = $this->serializer->serialize($entity, 'json');
|
||||
$deserialized = $this->serializer->deserialize($serialized, EntityTest::class, 'json');
|
||||
$options_expected = [
|
||||
'query' => $parsed_url['query'],
|
||||
'attributes' => ['class' => $class],
|
||||
];
|
||||
$this->assertSame($options_expected, $deserialized->field_test->options);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the deserialization.
|
||||
*/
|
||||
public function testLinkDeserialization(): void {
|
||||
// Create entity.
|
||||
$entity = EntityTest::create();
|
||||
$url = 'https://www.drupal.org?test_param=test_value';
|
||||
$parsed_url = UrlHelper::parse($url);
|
||||
$title = $this->randomMachineName();
|
||||
$entity->field_test->uri = $parsed_url['path'];
|
||||
$entity->field_test->title = $title;
|
||||
$entity->field_test->first()
|
||||
->get('options')
|
||||
->set('query', $parsed_url['query']);
|
||||
$json = json_decode($this->serializer->serialize($entity, 'json'), TRUE);
|
||||
$json['field_test'][0]['options'] = 'string data';
|
||||
$serialized = json_encode($json);
|
||||
$this->expectException(\LogicException::class);
|
||||
$this->expectExceptionMessage('The generic FieldItemNormalizer cannot denormalize string values for "options" properties of the "field_test" field (field item class: Drupal\link\Plugin\Field\FieldType\LinkItem).');
|
||||
$this->serializer->deserialize($serialized, EntityTest::class, 'json');
|
||||
}
|
||||
|
||||
}
|
||||
181
web/core/modules/link/tests/src/Kernel/LinkItemTest.php
Normal file
181
web/core/modules/link/tests/src/Kernel/LinkItemTest.php
Normal file
@ -0,0 +1,181 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Drupal\Tests\link\Kernel;
|
||||
|
||||
use Drupal\Component\Utility\UrlHelper;
|
||||
use Drupal\Core\Field\FieldItemListInterface;
|
||||
use Drupal\Core\Field\FieldItemInterface;
|
||||
use Drupal\Core\Url;
|
||||
use Drupal\entity_test\Entity\EntityTest;
|
||||
use Drupal\field\Entity\FieldConfig;
|
||||
use Drupal\field\Entity\FieldStorageConfig;
|
||||
use Drupal\Tests\field\Kernel\FieldKernelTestBase;
|
||||
use Drupal\link\LinkItemInterface;
|
||||
|
||||
/**
|
||||
* Tests the new entity API for the link field type.
|
||||
*
|
||||
* @group link
|
||||
*/
|
||||
class LinkItemTest extends FieldKernelTestBase {
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected static $modules = ['link'];
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function setUp(): void {
|
||||
parent::setUp();
|
||||
|
||||
// Create a generic, external, and internal link fields for validation.
|
||||
FieldStorageConfig::create([
|
||||
'field_name' => 'field_test',
|
||||
'entity_type' => 'entity_test',
|
||||
'type' => 'link',
|
||||
])->save();
|
||||
FieldConfig::create([
|
||||
'entity_type' => 'entity_test',
|
||||
'field_name' => 'field_test',
|
||||
'bundle' => 'entity_test',
|
||||
'settings' => ['link_type' => LinkItemInterface::LINK_GENERIC],
|
||||
])->save();
|
||||
FieldStorageConfig::create([
|
||||
'field_name' => 'field_test_external',
|
||||
'entity_type' => 'entity_test',
|
||||
'type' => 'link',
|
||||
])->save();
|
||||
FieldConfig::create([
|
||||
'entity_type' => 'entity_test',
|
||||
'field_name' => 'field_test_external',
|
||||
'bundle' => 'entity_test',
|
||||
'settings' => ['link_type' => LinkItemInterface::LINK_EXTERNAL],
|
||||
])->save();
|
||||
FieldStorageConfig::create([
|
||||
'field_name' => 'field_test_internal',
|
||||
'entity_type' => 'entity_test',
|
||||
'type' => 'link',
|
||||
])->save();
|
||||
FieldConfig::create([
|
||||
'entity_type' => 'entity_test',
|
||||
'field_name' => 'field_test_internal',
|
||||
'bundle' => 'entity_test',
|
||||
'settings' => ['link_type' => LinkItemInterface::LINK_INTERNAL],
|
||||
])->save();
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests using entity fields of the link field type.
|
||||
*/
|
||||
public function testLinkItem(): void {
|
||||
// Create entity.
|
||||
$entity = EntityTest::create();
|
||||
$url = 'https://www.drupal.org?test_param=test_value';
|
||||
$parsed_url = UrlHelper::parse($url);
|
||||
$title = $this->randomMachineName();
|
||||
$class = $this->randomMachineName();
|
||||
$entity->field_test->uri = $parsed_url['path'];
|
||||
$entity->field_test->title = $title;
|
||||
$entity->field_test->first()->get('options')->set('query', $parsed_url['query']);
|
||||
$entity->field_test->first()->get('options')->set('attributes', ['class' => $class]);
|
||||
$this->assertEquals([
|
||||
'query' => $parsed_url['query'],
|
||||
'attributes' => [
|
||||
'class' => $class,
|
||||
],
|
||||
'external' => TRUE,
|
||||
], $entity->field_test->first()->getUrl()->getOptions());
|
||||
$entity->name->value = $this->randomMachineName();
|
||||
$entity->save();
|
||||
|
||||
// Verify that the field value is changed.
|
||||
$id = $entity->id();
|
||||
$entity = EntityTest::load($id);
|
||||
$this->assertInstanceOf(FieldItemListInterface::class, $entity->field_test);
|
||||
$this->assertInstanceOf(FieldItemInterface::class, $entity->field_test[0]);
|
||||
$this->assertEquals($parsed_url['path'], $entity->field_test->uri);
|
||||
$this->assertEquals($parsed_url['path'], $entity->field_test[0]->uri);
|
||||
$this->assertEquals($title, $entity->field_test->title);
|
||||
$this->assertEquals($title, $entity->field_test[0]->title);
|
||||
$this->assertEquals($title, $entity->field_test[0]->getTitle());
|
||||
$this->assertEquals($class, $entity->field_test->options['attributes']['class']);
|
||||
$this->assertEquals($parsed_url['query'], $entity->field_test->options['query']);
|
||||
|
||||
// Update only the entity name property to check if the link field data will
|
||||
// remain intact.
|
||||
$entity->name->value = $this->randomMachineName();
|
||||
$entity->save();
|
||||
$id = $entity->id();
|
||||
$entity = EntityTest::load($id);
|
||||
$this->assertEquals($parsed_url['path'], $entity->field_test->uri);
|
||||
$this->assertEquals($class, $entity->field_test->options['attributes']['class']);
|
||||
$this->assertEquals($parsed_url['query'], $entity->field_test->options['query']);
|
||||
|
||||
// Verify changing the field value.
|
||||
$new_url = 'https://www.drupal.org';
|
||||
$new_title = $this->randomMachineName();
|
||||
$new_class = $this->randomMachineName();
|
||||
$entity->field_test->uri = $new_url;
|
||||
$entity->field_test->title = $new_title;
|
||||
$entity->field_test->first()->get('options')->set('query', NULL);
|
||||
$entity->field_test->first()->get('options')->set('attributes', ['class' => $new_class]);
|
||||
$this->assertEquals($new_url, $entity->field_test->uri);
|
||||
$this->assertEquals($new_title, $entity->field_test->title);
|
||||
$this->assertEquals($new_class, $entity->field_test->options['attributes']['class']);
|
||||
$this->assertNull($entity->field_test->options['query']);
|
||||
|
||||
// Read changed entity and assert changed values.
|
||||
$entity->save();
|
||||
$entity = EntityTest::load($id);
|
||||
$this->assertEquals($new_url, $entity->field_test->uri);
|
||||
$this->assertEquals($new_title, $entity->field_test->title);
|
||||
$this->assertEquals($new_class, $entity->field_test->options['attributes']['class']);
|
||||
|
||||
// Check that if we only set uri the default values for title and options
|
||||
// are also initialized.
|
||||
$entity->field_test = ['uri' => 'internal:/node/add'];
|
||||
$this->assertEquals('internal:/node/add', $entity->field_test->uri);
|
||||
$this->assertNull($entity->field_test->title);
|
||||
$this->assertSame([], $entity->field_test->options);
|
||||
|
||||
// Check that if we set uri and options then the default values are properly
|
||||
// initialized.
|
||||
$entity->field_test = [
|
||||
'uri' => 'internal:/node/add',
|
||||
'options' => ['query' => NULL],
|
||||
];
|
||||
$this->assertEquals('internal:/node/add', $entity->field_test->uri);
|
||||
$this->assertNull($entity->field_test->title);
|
||||
$this->assertNull($entity->field_test->options['query']);
|
||||
|
||||
// Check that if we set the direct value of link field it correctly set the
|
||||
// uri and the default values of the field.
|
||||
$entity->field_test = 'internal:/node/add';
|
||||
$this->assertEquals('internal:/node/add', $entity->field_test->uri);
|
||||
$this->assertNull($entity->field_test->title);
|
||||
$this->assertSame([], $entity->field_test->options);
|
||||
|
||||
// Check that setting options to NULL does not trigger an error when
|
||||
// calling getUrl();
|
||||
$entity->field_test->options = NULL;
|
||||
$this->assertInstanceOf(Url::class, $entity->field_test[0]->getUrl());
|
||||
|
||||
// Check that setting LinkItem value NULL doesn't generate any error or
|
||||
// warning.
|
||||
$entity->field_test[0] = NULL;
|
||||
$this->assertNull($entity->field_test[0]->getValue());
|
||||
|
||||
// Test the generateSampleValue() method for generic, external, and internal
|
||||
// link types.
|
||||
$entity = EntityTest::create();
|
||||
$entity->field_test->generateSampleItems();
|
||||
$entity->field_test_external->generateSampleItems();
|
||||
$entity->field_test_internal->generateSampleItems();
|
||||
$this->entityValidateAndSave($entity);
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,124 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Drupal\Tests\link\Kernel;
|
||||
|
||||
use Drupal\Tests\field\Kernel\FieldKernelTestBase;
|
||||
|
||||
/**
|
||||
* Tests link field validation.
|
||||
*
|
||||
* @group link
|
||||
*/
|
||||
class LinkItemUrlValidationTest extends FieldKernelTestBase {
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected static $modules = ['link'];
|
||||
|
||||
/**
|
||||
* Tests link validation.
|
||||
*/
|
||||
public function testExternalLinkValidation(): void {
|
||||
$definition = \Drupal::typedDataManager()
|
||||
->createDataDefinition('field_item:link');
|
||||
$link_item = \Drupal::typedDataManager()->create($definition);
|
||||
$test_links = $this->getTestLinks();
|
||||
|
||||
foreach ($test_links as $data) {
|
||||
[$value, $expected_violations] = $data;
|
||||
$link_item->setValue($value);
|
||||
$violations = $link_item->validate();
|
||||
$expected_count = count($expected_violations);
|
||||
$this->assertCount($expected_count, $violations, sprintf('Violation message count error for %s', $value));
|
||||
if ($expected_count) {
|
||||
$i = 0;
|
||||
foreach ($expected_violations as $error_msg) {
|
||||
// If the expected message contains a '%' add the current link value.
|
||||
if (strpos($error_msg, '%')) {
|
||||
$error_msg = sprintf($error_msg, $value);
|
||||
}
|
||||
$this->assertEquals($error_msg, $violations[$i++]->getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds an array of links to test.
|
||||
*
|
||||
* @return array
|
||||
* The first element of the array is the link value to test. The second
|
||||
* value is an array of expected violation messages.
|
||||
*/
|
||||
protected function getTestLinks(): array {
|
||||
$violation_0 = "The path '%s' is invalid.";
|
||||
$violation_1 = 'This value should be of the correct primitive type.';
|
||||
return [
|
||||
['invalid://not-a-valid-protocol', [$violation_0]],
|
||||
['http://www.example.com/', []],
|
||||
// Strings within parenthesis without leading space char.
|
||||
['http://www.example.com/strings_(string_within_parenthesis)', []],
|
||||
// Numbers within parenthesis without leading space char.
|
||||
['http://www.example.com/numbers_(9999)', []],
|
||||
['http://www.example.com/?name=ferret&color=purple', []],
|
||||
['http://www.example.com/page?name=ferret&color=purple', []],
|
||||
['http://www.example.com?a=&b[]=c&d[]=e&d[]=f&h==', []],
|
||||
['http://www.example.com#colors', []],
|
||||
// Use list of valid URLS from],
|
||||
// https://cran.r-project.org/web/packages/rex/vignettes/url_parsing.html.
|
||||
["http://foo.com/blah_blah", []],
|
||||
["http://foo.com/blah_blah/", []],
|
||||
["http://foo.com/blah_blah_(wikipedia)", []],
|
||||
["http://foo.com/blah_blah_(wikipedia)_(again)", []],
|
||||
["http://www.example.com/wpstyle/?p=364", []],
|
||||
["https://www.example.com/foo/?bar=baz&inga=42&quux", []],
|
||||
["http://✪df.ws/123", []],
|
||||
["http://userid:password@example.com:8080", []],
|
||||
["http://userid:password@example.com:8080/", []],
|
||||
["http://userid@example.com", []],
|
||||
["http://userid@example.com/", []],
|
||||
["http://userid@example.com:8080", []],
|
||||
["http://userid@example.com:8080/", []],
|
||||
["http://userid:password@example.com", []],
|
||||
["http://userid:password@example.com/", []],
|
||||
["http://➡.ws/䨹", []],
|
||||
["http://⌘.ws", []],
|
||||
["http://⌘.ws/", []],
|
||||
["http://foo.com/blah_(wikipedia)#cite-1", []],
|
||||
["http://foo.com/blah_(wikipedia)_blah#cite-1", []],
|
||||
// The following invalid URLs produce false positives.
|
||||
["http://foo.com/unicode_(✪)_in_parens", []],
|
||||
["http://foo.com/(something)?after=parens", []],
|
||||
["http://☺.damowmow.com/", []],
|
||||
["http://code.google.com/events/#&product=browser", []],
|
||||
["http://j.mp", []],
|
||||
["ftp://foo.bar/baz", []],
|
||||
["http://foo.bar/?q=Test%20URL-encoded%20stuff", []],
|
||||
["http://مثال.إختبار", []],
|
||||
["http://例子.测试", []],
|
||||
["http://-.~_!$&'()*+,;=:%40:80%2f::::::@example.com", []],
|
||||
["http://1337.net", []],
|
||||
["http://a.b-c.de", []],
|
||||
["radar://1234", [$violation_0]],
|
||||
["h://test", [$violation_0]],
|
||||
["ftps://foo.bar/", [$violation_0]],
|
||||
// Use invalid URLS from
|
||||
// https://cran.r-project.org/web/packages/rex/vignettes/url_parsing.html.
|
||||
['http://', [$violation_0, $violation_1]],
|
||||
["http://?", [$violation_0, $violation_1]],
|
||||
["http://??", [$violation_0, $violation_1]],
|
||||
["http://??/", [$violation_0, $violation_1]],
|
||||
["http://#", [$violation_0, $violation_1]],
|
||||
["http://##", [$violation_0, $violation_1]],
|
||||
["http://##/", [$violation_0, $violation_1]],
|
||||
["//", [$violation_0, $violation_1]],
|
||||
["///a", [$violation_0, $violation_1]],
|
||||
["///", [$violation_0, $violation_1]],
|
||||
["http:///a", [$violation_0, $violation_1]],
|
||||
];
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,339 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Drupal\Tests\link\Kernel;
|
||||
|
||||
use Drupal\entity_test\Entity\EntityTest;
|
||||
use Drupal\field\Entity\FieldConfig;
|
||||
use Drupal\field\Entity\FieldStorageConfig;
|
||||
use Drupal\link\LinkItemInterface;
|
||||
use Drupal\Tests\field\Kernel\FieldKernelTestBase;
|
||||
use Drupal\Tests\link\Traits\LinkInputValuesTraits;
|
||||
|
||||
// cspell:ignore Fragm
|
||||
|
||||
/**
|
||||
* Tests the 'link_separate' field formatter.
|
||||
*
|
||||
* The formatter is tested with several forms of complex query parameters. And
|
||||
* each form is tested with different display settings.
|
||||
*
|
||||
* @group link
|
||||
*/
|
||||
class LinkSeparateFormatterDisplayTest extends FieldKernelTestBase {
|
||||
|
||||
use LinkInputValuesTraits;
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected static $modules = ['link'];
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function setUp(): void {
|
||||
parent::setUp();
|
||||
|
||||
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' => [
|
||||
'title' => DRUPAL_OPTIONAL,
|
||||
'link_type' => LinkItemInterface::LINK_GENERIC,
|
||||
],
|
||||
])->save();
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests that links are rendered correctly.
|
||||
*
|
||||
* Run tests without dataProvider to improve speed.
|
||||
*
|
||||
* @see \Drupal\Tests\link\Traits\LinkInputValuesTraits::getLinkInputValues()
|
||||
* @see self::getTestCases()
|
||||
*/
|
||||
public function testLinkSeparateFormatter(): void {
|
||||
// Create an entity with link field values provided.
|
||||
$entity = EntityTest::create();
|
||||
$entity->field_test->setValue($this->getLinkInputValues());
|
||||
|
||||
foreach ($this->getTestCases() as $case_name => $case_options) {
|
||||
[$display_settings, $expected_results] = array_values($case_options);
|
||||
$this->assertEquals(count($this->getLinkInputValues()), count($expected_results), "Each field delta have expected result. Case name: '$case_name'");
|
||||
|
||||
// Render link field with 'link_separate' formatter and custom
|
||||
// display settings. Hide field label.
|
||||
$render_array = $entity->field_test->view([
|
||||
'label' => 'hidden',
|
||||
'settings' => $display_settings,
|
||||
'type' => 'link_separate',
|
||||
]);
|
||||
$output = (string) \Drupal::service('renderer')->renderRoot($render_array);
|
||||
// Convert each field delta value to separate array item.
|
||||
$field_deltas_display = explode("\n ", trim($output));
|
||||
|
||||
// Check results.
|
||||
foreach ($expected_results as $delta => $expected_result) {
|
||||
$rendered_delta = trim($field_deltas_display[$delta]);
|
||||
$this->assertEquals($expected_result, $rendered_delta, "Test case failed. Case name: '$case_name'. Delta: '$delta'. Uri: '{$this->getLinkInputValues()[$delta]['uri']}'");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function getTestCases(): \Generator {
|
||||
$defaultExpectedResults = [
|
||||
0 => '<div>
|
||||
<a href="http://www.example.com/content/articles/archive?author=John&year=2012#com">http://www.example.com/content/articles/archive?author=John&year=2012#com</a>
|
||||
</div>',
|
||||
1 => '<div>A very long & strange example title that could break the nice layout of the site
|
||||
<a href="http://www.example.org/content/articles/archive?author=John&year=2012#org">http://www.example.org/content/articles/archive?author=John&year=2012#org</a>
|
||||
</div>',
|
||||
2 => '<div>Fragment only
|
||||
<a href="#net">#net</a>
|
||||
</div>',
|
||||
3 => '<div>
|
||||
<a href="?a%5B0%5D=1&a%5B1%5D=2">?a%5B0%5D=1&a%5B1%5D=2</a>
|
||||
</div>',
|
||||
4 => '<div>
|
||||
<a href="?b%5B0%5D=1&b%5B1%5D=2">?b%5B0%5D=1&b%5B1%5D=2</a>
|
||||
</div>',
|
||||
16 => '<div>
|
||||
<a href="?b%5B0%5D=9&b%5B1%5D=8">?b%5B0%5D=9&b%5B1%5D=8</a>
|
||||
</div>',
|
||||
5 => '<div>
|
||||
<a href="?c%5B0%5D=1&c%5B1%5D=2&d=3">?c%5B0%5D=1&c%5B1%5D=2&d=3</a>
|
||||
</div>',
|
||||
6 => '<div>
|
||||
<a href="?e%5Bf%5D%5Bg%5D=h">?e%5Bf%5D%5Bg%5D=h</a>
|
||||
</div>',
|
||||
7 => '<div>
|
||||
<a href="?i%5Bj%5Bk%5D=l">?i%5Bj%5Bk%5D=l</a>
|
||||
</div>',
|
||||
8 => '<div>
|
||||
<a href="?x=2">?x=2</a>
|
||||
</div>',
|
||||
9 => '<div>
|
||||
<a href="?z%5B0%5D=2">?z%5B0%5D=2</a>
|
||||
</div>',
|
||||
10 => '<div>
|
||||
<a href=""></a>
|
||||
</div>',
|
||||
11 => '<div>Title, no link
|
||||
<a href=""></a>
|
||||
</div>',
|
||||
12 => '<div>
|
||||
<span></span>
|
||||
</div>',
|
||||
13 => '<div>Title, no link
|
||||
<span></span>
|
||||
</div>',
|
||||
14 => '<div>
|
||||
<button type="button"></button>
|
||||
</div>',
|
||||
15 => '<div>Title, button
|
||||
<button type="button"></button>
|
||||
</div>',
|
||||
];
|
||||
|
||||
yield 'default settings' => [
|
||||
'display settings' => [],
|
||||
'expected_results' => $defaultExpectedResults,
|
||||
];
|
||||
|
||||
yield 'trim_length=null' => [
|
||||
'display_settings' => ['trim_length' => NULL],
|
||||
'expected_results' => $defaultExpectedResults,
|
||||
];
|
||||
|
||||
yield 'trim_length=6' => [
|
||||
'display settings' => ['trim_length' => 6],
|
||||
'expected_results' => [
|
||||
0 => '<div>
|
||||
<a href="http://www.example.com/content/articles/archive?author=John&year=2012#com">http:…</a>
|
||||
</div>',
|
||||
1 => '<div>A ver…
|
||||
<a href="http://www.example.org/content/articles/archive?author=John&year=2012#org">http:…</a>
|
||||
</div>',
|
||||
2 => '<div>Fragm…
|
||||
<a href="#net">#net</a>
|
||||
</div>',
|
||||
3 => '<div>
|
||||
<a href="?a%5B0%5D=1&a%5B1%5D=2">?a%5B…</a>
|
||||
</div>',
|
||||
4 => '<div>
|
||||
<a href="?b%5B0%5D=1&b%5B1%5D=2">?b%5B…</a>
|
||||
</div>',
|
||||
16 => '<div>
|
||||
<a href="?b%5B0%5D=9&b%5B1%5D=8">?b%5B…</a>
|
||||
</div>',
|
||||
5 => '<div>
|
||||
<a href="?c%5B0%5D=1&c%5B1%5D=2&d=3">?c%5B…</a>
|
||||
</div>',
|
||||
6 => '<div>
|
||||
<a href="?e%5Bf%5D%5Bg%5D=h">?e%5B…</a>
|
||||
</div>',
|
||||
7 => '<div>
|
||||
<a href="?i%5Bj%5Bk%5D=l">?i%5B…</a>
|
||||
</div>',
|
||||
8 => '<div>
|
||||
<a href="?x=2">?x=2</a>
|
||||
</div>',
|
||||
9 => '<div>
|
||||
<a href="?z%5B0%5D=2">?z%5B…</a>
|
||||
</div>',
|
||||
10 => '<div>
|
||||
<a href=""></a>
|
||||
</div>',
|
||||
11 => '<div>Title…
|
||||
<a href=""></a>
|
||||
</div>',
|
||||
12 => '<div>
|
||||
<span></span>
|
||||
</div>',
|
||||
13 => '<div>Title…
|
||||
<span></span>
|
||||
</div>',
|
||||
14 => '<div>
|
||||
<button type="button"></button>
|
||||
</div>',
|
||||
15 => '<div>Title…
|
||||
<button type="button"></button>
|
||||
</div>',
|
||||
],
|
||||
];
|
||||
|
||||
yield 'attribute rel=null' => [
|
||||
'display_settings' => ['rel' => NULL],
|
||||
'expected_results' => $defaultExpectedResults,
|
||||
];
|
||||
yield 'attribute rel=nofollow' => [
|
||||
'display_settings' => ['rel' => 'nofollow'],
|
||||
'expected_results' => [
|
||||
0 => '<div>
|
||||
<a href="http://www.example.com/content/articles/archive?author=John&year=2012#com" rel="nofollow">http://www.example.com/content/articles/archive?author=John&year=2012#com</a>
|
||||
</div>',
|
||||
1 => '<div>A very long & strange example title that could break the nice layout of the site
|
||||
<a href="http://www.example.org/content/articles/archive?author=John&year=2012#org" rel="nofollow">http://www.example.org/content/articles/archive?author=John&year=2012#org</a>
|
||||
</div>',
|
||||
2 => '<div>Fragment only
|
||||
<a href="#net" rel="nofollow">#net</a>
|
||||
</div>',
|
||||
3 => '<div>
|
||||
<a href="?a%5B0%5D=1&a%5B1%5D=2" rel="nofollow">?a%5B0%5D=1&a%5B1%5D=2</a>
|
||||
</div>',
|
||||
4 => '<div>
|
||||
<a href="?b%5B0%5D=1&b%5B1%5D=2" rel="nofollow">?b%5B0%5D=1&b%5B1%5D=2</a>
|
||||
</div>',
|
||||
16 => '<div>
|
||||
<a href="?b%5B0%5D=9&b%5B1%5D=8" rel="nofollow">?b%5B0%5D=9&b%5B1%5D=8</a>
|
||||
</div>',
|
||||
5 => '<div>
|
||||
<a href="?c%5B0%5D=1&c%5B1%5D=2&d=3" rel="nofollow">?c%5B0%5D=1&c%5B1%5D=2&d=3</a>
|
||||
</div>',
|
||||
6 => '<div>
|
||||
<a href="?e%5Bf%5D%5Bg%5D=h" rel="nofollow">?e%5Bf%5D%5Bg%5D=h</a>
|
||||
</div>',
|
||||
7 => '<div>
|
||||
<a href="?i%5Bj%5Bk%5D=l" rel="nofollow">?i%5Bj%5Bk%5D=l</a>
|
||||
</div>',
|
||||
8 => '<div>
|
||||
<a href="?x=2" rel="nofollow">?x=2</a>
|
||||
</div>',
|
||||
9 => '<div>
|
||||
<a href="?z%5B0%5D=2" rel="nofollow">?z%5B0%5D=2</a>
|
||||
</div>',
|
||||
10 => '<div>
|
||||
<a href="" rel="nofollow"></a>
|
||||
</div>',
|
||||
11 => '<div>Title, no link
|
||||
<a href="" rel="nofollow"></a>
|
||||
</div>',
|
||||
12 => '<div>
|
||||
<span rel="nofollow"></span>
|
||||
</div>',
|
||||
13 => '<div>Title, no link
|
||||
<span rel="nofollow"></span>
|
||||
</div>',
|
||||
14 => '<div>
|
||||
<button rel="nofollow" type="button"></button>
|
||||
</div>',
|
||||
15 => '<div>Title, button
|
||||
<button rel="nofollow" type="button"></button>
|
||||
</div>',
|
||||
],
|
||||
];
|
||||
yield 'attribute target=null' => [
|
||||
'display_settings' => ['target' => NULL],
|
||||
'expected_results' => $defaultExpectedResults,
|
||||
];
|
||||
yield 'attribute target=_blank' => [
|
||||
'display_settings' => ['target' => '_blank'],
|
||||
'expected_results' => [
|
||||
0 => '<div>
|
||||
<a href="http://www.example.com/content/articles/archive?author=John&year=2012#com" target="_blank">http://www.example.com/content/articles/archive?author=John&year=2012#com</a>
|
||||
</div>',
|
||||
1 => '<div>A very long & strange example title that could break the nice layout of the site
|
||||
<a href="http://www.example.org/content/articles/archive?author=John&year=2012#org" target="_blank">http://www.example.org/content/articles/archive?author=John&year=2012#org</a>
|
||||
</div>',
|
||||
2 => '<div>Fragment only
|
||||
<a href="#net" target="_blank">#net</a>
|
||||
</div>',
|
||||
3 => '<div>
|
||||
<a href="?a%5B0%5D=1&a%5B1%5D=2" target="_blank">?a%5B0%5D=1&a%5B1%5D=2</a>
|
||||
</div>',
|
||||
4 => '<div>
|
||||
<a href="?b%5B0%5D=1&b%5B1%5D=2" target="_blank">?b%5B0%5D=1&b%5B1%5D=2</a>
|
||||
</div>',
|
||||
16 => '<div>
|
||||
<a href="?b%5B0%5D=9&b%5B1%5D=8" target="_blank">?b%5B0%5D=9&b%5B1%5D=8</a>
|
||||
</div>',
|
||||
5 => '<div>
|
||||
<a href="?c%5B0%5D=1&c%5B1%5D=2&d=3" target="_blank">?c%5B0%5D=1&c%5B1%5D=2&d=3</a>
|
||||
</div>',
|
||||
6 => '<div>
|
||||
<a href="?e%5Bf%5D%5Bg%5D=h" target="_blank">?e%5Bf%5D%5Bg%5D=h</a>
|
||||
</div>',
|
||||
7 => '<div>
|
||||
<a href="?i%5Bj%5Bk%5D=l" target="_blank">?i%5Bj%5Bk%5D=l</a>
|
||||
</div>',
|
||||
8 => '<div>
|
||||
<a href="?x=2" target="_blank">?x=2</a>
|
||||
</div>',
|
||||
9 => '<div>
|
||||
<a href="?z%5B0%5D=2" target="_blank">?z%5B0%5D=2</a>
|
||||
</div>',
|
||||
10 => '<div>
|
||||
<a href="" target="_blank"></a>
|
||||
</div>',
|
||||
11 => '<div>Title, no link
|
||||
<a href="" target="_blank"></a>
|
||||
</div>',
|
||||
12 => '<div>
|
||||
<span target="_blank"></span>
|
||||
</div>',
|
||||
13 => '<div>Title, no link
|
||||
<span target="_blank"></span>
|
||||
</div>',
|
||||
14 => '<div>
|
||||
<button target="_blank" type="button"></button>
|
||||
</div>',
|
||||
15 => '<div>Title, button
|
||||
<button target="_blank" type="button"></button>
|
||||
</div>',
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,74 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Drupal\Tests\link\Kernel\Plugin\migrate\field\d7;
|
||||
|
||||
use Drupal\KernelTests\KernelTestBase;
|
||||
use Drupal\migrate\Plugin\MigrationInterface;
|
||||
use Drupal\link\Plugin\migrate\field\d7\LinkField;
|
||||
use Prophecy\Argument;
|
||||
|
||||
/**
|
||||
* @coversDefaultClass \Drupal\link\Plugin\migrate\field\d7\LinkField
|
||||
* @group link
|
||||
*/
|
||||
class LinkFieldTest extends KernelTestBase {
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected static $modules = ['system'];
|
||||
|
||||
/**
|
||||
* @var \Drupal\migrate_drupal\Plugin\MigrateFieldInterface
|
||||
*/
|
||||
protected $plugin;
|
||||
|
||||
/**
|
||||
* @var \Drupal\migrate\Plugin\MigrationInterface
|
||||
*/
|
||||
protected $migration;
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function setUp(): void {
|
||||
parent::setUp();
|
||||
|
||||
$this->plugin = new LinkField([], 'link', []);
|
||||
|
||||
$migration = $this->prophesize(MigrationInterface::class);
|
||||
|
||||
// The plugin's alterFieldInstanceMigration() method will call
|
||||
// mergeProcessOfProperty() and return nothing. So, in order to examine the
|
||||
// process pipeline created by the plugin, we need to ensure that
|
||||
// getProcess() always returns the last input to mergeProcessOfProperty().
|
||||
$migration->mergeProcessOfProperty(Argument::type('string'), Argument::type('array'))
|
||||
->will(function ($arguments) use ($migration) {
|
||||
$migration->getProcess()->willReturn($arguments[1]);
|
||||
});
|
||||
|
||||
$this->migration = $migration->reveal();
|
||||
}
|
||||
|
||||
/**
|
||||
* @covers ::alterFieldInstanceMigration
|
||||
*/
|
||||
public function testAlterFieldInstanceMigration($method = 'alterFieldInstanceMigration'): void {
|
||||
$this->plugin->$method($this->migration);
|
||||
|
||||
$expected = [
|
||||
'plugin' => 'static_map',
|
||||
'source' => 'settings/title',
|
||||
'bypass' => TRUE,
|
||||
'map' => [
|
||||
'disabled' => DRUPAL_DISABLED,
|
||||
'optional' => DRUPAL_OPTIONAL,
|
||||
'required' => DRUPAL_REQUIRED,
|
||||
],
|
||||
];
|
||||
$this->assertSame($expected, $this->migration->getProcess());
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,62 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Drupal\Tests\link\Traits;
|
||||
|
||||
/**
|
||||
* Provides test values for the Link field.
|
||||
*/
|
||||
trait LinkInputValuesTraits {
|
||||
|
||||
/**
|
||||
* Link field values use for test.
|
||||
*
|
||||
* @return array
|
||||
* Values to use at link field setter.
|
||||
*/
|
||||
protected function getLinkInputValues(): array {
|
||||
$test_values = [
|
||||
// External links.
|
||||
0 => [
|
||||
'uri' => 'http://www.example.com/content/articles/archive?author=John&year=2012#com',
|
||||
],
|
||||
1 => [
|
||||
'uri' => 'http://www.example.org/content/articles/archive?author=John&year=2012#org',
|
||||
'title' => 'A very long & strange example title that could break the nice layout of the site',
|
||||
],
|
||||
2 => ['uri' => 'internal:#net', 'title' => 'Fragment only'],
|
||||
|
||||
// Complex internal links.
|
||||
// Result link: '?a[0]=1&a[1]=2'.
|
||||
3 => ['uri' => 'internal:?a[]=1&a[]=2'],
|
||||
4 => ['uri' => 'internal:?b[0]=1&b[1]=2'],
|
||||
// Injecting new test value in the middle of array.
|
||||
16 => ['uri' => 'internal:?b[0]=9&b[1]=8'],
|
||||
// UrlHelper::buildQuery will change order of params.
|
||||
// Result link: '?c[0]=1&c[1]=2&d=3'.
|
||||
5 => ['uri' => 'internal:?c[]=1&d=3&c[]=2'],
|
||||
6 => ['uri' => 'internal:?e[f][g]=h'],
|
||||
7 => ['uri' => 'internal:?i[j[k]]=l'],
|
||||
|
||||
// Query string replace value.
|
||||
// Result link: '?x=1&x=2'.
|
||||
8 => ['uri' => 'internal:?x=1&x=2'],
|
||||
// Result link: '?z[0]=2'.
|
||||
9 => ['uri' => 'internal:?z[0]=1&z[0]=2'],
|
||||
|
||||
// Special empty links.
|
||||
10 => ['uri' => 'route:<none>'],
|
||||
11 => ['uri' => 'route:<none>', 'title' => 'Title, no link'],
|
||||
12 => ['uri' => 'route:<nolink>'],
|
||||
13 => ['uri' => 'route:<nolink>', 'title' => 'Title, no link'],
|
||||
14 => ['uri' => 'route:<button>'],
|
||||
15 => ['uri' => 'route:<button>', 'title' => 'Title, button'],
|
||||
|
||||
];
|
||||
// Sort by keys, to be able to inject new test anywhere in the array.
|
||||
ksort($test_values, SORT_NUMERIC);
|
||||
return $test_values;
|
||||
}
|
||||
|
||||
}
|
||||
126
web/core/modules/link/tests/src/Unit/AttributeXssTest.php
Normal file
126
web/core/modules/link/tests/src/Unit/AttributeXssTest.php
Normal file
@ -0,0 +1,126 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Drupal\Tests\link\Unit;
|
||||
|
||||
use Drupal\link\AttributeXss;
|
||||
use Drupal\Tests\UnitTestCase;
|
||||
|
||||
/**
|
||||
* Tests AttributeXss.
|
||||
*
|
||||
* @group link
|
||||
* @covers \Drupal\link\AttributeXss
|
||||
*/
|
||||
final class AttributeXssTest extends UnitTestCase {
|
||||
|
||||
/**
|
||||
* Covers ::sanitizeAttributes.
|
||||
*
|
||||
* @dataProvider providerSanitizeAttributes
|
||||
*/
|
||||
public function testSanitizeAttributes(array $attributes, array $expected): void {
|
||||
self::assertSame($expected, AttributeXss::sanitizeAttributes($attributes));
|
||||
}
|
||||
|
||||
/**
|
||||
* Data provider for ::testSanitizeAttributes.
|
||||
*
|
||||
* @return \Generator
|
||||
* Test cases.
|
||||
*/
|
||||
public static function providerSanitizeAttributes(): \Generator {
|
||||
yield 'safe' => [
|
||||
['class' => ['foo', 'bar'], 'data-biscuit' => TRUE],
|
||||
['class' => ['foo', 'bar'], 'data-biscuit' => TRUE],
|
||||
];
|
||||
|
||||
yield 'valueless' => [
|
||||
['class' => ['foo', 'bar'], 'selected' => ''],
|
||||
['class' => ['foo', 'bar'], 'selected' => ''],
|
||||
];
|
||||
|
||||
yield 'empty names' => [
|
||||
['class' => ['foo', 'bar'], '' => 'live', ' ' => TRUE],
|
||||
['class' => ['foo', 'bar']],
|
||||
];
|
||||
|
||||
yield 'only empty names' => [
|
||||
['' => 'live', ' ' => TRUE],
|
||||
[],
|
||||
];
|
||||
|
||||
yield 'valueless, mangled with a space' => [
|
||||
['class' => ['foo', 'bar'], 'selected href' => 'http://example.com'],
|
||||
['class' => ['foo', 'bar'], 'selected' => 'selected', 'href' => 'http://example.com'],
|
||||
];
|
||||
|
||||
yield 'valueless, mangled with a space, blocked' => [
|
||||
['class' => ['foo', 'bar'], 'selected onclick href' => 'http://example.com'],
|
||||
['class' => ['foo', 'bar'], 'selected' => 'selected', 'href' => 'http://example.com'],
|
||||
];
|
||||
|
||||
yield 'with encoding' => [
|
||||
['class' => ['foo', 'bar'], 'data-how-good' => "It's the bee's knees"],
|
||||
['class' => ['foo', 'bar'], 'data-how-good' => "It's the bee's knees"],
|
||||
];
|
||||
|
||||
yield 'valueless, mangled with multiple spaces, blocked' => [
|
||||
['class' => ['foo', 'bar'], 'selected onclick href' => 'http://example.com'],
|
||||
['class' => ['foo', 'bar'], 'selected' => 'selected', 'href' => 'http://example.com'],
|
||||
];
|
||||
|
||||
yield 'valueless, mangled with multiple spaces, blocked, mangled first' => [
|
||||
['selected onclick href' => 'http://example.com', 'class' => ['foo', 'bar']],
|
||||
['selected' => 'selected', 'href' => 'http://example.com', 'class' => ['foo', 'bar']],
|
||||
];
|
||||
|
||||
yield 'valueless but with value' => [
|
||||
['class' => ['foo', 'bar'], 'selected' => 'selected', 'href' => 'http://example.com'],
|
||||
['class' => ['foo', 'bar'], 'selected' => 'selected', 'href' => 'http://example.com'],
|
||||
];
|
||||
|
||||
yield 'valueless but with value, bad protocol' => [
|
||||
['class' => ['foo', 'bar'], 'selected' => 'selected', 'href' => 'javascript:alert()'],
|
||||
['class' => ['foo', 'bar'], 'selected' => 'selected', 'href' => 'alert()'],
|
||||
];
|
||||
|
||||
yield 'valueless, mangled with a space and bad protocol' => [
|
||||
['class' => ['foo', 'bar'], 'selected href' => 'javascript:alert()'],
|
||||
['class' => ['foo', 'bar'], 'selected' => 'selected', 'href' => 'alert()'],
|
||||
];
|
||||
|
||||
yield 'valueless, mangled with a space and bad protocol, repeated' => [
|
||||
['class' => ['foo', 'bar'], 'selected href' => 'javascript:alert()', 'href' => 'http://example.com'],
|
||||
['class' => ['foo', 'bar'], 'selected' => 'selected', 'href' => 'alert()'],
|
||||
];
|
||||
|
||||
yield 'with a space' => [
|
||||
['class' => ['foo', 'bar'], 'href' => \urlencode('some file.pdf')],
|
||||
['class' => ['foo', 'bar'], 'href' => 'some+file.pdf'],
|
||||
];
|
||||
|
||||
yield 'with an unencoded space' => [
|
||||
['class' => ['foo', 'bar'], 'href' => 'some file.pdf'],
|
||||
['class' => ['foo', 'bar'], 'href' => 'some file.pdf'],
|
||||
];
|
||||
|
||||
yield 'xss onclick' => [
|
||||
['class' => ['foo', 'bar'], 'onclick' => 'alert("whoop");'],
|
||||
['class' => ['foo', 'bar']],
|
||||
];
|
||||
|
||||
yield 'xss onclick, valueless, mangled with a space' => [
|
||||
['class' => ['foo', 'bar'], 'selected onclick href' => 'http://example.com'],
|
||||
['class' => ['foo', 'bar'], 'selected' => 'selected', 'href' => 'http://example.com'],
|
||||
];
|
||||
|
||||
yield 'xss protocol' => [
|
||||
['class' => ['foo', 'bar'], 'src' => 'javascript:alert("whoop");'],
|
||||
['class' => ['foo', 'bar'], 'src' => 'alert("whoop");'],
|
||||
];
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
155
web/core/modules/link/tests/src/Unit/LinkFormatterTest.php
Normal file
155
web/core/modules/link/tests/src/Unit/LinkFormatterTest.php
Normal file
@ -0,0 +1,155 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Drupal\Tests\link\Unit;
|
||||
|
||||
use Drupal\Core\DependencyInjection\ContainerBuilder;
|
||||
use Drupal\Core\Entity\EntityInterface;
|
||||
use Drupal\Core\Field\FieldDefinitionInterface;
|
||||
use Drupal\Core\Field\FieldItemList;
|
||||
use Drupal\Core\Field\FieldTypePluginManagerInterface;
|
||||
use Drupal\Core\Path\PathValidatorInterface;
|
||||
use Drupal\Core\Routing\UrlGenerator;
|
||||
use Drupal\Core\Url;
|
||||
use Drupal\link\LinkItemInterface;
|
||||
use Drupal\link\Plugin\Field\FieldFormatter\LinkFormatter;
|
||||
use Drupal\Tests\UnitTestCase;
|
||||
|
||||
/**
|
||||
* Tests the Field Formatter for the link field type.
|
||||
*
|
||||
* @group link
|
||||
*/
|
||||
class LinkFormatterTest extends UnitTestCase {
|
||||
|
||||
/**
|
||||
* Tests when LinkItem::getUrl with malformed URL renders empty link.
|
||||
*
|
||||
* LinkItem::getUrl will throw \InvalidArgumentException.
|
||||
*/
|
||||
public function testFormatterLinkItemUrlMalformed(): void {
|
||||
$entity = $this->createMock(EntityInterface::class);
|
||||
|
||||
$linkItem = $this->createMock(LinkItemInterface::class);
|
||||
$exception = new \InvalidArgumentException();
|
||||
$linkItem->expects($this->any())
|
||||
->method('getParent')
|
||||
->willReturn($entity);
|
||||
$linkItem->expects($this->once())
|
||||
->method('getUrl')
|
||||
->willThrowException($exception);
|
||||
$linkItem->expects($this->any())
|
||||
->method('__get')
|
||||
->with('options')
|
||||
->willReturn([]);
|
||||
$fieldDefinition = $this->createMock(FieldDefinitionInterface::class);
|
||||
$fieldList = new FieldItemList($fieldDefinition, '', $linkItem);
|
||||
|
||||
$fieldTypePluginManager = $this->createMock(FieldTypePluginManagerInterface::class);
|
||||
$fieldTypePluginManager->expects($this->once())
|
||||
->method('createFieldItem')
|
||||
->willReturn($linkItem);
|
||||
$urlGenerator = $this->createMock(UrlGenerator::class);
|
||||
$urlGenerator->expects($this->once())
|
||||
->method('generateFromRoute')
|
||||
->with('<none>', [], [], FALSE)
|
||||
->willReturn('http://example.com');
|
||||
$container = new ContainerBuilder();
|
||||
$container->set('plugin.manager.field.field_type', $fieldTypePluginManager);
|
||||
$container->set('url_generator', $urlGenerator);
|
||||
\Drupal::setContainer($container);
|
||||
$fieldList->setValue([$linkItem]);
|
||||
|
||||
$pathValidator = $this->createMock(PathValidatorInterface::class);
|
||||
$linkFormatter = new LinkFormatter('', [], $fieldDefinition, [], '', '', [], $pathValidator);
|
||||
$elements = $linkFormatter->viewElements($fieldList, 'es');
|
||||
$this->assertEquals('link', $elements[0]['#type']);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests when LinkItem::getUrl throws an unexpected exception.
|
||||
*/
|
||||
public function testFormatterLinkItemUrlUnexpectedException(): void {
|
||||
$exception = new \Exception('Unexpected!!!');
|
||||
|
||||
$linkItem = $this->createMock(LinkItemInterface::class);
|
||||
$entity = $this->createMock(EntityInterface::class);
|
||||
$linkItem->expects($this->any())
|
||||
->method('getParent')
|
||||
->willReturn($entity);
|
||||
$linkItem->expects($this->once())
|
||||
->method('getUrl')
|
||||
->willThrowException($exception);
|
||||
$linkItem->expects($this->any())
|
||||
->method('__get')
|
||||
->with('options')
|
||||
->willReturn([]);
|
||||
$fieldDefinition = $this->createMock(FieldDefinitionInterface::class);
|
||||
$fieldList = new FieldItemList($fieldDefinition, '', $linkItem);
|
||||
|
||||
$fieldTypePluginManager = $this->createMock(FieldTypePluginManagerInterface::class);
|
||||
$fieldTypePluginManager->expects($this->once())
|
||||
->method('createFieldItem')
|
||||
->willReturn($linkItem);
|
||||
$container = new ContainerBuilder();
|
||||
$container->set('plugin.manager.field.field_type', $fieldTypePluginManager);
|
||||
\Drupal::setContainer($container);
|
||||
$fieldList->setValue([$linkItem]);
|
||||
|
||||
$pathValidator = $this->createMock(PathValidatorInterface::class);
|
||||
$linkFormatter = new LinkFormatter('', [], $fieldDefinition, [], '', '', [], $pathValidator);
|
||||
$this->expectException(\Exception::class);
|
||||
$this->expectExceptionMessage('Unexpected!!!');
|
||||
$linkFormatter->viewElements($fieldList, 'fr');
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests when LinkItem::getUrl returns a functional URL.
|
||||
*/
|
||||
public function testFormatterLinkItem(): void {
|
||||
$expectedUrl = Url::fromUri('route:<front>');
|
||||
|
||||
$linkItem = $this->createMock(LinkItemInterface::class);
|
||||
$entity = $this->createMock(EntityInterface::class);
|
||||
$linkItem->expects($this->any())
|
||||
->method('getParent')
|
||||
->willReturn($entity);
|
||||
$linkItem->expects($this->once())
|
||||
->method('getUrl')
|
||||
->willReturn($expectedUrl);
|
||||
$linkItem->expects($this->any())
|
||||
->method('__get')
|
||||
->with('options')
|
||||
->willReturn([]);
|
||||
$fieldDefinition = $this->createMock(FieldDefinitionInterface::class);
|
||||
$fieldList = new FieldItemList($fieldDefinition, '', $linkItem);
|
||||
|
||||
$fieldTypePluginManager = $this->createMock(FieldTypePluginManagerInterface::class);
|
||||
$fieldTypePluginManager->expects($this->once())
|
||||
->method('createFieldItem')
|
||||
->willReturn($linkItem);
|
||||
$urlGenerator = $this->createMock(UrlGenerator::class);
|
||||
$urlGenerator->expects($this->once())
|
||||
->method('generateFromRoute')
|
||||
->with('<front>', [], [], FALSE)
|
||||
->willReturn('http://example.com');
|
||||
$container = new ContainerBuilder();
|
||||
$container->set('plugin.manager.field.field_type', $fieldTypePluginManager);
|
||||
$container->set('url_generator', $urlGenerator);
|
||||
\Drupal::setContainer($container);
|
||||
$fieldList->setValue([$linkItem]);
|
||||
|
||||
$pathValidator = $this->createMock(PathValidatorInterface::class);
|
||||
$linkFormatter = new LinkFormatter('', [], $fieldDefinition, [], '', '', [], $pathValidator);
|
||||
$elements = $linkFormatter->viewElements($fieldList, 'zh');
|
||||
$this->assertEquals([
|
||||
[
|
||||
'#type' => 'link',
|
||||
'#title' => 'http://example.com',
|
||||
'#url' => $expectedUrl,
|
||||
],
|
||||
], $elements);
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,86 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Drupal\Tests\link\Unit\Plugin\Validation\Constraint;
|
||||
|
||||
use Drupal\link\Plugin\Validation\Constraint\LinkAccessConstraint;
|
||||
use Drupal\link\Plugin\Validation\Constraint\LinkAccessConstraintValidator;
|
||||
use Drupal\Tests\UnitTestCase;
|
||||
use Symfony\Component\Validator\Context\ExecutionContextInterface;
|
||||
|
||||
/**
|
||||
* Tests the LinkAccessConstraintValidator validator.
|
||||
*
|
||||
* @coversDefaultClass \Drupal\link\Plugin\Validation\Constraint\LinkAccessConstraintValidator
|
||||
* @group validation
|
||||
*/
|
||||
class LinkAccessConstraintValidatorTest extends UnitTestCase {
|
||||
|
||||
/**
|
||||
* Tests the access validation constraint for links.
|
||||
*
|
||||
* @covers ::validate
|
||||
* @dataProvider providerValidate
|
||||
*/
|
||||
public function testValidate(bool $mayLinkAnyPage, bool $urlAccess, bool $valid): void {
|
||||
// Mock a Url object that returns a boolean indicating user access.
|
||||
$url = $this->getMockBuilder('Drupal\Core\Url')
|
||||
->disableOriginalConstructor()
|
||||
->getMock();
|
||||
if ($mayLinkAnyPage) {
|
||||
$url->expects($this->never())
|
||||
->method('access');
|
||||
}
|
||||
else {
|
||||
$url->expects($this->once())
|
||||
->method('access')
|
||||
->willReturn($urlAccess);
|
||||
}
|
||||
|
||||
// Mock a link object that returns the URL object.
|
||||
$link = $this->createMock('Drupal\link\LinkItemInterface');
|
||||
$link->expects($this->any())
|
||||
->method('getUrl')
|
||||
->willReturn($url);
|
||||
|
||||
// Mock a user object that returns a boolean indicating user access to all
|
||||
// links.
|
||||
$user = $this->createMock('Drupal\Core\Session\AccountProxyInterface');
|
||||
$user->expects($this->any())
|
||||
->method('hasPermission')
|
||||
->with($this->equalTo('link to any page'))
|
||||
->willReturn($mayLinkAnyPage);
|
||||
|
||||
$context = $this->createMock(ExecutionContextInterface::class);
|
||||
if ($valid) {
|
||||
$context->expects($this->never())
|
||||
->method('addViolation');
|
||||
}
|
||||
else {
|
||||
$context->expects($this->once())
|
||||
->method('addViolation');
|
||||
}
|
||||
|
||||
$constraint = new LinkAccessConstraint();
|
||||
$validate = new LinkAccessConstraintValidator($user);
|
||||
$validate->initialize($context);
|
||||
$validate->validate($link, $constraint);
|
||||
}
|
||||
|
||||
/**
|
||||
* Data provider for LinkAccessConstraintValidator::validate().
|
||||
*
|
||||
* @return array
|
||||
* An array of tests, matching the parameter inputs for testValidate.
|
||||
*
|
||||
* @see \Drupal\Tests\link\LinkAccessConstraintValidatorTest::validate()
|
||||
*/
|
||||
public static function providerValidate(): \Generator {
|
||||
yield [TRUE, TRUE, TRUE];
|
||||
yield [TRUE, FALSE, TRUE];
|
||||
yield [FALSE, TRUE, TRUE];
|
||||
yield [FALSE, FALSE, FALSE];
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,111 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Drupal\Tests\link\Unit\Plugin\Validation\Constraint;
|
||||
|
||||
use Drupal\Component\Utility\UrlHelper;
|
||||
use Drupal\Core\Url;
|
||||
use Drupal\link\Plugin\Validation\Constraint\LinkExternalProtocolsConstraint;
|
||||
use Drupal\link\Plugin\Validation\Constraint\LinkExternalProtocolsConstraintValidator;
|
||||
use Drupal\Tests\UnitTestCase;
|
||||
use Symfony\Component\Validator\Context\ExecutionContextInterface;
|
||||
|
||||
/**
|
||||
* @coversDefaultClass \Drupal\link\Plugin\Validation\Constraint\LinkExternalProtocolsConstraintValidator
|
||||
* @group Link
|
||||
*/
|
||||
class LinkExternalProtocolsConstraintValidatorTest extends UnitTestCase {
|
||||
|
||||
/**
|
||||
* @covers ::validate
|
||||
* @dataProvider providerValidate
|
||||
* @runInSeparateProcess
|
||||
*/
|
||||
public function testValidate($url, $valid): void {
|
||||
$link = $this->createMock('Drupal\link\LinkItemInterface');
|
||||
$link->expects($this->any())
|
||||
->method('getUrl')
|
||||
->willReturn(Url::fromUri($url));
|
||||
$context = $this->createMock(ExecutionContextInterface::class);
|
||||
|
||||
if ($valid) {
|
||||
$context->expects($this->never())
|
||||
->method('addViolation');
|
||||
}
|
||||
else {
|
||||
$context->expects($this->once())
|
||||
->method('addViolation');
|
||||
}
|
||||
|
||||
// Setup some more allowed protocols.
|
||||
UrlHelper::setAllowedProtocols(['http', 'https', 'magnet']);
|
||||
|
||||
$constraint = new LinkExternalProtocolsConstraint();
|
||||
|
||||
$validator = new LinkExternalProtocolsConstraintValidator();
|
||||
$validator->initialize($context);
|
||||
$validator->validate($link, $constraint);
|
||||
}
|
||||
|
||||
/**
|
||||
* Data provider for ::testValidate.
|
||||
*/
|
||||
public static function providerValidate() {
|
||||
$data = [];
|
||||
|
||||
// Test allowed protocols.
|
||||
$data[] = ['http://www.example.com', TRUE];
|
||||
$data[] = ['https://www.example.com', TRUE];
|
||||
// cSpell:disable-next-line
|
||||
$data[] = ['magnet:?xt=urn:sha1:YNCKHTQCWBTRNJIV4WNAE52SJUQCZO5C', TRUE];
|
||||
|
||||
// Invalid protocols.
|
||||
$data[] = ['ftp://ftp.funet.fi/pub/standards/RFC/rfc959.txt', FALSE];
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* @covers ::validate
|
||||
*
|
||||
* @see \Drupal\Core\Url::fromUri
|
||||
*/
|
||||
public function testValidateWithMalformedUri(): void {
|
||||
$link = $this->createMock('Drupal\link\LinkItemInterface');
|
||||
$link->expects($this->any())
|
||||
->method('getUrl')
|
||||
->willThrowException(new \InvalidArgumentException());
|
||||
|
||||
$context = $this->createMock(ExecutionContextInterface::class);
|
||||
$context->expects($this->never())
|
||||
->method('addViolation');
|
||||
|
||||
$constraint = new LinkExternalProtocolsConstraint();
|
||||
|
||||
$validator = new LinkExternalProtocolsConstraintValidator();
|
||||
$validator->initialize($context);
|
||||
$validator->validate($link, $constraint);
|
||||
}
|
||||
|
||||
/**
|
||||
* @covers ::validate
|
||||
*/
|
||||
public function testValidateIgnoresInternalUrls(): void {
|
||||
$link = $this->createMock('Drupal\link\LinkItemInterface');
|
||||
$link->expects($this->any())
|
||||
->method('getUrl')
|
||||
->willReturn(Url::fromRoute('example.test'));
|
||||
|
||||
$context = $this->createMock(ExecutionContextInterface::class);
|
||||
$context->expects($this->never())
|
||||
->method('addViolation');
|
||||
|
||||
$constraint = new LinkExternalProtocolsConstraint();
|
||||
|
||||
$validator = new LinkExternalProtocolsConstraintValidator();
|
||||
$validator->initialize($context);
|
||||
$validator->validate($link, $constraint);
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,118 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Drupal\Tests\link\Unit\Plugin\Validation\Constraint;
|
||||
|
||||
use Drupal\Core\Routing\UrlGeneratorInterface;
|
||||
use Drupal\Core\Url;
|
||||
use Drupal\link\LinkItemInterface;
|
||||
use Drupal\link\Plugin\Validation\Constraint\LinkNotExistingInternalConstraint;
|
||||
use Drupal\link\Plugin\Validation\Constraint\LinkNotExistingInternalConstraintValidator;
|
||||
use Drupal\Tests\UnitTestCase;
|
||||
use PHPUnit\Framework\MockObject\MockObject;
|
||||
use Symfony\Component\Routing\Exception\RouteNotFoundException;
|
||||
use Symfony\Component\Validator\Context\ExecutionContextInterface;
|
||||
|
||||
/**
|
||||
* @coversDefaultClass \Drupal\link\Plugin\Validation\Constraint\LinkNotExistingInternalConstraintValidator
|
||||
* @group Link
|
||||
*/
|
||||
class LinkNotExistingInternalConstraintValidatorTest extends UnitTestCase {
|
||||
|
||||
/**
|
||||
* @covers ::validate
|
||||
*/
|
||||
public function testValidateFromUri(): void {
|
||||
$url = Url::fromUri('https://www.drupal.org');
|
||||
|
||||
$link = $this->createMock(LinkItemInterface::class);
|
||||
$link->expects($this->any())
|
||||
->method('getUrl')
|
||||
->willReturn($url);
|
||||
|
||||
$context = $this->createMock(ExecutionContextInterface::class);
|
||||
$context->expects($this->never())
|
||||
->method('addViolation');
|
||||
|
||||
$this->validate($link, $context);
|
||||
}
|
||||
|
||||
/**
|
||||
* @covers ::validate
|
||||
*/
|
||||
public function testValidateFromRoute(): void {
|
||||
$url = Url::fromRoute('example.existing_route');
|
||||
|
||||
$urlGenerator = $this->createMock(UrlGeneratorInterface::class);
|
||||
$urlGenerator->expects($this->any())
|
||||
->method('generateFromRoute')
|
||||
->with('example.existing_route', [], [])
|
||||
->willReturn('/example/existing');
|
||||
$url->setUrlGenerator($urlGenerator);
|
||||
|
||||
$link = $this->createMock(LinkItemInterface::class);
|
||||
$link->expects($this->any())
|
||||
->method('getUrl')
|
||||
->willReturn($url);
|
||||
|
||||
$context = $this->createMock(ExecutionContextInterface::class);
|
||||
$context->expects($this->never())
|
||||
->method('addViolation');
|
||||
|
||||
$this->validate($link, $context);
|
||||
}
|
||||
|
||||
/**
|
||||
* @covers ::validate
|
||||
*/
|
||||
public function testValidateFromNonExistingRoute(): void {
|
||||
$url = Url::fromRoute('example.not_existing_route');
|
||||
|
||||
$urlGenerator = $this->createMock(UrlGeneratorInterface::class);
|
||||
$urlGenerator->expects($this->any())
|
||||
->method('generateFromRoute')
|
||||
->with('example.not_existing_route', [], [])
|
||||
->willThrowException(new RouteNotFoundException());
|
||||
$url->setUrlGenerator($urlGenerator);
|
||||
|
||||
$link = $this->createMock(LinkItemInterface::class);
|
||||
$link->expects($this->any())
|
||||
->method('getUrl')
|
||||
->willReturn($url);
|
||||
|
||||
$context = $this->createMock(ExecutionContextInterface::class);
|
||||
$context->expects($this->once())
|
||||
->method('addViolation');
|
||||
|
||||
$this->validate($link, $context);
|
||||
}
|
||||
|
||||
/**
|
||||
* @covers ::validate
|
||||
*
|
||||
* @see \Drupal\Core\Url::fromUri
|
||||
*/
|
||||
public function testValidateWithMalformedUri(): void {
|
||||
$link = $this->createMock(LinkItemInterface::class);
|
||||
$link->expects($this->any())
|
||||
->method('getUrl')
|
||||
->willThrowException(new \InvalidArgumentException());
|
||||
|
||||
$context = $this->createMock(ExecutionContextInterface::class);
|
||||
$context->expects($this->never())
|
||||
->method('addViolation');
|
||||
|
||||
$this->validate($link, $context);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate the link.
|
||||
*/
|
||||
protected function validate(LinkItemInterface&MockObject $link, ExecutionContextInterface&MockObject $context): void {
|
||||
$validator = new LinkNotExistingInternalConstraintValidator();
|
||||
$validator->initialize($context);
|
||||
$validator->validate($link, new LinkNotExistingInternalConstraint());
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,67 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Drupal\Tests\link\Unit\Plugin\migrate\field\d6;
|
||||
|
||||
use Drupal\migrate\Plugin\MigrationInterface;
|
||||
use Drupal\Tests\UnitTestCase;
|
||||
use Drupal\link\Plugin\migrate\field\d6\LinkField;
|
||||
use Prophecy\Argument;
|
||||
|
||||
/**
|
||||
* @coversDefaultClass \Drupal\link\Plugin\migrate\field\d6\LinkField
|
||||
* @group link
|
||||
*/
|
||||
class LinkFieldTest extends UnitTestCase {
|
||||
|
||||
/**
|
||||
* The migrate field plugin.
|
||||
*
|
||||
* @var \Drupal\migrate_drupal\Plugin\MigrateFieldInterface
|
||||
*/
|
||||
protected $plugin;
|
||||
|
||||
/**
|
||||
* The migration.
|
||||
*
|
||||
* @var \Drupal\migrate\Plugin\MigrationInterface
|
||||
*/
|
||||
protected $migration;
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function setUp(): void {
|
||||
parent::setUp();
|
||||
|
||||
$this->plugin = new LinkField([], 'link', []);
|
||||
|
||||
$migration = $this->prophesize(MigrationInterface::class);
|
||||
|
||||
// The plugin's defineValueProcessPipeline() method will call
|
||||
// mergeProcessOfProperty() and return nothing. So, in order to examine the
|
||||
// process pipeline created by the plugin, we need to ensure that
|
||||
// getProcess() always returns the last input to mergeProcessOfProperty().
|
||||
$migration->mergeProcessOfProperty(Argument::type('string'), Argument::type('array'))
|
||||
->will(function ($arguments) use ($migration) {
|
||||
$migration->getProcess()->willReturn($arguments[1]);
|
||||
});
|
||||
|
||||
$this->migration = $migration->reveal();
|
||||
}
|
||||
|
||||
/**
|
||||
* @covers ::defineValueProcessPipeline
|
||||
*/
|
||||
public function testDefineValueProcessPipeline($method = 'defineValueProcessPipeline'): void {
|
||||
$this->plugin->$method($this->migration, 'field_name', []);
|
||||
|
||||
$expected = [
|
||||
'plugin' => 'field_link',
|
||||
'source' => 'field_name',
|
||||
];
|
||||
$this->assertSame($expected, $this->migration->getProcess());
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,135 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Drupal\Tests\link\Unit\Plugin\migrate\process;
|
||||
|
||||
use Drupal\link\Plugin\migrate\process\FieldLink;
|
||||
use Drupal\migrate\MigrateExecutableInterface;
|
||||
use Drupal\migrate\Plugin\MigrationInterface;
|
||||
use Drupal\migrate\Row;
|
||||
use Drupal\Tests\UnitTestCase;
|
||||
|
||||
/**
|
||||
* Tests the link field migrate process plugin.
|
||||
*
|
||||
* @group Link
|
||||
*/
|
||||
class FieldLinkTest extends UnitTestCase {
|
||||
|
||||
/**
|
||||
* Tests the URL transformations in the FieldLink process plugin.
|
||||
*
|
||||
* @dataProvider canonicalizeUriDataProvider
|
||||
*/
|
||||
public function testCanonicalizeUri($url, $expected, $configuration = []): void {
|
||||
$link_plugin = new FieldLink($configuration, '', [], $this->createMock(MigrationInterface::class));
|
||||
$transformed = $link_plugin->transform([
|
||||
'url' => $url,
|
||||
'title' => '',
|
||||
'attributes' => serialize([]),
|
||||
], $this->createMock(MigrateExecutableInterface::class), $this->getMockBuilder(Row::class)->disableOriginalConstructor()->getMock(), NULL);
|
||||
$this->assertEquals($expected, $transformed['uri']);
|
||||
}
|
||||
|
||||
/**
|
||||
* Data provider for testCanonicalizeUri.
|
||||
*/
|
||||
public static function canonicalizeUriDataProvider() {
|
||||
return [
|
||||
'Simple front-page' => [
|
||||
'<front>',
|
||||
'internal:/',
|
||||
],
|
||||
'Front page with query' => [
|
||||
'<front>?query=1',
|
||||
'internal:/?query=1',
|
||||
],
|
||||
'No leading forward slash' => [
|
||||
'node/10',
|
||||
'internal:/node/10',
|
||||
],
|
||||
'Leading forward slash' => [
|
||||
'/node/10',
|
||||
'internal:/node/10',
|
||||
],
|
||||
'Existing scheme' => [
|
||||
'scheme:test',
|
||||
'scheme:test',
|
||||
],
|
||||
'Absolute URL with protocol prefix' => [
|
||||
'http://www.google.com',
|
||||
'http://www.google.com',
|
||||
],
|
||||
'Absolute URL without protocol prefix' => [
|
||||
'www.yahoo.com',
|
||||
'http://www.yahoo.com',
|
||||
],
|
||||
'Absolute URL without protocol prefix nor www' => [
|
||||
'yahoo.com',
|
||||
'https://yahoo.com',
|
||||
['uri_scheme' => 'https://'],
|
||||
],
|
||||
'Absolute URL without explicit protocol (protocol-relative)' => [
|
||||
'//example.com',
|
||||
'http://example.com',
|
||||
],
|
||||
'Absolute URL with non-standard characters' => [
|
||||
'http://www.ßÀÑÐ¥ƒå¢ë.com',
|
||||
'http://www.ßÀÑÐ¥ƒå¢ë.com',
|
||||
],
|
||||
'Absolute URL with non-standard characters, without protocol prefix' => [
|
||||
'www.ÐØÑ¢åþë.com',
|
||||
'http://www.ÐØÑ¢åþë.com',
|
||||
],
|
||||
'Absolute URL with non-standard top level domain' => [
|
||||
'http://www.example.xxx',
|
||||
'http://www.example.xxx',
|
||||
],
|
||||
'Internal link with fragment' => [
|
||||
'/node/10#top',
|
||||
'internal:/node/10#top',
|
||||
],
|
||||
'External link with fragment' => [
|
||||
'http://www.example.com/page#links',
|
||||
'http://www.example.com/page#links',
|
||||
],
|
||||
'empty' => [
|
||||
'',
|
||||
'route:<nolink>',
|
||||
],
|
||||
'No link' => [
|
||||
'<nolink>',
|
||||
'route:<nolink>',
|
||||
],
|
||||
'none' => [
|
||||
'<none>',
|
||||
'route:<nolink>',
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the attributes that are deeply serialized are discarded.
|
||||
*/
|
||||
public function testCanonicalizeUriSerialized(): void {
|
||||
$link_plugin = new FieldLink([], '', [], $this->createMock(MigrationInterface::class));
|
||||
$migrate_executable = $this->createMock(MigrateExecutableInterface::class);
|
||||
$row = new Row();
|
||||
|
||||
$transformed = $link_plugin->transform([
|
||||
'url' => '',
|
||||
'title' => '',
|
||||
'attributes' => serialize(serialize(['not too deep'])),
|
||||
], $migrate_executable, $row, NULL);
|
||||
$this->assertEquals(['not too deep'], $transformed['options']['attributes']);
|
||||
|
||||
$transformed = $link_plugin->transform([
|
||||
'url' => '',
|
||||
'title' => '',
|
||||
'attributes' => serialize(serialize(serialize(['too deep']))),
|
||||
], $migrate_executable, $row, NULL);
|
||||
$this->assertEmpty($transformed['options']['attributes']);
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,5 @@
|
||||
name: 'Link Test Theme'
|
||||
type: theme
|
||||
description: 'Theme for testing link module'
|
||||
version: VERSION
|
||||
base theme: stark
|
||||
@ -0,0 +1,19 @@
|
||||
{#
|
||||
/**
|
||||
* @file
|
||||
* Theme override of a link with separate title and URL elements.
|
||||
*
|
||||
* Available variables:
|
||||
* - link: The link that has already been formatted by l().
|
||||
* - title: (optional) A descriptive or alternate title for the link, which may
|
||||
* be different than the actual link text.
|
||||
*
|
||||
* @see template_preprocess_link_formatter_link_separate()
|
||||
*/
|
||||
#}
|
||||
<div class="link-item">
|
||||
{%- if title -%}
|
||||
<div class="link-title">{{- title -}}</div>
|
||||
{%- endif -%}
|
||||
<div class="link-url">{{- link -}}</div>
|
||||
</div>
|
||||
Reference in New Issue
Block a user