LinkFieldTest.php 27.2 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\Tests\BrowserTestBase;
12
use Drupal\field\Entity\FieldStorageConfig;
13 14 15

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

  /**
   * Modules to enable.
   *
   * @var array
   */
26
  public static $modules = ['entity_test', 'link', 'node'];
27

28 29 30
  /**
   * A field to use in this test class.
   *
31
   * @var \Drupal\field\Entity\FieldStorageConfig
32
   */
33
  protected $fieldStorage;
34 35 36 37

  /**
   * The instance used in this test class.
   *
38
   * @var \Drupal\field\Entity\FieldConfig
39
   */
40
  protected $field;
41

42
  protected function setUp() {
43 44
    parent::setUp();

45
    $this->drupalLogin($this->drupalCreateUser([
46 47
      'view test entity',
      'administer entity_test content',
48
      'link to any page',
49
    ]));
50 51 52 53 54
  }

  /**
   * Tests link field URL validation.
   */
55
  public function testURLValidation() {
56
    $field_name = Unicode::strtolower($this->randomMachineName());
57
    // Create a field with settings to validate.
58
    $this->fieldStorage = FieldStorageConfig::create([
59
      'field_name' => $field_name,
60
      'entity_type' => 'entity_test',
61
      'type' => 'link',
62
    ]);
63
    $this->fieldStorage->save();
64
    $this->field = FieldConfig::create([
65
      'field_storage' => $this->fieldStorage,
66
      'bundle' => 'entity_test',
67
      'settings' => [
68
        'title' => DRUPAL_DISABLED,
69
        'link_type' => LinkItemInterface::LINK_GENERIC,
70
      ],
71
    ]);
72
    $this->field->save();
73
    entity_get_form_display('entity_test', 'entity_test', 'default')
74
      ->setComponent($field_name, [
75
        'type' => 'link_default',
76
        'settings' => [
77
          'placeholder_url' => 'http://example.com',
78 79
        ],
      ])
80
      ->save();
81
    entity_get_display('entity_test', 'entity_test', 'full')
82
      ->setComponent($field_name, [
83
        'type' => 'link',
84
      ])
85 86
      ->save();

87
    // Display creation form.
88
    $this->drupalGet('entity_test/add');
89
    $this->assertFieldByName("{$field_name}[0][uri]", '', 'Link URL field is displayed');
90
    $this->assertRaw('placeholder="http://example.com"');
91

92
    // Create a path alias.
93
    \Drupal::service('path.alias_storage')->save('/admin', '/a/path/alias');
94 95 96 97

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

98 99 100 101 102 103
    // Create an entity with restricted view access.
    $entity_test_no_label_access = EntityTest::create([
      'name' => 'forbid_access',
    ]);
    $entity_test_no_label_access->save();

104 105
    // Define some valid URLs (keys are the entered values, values are the
    // strings displayed to the user).
106
    $valid_external_entries = [
107
      'http://www.example.com/' => 'http://www.example.com/',
108 109 110 111
      // 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)',
112 113
    ];
    $valid_internal_entries = [
114 115 116 117 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',

      // @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',
126
      '<front>?example=llama' => '&lt;front&gt;?example=llama',
127 128 129 130 131 132 133 134 135 136

      // 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.
137
      'entity:entity_test/' . $entity_test_no_label_access->id() => '- Restricted access - (' . $entity_test_no_label_access->id() . ')',
138 139
      // URI for an entity that doesn't exist, but with a valid ID.
      'entity:user/999999' => 'entity:user/999999',
140
    ];
141

142
    // Define some invalid URLs.
143
    $validation_error_1 = "The path '@link_path' is invalid.";
144
    $validation_error_2 = 'Manually entered paths should start with /, ? or #.';
145
    $validation_error_3 = "The path '@link_path' is inaccessible.";
146
    $invalid_external_entries = [
147
      // Invalid protocol
148
      'invalid://not-a-valid-protocol' => $validation_error_1,
149
      // Missing host name
150
      'http://' => $validation_error_1,
151 152
    ];
    $invalid_internal_entries = [
153 154
      'no-leading-slash' => $validation_error_2,
      'entity:non_existing_entity_type/yar' => $validation_error_1,
155 156
      // URI for an entity that doesn't exist, with an invalid ID.
      'entity:user/invalid-parameter' => $validation_error_1,
157
    ];
158 159 160 161 162 163

    // 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.
164
    $this->field->setSetting('link_type', LinkItemInterface::LINK_EXTERNAL);
165
    $this->field->save();
166 167 168 169
    $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.
170
    $this->field->setSetting('link_type', LinkItemInterface::LINK_INTERNAL);
171
    $this->field->save();
172 173
    $this->assertValidEntries($field_name, $valid_internal_entries);
    $this->assertInvalidEntries($field_name, $valid_external_entries + $invalid_internal_entries);
174 175 176 177 178 179 180 181

    // 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]);
182 183 184 185 186 187 188 189 190 191 192
  }

  /**
   * 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) {
193
    foreach ($valid_entries as $uri => $string) {
194
      $edit = [
195
        "{$field_name}[0][uri]" => $uri,
196
      ];
197
      $this->drupalPostForm('entity_test/add', $edit, t('Save'));
198
      preg_match('|entity_test/manage/(\d+)|', $this->getUrl(), $match);
199
      $id = $match[1];
200
      $this->assertText(t('entity_test @id has been created.', ['@id' => $id]));
201
      $this->assertRaw($string);
202 203 204 205 206 207 208 209 210 211 212 213
    }
  }

  /**
   * 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) {
214
    foreach ($invalid_entries as $invalid_value => $error_message) {
215
      $edit = [
216
        "{$field_name}[0][uri]" => $invalid_value,
217
      ];
218
      $this->drupalPostForm('entity_test/add', $edit, t('Save'));
219
      $this->assertText(t($error_message, ['@link_path' => $invalid_value]));
220 221 222 223
    }
  }

  /**
224
   * Tests the link title settings of a link field.
225
   */
