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
      'link to any page',
56 57 58 59 60 61 62 63
    ));
    $this->drupalLogin($this->web_user);
  }

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

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

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

111 112
    // Define some invalid URLs.
    $invalid_external_entries = array(
113 114 115 116 117 118 119
      // Missing protcol
      'not-an-url',
      // Invalid protocol
      'invalid://not-a-valid-protocol',
      // Missing host name
      'http://',
    );
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(
152 153
        'user_id' => 1,
        'name' => $this->randomMachineName(),
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
        "{$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) {
174
      $edit = array(
175 176
        'user_id' => 1,
        'name' => $this->randomMachineName(),
177
        "{$field_name}[0][url]" => $invalid_value,
178
      );
179
      $this->drupalPostForm('entity_test/add', $edit, t('Save'));
180 181 182 183 184
      $this->assertText(t('The URL @url is not valid.', array('@url' => $invalid_value)));
    }
  }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        $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">';
520
            $expected .= '<div class="link-url"><a href="' . String::checkPlain($url) . '">' . String::checkPlain($url_title) . '</a></div>';
521 522 523 524 525 526 527
            $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">';
528 529
            $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>';
530 531 532 533 534 535
            $expected .= '</div>';
            $this->assertRaw($expected);
            break;

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

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

573
}