LinkFieldTest.php 30.6 KB
Newer Older
1 2
<?php

3
namespace Drupal\Tests\link\Functional;
4

5
use Drupal\Component\Utility\Html;
6
use Drupal\Component\Utility\Unicode;
7
use Drupal\Core\Url;
8
use Drupal\entity_test\Entity\EntityTest;
9
use Drupal\field\Entity\FieldConfig;
10
use Drupal\link\LinkItemInterface;
11
use Drupal\node\NodeInterface;
12
use Drupal\Tests\BrowserTestBase;
13
use Drupal\field\Entity\FieldStorageConfig;
14 15 16

/**
 * Tests link field widgets and formatters.
17 18
 *
 * @group link
19
 */
20
class LinkFieldTest extends BrowserTestBase {
21 22 23 24 25 26

  /**
   * Modules to enable.
   *
   * @var array
   */
27
  public static $modules = [
28 29 30 31 32
    'entity_test',
    'link',
    'node',
    'link_test_base_field',
  ];
33

34 35 36
  /**
   * A field to use in this test class.
   *
37
   * @var \Drupal\field\Entity\FieldStorageConfig
38
   */
39
  protected $fieldStorage;
40 41 42 43

  /**
   * The instance used in this test class.
   *
44
   * @var \Drupal\field\Entity\FieldConfig
45
   */
46
  protected $field;
47

48
  protected function setUp() {
49 50
    parent::setUp();

51
    $this->drupalLogin($this->drupalCreateUser([
52 53
      'view test entity',
      'administer entity_test content',
54
      'link to any page',
55
    ]));
56 57 58 59 60
  }