226
  public function testLinkTitle() {
227
    $field_name = Unicode::strtolower($this->randomMachineName());
228
    // Create a field with settings to validate.
229
    $this->fieldStorage = FieldStorageConfig::create([
230
      'field_name' => $field_name,
231
      'entity_type' => 'entity_test',
232
      'type' => 'link',
233
    ]);
234
    $this->fieldStorage->save();
235
    $this->field = FieldConfig::create([
236
      'field_storage' => $this->fieldStorage,
237
      'bundle' => 'entity_test',
238
      'label' => 'Read more about this entity',
239
      'settings' => [
240
        'title' => DRUPAL_OPTIONAL,
241
        'link_type' => LinkItemInterface::LINK_GENERIC,
242
      ],
243
    ]);
244
    $this->field->save();
245
    entity_get_form_display('entity_test', 'entity_test', 'default')
246
      ->setComponent($field_name, [
247
        'type' => 'link_default',
248
        'settings' => [
249
          'placeholder_url' => 'http://example.com',
250
          'placeholder_title' => 'Enter the text for this link',
251 252
        ],
      ])
253
      ->save();
254
    entity_get_display('entity_test', 'entity_test', 'full')
255
      ->setComponent($field_name, [
256 257
        'type' => 'link',
        'label' => 'hidden',
258
      ])
259 260
      ->save();

261
    // Verify that the link text field works according to the field setting.
262
    foreach ([DRUPAL_DISABLED, DRUPAL_REQUIRED, DRUPAL_OPTIONAL] as $title_setting) {
263
      // Update the link title field setting.
264
      $this->field->setSetting('title', $title_setting);
265
      $this->field->save();
266 267

      // Display creation form.
268
      $this->drupalGet('entity_test/add');
269 270
      // Assert label is shown.
      $this->assertText('Read more about this entity');
271
      $this->assertFieldByName("{$field_name}[0][uri]", '', 'URL field found.');
272
      $this->assertRaw('placeholder="http://example.com"');
273 274

      if ($title_setting === DRUPAL_DISABLED) {
275
        $this->assertNoFieldByName("{$field_name}[0][title]", '', 'Link text field not found.');
276
        $this->assertNoRaw('placeholder="Enter the text for this link"');
277 278
      }
      else {
279
        $this->assertRaw('placeholder="Enter the text for this link"');
280

281
        $this->assertFieldByName("{$field_name}[0][title]", '', 'Link text field found.');
282
        if ($title_setting === DRUPAL_REQUIRED) {
283
          // Verify that the link text is required, if the URL is non-empty.
284
          $edit = [
285
            "{$field_name}[0][uri]" => 'http://www.example.com',
286
          ];
287
          $this->drupalPostForm(NULL, $edit, t('Save'));
288
          $this->assertText(t('@name field is required.', ['@name' => t('Link text')]));
289

290
          // Verify that the link text is not required, if the URL is empty.
291
          $edit = [
292
            "{$field_name}[0][uri]" => '',
293
          ];
294
          $this->drupalPostForm(NULL, $edit, t('Save'));
295
          $this->assertNoText(t('@name field is required.', ['@name' => t('Link text')]));
296

297
          // Verify that a URL and link text meets requirements.
298
          $this->drupalGet('entity_test/add');
299
          $edit = [
300
            "{$field_name}[0][uri]" => 'http://www.example.com',
301
            "{$field_name}[0][title]" => 'Example',
302
          ];
303
          $this->drupalPostForm(NULL, $edit, t('Save'));
304
          $this->assertNoText(t('@name field is required.', ['@name' => t('Link text')]));
305 306 307 308
        }
      }
    }

309
    // Verify that a link without link text is rendered using the URL as text.
310
    $value = 'http://www.example.com/';
311
    $edit = [
312
      "{$field_name}[0][uri]" => $value,
313
      "{$field_name}[0][title]" => '',
314
    ];
315
    $this->drupalPostForm(NULL, $edit, t('Save'));
316
    preg_match('|entity_test/manage/(\d+)|', $this->getUrl(), $match);
317
    $id = $match[1];
318
    $this->assertText(t('entity_test @id has been created.', ['@id' => $id]));
319

320 321 322
    $output = $this->renderTestEntity($id);
    $expected_link = (string) \Drupal::l($value, Url::fromUri($value));
    $this->assertContains($expected_link, $output);
323

324
    // Verify that a link with text is rendered using the link text.
325
    $title = $this->randomMachineName();
326
    $edit = [
327
      "{$field_name}[0][title]" => $title,
328
    ];
329
    $this->drupalPostForm("entity_test/manage/$id/edit", $edit, t('Save'));
330
    $this->assertText(t('entity_test @id has been updated.', ['@id' => $id]));
331

332 333 334
    $output = $this->renderTestEntity($id);
    $expected_link = (string) \Drupal::l($title, Url::fromUri($value));
    $this->assertContains($expected_link, $output);
335 336 337 338 339
  }

  /**
   * Tests the default 'link' formatter.
   */
