LinkFieldTest.php 21 KB
Newer Older
1 2 3 4 5 6 7 8 9
<?php

/**
 * @file
 * Contains Drupal\link\Tests\LinkFieldTest.
 */

namespace Drupal\link\Tests;

10
use Drupal\Component\Utility\String;
11
use Drupal\Component\Utility\Unicode;
12 13
use Drupal\link\LinkItemInterface;
use Drupal\simpletest\WebTestBase;
14 15 16

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

  /**
   * Modules to enable.
   *
   * @var array
   */
27
  public static $modules = array('entity_test', 'link');
28

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

  /**
   * The instance used in this test class.
   *
39
   * @var \Drupal\field\Entity\FieldConfig
40
   */
41
  protected $field;
42 43 44 45 46 47 48 49

  /**
   * A user with permission to view and manage test entities.
   *
   * @var object
   */
  protected $web_user;

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

    $this->web_user = $this->drupalCreateUser(array(
54 55
      'view test entity',
      'administer entity_test content',
56
      'link to any page',
57 58 59 60 61 62 63 64
    ));
    $this->drupalLogin($this->web_user);
  }

  /**
   * Tests link field URL validation.
   */
  function testURLValidation() {
65
    $field_name = Unicode::strtolower($this->randomMachineName());
66
    // Create a field with settings to validate.
67
    $this->fieldStorage = entity_create('field_storage_config', array(
68
      'field_name' => $field_name,
69
      'entity_type' => 'entity_test',
70
      'type' => 'link',
71
    ));
72
    $this->fieldStorage->save();
73
    $this->field = entity_create('field_config', array(
74
      'field_storage' => $this->fieldStorage,
75
      'bundle' => 'entity_test',
76 77
      'settings' => array(
        'title' => DRUPAL_DISABLED,
78
        'link_type' => LinkItemInterface::LINK_GENERIC,
79
      ),
80
    ));
81
    $this->field->save();
82
    entity_get_form_display('entity_test', 'entity_test', 'default')
83
      ->setComponent($field_name, array(
84
        'type' => 'link_default',
85 86 87
        'settings' => array(
          'placeholder_url' => 'http://example.com',
        ),
88 89
      ))
      ->save();
90
    entity_get_display('entity_test', 'entity_test', 'full')
91
      ->setComponent($field_name, array(
92 93 94 95
        'type' => 'link',
      ))
      ->save();

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

101 102
    // Create a path alias.
    \Drupal::service('path.alias_storage')->save('admin', 'a/path/alias');
103 104 105 106 107 108
    // Define some valid URLs.
    $valid_external_entries = array(
      'http://www.example.com/',
    );
    $valid_internal_entries = array(
      'entity_test/add',
109
      'a/path/alias',
110 111
    );

112 113
    // Define some invalid URLs.
    $invalid_external_entries = array(
114 115 116 117 118 119 120
      // Missing protcol
      'not-an-url',
      // Invalid protocol
      'invalid://not-a-valid-protocol',
      // Missing host name
      'http://',
    );
121 122 123 124 125 126 127 128 129
    $invalid_internal_entries = array(
      'non/existing/path',
    );

    // 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.
130 131
    $this->field->settings['link_type'] = LinkItemInterface::LINK_EXTERNAL;
    $this->field->save();
132 133 134 135
    $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.
136 137
    $this->field->settings['link_type'] = LinkItemInterface::LINK_INTERNAL;
    $this->field->save();
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
    $this->assertValidEntries($field_name, $valid_internal_entries);
    $this->assertInvalidEntries($field_name, $valid_external_entries + $invalid_internal_entries);
  }

  /**
   * 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) {
    foreach ($valid_entries as $value) {
      $edit = array(
        "{$field_name}[0][url]" => $value,
      );
      $this->drupalPostForm('entity_test/add', $edit, t('Save'));
      preg_match('|entity_test/manage/(\d+)|', $this->url, $match);
      $id = $match[1];
      $this->assertText(t('entity_test @id has been created.', array('@id' => $id)));
      $this->assertRaw($value);
    }
  }

  /**
   * 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) {
    foreach ($invalid_entries as $invalid_value) {
173
      $edit = array(
174
        "{$field_name}[0][url]" => $invalid_value,
175
      );
176
      $this->drupalPostForm('entity_test/add', $edit, t('Save'));
177 178 179 180 181
      $this->assertText(t('The URL @url is not valid.', array('@url' => $invalid_value)));
    }
  }

  /**
182
   * Tests the link title settings of a link field.
183 184
   */
  function testLinkTitle() {
185
    $field_name = Unicode::strtolower($this->randomMachineName());
186
    // Create a field with settings to validate.
187
    $this->fieldStorage = entity_create('field_storage_config', array(
188
      'field_name' => $field_name,
189
      'entity_type' => 'entity_test',
190
      'type' => 'link',
191
    ));
192
    $this->fieldStorage->save();
193
    $this->field = entity_create('field_config', array(
194
      'field_storage' => $this->fieldStorage,
195
      'bundle' => 'entity_test',
196
      'label' => 'Read more about this entity',
197 198
      'settings' => array(
        'title' => DRUPAL_OPTIONAL,
199
        'link_type' => LinkItemInterface::LINK_GENERIC,
200
      ),
201
    ));
202
    $this->field->save();
203
    entity_get_form_display('entity_test', 'entity_test', 'default')
204
      ->setComponent($field_name, array(
205
        'type' => 'link_default',
206 207
        'settings' => array(
          'placeholder_url' => 'http://example.com',
208
          'placeholder_title' => 'Enter the text for this link',
209
        ),
210 211
      ))
      ->save();
212
    entity_get_display('entity_test', 'entity_test', 'full')
213
      ->setComponent($field_name, array(
214 215 216 217 218
        'type' => 'link',
        'label' => 'hidden',
      ))
      ->save();

219
    // Verify that the link text field works according to the field setting.
220
    foreach (array(DRUPAL_DISABLED, DRUPAL_REQUIRED, DRUPAL_OPTIONAL) as $title_setting) {
221
      // Update the link title field setting.
222 223
      $this->field->settings['title'] = $title_setting;
      $this->field->save();
224 225

      // Display creation form.
226
      $this->drupalGet('entity_test/add');
227 228
      // Assert label is shown.
      $this->assertText('Read more about this entity');
229
      $this->assertFieldByName("{$field_name}[0][url]", '', 'URL field found.');
230
      $this->assertRaw('placeholder="http://example.com"');
231 232

      if ($title_setting === DRUPAL_DISABLED) {
233
        $this->assertNoFieldByName("{$field_name}[0][title]", '', 'Link text field not found.');
234
        $this->assertNoRaw('placeholder="Enter the text for this link"');
235 236
      }
      else {
237
        $this->assertRaw('placeholder="Enter the text for this link"');
238

239
        $this->assertFieldByName("{$field_name}[0][title]", '', 'Link text field found.');
240
        if ($title_setting === DRUPAL_REQUIRED) {
241
          // Verify that the link text is required, if the URL is non-empty.
242
          $edit = array(
243
            "{$field_name}[0][url]" => 'http://www.example.com',
244
          );
245
          $this->drupalPostForm(NULL, $edit, t('Save'));
246
          $this->assertText(t('!name field is required.', array('!name' => t('Link text'))));
247

248
          // Verify that the link text is not required, if the URL is empty.
249
          $edit = array(
250
            "{$field_name}[0][url]" => '',
251
          );
252
          $this->drupalPostForm(NULL, $edit, t('Save'));
253
          $this->assertNoText(t('!name field is required.', array('!name' => t('Link text'))));
254

255
          // Verify that a URL and link text meets requirements.
256
          $this->drupalGet('entity_test/add');
257
          $edit = array(
258 259
            "{$field_name}[0][url]" => 'http://www.example.com',
            "{$field_name}[0][title]" => 'Example',
260
          );
261
          $this->drupalPostForm(NULL, $edit, t('Save'));
262
          $this->assertNoText(t('!name field is required.', array('!name' => t('Link text'))));
263 264 265 266
        }
      }
    }

267
    // Verify that a link without link text is rendered using the URL as text.
268 269
    $value = 'http://www.example.com/';
    $edit = array(
270 271
      "{$field_name}[0][url]" => $value,
      "{$field_name}[0][title]" => '',
272
    );
273
    $this->drupalPostForm(NULL, $edit, t('Save'));
274
    preg_match('|entity_test/manage/(\d+)|', $this->url, $match);
275
    $id = $match[1];
276
    $this->assertText(t('entity_test @id has been created.', array('@id' => $id)));
277 278

    $this->renderTestEntity($id);
279
    $expected_link = _l($value, $value);
280 281
    $this->assertRaw($expected_link);

282
    // Verify that a link with text is rendered using the link text.
283
    $title = $this->randomMachineName();
284
    $edit = array(
285
      "{$field_name}[0][title]" => $title,
286
    );
287
    $this->drupalPostForm("entity_test/manage/$id", $edit, t('Save'));
288
    $this->assertText(t('entity_test @id has been updated.', array('@id' => $id)));
289 290

    $this->renderTestEntity($id);
291
    $expected_link = _l($title, $value);
292 293 294 295 296 297 298
    $this->assertRaw($expected_link);
  }

  /**
   * Tests the default 'link' formatter.
   */
  function testLinkFormatter() {
299
    $field_name = Unicode::strtolower($this->randomMachineName());
300
    // Create a field with settings to validate.
301
    $this->fieldStorage = entity_create('field_storage_config', array(
302
      'field_name' => $field_name,
303
      'entity_type' => 'entity_test',
304 305
      'type' => 'link',
      'cardinality' => 2,
306
    ));
307
    $this->fieldStorage->save();
308
    entity_create('field_config', array(
309
      'field_storage' => $this->fieldStorage,
310
      'label' => 'Read more about this entity',
311
      'bundle' => 'entity_test',
312 313
      'settings' => array(
        'title' => DRUPAL_OPTIONAL,
314
        'link_type' => LinkItemInterface::LINK_GENERIC,
315
      ),
316
    ))->save();
317
    entity_get_form_display('entity_test', 'entity_test', 'default')
318
      ->setComponent($field_name, array(
319 320 321
        'type' => 'link_default',
      ))
      ->save();
322 323 324 325
    $display_options = array(
      'type' => 'link',
      'label' => 'hidden',
    );
326
    entity_get_display('entity_test', 'entity_test', 'full')
327
      ->setComponent($field_name, $display_options)
328 329
      ->save();

330 331
    // Create an entity with two link field values:
    // - The first field item uses a URL only.
332
    // - The second field item uses a URL and link text.
333 334
    // For consistency in assertion code below, the URL is assigned to the title
    // variable for the first field.
335
    $this->drupalGet('entity_test/add');
336 337 338 339 340 341
    $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';
    $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';
    $edit = array(
342
      "{$field_name}[0][url]" => $url1,
343
      // Note that $title1 is not submitted.
344 345 346
      "{$field_name}[0][title]" => '',
      "{$field_name}[1][url]" => $url2,
      "{$field_name}[1][title]" => $title2,
347
    );
348 349
    // Assert label is shown.
    $this->assertText('Read more about this entity');
350
    $this->drupalPostForm(NULL, $edit, t('Save'));
351
    preg_match('|entity_test/manage/(\d+)|', $this->url, $match);
352
    $id = $match[1];
353
    $this->assertText(t('entity_test @id has been created.', array('@id' => $id)));
354 355 356 357

    // 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
358
    // _l() and options/attributes. Only 'url_plain' has a dependency on
359 360 361 362 363 364
    // 'url_only', so we have a total of ~10 cases.
    $options = array(
      'trim_length' => array(NULL, 6),
      'rel' => array(NULL, 'nofollow'),
      'target' => array(NULL, '_blank'),
      'url_only' => array(
365 366 367 368
        array('url_only' => FALSE),
        array('url_only' => FALSE, 'url_plain' => TRUE),
        array('url_only' => TRUE),
        array('url_only' => TRUE, 'url_plain' => TRUE),
369 370 371 372 373 374
      ),
    );
    foreach ($options as $setting => $values) {
      foreach ($values as $new_value) {
        // Update the field formatter settings.
        if (!is_array($new_value)) {
375
          $display_options['settings'] = array($setting => $new_value);
376 377
        }
        else {
378
          $display_options['settings'] = $new_value;
379
        }
380
        entity_get_display('entity_test', 'entity_test', 'full')
381
          ->setComponent($field_name, $display_options)
382
          ->save();
383 384 385 386 387

        $this->renderTestEntity($id);
        switch ($setting) {
          case 'trim_length':
            $url = $url1;
388
            $title = isset($new_value) ? Unicode::truncate($title1, $new_value, FALSE, TRUE) : $title1;
389
            $this->assertRaw('<a href="' . String::checkPlain($url) . '">' . String::checkPlain($title) . '</a>');
390 391

            $url = $url2;
392
            $title = isset($new_value) ? Unicode::truncate($title2, $new_value, FALSE, TRUE) : $title2;
393
            $this->assertRaw('<a href="' . String::checkPlain($url) . '">' . String::checkPlain($title) . '</a>');
394 395 396 397
            break;

          case 'rel':
            $rel = isset($new_value) ? ' rel="' . $new_value . '"' : '';
398 399
            $this->assertRaw('<a href="' . String::checkPlain($url1) . '"' . $rel . '>' . String::checkPlain($title1) . '</a>');
            $this->assertRaw('<a href="' . String::checkPlain($url2) . '"' . $rel . '>' . String::checkPlain($title2) . '</a>');
400 401 402 403
            break;

          case 'target':
            $target = isset($new_value) ? ' target="' . $new_value . '"' : '';
404 405
            $this->assertRaw('<a href="' . String::checkPlain($url1) . '"' . $target . '>' . String::checkPlain($title1) . '</a>');
            $this->assertRaw('<a href="' . String::checkPlain($url2) . '"' . $target . '>' . String::checkPlain($title2) . '</a>');
406 407 408 409 410
            break;

          case 'url_only':
            // In this case, $new_value is an array.
            if (!$new_value['url_only']) {
411 412
              $this->assertRaw('<a href="' . String::checkPlain($url1) . '">' . String::checkPlain($title1) . '</a>');
              $this->assertRaw('<a href="' . String::checkPlain($url2) . '">' . String::checkPlain($title2) . '</a>');
413 414 415
            }
            else {
              if (empty($new_value['url_plain'])) {
416 417
                $this->assertRaw('<a href="' . String::checkPlain($url1) . '">' . String::checkPlain($url1) . '</a>');
                $this->assertRaw('<a href="' . String::checkPlain($url2) . '">' . String::checkPlain($url2) . '</a>');
418 419
              }
              else {
420 421 422 423
                $this->assertNoRaw('<a href="' . String::checkPlain($url1) . '">' . String::checkPlain($url1) . '</a>');
                $this->assertNoRaw('<a href="' . String::checkPlain($url2) . '">' . String::checkPlain($url2) . '</a>');
                $this->assertRaw(String::checkPlain($url1));
                $this->assertRaw(String::checkPlain($url2));
424 425 426 427 428 429 430 431 432 433 434 435 436 437 438
              }
            }
            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.
   */
  function testLinkSeparateFormatter() {
439
    $field_name = Unicode::strtolower($this->randomMachineName());
440
    // Create a field with settings to validate.
441
    $this->fieldStorage = entity_create('field_storage_config', array(
442
      'field_name' => $field_name,
443
      'entity_type' => 'entity_test',
444 445
      'type' => 'link',
      'cardinality' => 2,
446
    ));
447
    $this->fieldStorage->save();
448
    entity_create('field_config', array(
449
      'field_storage' => $this->fieldStorage,
450
      'bundle' => 'entity_test',
451 452
      'settings' => array(
        'title' => DRUPAL_OPTIONAL,
453
        'link_type' => LinkItemInterface::LINK_GENERIC,
454
      ),
455
    ))->save();
456 457 458
    $display_options = array(
      'type' => 'link_separate',
      'label' => 'hidden',
459
    );
460
    entity_get_form_display('entity_test', 'entity_test', 'default')
461
      ->setComponent($field_name, array(
462 463 464
        'type' => 'link_default',
      ))
      ->save();
465
    entity_get_display('entity_test', 'entity_test', 'full')
466
      ->setComponent($field_name, $display_options)
467 468
      ->save();

469 470
    // Create an entity with two link field values:
    // - The first field item uses a URL only.
471
    // - The second field item uses a URL and link text.
472 473
    // For consistency in assertion code below, the URL is assigned to the title
    // variable for the first field.
474
    $this->drupalGet('entity_test/add');
475 476 477 478 479
    $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';
    // 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';
    $edit = array(
480 481 482
      "{$field_name}[0][url]" => $url1,
      "{$field_name}[1][url]" => $url2,
      "{$field_name}[1][title]" => $title2,
483
    );
484
    $this->drupalPostForm(NULL, $edit, t('Save'));
485
    preg_match('|entity_test/manage/(\d+)|', $this->url, $match);
486
    $id = $match[1];
487
    $this->assertText(t('entity_test @id has been created.', array('@id' => $id)));
488 489 490 491 492 493 494 495 496 497

    // Verify that the link is output according to the formatter settings.
    $options = array(
      'trim_length' => array(NULL, 6),
      'rel' => array(NULL, 'nofollow'),
      'target' => array(NULL, '_blank'),
    );
    foreach ($options as $setting => $values) {
      foreach ($values as $new_value) {
        // Update the field formatter settings.
498
        $display_options['settings'] = array($setting => $new_value);
499
        entity_get_display('entity_test', 'entity_test', 'full')
500
          ->setComponent($field_name, $display_options)
501
          ->save();
502 503 504 505 506

        $this->renderTestEntity($id);
        switch ($setting) {
          case 'trim_length':
            $url = $url1;
507
            $url_title = isset($new_value) ? Unicode::truncate($url, $new_value, FALSE, TRUE) : $url;
508
            $expected = '<div class="link-item">';
509
            $expected .= '<div class="link-url"><a href="' . String::checkPlain($url) . '">' . String::checkPlain($url_title) . '</a></div>';
510 511 512 513
            $expected .= '</div>';
            $this->assertRaw($expected);

            $url = $url2;
514 515
            $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;
516
            $expected = '<div class="link-item">';
517 518
            $expected .= '<div class="link-title">' . String::checkPlain($title) . '</div>';
            $expected .= '<div class="link-url"><a href="' . String::checkPlain($url) . '">' . String::checkPlain($url_title) . '</a></div>';
519 520 521 522 523 524
            $expected .= '</div>';
            $this->assertRaw($expected);
            break;

          case 'rel':
            $rel = isset($new_value) ? ' rel="' . $new_value . '"' : '';
525 526
            $this->assertRaw('<div class="link-url"><a href="' . String::checkPlain($url1) . '"' . $rel . '>' . String::checkPlain($url1) . '</a></div>');
            $this->assertRaw('<div class="link-url"><a href="' . String::checkPlain($url2) . '"' . $rel . '>' . String::checkPlain($url2) . '</a></div>');
527 528 529 530
            break;

          case 'target':
            $target = isset($new_value) ? ' target="' . $new_value . '"' : '';
531 532
            $this->assertRaw('<div class="link-url"><a href="' . String::checkPlain($url1) . '"' . $target . '>' . String::checkPlain($url1) . '</a></div>');
            $this->assertRaw('<div class="link-url"><a href="' . String::checkPlain($url2) . '"' . $target . '>' . String::checkPlain($url2) . '</a></div>');
533 534 535 536 537 538 539 540 541 542 543 544 545 546
            break;
        }
      }
    }
  }

  /**
   * Renders a test_entity and sets the output in the internal browser.
   *
   * @param int $id
   *   The test_entity ID to render.
   * @param string $view_mode
   *   (optional) The view mode to use for rendering.
   * @param bool $reset
547
   *   (optional) Whether to reset the entity_test storage cache. Defaults to
548 549 550 551
   *   TRUE to simplify testing.
   */
  protected function renderTestEntity($id, $view_mode = 'full', $reset = TRUE) {
    if ($reset) {
552
      $this->container->get('entity.manager')->getStorage('entity_test')->resetCache(array($id));
553
    }
554
    $entity = entity_load('entity_test', $id);
555
    $display = entity_get_display($entity->getEntityTypeId(), $entity->bundle(), $view_mode);
556 557
    $content = $display->build($entity);
    $output = drupal_render($content);
558 559 560
    $this->drupalSetContent($output);
    $this->verbose($output);
  }
561

562
}