LinkFieldTest.php 33 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\Entity\Entity\EntityViewDisplay;
8
use Drupal\Core\Link;
9
use Drupal\Core\Url;
10
use Drupal\entity_test\Entity\EntityTest;
11
use Drupal\field\Entity\FieldConfig;
12
use Drupal\link\LinkItemInterface;
13
use Drupal\node\NodeInterface;
14
use Drupal\Tests\BrowserTestBase;
15
use Drupal\field\Entity\FieldStorageConfig;
16 17 18

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

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

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

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

50
  protected function setUp() {
51 52
    parent::setUp();

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

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

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

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

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

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

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

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

132 133 134 135
      // @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',
136
      '<front>?example=llama' => '&lt;front&gt;?example=llama',
137

138 139 140 141 142
      // Text-only links.
      '<nolink>' => '&lt;nolink&gt;',
      'route:<nolink>' => '&lt;nolink&gt;',
      '<none>' => '&lt;none&gt;',

143 144 145 146 147 148 149 150 151
      // 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.
152
      'entity:node/' . $restricted_node->id() => '- Restricted access - (' . $restricted_node->id() . ')',
153 154
      // URI for an entity that doesn't exist, but with a valid ID.
      'entity:user/999999' => 'entity:user/999999',
155
    ];
156

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

    // 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.
179
    $this->field->setSetting('link_type', LinkItemInterface::LINK_EXTERNAL);
180
    $this->field->save();
181 182 183 184
    $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.
185
    $this->field->setSetting('link_type', LinkItemInterface::LINK_INTERNAL);
186
    $this->field->save();
187 188
    $this->assertValidEntries($field_name, $valid_internal_entries);
    $this->assertInvalidEntries($field_name, $valid_external_entries + $invalid_internal_entries);
189 190 191 192 193 194 195 196

    // 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]);
