<?php

/**
 * Tests administration of select or other field widgets and formatters.
 */
class SelectOrOtherAdminTestCase extends DrupalWebTestCase {

  /**
   * @var object
   *  The administrator user.
   */
  protected $adminUser;

  /**
   * @var array
   *   The field info.
   */
  protected $field;

  /**
   * @var array
   *   The field instance info.
   */
  protected $instance;

  public static function getInfo() {
    return array(
      'name' => 'Select or Other admin',
      'description' => 'Ensure that Select or Other administration functions as expected.',
      'group' => 'Select or Other',
    );
  }


  public function setUp() {
    parent::setUp(array('field_ui', 'text', 'select_or_other'));
    // Create and log in our privileged user.
    $this->adminUser = $this->drupalCreateUser(
      array(
        'create page content',
        'edit own page content',
        'administer content types',
        'administer site configuration',
        'administer fields',
      )
    );
    $this->drupalLogin($this->adminUser);

    $field = array(
      'field_name' => drupal_strtolower($this->randomName()),
      'type' => 'text',
      'cardinality' => FIELD_CARDINALITY_UNLIMITED,
    );
    $this->field = field_create_field($field);

    $instance = array(
      'field_name' => $field['field_name'],
      'entity_type' => 'node',
      'bundle' => 'page',
      'widget' => array(
        'type' => 'select_or_other',
        'settings' => array(
          'available_options' => "keyed|Keyed\r\nunkeyed",
        ),
      ),
    );

    $this->instance = field_create_instance($instance);
  }

  /**
   * Regression test for the available options field.
   *
   * Empty lines would cause notices when displaying field values with the
   * select or other field formatter.
   */
  public function testAvailableOptions() {
    $langcode = LANGUAGE_NONE;
    // Change field settings.
    $edit = array('instance[widget][settings][available_options]' => "keyed|Keyed\r\nunkeyed\r\n");
    $this->drupalpost("admin/structure/types/manage/page/fields/{$this->field['field_name']}", $edit, t('Save settings'));
    // Change field display settings.
    $edit = array("fields[{$this->field['field_name']}][type]" => 'select_or_other_formatter');
    $this->drupalpost("admin/structure/types/manage/page/display/", $edit, t('Save'));

    // Create a node
    $edit = array(
      "title" => $this->randomName(8),
      "{$this->field['field_name']}[{$langcode}][select][]" => 'keyed',
    );
    $this->drupalPost('node/add/page', $edit, t('Save'));

    // Check if the values have been created.
    $this->assertRaw('Keyed');
  }

}