  /**
   * Tests link field URL validation.
   */
61
  public function testURLValidation() {
62
    $field_name = mb_strtolower($this->randomMachineName());
63
    // Create a field with settings to validate.
64
    $this->fieldStorage = FieldStorageConfig::create([
65
      'field_name' => $field_name,
66
      'entity_type' => 'entity_test',
67
      'type' => 'link',
68
    ]);
69
    $this->fieldStorage->save();
70
    $this->field = FieldConfig::create([
71
      'field_storage' => $this->fieldStorage,
72
      'bundle' => 'entity_test',
73
      'settings' => [
74
        'title' => DRUPAL_DISABLED,
75
        'link_type' => LinkItemInterface::LINK_GENERIC,
76
      ],
77
    ]);
78
    $this->field->save();
79 80 81
    /** @var \Drupal\Core\Entity\EntityDisplayRepositoryInterface $display_repository */
    $display_repository = \Drupal::service('entity_display.repository');
    $display_repository->getFormDisplay('entity_test', 'entity_test')
82
      ->setComponent($field_name, [
83
        'type' => 'link_default',
84
        'settings' => [
85
          'placeholder_url' => 'http://example.com',
86 87
        ],
      ])
88
      ->save();
89
    $display_repository->getViewDisplay('entity_test', 'entity_test', 'full')
90
      ->setComponent($field_name, [
91
        'type' => 'link',
92
      ])
93 94
      ->save();

95
    // Display creation form.
96
    $this->drupalGet('entity_test/add');
97
    $this->assertFieldByName("{$field_name}[0][uri]", '', 'Link URL field is displayed');
98
    $this->assertRaw('placeholder="http://example.com"');
99

100
    // Create a path alias.
101
    \Drupal::service('path.alias_storage')->save('/admin', '/a/path/alias');
102 103 104 105

    // Create a node to test the link widget.
    $node = $this->drupalCreateNode();

106
    $restricted_node = $this->drupalCreateNode(['status' => NodeInterface::NOT_PUBLISHED]);
107

108 109
    // Define some valid URLs (keys are the entered values, values are the
    // strings displayed to the user).
110
    $valid_external_entries = [
111
      'http://www.example.com/' => 'http://www.example.com/',
112 113 114 115
      // 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)',
116 117
    ];
    $valid_internal_entries = [
118 119 120 121 122 123 124 125
      '/entity_test/add' => '/entity_test/add',
      '/a/path/alias' => '/a/path/alias',

      // Front page, with query string and fragment.
      '/' => '&lt;front&gt;',
      '/?example=llama' => '&lt;front&gt;?example=llama',
      '/#example' => '&lt;front&gt;#example',

126 127 128 129
      // Trailing spaces should be ignored.
      '/ ' => '&lt;front&gt;',
      '/path with spaces ' => '/path with spaces',

130 131 132 133
      // @todo '<front>' is valid input for BC reasons, may be removed by
      //   https://www.drupal.org/node/2421941
      '<front>' => '&lt;front&gt;',
      '<front>#example' => '&lt;front&gt;#example',
134
      '<front>?example=llama' => '&lt;front&gt;?example=llama',
135 136 137 138 139 140 141 142 143 144

      // Query string and fragment.
      '?example=llama' => '?example=llama',
      '#example' => '#example',

      // Entity reference autocomplete value.
      $node->label() . ' (1)' => $node->label() . ' (1)',
      // Entity URI displayed as ER autocomplete value when displayed in a form.
      'entity:node/1' => $node->label() . ' (1)',
      // URI for an entity that exists, but is not accessible by the user.
145
      'entity:node/' . $restricted_node->id() => '- Restricted access - (' . $restricted_node->id() . ')',
146 147
      // URI for an entity that doesn't exist, but with a valid ID.
      'entity:user/999999' => 'entity:user/999999',
148
    ];
149

150
    // Define some invalid URLs.
151
    $validation_error_1 = "The path '@link_path' is invalid.";
152
    $validation_error_2 = 'Manually entered paths should start with one of the following characters: / ? #';
153
    $validation_error_3 = "The path '@link_path' is inaccessible.";
154
    $invalid_external_entries = [
155
      // Invalid protocol
156
      'invalid://not-a-valid-protocol' => $validation_error_1,
157
      // Missing host name
158
      'http://' => $validation_error_1,
159 160
    ];
    $invalid_internal_entries = [
161 162
      'no-leading-slash' => $validation_error_2,
      'entity:non_existing_entity_type/yar' => $validation_error_1,
163 164
      // URI for an entity that doesn't exist, with an invalid ID.
      'entity:user/invalid-parameter' => $validation_error_1,
165
    ];
166 167 168 169 170 171

    // 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.
172
    $this->field->setSetting('link_type', LinkItemInterface::LINK_EXTERNAL);
173
    $this->field->save();
174 175 176 177
    $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.
178
    $this->field->setSetting('link_type', LinkItemInterface::LINK_INTERNAL);
179
    $this->field->save();
180 181
    $this->assertValidEntries($field_name, $valid_internal_entries);
    $this->assertInvalidEntries($field_name, $valid_external_entries + $invalid_internal_entries);
182 183 184 185 186 187 188 189

    // 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]);
190 191 192 193 194 195 196 197 198 199 200
  }

  /**
   * Asserts that valid URLs can be submitted.
   *
   * @param string $field_name
   *   The field name.
   * @param array $valid_entries
   *   An array of valid URL entries.
   */
  protected function assertValidEntries($field_name, array $valid_entries) {
201
    foreach ($valid_entries as $uri => $string) {
202
      $edit = [
203
        "{$field_name}[0][uri]" => $uri,
204
      ];
205
      $this->drupalPostForm('entity_test/add', $edit, t('Save'));
206
      preg_match('|entity_test/manage/(\d+)|', $this->getUrl(), $match);
207
      $id = $match[1];
208
      $this->assertText(t('entity_test @id has been created.', ['@id' => $id]));
209
      $this->assertRaw('"' . $string . '"');
210 211 212 213 214 215 216 217 218 219 220 221
    }
  }

  /**
   * Asserts that invalid URLs cannot be submitted.
   *
   * @param string $field_name
   *   The field name.
   * @param array $invalid_entries
   *   An array of invalid URL entries.
   */
  protected function assertInvalidEntries($field_name, array $invalid_entries) {
222
    foreach ($invalid_entries as $invalid_value => $error_message) {
223
      $edit = [
224
        "{$field_name}[0][uri]" => $invalid_value,
225
      ];
226
      $this->drupalPostForm('entity_test/add', $edit, t('Save'));
227
      $this->assertText(t($error_message, ['@link_path' => $invalid_value]));
228 229 230 231
    }
  }