197 198 199 200 201 202 203 204 205 206 207
  }

  /**
   * 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) {
208
    foreach ($valid_entries as $uri => $string) {
209
      $edit = [
210
        "{$field_name}[0][uri]" => $uri,
211
      ];
212
      $this->drupalPostForm('entity_test/add', $edit, t('Save'));
213
      preg_match('|entity_test/manage/(\d+)|', $this->getUrl(), $match);
214
      $id = $match[1];
215
      $this->assertText(t('entity_test @id has been created.', ['@id' => $id]));
216
      $this->assertRaw('"' . $string . '"');
217 218 219 220 221 222 223 224 225 226 227 228
    }
  }

  /**
   * 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) {
229
    foreach ($invalid_entries as $invalid_value => $error_message) {
230
      $edit = [
231
        "{$field_name}[0][uri]" => $invalid_value,
232
      ];
233
      $this->drupalPostForm('entity_test/add', $edit, t('Save'));
234
      $this->assertText(t($error_message, ['@link_path' => $invalid_value]));
235 236 237 238
    }
  }

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

278
    // Verify that the link text field works according to the field setting.
279
    foreach ([DRUPAL_DISABLED, DRUPAL_REQUIRED, DRUPAL_OPTIONAL] as $title_setting) {
280
      // Update the link title field setting.
281
      $this->field->setSetting('title', $title_setting);
282
      $this->field->save();
283 284

      // Display creation form.
285
      $this->drupalGet('entity_test/add');
286 287
      // Assert label is shown.
      $this->assertText('Read more about this entity');
288
      $this->assertFieldByName("{$field_name}[0][uri]", '', 'URL field found.');
289
      $this->assertRaw('placeholder="http://example.com"');
290 291

      if ($title_setting === DRUPAL_DISABLED) {
292
        $this->assertNoFieldByName("{$field_name}[0][title]", '', 'Link text field not found.');
293
        $this->assertNoRaw('placeholder="Enter the text for this link"');
294 295
      }
      else {
296
        $this->assertRaw('placeholder="Enter the text for this link"');
297

298
        $this->assertFieldByName("{$field_name}[0][title]", '', 'Link text field found.');
299 300 301 302 303 304 305 306
        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')]));
        }
307
        if ($title_setting === DRUPAL_REQUIRED) {
308
          // Verify that the link text is required, if the URL is non-empty.
309
          $edit = [
310
            "{$field_name}[0][uri]" => 'http://www.example.com',
311
          ];
312
          $this->drupalPostForm(NULL, $edit, t('Save'));
313
          $this->assertText(t('@title field is required if there is @uri input.', ['@title' => t('Link text'), '@uri' => t('URL')]));
314

315
          // Verify that the link text is not required, if the URL is empty.
316
          $edit = [
317
            "{$field_name}[0][uri]" => '',
318
          ];
319
          $this->drupalPostForm(NULL, $edit, t('Save'));
320
          $this->assertNoText(t('@name field is required.', ['@name' => t('Link text')]));
321

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

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

345
    $output = $this->renderTestEntity($id);
346
    $expected_link = (string) Link::fromTextAndUrl($value, Url::fromUri($value))->toString();
347
    $this->assertContains($expected_link, $output);
348

349
    // Verify that a link with text is rendered using the link text.
350
    $title = $this->randomMachineName();
351
    $edit = [
352
      "{$field_name}[0][title]" => $title,
353
    ];
354
    $this->drupalPostForm("entity_test/manage/$id/edit", $edit, t('Save'));
355
    $this->assertText(t('entity_test @id has been updated.', ['@id' => $id]));
356

357
    $output = $this->renderTestEntity($id);
358
    $expected_link = (string) Link::fromTextAndUrl($title, Url::fromUri($value))->toString();
359
    $this->assertContains($expected_link, $output);
360 361 362 363 364
  }

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

399
    // Create an entity with three link field values:
400
    // - The first field item uses a URL only.
401
    // - The second field item uses a URL and link text.
402
    // - The third field item uses a fragment-only URL with text.
403 404
    // For consistency in assertion code below, the URL is assigned to the title
    // variable for the first field.
405
    $this->drupalGet('entity_test/add');
406 407
    $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';
408
    $url3 = '#net';
409 410 411
    $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';
412
    $title3 = 'Fragment only';
413
    $edit = [
414
      "{$field_name}[0][uri]" => $url1,
415
      // Note that $title1 is not submitted.
416
      "{$field_name}[0][title]" => '',
417
      "{$field_name}[1][uri]" => $url2,
418
      "{$field_name}[1][title]" => $title2,
419 420
      "{$field_name}[2][uri]" => $url3,
      "{$field_name}[2][title]" => $title3,
421
    ];
422 423
    // Assert label is shown.
    $this->assertText('Read more about this entity');
424
    $this->drupalPostForm(NULL, $edit, t('Save'));
425
    preg_match('|entity_test/manage/(\d+)|', $this->getUrl(), $match);
426
    $id = $match[1];
427
    $this->assertText(t('entity_test @id has been created.', ['@id' => $id]));
428 429 430 431

    // 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
432 433
    // the link generator and options/attributes. Only 'url_plain' has a
    // dependency on 'url_only', so we have a total of ~10 cases.
434 435 436 437 438 439 440 441 442 443 444
    $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],
      ],
    ];
445 446 447 448
    foreach ($options as $setting => $values) {
      foreach ($values as $new_value) {
        // Update the field formatter settings.
        if (!is_array($new_value)) {
449
          $display_options['settings'] = [$setting => $new_value];
450 451
        }
        else {
452
          $display_options['settings'] = $new_value;
453
        }
454
        $display_repository->getViewDisplay('entity_test', 'entity_test', 'full')
455
          ->setComponent($field_name, $display_options)
456
          ->save();
457

458
        $output = $this->renderTestEntity($id);
459 460 461
        switch ($setting) {
          case 'trim_length':
            $url = $url1;
462
            $title = isset($new_value) ? Unicode::truncate($title1, $new_value, FALSE, TRUE) : $title1;
463
            $this->assertContains('<a href="' . Html::escape($url) . '">' . Html::escape($title) . '</a>', $output);
464 465

            $url = $url2;
466
            $title = isset($new_value) ? Unicode::truncate($title2, $new_value, FALSE, TRUE) : $title2;
467
            $this->assertContains('<a href="' . Html::escape($url) . '">' . Html::escape($title) . '</a>', $output);
468 469 470

            $url = $url3;
            $title = isset($new_value) ? Unicode::truncate($title3, $new_value, FALSE, TRUE) : $title3;
471
            $this->assertContains('<a href="' . Html::escape($url) . '">' . Html::escape($title) . '</a>', $output);
472 473 474 475
            break;

          case 'rel':
            $rel = isset($new_value) ? ' rel="' . $new_value . '"' : '';
476 477 478
            $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);
479 480 481 482
            break;

          case 'target':
            $target = isset($new_value) ? ' target="' . $new_value . '"' : '';
483 484 485
            $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);
486 487 488 489 490
            break;

          case 'url_only':
            // In this case, $new_value is an array.
            if (!$new_value['url_only']) {
491 492 493
              $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);
494 495 496
            }
            else {
              if (empty($new_value['url_plain'])) {
497 498 499
                $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);
500 501
              }
              else {
502 503 504 505 506 507
                $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);
508 509 510 511 512 513 514 515 516 517 518 519 520 521
              }
            }
            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.
   */
