<commit_before><?php
class Generation{
	public function __construct($config){
		$this->_set_config($config);
	}

	/**
	 * 输出mvc文件
	 * @Author   zjf
	 * @DateTime 2017-03-11
	 * @param 	 Array $config 		配置信息
	 * @return   array     			输出的每个文件的信息
	 */
	public function output_mvc_file(){
		
		// 获取配置文件
		$generation_config = remove_json_indent($this->generation_config);

		// 生成bean
		$beans = json_decode($generation_config, TRUE);
		
		if ($beans == null) {
			return_json("配置文件格式有误，请检查配置文件是否符合json格式",false);
		}

		// 处理beans（填入初始值）
		$this->_handle_beans($beans);
		// var_dump($beans);die();
		//循环生成
		foreach ($beans as $bean_name => $bean) {
			
			//models
			/**
			 * Loader：public function model($model, $name = '', $db_conn = FALSE)
			 * $model是模型的名字
			 * $name是模型使用的名字（未设置会$name = $model）
			 * 加载模型文件前会先》：$model = ucfirst($model)
			 * eg：
			 * $this->load('xxx_xxx_model');，用$this->xxx_xxx_model使用，找Xxx_xxx_model.php加载
			 * $this->load('xxx_Xxx_Model');，用$this->xxx_Xxx_Model使用，找Xxx_Xxx_Model.php加载
			 */
			$model_name = ucfirst($bean_name);
			ob_start();
	        require('./m_template.php');
	        $model = ob_get_contents();
	        @ob_end_clean();
	        if (!is_dir($this->folder['m'])) mkdir($this->folder['m']);
	  		file_put_contents("{$this->folder['m']}/{$model_name}_model.php", $model);
			
			//views
			ob_start();
	        require('./v_template.php');
	        $view = ob_get_contents();
	        @ob_end_clean();
	        if (!is_dir($this->folder['v'])) mkdir($this->folder['v']);
	  		file_put_contents("{$this->folder['v']}/$bean_name.html", $view);

	  		//controllers
	  		/**
	  		 * （$RTR是路由类的单例的引用：$RTR =& load_class('Router', 'core', isset($routing) ? $routing : NULL);
	  		 * 加载控制器前会进行：$class = ucfirst($RTR->class);
	  		 * $method = $RTR->method;
	  		 */
	  		$controller_name = ucfirst($bean_name);
	  		ob_start();
	        require('./c_template.php');
	        $view = ob_get_contents();
	        @ob_end_clean();
	        if (!is_dir($this->folder['c'])) mkdir($this->folder['c']);
	  		file_put_contents("{$this->folder['c']}/$controller_name.php", $view);
		}

		//header
		ob_start();
		require('./header_template.php');
		$view = ob_get_contents();
		@ob_end_clean();
		file_put_contents("{$this->folder['v']}/header.html", $view);

		//footer
		ob_start();
		require('./footer_template.php');
		$view = ob_get_contents();
		@ob_end_clean();
		file_put_contents("{$this->folder['v']}/footer.html", $view);

		return true;
	}