  /**
232
   * Tests the link title settings of a link field.
233
   */
234
  public function testLinkTitle() {
235
    $field_name = mb_strtolower($this->randomMachineName());
236
    // Create a field with settings to validate.
237
    $this->fieldStorage = FieldStorageConfig::create([
238
      'field_name' => $field_name,
239
      'entity_type' => 'entity_test',
240
      'type' => 'link',
241
    ]);
242
    $this->fieldStorage->save();
243
    $this->field = FieldConfig::create([
244
      'field_storage' => $this->fieldStorage,
245
      'bundle' => 'entity_test',
246
      'label' => 'Read more about this entity',
247
      'settings' => [
248
        'title' => DRUPAL_OPTIONAL,
249
        'link_type' => LinkItemInterface::LINK_GENERIC,
250
      ],
251
    ]);
252
    $this->field->save();
253 254 255
    /** @var \Drupal\Core\Entity\EntityDisplayRepositoryInterface $display_repository */
    $display_repository = \Drupal::service('entity_display.repository');
    $display_repository->getFormDisplay('entity_test', 'entity_test')
256
      ->setComponent($field_name, [
257
        'type' => 'link_default',
258
        'settings' => [
259
          'placeholder_url' => 'http://example.com',
260
          'placeholder_title' => 'Enter the text for this link',
261 262
        ],
      ])
263
      ->save();
264
    $display_repository->getViewDisplay('entity_test', 'entity_test', 'full')
265
      ->setComponent($field_name, [
266 267
        'type' => 'link',
        'label' => 'hidden',
268
      ])
269 270
      ->save();

271
    // Verify that the link text field works according to the field setting.
272
    foreach ([DRUPAL_DISABLED, DRUPAL_REQUIRED, DRUPAL_OPTIONAL] as $title_setting) {
273
      // Update the link title field setting.
274
      $this->field->setSetting('title', $title_setting);
275
      $this->field->save();
276 277

      // Display creation form.
278
      $this->drupalGet('entity_test/add');
279 280
      // Assert label is shown.
      $this->assertText('Read more about this entity');
281
      $this->assertFieldByName("{$field_name}[0][uri]", '', 'URL field found.');
282
      $this->assertRaw('placeholder="http://example.com"');
283 284

      if ($title_setting === DRUPAL_DISABLED) {
285
        $this->assertNoFieldByName("{$field_name}[0][title]", '', 'Link text field not found.');
286
        $this->assertNoRaw('placeholder="Enter the text for this link"');
287 288
      }
      else {
289
        $this->assertRaw('placeholder="Enter the text for this link"');
290

291
        $this->assertFieldByName("{$field_name}[0][title]", '', 'Link text field found.');
292 293 294 295 296 297 298 299
        if ($title_setting === DRUPAL_OPTIONAL) {
          // Verify that the URL is required, if the link text is non-empty.
          $edit = [
            "{$field_name}[0][title]" => 'Example',
          ];
          $this->drupalPostForm(NULL, $edit, t('Save'));
          $this->assertText(t('The URL field is required when the @title field is specified.', ['@title' => t('Link text')]));
        }
300
        if ($title_setting === DRUPAL_REQUIRED) {
301
          // Verify that the link text is required, if the URL is non-empty.
302
          $edit = [
303
            "{$field_name}[0][uri]" => 'http://www.example.com',
304
          ];
305
          $this->drupalPostForm(NULL, $edit, t('Save'));
306
          $this->assertText(t('@title field is required if there is @uri input.', ['@title' => t('Link text'), '@uri' => t('URL')]));
307

308
          // Verify that the link text is not required, if the URL is empty.
309
          $edit = [
310
            "{$field_name}[0][uri]" => '',
311
          ];
312
          $this->drupalPostForm(NULL, $edit, t('Save'));
313
          $this->assertNoText(t('@name field is required.', ['@name' => t('Link text')]));
314

315
          // Verify that a URL and link text meets requirements.
316
          $this->drupalGet('entity_test/add');
317
          $edit = [
318
            "{$field_name}[0][uri]" => 'http://www.example.com',
319
            "{$field_name}[0][title]" => 'Example',
320
          ];
321
          $this->drupalPostForm(NULL, $edit, t('Save'));
322
          $this->assertNoText(t('@name field is required.', ['@name' => t('Link text')]));
323 324 325 326
        }
      }
    }

327
    // Verify that a link without link text is rendered using the URL as text.
328
    $value = 'http://www.example.com/';
329
    $edit = [
330
      "{$field_name}[0][uri]" => $value,
331
      "{$field_name}[0][title]" => '',
332
    ];
333
    $this->drupalPostForm(NULL, $edit, t('Save'));
334
    preg_match('|entity_test/manage/(\d+)|', $this->getUrl(), $match);
335
    $id = $match[1];
336
    $this->assertText(t('entity_test @id has been created.', ['@id' => $id]));
337

338 339 340
    $output = $this->renderTestEntity($id);
    $expected_link = (string) \Drupal::l($value, Url::fromUri($value));
    $this->assertContains($expected_link, $output);
341

342
    // Verify that a link with text is rendered using the link text.
343
    $title = $this->randomMachineName();
344
    $edit = [
345
      "{$field_name}[0][title]" => $title,
346
    ];
347
    $this->drupalPostForm("entity_test/manage/$id/edit", $edit, t('Save'));
348
    $this->assertText(t('entity_test @id has been updated.', ['@id' => $id]));
349

350 351 352
    $output = $this->renderTestEntity($id);
    $expected_link = (string) \Drupal::l($title, Url::fromUri($value));
    $this->assertContains($expected_link, $output);
353 354 355 356 357
  }