340
  public function testLinkFormatter() {
341
    $field_name = Unicode::strtolower($this->randomMachineName());
342
    // Create a field with settings to validate.
343
    $this->fieldStorage = FieldStorageConfig::create([
344
      'field_name' => $field_name,
345
      'entity_type' => 'entity_test',
346
      'type' => 'link',
347
      'cardinality' => 3,
348
    ]);
349
    $this->fieldStorage->save();
350
    FieldConfig::create([
351
      'field_storage' => $this->fieldStorage,
352
      'label' => 'Read more about this entity',
353
      'bundle' => 'entity_test',
354
      'settings' => [
355
        'title' => DRUPAL_OPTIONAL,
356
        'link_type' => LinkItemInterface::LINK_GENERIC,
357
      ],
358
    ])->save();
359
    entity_get_form_display('entity_test', 'entity_test', 'default')
360
      ->setComponent($field_name, [
361
        'type' => 'link_default',
362
      ])
363
      ->save();
364
    $display_options = [
365 366
      'type' => 'link',
      'label' => 'hidden',
367
    ];
368
    entity_get_display('entity_test', 'entity_test', 'full')
369
      ->setComponent($field_name, $display_options)
370 371
      ->save();

372
    // Create an entity with three link field values:
373
    // - The first field item uses a URL only.
374
    // - The second field item uses a URL and link text.
375
    // - The third field item uses a fragment-only URL with text.
376 377
    // For consistency in assertion code below, the URL is assigned to the title
    // variable for the first field.
378
    $this->drupalGet('entity_test/add');
379 380
    $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';
381
    $url3 = '#net';
382 383 384
    $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';
385
    $title3 = 'Fragment only';
386
    $edit = [
387
      "{$field_name}[0][uri]" => $url1,
388
      // Note that $title1 is not submitted.
389
      "{$field_name}[0][title]" => '',
390
      "{$field_name}[1][uri]" => $url2,
391
      "{$field_name}[1][title]" => $title2,
392 393
      "{$field_name}[2][uri]" => $url3,
      "{$field_name}[2][title]" => $title3,
394
    ];
395 396
    // Assert label is shown.
    $this->assertText('Read more about this entity');
397
    $this->drupalPostForm(NULL, $edit, t('Save'));
398
    preg_match('|entity_test/manage/(\d+)|', $this->getUrl(), $match);
399
    $id = $match[1];
400
    $this->assertText(t('entity_test @id has been created.', ['@id' => $id]));
401 402 403 404

    // 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
405 406
    // the link generator and options/attributes. Only 'url_plain' has a
    // dependency on 'url_only', so we have a total of ~10 cases.
407 408 409 410 411 412 413 414 415 416 417
    $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],
      ],
    ];