	/**
	 * 创建表的bean
	 * @Author   zjf
	 * @DateTime 2017-03-10
	 * @return   string     返回表对应的配置（json）字符串
	 */
	public function create_tables_bean(){
		// 1。获取tables数组并处理成规定格式
		$tables_source = $this->_get_tables_info();
		if (json_encode($tables_source) === false) {
			return_json("读取数据库“{$this->db}”中表的信息发生错误（错误原因：创建表的语句中的中文不是utf8编码）", false);
		}
		$tables = array();
		// var_dump($tables_source);die();
		foreach ($tables_source as $table_name => $table_source) {
			$tables[$table_name] = array();
			$tables[$table_name]['tbl_comment'] = $table_source['tbl_comment'];
			// 主键
			foreach ($table_source['col'] as $column) {
				if ($column['key'] == "PRI") {
					// 主键
					$col['field'] = $column['field'];
					$col['comment'] = $column['comment'];
					$tables[$table_name]['id'][] = $col;
				}
			}

			// 外键
			// $matchs[1]：这张表连接的字段，$matchs[2]：主表，$matchs[3]：主表的字段
			preg_match_all("/FOREIGN KEY \(`(.*?)`\) REFERENCES `(.*?)` \(`(.*?)`\)/",$table_source['create_str'],$matchs);
			foreach ($matchs[1] as $key => $value) {
				$join_table_name = $matchs[2][$key];
				$tables[$table_name]['join'][$join_table_name]['pri_field'] = "{$matchs[2][$key]}.{$matchs[3][$key]}";
				$tables[$table_name]['join'][$join_table_name]['join_field'] = "$table_name.{$matchs[1][$key]}";
			}

			// 普通字段
			foreach ($table_source['col'] as $column) {
				if ($column['extra'] != 'auto_increment') {
					$col['field'] = $column['field'];
					$col['comment'] = $column['comment'];
					// type和validation
					if ($left_bracket_pos = strpos($column['type'],'(')) {
						// 有左括号
						$type = substr($column['type'], 0, $left_bracket_pos);
						$type_bracket = substr($column['type'], $left_bracket_pos + 1, -1);
					}else{
						$type = $column['type'];
					}
					switch ($type) {
						// 数字
						case 'int':
							$col['type'] = 'input';
							$col['validation'] = 'type="number" ';
							$col['validation'] .= 'maxlength="'.$type_bracket.'" ';
							break;
						// 字符串
						case 'varchar':
							$col['type'] = 'input';
							$col['validation'] = 'maxlength="'.$type_bracket.'" ';
							break;
						case 'text':
							$col['type'] = 'text';
							break;
						// enum和set
						case 'enum':
							$col['type'] = 'select';
							$col['select_options'] = explode(',', str_replace("'", '', $type_bracket));
							break;
						case 'set':
							$col['type'] = 'multichoice';
							$col['multichoice_options'] = explode(',', str_replace("'", '', $type_bracket));
							break;
						// 日期和时间
						case 'datetime':
							$col['type'] = 'datetime';
							break;
						case 'timestamp':
							$col['type'] = 'timestamp';
							break;
						case 'date':
							$col['type'] = 'date';
							break;
						case 'time':
							$col['type'] = 'time';
							break;
						case 'year':
							$col['type'] = 'year';
							break;
						default:
							$col['type'] = 'input';
							break;
					}
					// 是否为null
					$col['validation'] = ($column['is_nullable'] == 'NO' && $column['default'] === null) || $column['key'] == 'PRI' ? 'required ' : '';
					$tables[$table_name]['col'][] = $col;
				}
			}
			
		}
		// foreach ($tables_source[$matchs[1]]['col'] as $column_for_join) {
		// 	$join_col = array();
		// 	$join_col['field'] = $column_for_join['field'];
		// 	$join_col['comment'] = $column_for_join['comment'];
		// 	$tables[$table_name]['join'][$matchs[1]]['col'][] = $join_col;
		// }
		// var_dump($tables);die();

		// 将tables数组转换为json字符串（不自动转换为unicode编码），调整缩进并返回
		return add_json_indent(json_unescaped_unicode_encode($tables));
	}

	/**
	 * 获取数据库中的全部表
	 * @Author   zjf<commit_msg>fix a bug when bulid table bean.<commit_after><?php
class Generation{
	public function __construct($config){
		$this->_set_config($config);
	}

	/**
	 * 输出mvc文件
	 * @Author   zjf
	 * @DateTime 2017-03-11
	 * @param 	 Array $config 		配置信息
	 * @return   array     			输出的每个文件的信息
	 */
	public function output_mvc_file(){
		
		// 获取配置文件
		$generation_config = remove_json_indent($this->generation_config);

		// 生成bean
		$beans = json_decode($generation_config, TRUE);
		
		if ($beans == null) {
			return_json("配置文件格式有误，请检查配置文件是否符合json格式",false);
		}

		// 处理beans（填入初始值）
		$this->_handle_beans($beans);
		// var_dump($beans);die();
		//循环生成
		foreach ($beans as $bean_name => $bean) {
			
			//models
			/**
			 * Loader：public function model($model, $name = '', $db_conn = FALSE)
			 * $model是模型的名字
			 * $name是模型使用的名字（未设置会$name = $model）
			 * 加载模型文件前会先》：$model = ucfirst($model)
			 * eg：
			 * $this->load('xxx_xxx_model');，用$this->xxx_xxx_model使用，找Xxx_xxx_model.php加载
			 * $this->load('xxx_Xxx_Model');，用$this->xxx_Xxx_Model使用，找Xxx_Xxx_Model.php加载
			 */
			$model_name = ucfirst($bean_name);
			ob_start();
	        require('./m_template.php');
	        $model = ob_get_contents();
	        @ob_end_clean();
	        if (!is_dir($this->folder['m'])) mkdir($this->folder['m']);
	  		file_put_contents("{$this->folder['m']}/{$model_name}_model.php", $model);
			
			//views
			ob_start();
	        require('./v_template.php');
	        $view = ob_get_contents();
	        @ob_end_clean();
	        if (!is_dir($this->folder['v'])) mkdir($this->folder['v']);
	  		file_put_contents("{$this->folder['v']}/$bean_name.html", $view);

	  		//controllers
	  		/**
	  		 * （$RTR是路由类的单例的引用：$RTR =& load_class('Router', 'core', isset($routing) ? $routing : NULL);
	  		 * 加载控制器前会进行：$class = ucfirst($RTR->class);
	  		 * $method = $RTR->method;
	  		 */
	  		$controller_name = ucfirst($bean_name);
	  		ob_start();
	        require('./c_template.php');
	        $view = ob_get_contents();
	        @ob_end_clean();
	        if (!is_dir($this->folder['c'])) mkdir($this->folder['c']);
	  		file_put_contents("{$this->folder['c']}/$controller_name.php", $view);
		}

		//header
		ob_start();
		require('./header_template.php');
		$view = ob_get_contents();
		@ob_end_clean();
		file_put_contents("{$this->folder['v']}/header.html", $view);

		//footer
		ob_start();
		require('./footer_template.php');
		$view = ob_get_contents();
		@ob_end_clean();
		file_put_contents("{$this->folder['v']}/footer.html", $view);

		return true;
	}

