<?php

/**
 * @file
 * Tests for the Configuration module.
 */

use Drupal\Core\Config\FileStorage;
use Drupal\simpletest\WebTestBase;

/**
 * Tests the secure file writer.
 */
class ConfigFileSecurityTestCase extends WebTestBase {
  protected $filename = 'foo.bar';

  protected $testContent = array('greeting' => 'Good morning, Denver!');

  public static function getInfo() {
    return array(
      'name' => 'File security',
      'description' => 'Tests security of saved configuration files.',
      'group' => 'Configuration',
    );
  }

  /**
   * Tests that a file written by this system can be successfully read back.
   */
  function testFilePersist() {
    $file = new FileStorage($this->filename);
    $file->write($this->testContent);

    unset($file);

    // Reading should throw an exception in case of bad validation.
    // Note that if any other exception is thrown, we let the test system
    // handle catching and reporting it.
    try {
      $file = new FileStorage($this->filename);
      $saved_content = $file->read();

      $this->assertEqual($saved_content, $this->testContent);
    }
    catch (Exception $e) {
      $this->fail('File failed verification when being read.');
    }
  }
}

/**
 * Tests reading and writing file contents.
 */
class ConfigFileContentTestCase extends WebTestBase {
  protected $fileExtension = 'xml';

  public static function getInfo() {
    return array(
      'name' => 'File content',
      'description' => 'Tests reading and writing of configuration files.',
      'group' => 'Configuration',
    );
  }

  /**
   * Tests setting, writing, and reading of a configuration setting.
   */
  function testReadWriteConfig() {
    $config_dir = config_get_config_directory();
    $name = 'foo.bar';
    $key = 'foo';
    $value = 'bar';
    $nested_key = 'biff.bang';
    $nested_value = 'pow';
    $array_key = 'array';
    $array_value = array(
      'foo' => 'bar',
      'biff' => array(
        'bang' => 'pow',
      )
    );
    $casting_array_key = 'casting_array';
    $casting_array_false_value_key = 'casting_array.cast.false';
    $casting_array_value = array(
      'cast' => array(
        'false' => FALSE,
      )
    );
    $nested_array_key = 'nested.array';
    $true_key = 'true';
    $false_key = 'false';

    // Attempt to read non-existing configuration.
    $config = config($name);

    // Verify an configuration object is returned.
//    $this->assertEqual($config->name, $name);
    $this->assertTrue($config, t('Config object created.'));

    // Verify the configuration object is empty.
    $this->assertEqual($config->get(), array(), t('New config object is empty.'));

    // Verify nothing was saved.
    $db_config = db_query('SELECT * FROM {config} WHERE name = :name', array(':name' => $name))->fetch();
    $this->assertIdentical($db_config, FALSE, t('Active store does not have a record for %name', array('%name' => $name)));
    $this->assertFalse(file_exists($config_dir . '/' . $name . '.' . $this->fileExtension), 'Configuration file does not exist.');

    // Add a top level value
    $config = config($name);
    $config->set($key, $value);

    // Add a nested value
    $config->set($nested_key, $nested_value);

    // Add an array
    $config->set($array_key, $array_value);

    // Add a nested array
    $config->set($nested_array_key, $array_value);

    // Add a boolean false value. Should get cast to 0
    $config->set($false_key, FALSE);

    // Add a boolean true value. Should get cast to 1
    $config->set($true_key, TRUE);

    // Add an array with a nested boolean false that should get cast to 0.
    $config->set($casting_array_key, $casting_array_value);
    $config->save();

    // Verify the database entry exists.
    $db_config = db_query('SELECT * FROM {config} WHERE name = :name', array(':name' => $name))->fetch();
    $this->assertEqual($db_config->name, $name, t('After saving configuration, active store has a record for %name', array('%name' => $name)));

    // Verify the file exists.
    $this->assertTrue(file_exists($config_dir . '/' . $name . '.' . $this->fileExtension), t('After saving configuration, config file exists.'));

    // Read top level value
    $config = config($name);
//    $this->assertEqual($config->name, $name);
    $this->assertTrue($config, 'Config object created.');
    $this->assertEqual($config->get($key), 'bar', t('Top level configuration value found.'));

    // Read nested value
    $this->assertEqual($config->get($nested_key), $nested_value, t('Nested configuration value found.'));

    // Read array
    $this->assertEqual($config->get($array_key), $array_value, t('Top level array configuration value found.'));

    // Read nested array
    $this->assertEqual($config->get($nested_array_key), $array_value, t('Nested array configuration value found.'));

    // Read a top level value that doesn't exist
    $this->assertNull($config->get('i_dont_exist'), t('Non-existent top level value returned NULL.'));

    // Read a nested value that doesn't exist
    $this->assertNull($config->get('i.dont.exist'), t('Non-existent nested value returned NULL.'));

    // Read false value
    $this->assertEqual($config->get($false_key), '0', t('Boolean FALSE value returned the string \'0\'.'));

    // Read true value
    $this->assertEqual($config->get($true_key), '1', t('Boolean TRUE value returned the string \'1\'.'));

    // Read false that had been nested in an array value
    $this->assertEqual($config->get($casting_array_false_value_key), '0', t('Nested boolean FALSE value returned the string \'0\'.'));

    // Unset a top level value
    $config->clear($key);

    // Unset a nested value
    $config->clear($nested_key);
    $config->save();
    $config = config($name);

    // Read unset top level value
    $this->assertNull($config->get($key), t('Top level value unset.'));

    // Read unset nested value
    $this->assertNull($config->get($nested_key), t('Nested value unset.'));

    // Create two new configuration files to test listing
    $config = config('foo.baz');
    $config->set($key, $value);
    $config->save();

    // Test chained set()->save()
    $chained_name = 'biff.bang';
    $config = config($chained_name);
    $config->set($key, $value)->save();

    // Verify the database entry exists from a chained save.
    $db_config = db_query('SELECT * FROM {config} WHERE name = :name', array(':name' => $chained_name))->fetch();
    $this->assertEqual($db_config->name, $chained_name, t('After saving configuration by chaining through set(), active store has a record for %name', array('%name' => $chained_name)));

    // Verify the file exists from a chained save.
    $this->assertTrue(file_exists($config_dir . '/' . $chained_name . '.' . $this->fileExtension), t('After saving configuration by chaining through set(), config file exists.'));

    // Get file listing for all files starting with 'foo'. Should return
    // two elements.
    $files = config_get_files_with_prefix('foo');
    $this->assertEqual(count($files), 2, 'Two files listed with the prefix \'foo\'.');

    // Get file listing for all files starting with 'biff'. Should return
    // one element.
    $files = config_get_files_with_prefix('biff');
    $this->assertEqual(count($files), 1, 'One file listed with the prefix \'biff\'.');

    // Get file listing for all files starting with 'foo.bar'. Should return
    // one element.
    $files = config_get_files_with_prefix('foo.bar');
    $this->assertEqual(count($files), 1, 'One file listed with the prefix \'foo.bar\'.');

    // Get file listing for all files starting with 'bar'. Should return
    // an empty array.
    $files = config_get_files_with_prefix('bar');
    $this->assertEqual($files, array(), 'No files listed with the prefix \'bar\'.');

    // Delete the configuration.
    $config = config($name);
    $config->delete();

    // Verify the database entry no longer exists.
    $db_config = db_query('SELECT * FROM {config} WHERE name = :name', array(':name' => $name))->fetch();
    $this->assertIdentical($db_config, FALSE);
    $this->assertFalse(file_exists($config_dir . '/' . $name . '.' . $this->fileExtension));

    // Attempt to delete non-existing configuration.
  }
}

  /**
   * Tests configuration overriding from settings.php.
   */