418 419 420 421
    foreach ($options as $setting => $values) {
      foreach ($values as $new_value) {
        // Update the field formatter settings.
        if (!is_array($new_value)) {
422
          $display_options['settings'] = [$setting => $new_value];
423 424
        }
        else {
425
          $display_options['settings'] = $new_value;
426
        }
427
        entity_get_display('entity_test', 'entity_test', 'full')
428
          ->setComponent($field_name, $display_options)
429
          ->save();
430

431
        $output = $this->renderTestEntity($id);
432 433 434
        switch ($setting) {
          case 'trim_length':
            $url = $url1;
435
            $title = isset($new_value) ? Unicode::truncate($title1, $new_value, FALSE, TRUE) : $title1;
436
            $this->assertContains('<a href="' . Html::escape($url) . '">' . Html::escape($title) . '</a>', $output);
437 438

            $url = $url2;
439
            $title = isset($new_value) ? Unicode::truncate($title2, $new_value, FALSE, TRUE) : $title2;
440
            $this->assertContains('<a href="' . Html::escape($url) . '">' . Html::escape($title) . '</a>', $output);
441 442 443

            $url = $url3;
            $title = isset($new_value) ? Unicode::truncate($title3, $new_value, FALSE, TRUE) : $title3;
444
            $this->assertContains('<a href="' . Html::escape($url) . '">' . Html::escape($title) . '</a>', $output);
445 446 447 448
            break;

          case 'rel':
            $rel = isset($new_value) ? ' rel="' . $new_value . '"' : '';
449 450 451
            $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);
452 453 454 455
            break;

          case 'target':
            $target = isset($new_value) ? ' target="' . $new_value . '"' : '';
456 457 458
            $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);
459 460 461 462 463
            break;

          case 'url_only':
            // In this case, $new_value is an array.
            if (!$new_value['url_only']) {
464 465 466
              $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);
467 468 469
            }
            else {
              if (empty($new_value['url_plain'])) {
470 471 472
                $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);
473 474
              }
              else {
475 476 477 478 479 480
                $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);
481 482 483 484 485 486 487 488 489 490 491 492 493 494
              }
            }
            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.
   */
