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\Url;
9
use Drupal\entity_test\Entity\EntityTest;
10
use Drupal\field\Entity\FieldConfig;
11
use Drupal\link\LinkItemInterface;
12
use Drupal\node\NodeInterface;
13
use Drupal\Tests\BrowserTestBase;
14
use Drupal\field\Entity\FieldStorageConfig;
15 16 17

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

344 345 346
    $output = $this->renderTestEntity($id);
    $expected_link = (string) \Drupal::l($value, Url::fromUri($value));
    $this->assertContains($expected_link, $output);
347

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

356 357 358
    $output = $this->renderTestEntity($id);
    $expected_link = (string) \Drupal::l($title, Url::fromUri($value));
    $this->assertContains($expected_link, $output);
359 360 361 362 363
  }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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 737 738 739 740 741 742
  /**
   * 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 =