<?
class DbConnectModule implements charcoal_IModule
{
	/*
	 *    コンストラクタ
	 */
	public function __construct()
	{
	}

	/*
	 * モジュール名
	 */
	public function getModuleName()
	{
		return "DB Connect module";
	}

	/*
	 * モジュールを初期化する
	 */
	public function init( charcoal_Config $config )
	{
	}

	/*
	 * モジュールの処理を実行する
	 */
	public function execute( $action, charcoal_Request $request, charcoal_ProcedureContext $context, charcoal_Response $response )
	{
		// フォームデータを取得
		$backend    = $request->get( "backend" );
		$server     = $request->get( "server" );
		$user       = $request->get( "user" );
		$password   = $request->get( "password" );
		$db_name    = $request->get( "db_name" );
		$charset    = $request->get( "charset" );

		// YAMLにするための配列データを作成
		$data[ 'backend' ]   = $backend;
		$data[ 'server' ]    = $server;
		$data[ 'user' ]      = $user;
		$data[ 'password' ]  = $password;
		$data[ 'db_name' ]   = $db_name;
		$data[ 'charset' ]   = $charset;

		// Spycを使い、ファイルに書き出す
		$profile_name = charcoal_Profile::getProfileName();
		$config_file = WEBAPP_DIR . "/" . APPLICATION . "/config/data_sources/pear_db.$profile_name.data_source.yml";

		$yaml = Spyc::YAMLDump($data,4,60); 

		$fp = fopen($config_file,"w");
		fwrite($fp, $yaml);
		fclose($fp);

		// DataSource取得
		$data_source = $context->getDB()->getDataSource();

		// 接続チェック
		try{
			$data_source->connect( $backend, $user, $password, $server, NULL );
		}
		catch ( Exception $ex ){
			$context->set( "error_message", "DB接続できません。" );
print "failed!";
			return "failed";
		}

		// データベース名を出力
		$context->set( "db_name", $db_name );

		// 接続情報を保存
		$context->getSession()->set( "backend", $backend );
		$context->getSession()->set( "server", $server );
		$context->getSession()->set( "user", $user );
		$context->getSession()->set( "password", $password );
		$context->getSession()->set( "db_name", $db_name );
		$context->getSession()->set( "charset", $charset );

		return "success";
	}
}
?>