class ConfOverrideTestCase extends WebTestBase {
  protected $testContent = 'Good morning, Denver!';

  public static function getInfo() {
    return array(
      'name' => 'Configuration overrides',
      'description' => 'Tests configuration overrides through settings.php.',
      'group' => 'Configuration',
    );
  }

  /**
   * Test configuration override.
   */
  function testConfigurationOverride() {
    global $conf;
    $config = config('system.performance');
    $this->assertNotEqual($config->get('cache'), $this->testContent);

    $conf['system.performance']['cache'] = $this->testContent;
    $config = config('system.performance');
    $this->assertEqual($config->get('cache'), $conf['system.performance']['cache']);
  }
}

/**
 * Tests function providing configuration upgrade from Drupal 7 to 8.
 */
class ConfUpdate7to8TestCase extends WebTestBase {
  protected $testContent = 'Olá, Sao Paulo!';

  public static function getInfo() {
    return array(
      'name' => 'Configuration update from Drupal 7 to 8',
      'description' => 'Tests the ability to update Drupal 7 variables to the
        configuration management system.',
      'group' => 'Configuration',
    );
  }

  function setUp() {
    parent::setUp('config_upgrade');
    require_once DRUPAL_ROOT . '/core/includes/update.inc';
  }

  /**
   * Test configuration update function.
   */
  function testConfigurationUpdate() {
    // Ensure that the variable table has the object. The variable table will
    // remain in place for Drupal 8 to provide an upgrade path for overridden
    // variables.
    db_merge('variable')->key(array('name' => 'config_test_foo'))->fields(array('value' => serialize($this->testContent)))->execute();
    db_merge('variable')->key(array('name' => 'config_bar'))->fields(array('value' => serialize($this->testContent)))->execute();

    update_variables_to_config('config.test', array('config_test_bar' => 'config_bar'));
    $config = config('config.test');
    $this->assertEqual($config->get('config_test_foo'), $this->testContent);
    $this->assertEqual($config->get('config_test_bar'), $this->testContent);
  }
}