  /**
   * Tests the default 'link' formatter.
   */
358
  public function testLinkFormatter() {
359
    $field_name = mb_strtolower($this->randomMachineName());
360
    // Create a field with settings to validate.
361
    $this->fieldStorage = FieldStorageConfig::create([
362
      'field_name' => $field_name,
363
      'entity_type' => 'entity_test',
364
      'type' => 'link',
365
      'cardinality' => 3,
366
    ]);
367
    $this->fieldStorage->save();
368
    FieldConfig::create([
369
      'field_storage' => $this->fieldStorage,
370
      'label' => 'Read more about this entity',
371
      'bundle' => 'entity_test',
372
      'settings' => [
373
        'title' => DRUPAL_OPTIONAL,
374
        'link_type' => LinkItemInterface::LINK_GENERIC,
375
      ],
376
    ])->save();
377 378 379
    /** @var \Drupal\Core\Entity\EntityDisplayRepositoryInterface $display_repository */
    $display_repository = \Drupal::service('entity_display.repository');
    $display_repository->getFormDisplay('entity_test', 'entity_test')
380
      ->setComponent($field_name, [
381
        'type' => 'link_default',
382
      ])
383
      ->save();
384
    $display_options = [
385 386
      'type' => 'link',
      'label' => 'hidden',
387
    ];
388
    $display_repository->getViewDisplay('entity_test', 'entity_test', 'full')
389
      ->setComponent($field_name, $display_options)
390 391
      ->save();

392
    // Create an entity with three link field values:
393
    // - The first field item uses a URL only.
394
    // - The second field item uses a URL and link text.
395
    // - The third field item uses a fragment-only URL with text.
396 397
    // For consistency in assertion code below, the URL is assigned to the title
    // variable for the first field.
398
    $this->drupalGet('entity_test/add');
399 400
    $url1 = 'http://www.example.com/content/articles/archive?author=John&year=2012#com';
    $url2 = 'http://www.example.org/content/articles/archive?author=John&year=2012#org';
401
    $url3 = '#net';
402 403 404
    $title1 = $url1;
    // Intentionally contains an ampersand that needs sanitization on output.
    $title2 = 'A very long & strange example title that could break the nice layout of the site';
405
    $title3 = 'Fragment only';
406
    $edit = [
407
      "{$field_name}[0][uri]" => $url1,
408
      // Note that $title1 is not submitted.
409
      "{$field_name}[0][title]" => '',
410
      "{$field_name}[1][uri]" => $url2,
411
      "{$field_name}[1][title]" => $title2,
412 413
      "{$field_name}[2][uri]" => $url3,
      "{$field_name}[2][title]" => $title3,
414
    ];
415 416
    // Assert label is shown.
    $this->assertText('Read more about this entity');
417
    $this->drupalPostForm(NULL, $edit, t('Save'));
418
    preg_match('|entity_test/manage/(\d+)|', $this->getUrl(), $match);
419
    $id = $match[1];
420
    $this->assertText(t('entity_test @id has been created.', ['@id' => $id]));
421 422 423 424

    // Verify that the link is output according to the formatter settings.
    // Not using generatePermutations(), since that leads to 32 cases, which
    // would not test actual link field formatter functionality but rather
425 426
    // the link generator and options/attributes. Only 'url_plain' has a
    // dependency on 'url_only', so we have a total of ~10 cases.
427 428 429 430 431 432 433 434 435 436 437
    $options = [
      'trim_length' => [NULL, 6],
      'rel' => [NULL, 'nofollow'],
      'target' => [NULL, '_blank'],
      'url_only' => [
        ['url_only' => FALSE],
        ['url_only' => FALSE, 'url_plain' => TRUE],
        ['url_only' => TRUE],
        ['url_only' => TRUE, 'url_plain' => TRUE],
      ],
    ];
438 439 440 441
    foreach ($options as $setting => $values) {
      foreach ($values as $new_value) {
        // Update the field formatter settings.
        if (!is_array($new_value)) {
442
          $display_options['settings'] = [$setting => $new_value];
443 444
        }
        else {
445
          $display_options['settings'] = $new_value;
446
        }
447
        $display_repository->getViewDisplay('entity_test', 'entity_test', 'full')
448
          ->setComponent($field_name, $display_options)
449
          ->save();
450

451
        $output = $this->renderTestEntity($id);
452 453 454
        switch ($setting) {
          case 'trim_length':
            $url = $url1;
455
            $title = isset($new_value) ? Unicode::truncate($title1, $new_value, FALSE, TRUE) : $title1;
456
            $this->assertContains('<a href="' . Html::escape($url) . '">' . Html::escape($title) . '</a>', $output);
457 458

            $url = $url2;
459
            $title = isset($new_value) ? Unicode::truncate($title2, $new_value, FALSE, TRUE) : $title2;
460
            $this->assertContains('<a href="' . Html::escape($url) . '">' . Html::escape($title) . '</a>', $output);
461 462 463

            $url = $url3;
            $title = isset($new_value) ? Unicode::truncate($title3, $new_value, FALSE, TRUE) : $title3;
464
            $this->assertContains('<a href="' . Html::escape($url) . '">' . Html::escape($title) . '</a>', $output);
465 466 467 468
            break;

          case 'rel':
            $rel = isset($new_value) ? ' rel="' . $new_value . '"' : '';
469 470 471
            $this->assertContains('<a href="' . Html::escape($url1) . '"' . $rel . '>' . Html::escape($title1) . '</a>', $output);
            $this->assertContains('<a href="' . Html::escape($url2) . '"' . $rel . '>' . Html::escape($title2) . '</a>', $output);
            $this->assertContains('<a href="' . Html::escape($url3) . '"' . $rel . '>' . Html::escape($title3) . '</a>', $output);
472 473 474 475
            break;

          case 'target':
            $target = isset($new_value) ? ' target="' . $new_value . '"' : '';
476 477 478
            $this->assertContains('<a href="' . Html::escape($url1) . '"' . $target . '>' . Html::escape($title1) . '</a>', $output);
            $this->assertContains('<a href="' . Html::escape($url2) . '"' . $target . '>' . Html::escape($title2) . '</a>', $output);
            $this->assertContains('<a href="' . Html::escape($url3) . '"' . $target . '>' . Html::escape($title3) . '</a>', $output);
479 480 481 482 483
            break;

          case 'url_only':
            // In this case, $new_value is an array.
            if (!$new_value['url_only']) {
484 485 486
              $this->assertContains('<a href="' . Html::escape($url1) . '">' . Html::escape($title1) . '</a>', $output);
              $this->assertContains('<a href="' . Html::escape($url2) . '">' . Html::escape($title2) . '</a>', $output);
              $this->assertContains('<a href="' . Html::escape($url3) . '">' . Html::escape($title3) . '</a>', $output);
487 488 489
            }
            else {
              if (empty($new_value['url_plain'])) {
490 491 492
                $this->assertContains('<a href="' . Html::escape($url1) . '">' . Html::escape($url1) . '</a>', $output);
                $this->assertContains('<a href="' . Html::escape($url2) . '">' . Html::escape($url2) . '</a>', $output);
                $this->assertContains('<a href="' . Html::escape($url3) . '">' . Html::escape($url3) . '</a>', $output);
493 494
              }
              else {
495 496 497 498 499 500
                $this->assertNotContains('<a href="' . Html::escape($url1) . '">' . Html::escape($url1) . '</a>', $output);
                $this->assertNotContains('<a href="' . Html::escape($url2) . '">' . Html::escape($url2) . '</a>', $output);
                $this->assertNotContains('<a href="' . Html::escape($url3) . '">' . Html::escape($url3) . '</a>', $output);
                $this->assertContains(Html::escape($url1), $output);
                $this->assertContains(Html::escape($url2), $output);
                $this->assertContains(Html::escape($url3), $output);
501 502 503 504 505 506 507 508 509 510 511 512 513 514
              }
            }
            break;
        }
      }
    }
  }