	/**
	 * 创建表的bean
	 * @Author   zjf
	 * @DateTime 2017-03-10
	 * @return   string     返回表对应的配置（json）字符串
	 */
	public function create_tables_bean(){
		// 1。获取tables数组并处理成规定格式
		$tables_source = $this->_get_tables_info();
		if (json_encode($tables_source) === false) {
			return_json("读取数据库“{$this->db}”中表的信息发生错误（错误原因：创建表的语句中的中文不是utf8编码）", false);
		}
		$tables = array();
		// var_dump($tables_source);die();
		foreach ($tables_source as $table_name => $table_source) {
			$tables[$table_name] = array();
			$tables[$table_name]['tbl_comment'] = $table_source['tbl_comment'];
			// 主键
			foreach ($table_source['col'] as $column) {
				if ($column['key'] == "PRI") {
					// 主键
					$col['field'] = $column['field'];
					$col['comment'] = $column['comment'];
					$tables[$table_name]['id'][] = $col;
				}
			}

			// 外键
			// $matchs[1]：这张表连接的字段，$matchs[2]：主表，$matchs[3]：主表的字段
			preg_match_all("/FOREIGN KEY \(`(.*?)`\) REFERENCES `(.*?)` \(`(.*?)`\)/",$table_source['create_str'],$matchs);
			foreach ($matchs[1] as $key => $value) {
				$join_table_name = $matchs[2][$key];
				$tables[$table_name]['join'][$join_table_name]['pri_field'] = "{$matchs[2][$key]}.{$matchs[3][$key]}";
				$tables[$table_name]['join'][$join_table_name]['join_field'] = "$table_name.{$matchs[1][$key]}";
			}

			// 普通字段
			foreach ($table_source['col'] as $column) {
				if ($column['extra'] != 'auto_increment') {
					// 重置col。不然可能给字段加上多余的信息
					$col = array();
					$col['field'] = $column['field'];
					$col['comment'] = $column['comment'];
					// type和validation
					if ($left_bracket_pos = strpos($column['type'],'(')) {
						// 有左括号
						$type = substr($column['type'], 0, $left_bracket_pos);
						$type_bracket = substr($column['type'], $left_bracket_pos + 1, -1);
					}else{
						$type = $column['type'];
					}
					switch ($type) {
						// 数字
						case 'int':
							$col['type'] = 'input';
							$col['validation'] = 'type="number" ';
							$col['validation'] .= 'maxlength="'.$type_bracket.'" ';
							break;
						// 字符串
						case 'varchar':
							$col['type'] = 'input';
							$col['validation'] = 'maxlength="'.$type_bracket.'" ';
							break;
						case 'text':
							$col['type'] = 'text';
							break;
						// enum和set
						case 'enum':
							$col['type'] = 'select';
							$col['select_options'] = explode(',', str_replace("'", '', $type_bracket));
							var_dump($column);
							break;
						case 'set':
							$col['type'] = 'multichoice';
							$col['multichoice_options'] = explode(',', str_replace("'", '', $type_bracket));
							break;
						// 日期和时间
						case 'datetime':
							$col['type'] = 'datetime';
							break;
						case 'timestamp':
							$col['type'] = 'timestamp';
							break;
						case 'date':
							$col['type'] = 'date';
							break;
						case 'time':
							$col['type'] = 'time';
							break;
						case 'year':
							$col['type'] = 'year';
							break;
						default:
							$col['type'] = 'input';
							break;
					}
					// 是否为null
					$col['validation'] = ($column['is_nullable'] == 'NO' && $column['default'] === null) || $column['key'] == 'PRI' ? 'required ' : '';
					$tables[$table_name]['col'][] = $col;
				}
			}
			
		}
		// foreach ($tables_source[$matchs[1]]['col'] as $column_for_join) {
		// 	$join_col = array();
		// 	$join_col['field'] = $column_for_join['field'];
		// 	$join_col['comment'] = $column_for_join['comment'];
		// 	$tables[$table_name]['join'][$matchs[1]]['col'][] = $join_col;
		// }
		// var_dump($tables);die();

		// 将tables数组转换为json字符串（不自动转换为unicode编码），调整缩进并返回
		var_dump($tables);
		return add_json_indent(json_unescaped_unicode_encode($tables));
	}

	/**
	 * 获取数据库中的全部表
	 * @Author   zjf
{'fraction_non_alphanumeric': 0.21720447543376034, 'fraction_numerical': 0.005026755310523755, 'mean_word_length': 3.1420416386836805, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 53, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6632372', 'n_tokens_mistral': 5838, 'n_tokens_neox': 4864, 'n_words': 644}