<?php

/**
 * @file
 * Confirm path aliases are saved internally as the system path.
 */

/**
 * Confirm path aliases are saved internally as the system path.
 */
class LinkConvertInternalPathsTest extends LinkBaseTestClass {

  /**
   * Description of the tests.
   */
  public static function getInfo() {
    return array(
      'name' => 'Conversion of internal path aliases',
      'description' => 'Test that internal path aliases are saved as system paths.',
      'group' => 'Link',
    );
  }

  /**
   * {@inheritdoc}
   */
  public function setUp(array $modules = array()) {
    $modules[] = 'path';
    parent::setUp($modules);
  }

  /**
   * Test the alias handling.
   */
  public function testInternalPathConversion() {
    // Create 2 fields, one which converts aliases and one which doesn't.
    $settings = array(
      'instance[settings][convert_aliases]' => TRUE,
    );
    $field_name_converts = $this->createLinkField('page', $settings);
    $field_name_plain = $this->createLinkField('page');

    // Programatically create a node with an alias to link to.
    $aliased_node = (object) array(
      'type' => 'page',
      'uid' => 1,
      'title' => $this->randomName(),
      'path' => array(
        'alias' => $this->randomName(),
      ),
      // This is needed for path alias to be saved.
      'language' => LANGUAGE_NONE,
    );
    node_save($aliased_node);

    $this->drupalGet($aliased_node->path['alias']);
    $this->assertText($aliased_node->title, 'Aliased node created.');

    $this->drupalGet('node/add/page');

    $label = $this->randomName();
    $edit = array(
      'title' => $label,
      $field_name_converts . '[und][0][title]' => $label,
      $field_name_converts . '[und][0][url]' => $aliased_node->path['alias'],
      $field_name_plain . '[und][0][title]' => $label,
      $field_name_plain . '[und][0][url]' => $aliased_node->path['alias'],
    );
    $this->drupalPost(NULL, $edit, t('Save'));
    $this->assertRaw(' has been created.', 'Node created');

    // Load the node that was created.
    $url = $this->getUrl();
    $split = explode('/', $url);
    $nid = array_pop($split);

    $node = node_load($nid);

    $link_field_converts_items = field_get_items('node', $node, $field_name_converts);
    $this->assertEqual($link_field_converts_items[0]['url'], "node/{$aliased_node->nid}", "The field value was saved as the internal path for the alias.");

    $link_field_plain_items = field_get_items('node', $node, $field_name_plain);
    $this->assertEqual($link_field_plain_items[0]['url'], $aliased_node->path['alias'], "The field value was saved as the given alias.");
  }

}