  /**
   * Tests the 'link_separate' formatter.
   *
   * This test is mostly the same as testLinkFormatter(), but they cannot be
   * merged, since they involve different configuration and output.
   */
515
  public function testLinkSeparateFormatter() {
516
    $field_name = mb_strtolower($this->randomMachineName());
517
    // Create a field with settings to validate.
518
    $this->fieldStorage = FieldStorageConfig::create([
519
      'field_name' => $field_name,
520
      'entity_type' => 'entity_test',
521
      'type' => 'link',
522
      'cardinality' => 3,
523
    ]);
524
    $this->fieldStorage->save();
525
    FieldConfig::create([
526
      'field_storage' => $this->fieldStorage,
527
      'bundle' => 'entity_test',
528
      'settings' => [
529
        'title' => DRUPAL_OPTIONAL,
530
        'link_type' => LinkItemInterface::LINK_GENERIC,
531
      ],
532
    ])->save();
533
    $display_options = [
534 535
      'type' => 'link_separate',
      'label' => 'hidden',
536
    ];
537 538 539
    /** @var \Drupal\Core\Entity\EntityDisplayRepositoryInterface $display_repository */
    $display_repository = \Drupal::service('entity_display.repository');
    $display_repository->getFormDisplay('entity_test', 'entity_test')
540
      ->setComponent($field_name, [
541
        'type' => 'link_default',
542
      ])
543
      ->save();
544
    $display_repository->getViewDisplay('entity_test', 'entity_test', 'full')
545
      ->setComponent($field_name, $display_options)
546 547
      ->save();

548
    // Create an entity with three link field values:
549
    // - The first field item uses a URL only.
550
    // - The second field item uses a URL and link text.
551
    // - The third field item uses a fragment-only URL with text.
552 553
    // For consistency in assertion code below, the URL is assigned to the title
    // variable for the first field.
554
    $this->drupalGet('entity_test/add');
555 556
    $url1 = 'http://www.example.com/content/articles/archive?author=John&year=2012#com';
    $url2 = 'http://www.example.org/content/articles/archive?author=John&year=2012#org';
557
    $url3 = '#net';
558 559
    // Intentionally contains an ampersand that needs sanitization on output.
    $title2 = 'A very long & strange example title that could break the nice layout of the site';
560
    $title3 = 'Fragment only';
561
    $edit = [
562 563
      "{$field_name}[0][uri]" => $url1,
      "{$field_name}[1][uri]" => $url2,
564
      "{$field_name}[1][title]" => $title2,
565 566
      "{$field_name}[2][uri]" => $url3,
      "{$field_name}[2][title]" => $title3,
567
    ];
568
    $this->drupalPostForm(NULL, $edit, t('Save'));
569
    preg_match('|entity_test/manage/(\d+)|', $this->getUrl(), $match);
570
    $id = $match[1];
571
    $this->assertText(t('entity_test @id has been created.', ['@id' => $id]));
572 573

    // Verify that the link is output according to the formatter settings.
574 575 576 577 578
    $options = [
      'trim_length' => [NULL, 6],
      'rel' => [NULL, 'nofollow'],
      'target' => [NULL, '_blank'],
    ];
579 580 581
    foreach ($options as $setting => $values) {
      foreach ($values as $new_value) {
        // Update the field formatter settings.
582
        $display_options['settings'] = [$setting => $new_value];
583
        $display_repository->getViewDisplay('entity_test', 'entity_test', 'full')
584
          ->setComponent($field_name, $display_options)
585
          ->save();
586

587
        $output = $this->renderTestEntity($id);
588 589 590
        switch ($setting) {
          case 'trim_length':
            $url = $url1;
591
            $url_title = isset($new_value) ? Unicode::truncate($url, $new_value, FALSE, TRUE) : $url;
592
            $expected = '<div class="link-item">';
593
            $expected .= '<div class="link-url"><a href="' . Html::escape($url) . '">' . Html::escape($url_title) . '</a></div>';
594
            $expected .= '</div>';
595
            $this->assertContains($expected, $output);
596 597

            $url = $url2;
598 599
            $url_title = isset($new_value) ? Unicode::truncate($url, $new_value, FALSE, TRUE) : $url;
            $title = isset($new_value) ? Unicode::truncate($title2, $new_value, FALSE, TRUE) : $title2;
600
            $expected = '<div class="link-item">';
601 602
            $expected .= '<div class="link-title">' . Html::escape($title) . '</div>';
            $expected .= '<div class="link-url"><a href="' . Html::escape($url) . '">' . Html::escape($url_title) . '</a></div>';
603
            $expected .= '</div>';
604
            $this->assertContains($expected, $output);
605 606 607 608 609 610 611 612

            $url = $url3;
            $url_title = isset($new_value) ? Unicode::truncate($url, $new_value, FALSE, TRUE) : $url;
            $title = isset($new_value) ? Unicode::truncate($title3, $new_value, FALSE, TRUE) : $title3;
            $expected = '<div class="link-item">';
            $expected .= '<div class="link-title">' . Html::escape($title) . '</div>';
            $expected .= '<div class="link-url"><a href="' . Html::escape($url) . '">' . Html::escape($url_title) . '</a></div>';
            $expected .= '</div>';
613
            $this->assertContains($expected, $output);
614 615 616 617
            break;

          case 'rel':
            $rel = isset($new_value) ? ' rel="' . $new_value . '"' : '';
618 619 620
            $this->assertContains('<div class="link-url"><a href="' . Html::escape($url1) . '"' . $rel . '>' . Html::escape($url1) . '</a></div>', $output);
            $this->assertContains('<div class="link-url"><a href="' . Html::escape($url2) . '"' . $rel . '>' . Html::escape($url2) . '</a></div>', $output);
            $this->assertContains('<div class="link-url"><a href="' . Html::escape($url3) . '"' . $rel . '>' . Html::escape($url3) . '</a></div>', $output);
621 622 623 624
            break;

          case 'target':
            $target = isset($new_value) ? ' target="' . $new_value . '"' : '';
625 626 627
            $this->assertContains('<div class="link-url"><a href="' . Html::escape($url1) . '"' . $target . '>' . Html::escape($url1) . '</a></div>', $output);
            $this->assertContains('<div class="link-url"><a href="' . Html::escape($url2) . '"' . $target . '>' . Html::escape($url2) . '</a></div>', $output);
            $this->assertContains('<div class="link-url"><a href="' . Html::escape($url3) . '"' . $target . '>' . Html::escape($url3) . '</a></div>', $output);
628 629 630 631 632 633
            break;
        }
      }
    }
  }

634 635 636 637 638 639 640 641 642 643 644
  /**
   * Test '#link_type' property exists on 'link_default' widget.
   *
   * Make sure the 'link_default' widget exposes a '#link_type' property on
   * its element. Modules can use it to understand if a text form element is
   * a link and also which LinkItemInterface::LINK_* is (EXTERNAL, GENERIC,
   * INTERNAL).
   */
  public function testLinkTypeOnLinkWidget() {

    $link_type = LinkItemInterface::LINK_EXTERNAL;
645
    $field_name = mb_strtolower($this->randomMachineName());
646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676

    // Create a field with settings to validate.
    $this->fieldStorage = FieldStorageConfig::create([
      'field_name' => $field_name,
      'entity_type' => 'entity_test',
      'type' => 'link',
      'cardinality' => 1,
    ]);
    $this->fieldStorage->save();
    FieldConfig::create([
      'field_storage' => $this->fieldStorage,
      'label' => 'Read more about this entity',
      'bundle' => 'entity_test',
      'settings' => [
        'title' => DRUPAL_OPTIONAL,
        'link_type' => $link_type,
      ],
    ])->save();

    $this->container->get('entity.manager')
      ->getStorage('entity_form_display')
      ->load('entity_test.entity_test.default')
      ->setComponent($field_name, [
        'type' => 'link_default',
      ])
      ->save();

    $form = \Drupal::service('entity.form_builder')->getForm(EntityTest::create());
    $this->assertEqual($form[$field_name]['widget'][0]['uri']['#link_type'], $link_type);
  }

677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736
  /**
   * Tests editing a link to a non-node entity.
   */
  public function testEditNonNodeEntityLink() {

    $entity_type_manager = \Drupal::entityTypeManager();
    $entity_test_storage = $entity_type_manager->getStorage('entity_test');

    // Create a field with settings to validate.
    $this->fieldStorage = FieldStorageConfig::create([
      'field_name' => 'field_link',
      'entity_type' => 'entity_test',
      'type' => 'link',
      'cardinality' => 1,
    ]);
    $this->fieldStorage->save();
    FieldConfig::create([
      'field_storage' => $this->fieldStorage,
      'label' => 'Read more about this entity',
      'bundle' => 'entity_test',
      'settings' => [
        'title' => DRUPAL_OPTIONAL,
      ],
    ])->save();

    $entity_type_manager
      ->getStorage('entity_form_display')
      ->load('entity_test.entity_test.default')
      ->setComponent('field_link', [
        'type' => 'link_default',
      ])
      ->save();

    // Create a node and a test entity to have a possibly valid reference for
    // both. Create another test entity that references the first test entity.
    $entity_test_link = $entity_test_storage->create(['name' => 'correct link target']);
    $entity_test_link->save();

    $node = $this->drupalCreateNode(['wrong link target']);

    $correct_link = 'entity:entity_test/' . $entity_test_link->id();
    $entity_test = $entity_test_storage->create([
      'name' => 'correct link target',
      'field_link' => $correct_link,
    ]);
    $entity_test->save();

    // Edit the entity and save it, verify the correct link is kept and not
    // changed to point to a node. Currently, widget does not support non-node
    // autocomplete and therefore must show the link unaltered.
    $this->drupalGet($entity_test->toUrl('edit-form'));
    $this->assertSession()->fieldValueEquals('field_link[0][uri]', $correct_link);
    $this->drupalPostForm(NULL, [], 'Save');

    $entity_test_storage->resetCache();
    $entity_test = $entity_test_storage->load($entity_test->id());

    $this->assertEquals($correct_link, $entity_test->get('field_link')->uri);
  }

737
  /**
738
   * Renders a test_entity and returns the output.
739