コード例 #1
0
ファイル: PurArray.php プロジェクト: rintaun/himawari
	/**
	 * Serialize an array to a file. Unless provided, the serialization
	 * format is derived from the file path extension.
	 * 
	 * Options include:
	 * - format Serialization method (js and json accepted);
	 * - from_encoding Encoding of the provided array
	 * - to_encoding Encoding of the destination file
	 * 
	 * Javascript is meant to be understood as JSON surrounded by parenthesis, not
	 * as the full Javascript language. This form is usefull when text editors
	 * support the Javascript synthax and not the JSON one.
	 * 
	 * JSON imposes the UTF-8 encoding. When converting to/from it, it is not the 
	 * PHP array which is encoded/decoded but the JSON string. Also, always 
	 * provide the source encoding when reading from a file written in a 
	 * different encoding than UTF-8.
	 * 
	 * @return boolean True on success
	 * @param string $path Path to the destination file
	 * @param array $array Array to serialize
	 * @param array $options[optional]
	 */
	public static function write($path,array $array,array $options=array()){
		$options = self::sanitize($options);
		if(!isset($options['format'])){
			$dot = strrpos(basename($path),'.');
			if($dot===false) throw new Exception('Format Undertermined From Path: "'.basename($path).'"');
			$format = substr(basename($path),$dot+1);
		}
		switch($format){
			case 'json':
				$array = PurJson::encode($array,$options);
				break;
			case 'js':
				$array = PurJson::encode($array,$options);
				$array = '('.$array.')';
				break;
			default:
				throw new Exception('Unsupported Format: "'.$format.'"');
		}
		return PurFile::write($path,$array,$options);
	}