LinkFieldTest.php 21.4 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 12
use Drupal\link\LinkItemInterface;
use Drupal\simpletest\WebTestBase;
13 14 15

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

  /**
   * Modules to enable.
   *
   * @var array
   */
26
  public static $modules = array('entity_test', 'link');
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\FieldInstanceConfig
39 40 41 42 43 44 45 46 47 48
   */
  protected $instance;

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

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

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

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

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

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

110 111
    // Define some invalid URLs.
    $invalid_external_entries = array(
112 113 114 115 116 117 118
      // Missing protcol
      'not-an-url',
      // Invalid protocol
      'invalid://not-a-valid-protocol',
      // Missing host name
      'http://',
    );
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
    $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.
    $this->instance->settings['link_type'] = LinkItemInterface::LINK_EXTERNAL;
    $this->instance->save();
    $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.
    $this->instance->settings['link_type'] = LinkItemInterface::LINK_INTERNAL;
    $this->instance->save();
    $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(
        'user_id' => 1,
152
        'name' => $this->randomMachineName(),
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
        "{$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
        'user_id' => 1,
175
        'name' => $this->randomMachineName(),
176
        "{$field_name}[0][url]" => $invalid_value,
177
      );
178
      $this->drupalPostForm('entity_test/add', $edit, t('Save'));
179 180 181 182 183
      $this->assertText(t('The URL @url is not valid.', array('@url' => $invalid_value)));
    }
  }

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

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

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

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

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

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

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

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

    $this->renderTestEntity($id);
    $expected_link = l($value, $value);
    $this->assertRaw($expected_link);

286
    // Verify that a link with text is rendered using the link text.
287
    $title = $this->randomMachineName();
288
    $edit = array(
289
      'user_id' => 1,
290
      'name' => $this->randomMachineName(),
291
      "{$field_name}[0][title]" => $title,
292
    );
293
    $this->drupalPostForm("entity_test/manage/$id", $edit, t('Save'));
294
    $this->assertText(t('entity_test @id has been updated.', array('@id' => $id)));
295 296 297 298 299 300 301 302 303 304

    $this->renderTestEntity($id);
    $expected_link = l($title, $value);
    $this->assertRaw($expected_link);
  }

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

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

    // 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
366
    // l() and options/attributes. Only 'url_plain' has a dependency on
367 368 369 370 371 372
    // '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(
373 374 375 376
        array('url_only' => FALSE),
        array('url_only' => FALSE, 'url_plain' => TRUE),
        array('url_only' => TRUE),
        array('url_only' => TRUE, 'url_plain' => TRUE),
377 378 379 380 381 382
      ),
    );
    foreach ($options as $setting => $values) {
      foreach ($values as $new_value) {
        // Update the field formatter settings.
        if (!is_array($new_value)) {
383
          $display_options['settings'] = array($setting => $new_value);
384 385
        }
        else {
386
          $display_options['settings'] = $new_value;
387
        }
388
        entity_get_display('entity_test', 'entity_test', 'full')
389
          ->setComponent($field_name, $display_options)
390
          ->save();
391 392 393 394 395 396

        $this->renderTestEntity($id);
        switch ($setting) {
          case 'trim_length':
            $url = $url1;
            $title = isset($new_value) ? truncate_utf8($title1, $new_value, FALSE, TRUE) : $title1;
397
            $this->assertRaw('<a href="' . String::checkPlain($url) . '">' . String::checkPlain($title) . '</a>');
398 399 400

            $url = $url2;
            $title = isset($new_value) ? truncate_utf8($title2, $new_value, FALSE, TRUE) : $title2;
401
            $this->assertRaw('<a href="' . String::checkPlain($url) . '">' . String::checkPlain($title) . '</a>');
402 403 404 405
            break;

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

          case 'target':
            $target = isset($new_value) ? ' target="' . $new_value . '"' : '';
412 413
            $this->assertRaw('<a href="' . String::checkPlain($url1) . '"' . $target . '>' . String::checkPlain($title1) . '</a>');
            $this->assertRaw('<a href="' . String::checkPlain($url2) . '"' . $target . '>' . String::checkPlain($title2) . '</a>');
414 415 416 417 418
            break;

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

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

    // 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.
508
        $display_options['settings'] = array($setting => $new_value);
509
        entity_get_display('entity_test', 'entity_test', 'full')
510
          ->setComponent($field_name, $display_options)
511
          ->save();
512 513 514 515 516 517 518

        $this->renderTestEntity($id);
        switch ($setting) {
          case 'trim_length':
            $url = $url1;
            $url_title = isset($new_value) ? truncate_utf8($url, $new_value, FALSE, TRUE) : $url;
            $expected = '<div class="link-item">';
519
            $expected .= '<div class="link-url"><a href="' . String::checkPlain($url) . '">' . String::checkPlain($url_title) . '</a></div>';
520 521 522 523 524 525 526
            $expected .= '</div>';
            $this->assertRaw($expected);

            $url = $url2;
            $url_title = isset($new_value) ? truncate_utf8($url, $new_value, FALSE, TRUE) : $url;
            $title = isset($new_value) ? truncate_utf8($title2, $new_value, FALSE, TRUE) : $title2;
            $expected = '<div class="link-item">';
527 528
            $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>';
529 530 531 532 533 534
            $expected .= '</div>';
            $this->assertRaw($expected);
            break;

          case 'rel':
            $rel = isset($new_value) ? ' rel="' . $new_value . '"' : '';
535 536
            $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>');
537 538 539 540
            break;

          case 'target':
            $target = isset($new_value) ? ' target="' . $new_value . '"' : '';
541 542
            $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>');
543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561
            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
   *   (optional) Whether to reset the test_entity controller cache. Defaults to
   *   TRUE to simplify testing.
   */
  protected function renderTestEntity($id, $view_mode = 'full', $reset = TRUE) {
    if ($reset) {
562
      $this->container->get('entity.manager')->getStorage('entity_test')->resetCache(array($id));
563
    }
564
    $entity = entity_load('entity_test', $id);
565
    $display = entity_get_display($entity->getEntityTypeId(), $entity->bundle(), $view_mode);
566 567
    $content = $display->build($entity);
    $output = drupal_render($content);
568 569 570
    $this->drupalSetContent($output);
    $this->verbose($output);
  }
571

572
}