495
  public function testLinkSeparateFormatter() {
496
    $field_name = Unicode::strtolower($this->randomMachineName());
497
    // Create a field with settings to validate.
498
    $this->fieldStorage = FieldStorageConfig::create([
499
      'field_name' => $field_name,
500
      'entity_type' => 'entity_test',
501
      'type' => 'link',
502
      'cardinality' => 3,
503
    ]);
504
    $this->fieldStorage->save();
505
    FieldConfig::create([
506
      'field_storage' => $this->fieldStorage,
507
      'bundle' => 'entity_test',
508
      'settings' => [
509
        'title' => DRUPAL_OPTIONAL,
510
        'link_type' => LinkItemInterface::LINK_GENERIC,
511
      ],
512
    ])->save();
513
    $display_options = [
514 515
      'type' => 'link_separate',
      'label' => 'hidden',
516
    ];
517
    entity_get_form_display('entity_test', 'entity_test', 'default')
518
      ->setComponent($field_name, [
519
        'type' => 'link_default',
520
      ])
521
      ->save();
522
    entity_get_display('entity_test', 'entity_test', 'full')
523
      ->setComponent($field_name, $display_options)
524 525
      ->save();

526
    // Create an entity with three link field values:
527
    // - The first field item uses a URL only.
528
    // - The second field item uses a URL and link text.
529
    // - The third field item uses a fragment-only URL with text.
530 531
    // For consistency in assertion code below, the URL is assigned to the title
    // variable for the first field.
532
    $this->drupalGet('entity_test/add');
533 534
    $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';
535
    $url3 = '#net';
536 537
    // 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';
538
    $title3 = 'Fragment only';
539
    $edit = [
540 541
      "{$field_name}[0][uri]" => $url1,
      "{$field_name}[1][uri]" => $url2,
542
      "{$field_name}[1][title]" => $title2,
543 544
      "{$field_name}[2][uri]" => $url3,
      "{$field_name}[2][title]" => $title3,
545
    ];
546
    $this->drupalPostForm(NULL, $edit, t('Save'));
547
    preg_match('|entity_test/manage/(\d+)|', $this->getUrl(), $match);
548
    $id = $match[1];
549
    $this->assertText(t('entity_test @id has been created.', ['@id' => $id]));
550 551

    // Verify that the link is output according to the formatter settings.
552 553 554 555 556
    $options = [
      'trim_length' => [NULL, 6],
      'rel' => [NULL, 'nofollow'],
      'target' => [NULL, '_blank'],
    ];
557 558 559
    foreach ($options as $setting => $values) {
      foreach ($values as $new_value) {
        // Update the field formatter settings.
560
        $display_options['settings'] = [$setting => $new_value];
561
        entity_get_display('entity_test', 'entity_test', 'full')
562
          ->setComponent($field_name, $display_options)
563
          ->save();
564

565
        $output = $this->renderTestEntity($id);
566 567 568
        switch ($setting) {
          case 'trim_length':
            $url = $url1;
569
            $url_title = isset($new_value) ? Unicode::truncate($url, $new_value, FALSE, TRUE) : $url;
570
            $expected = '<div class="link-item">';
571
            $expected .= '<div class="link-url"><a href="' . Html::escape($url) . '">' . Html::escape($url_title) . '</a></div>';
572
            $expected .= '</div>';
573
            $this->assertContains($expected, $output);
574 575

            $url = $url2;
576 577
            $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;
578
            $expected = '<div class="link-item">';
579 580
            $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>';
581
            $expected .= '</div>';
582
            $this->assertContains($expected, $output);
583 584 585 586 587 588 589 590

            $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>';
591
            $this->assertContains($expected, $output);
592 593 594 595
            break;

          case 'rel':
            $rel = isset($new_value) ? ' rel="' . $new_value . '"' : '';
596 597 598
            $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);
599 600 601 602
            break;

          case 'target':
            $target = isset($new_value) ? ' target="' . $new_value . '"' : '';
603 604 605
            $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);
606 607 608 609 610 611
            break;
        }
      }
    }
  }

612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654
  /**
   * Test '#link_type' property exists on 'link_default' widget.
   *
   * Make sure the 'link_default' widget exposes a '#link_type' property on
   * its element. Modules can use it to understand if a text form element is
   * a link and also which LinkItemInterface::LINK_* is (EXTERNAL, GENERIC,
   * INTERNAL).
   */
  public function testLinkTypeOnLinkWidget() {

    $link_type = LinkItemInterface::LINK_EXTERNAL;
    $field_name = Unicode::strtolower($this->randomMachineName());

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

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

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

655
  /**
656
   * Renders a test_entity and returns the output.
657 658 659 660 661 662
   *
   * @param int $id
   *   The test_entity ID to render.
   * @param string $view_mode
   *   (optional) The view mode to use for rendering.
   * @param bool $reset
663
   *   (optional) Whether to reset the entity_test storage cache. Defaults to
664
   *   TRUE to simplify testing.
665 666 667
   *
   * @return string
   *   The rendered HTML output.
668 669 670
   */
  protected function renderTestEntity($id, $view_mode = 'full', $reset = TRUE) {
    if ($reset) {
671
      $this->container->get('entity.manager')->getStorage('entity_test')->resetCache([$id]);
672
    }
673
    $entity = EntityTest::load($id);
674
    $display = entity_get_display($entity->getEntityTypeId(), $entity->bundle(), $view_mode);
675
    $content = $display->build($entity);
676
    $output = \Drupal::service('renderer')->renderRoot($content);
677
    $output = (string) $output;
678
    $this->verbose($output);
679
    return $output;
680
  }
681

682
}