function LinkFieldTest::testURLValidation

Tests link field URL validation.

File

drupal/core/modules/link/lib/Drupal/link/Tests/LinkFieldTest.php, line 46
Contains Drupal\link\Tests\LinkFieldTest.

Class

LinkFieldTest
Tests link field widgets and formatters.

Namespace

Drupal\link\Tests

Code

function testURLValidation() {

  // Create a field with settings to validate.
  $this->field = array(
    'field_name' => drupal_strtolower($this
      ->randomName()),
    'type' => 'link',
  );
  field_create_field($this->field);
  $this->instance = array(
    'field_name' => $this->field['field_name'],
    'entity_type' => 'entity_test',
    'bundle' => 'entity_test',
    'settings' => array(
      'title' => DRUPAL_DISABLED,
    ),
  );
  field_create_instance($this->instance);
  entity_get_form_display('entity_test', 'entity_test', 'default')
    ->setComponent($this->field['field_name'], array(
    'type' => 'link_default',
    'settings' => array(
      'placeholder_url' => 'http://example.com',
    ),
  ))
    ->save();
  entity_get_display('entity_test', 'entity_test', 'full')
    ->setComponent($this->field['field_name'], array(
    'type' => 'link',
  ))
    ->save();
  $langcode = Language::LANGCODE_NOT_SPECIFIED;

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

  // Verify that a valid URL can be submitted.
  $value = 'http://www.example.com/';
  $edit = array(
    'user_id' => 1,
    'name' => $this
      ->randomName(),
    "{$this->field['field_name']}[{$langcode}][0][url]" => $value,
  );
  $this
    ->drupalPost(NULL, $edit, t('Save'));
  preg_match('|entity_test/manage/(\\d+)/edit|', $this->url, $match);
  $id = $match[1];
  $this
    ->assertText(t('entity_test @id has been created.', array(
    '@id' => $id,
  )));
  $this
    ->assertRaw($value);

  // Verify that invalid URLs cannot be submitted.
  $wrong_entries = array(
    // Missing protcol
    'not-an-url',
    // Invalid protocol
    'invalid://not-a-valid-protocol',
    // Missing host name
    'http://',
  );
  $this
    ->drupalGet('entity_test/add');
  foreach ($wrong_entries as $invalid_value) {
    $edit = array(
      'user_id' => 1,
      'name' => $this
        ->randomName(),
      "{$this->field['field_name']}[{$langcode}][0][url]" => $invalid_value,
    );
    $this
      ->drupalPost(NULL, $edit, t('Save'));
    $this
      ->assertText(t('The URL @url is not valid.', array(
      '@url' => $invalid_value,
    )));
  }
}