522
  public function testLinkSeparateFormatter() {
523
    $field_name = mb_strtolower($this->randomMachineName());
524
    // Create a field with settings to validate.
525
    $this->fieldStorage = FieldStorageConfig::create([
526
      'field_name' => $field_name,
527
      'entity_type' => 'entity_test',
528
      'type' => 'link',
529
      'cardinality' => 3,
530
    ]);
531
    $this->fieldStorage->save();
532
    FieldConfig::create([
533
      'field_storage' => $this->fieldStorage,
534
      'bundle' => 'entity_test',
535
      'settings' => [
536
        'title' => DRUPAL_OPTIONAL,
537
        'link_type' => LinkItemInterface::LINK_GENERIC,
538
      ],
539
    ])->save();
540
    $display_options = [
541 542
      'type' => 'link_separate',
      'label' => 'hidden',
543
    ];
544 545 546
    /** @var \Drupal\Core\Entity\EntityDisplayRepositoryInterface $display_repository */
    $display_repository = \Drupal::service('entity_display.repository');
    $display_repository->getFormDisplay('entity_test', 'entity_test')
547
      ->setComponent($field_name, [
548
        'type' => 'link_default',
549
      ])
550
      ->save();
551
    $display_repository->getViewDisplay('entity_test', 'entity_test', 'full')
552
      ->setComponent($field_name, $display_options)
553 554
      ->save();

555
    // Create an entity with three link field values:
556
    // - The first field item uses a URL only.
557
    // - The second field item uses a URL and link text.
558
    // - The third field item uses a fragment-only URL with text.
559 560
    // For consistency in assertion code below, the URL is assigned to the title
    // variable for the first field.
561
    $this->drupalGet('entity_test/add');
562 563
    $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';
564
    $url3 = '#net';
565 566
    // 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';
567
    $title3 = 'Fragment only';
568
    $edit = [
569 570
      "{$field_name}[0][uri]" => $url1,
      "{$field_name}[1][uri]" => $url2,
571
      "{$field_name}[1][title]" => $title2,
572 573
      "{$field_name}[2][uri]" => $url3,
      "{$field_name}[2][title]" => $title3,
574
    ];
575
    $this->drupalPostForm(NULL, $edit, t('Save'));
576
    preg_match('|entity_test/manage/(\d+)|', $this->getUrl(), $match);
577
    $id = $match[1];
578
    $this->assertText(t('entity_test @id has been created.', ['@id' => $id]));
579 580

    // Verify that the link is output according to the formatter settings.
581 582 583 584 585
    $options = [
      'trim_length' => [NULL, 6],
      'rel' => [NULL, 'nofollow'],
      'target' => [NULL, '_blank'],
    ];
586 587 588
    foreach ($options as $setting => $values) {
      foreach ($values as $new_value) {
        // Update the field formatter settings.
589
        $display_options['settings'] = [$setting => $new_value];
590
        $display_repository->getViewDisplay('entity_test', 'entity_test', 'full')
591
          ->setComponent($field_name, $display_options)
592
          ->save();
593

594
        $output = $this->renderTestEntity($id);
595 596 597
        switch ($setting) {
          case 'trim_length':
            $url = $url1;
598
            $url_title = isset($new_value) ? Unicode::truncate($url, $new_value, FALSE, TRUE) : $url;
599
            $expected = '<div class="link-item">';
600
            $expected .= '<div class="link-url"><a href="' . Html::escape($url) . '">' . Html::escape($url_title) . '</a></div>';
601
            $expected .= '</div>';
602
            $this->assertContains($expected, $output);
603 604

            $url = $url2;
605 606
            $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;
607
            $expected = '<div class="link-item">';
608 609
            $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>';
610
            $expected .= '</div>';
611
            $this->assertContains($expected, $output);
612 613 614 615 616 617 618 619

            $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>';
620
            $this->assertContains($expected, $output);
621 622 623 624
            break;

          case 'rel':
            $rel = isset($new_value) ? ' rel="' . $new_value . '"' : '';
625 626 627
            $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);
628 629 630 631
            break;

          case 'target':
            $target = isset($new_value) ? ' target="' . $new_value . '"' : '';
632 633 634
            $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);
635 636 637 638 639 640
            break;
        }
      }
    }
  }

641 642 643 644 645 646 647 648 649 650 651
  /**
   * 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;
652
    $field_name = mb_strtolower($this->randomMachineName());
653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671

    // 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();

672
    $this->container->get('entity_type.manager')
673 674 675 676 677 678 679 680 681 682 683
      ->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);
  }

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