<?php
 * 将markdown文件中的表格转化为对应的sql语句
 * 表格格式:http://git.ibbd.net/ibbd/ibbd-bc-py/blob/master/doc/db-tables.md 
 *
 * @example
### table中文说明:tablename
desc....
字段       | 类型        | 其他属性 | 说明
---        | ---         | ---      | ---
fieldname1 | varchar(50) | index    | 该字段的说明
 *
 * @author Alex <cyy0523xc@gmail.com>
 * @copyright IBBD
 * @see 
 * @todo 组合索引,前缀索引
 * @version 20141014
 */
define('PATTORN_TABLE_NAME',     '/^##+.*(:|:)(?P<tablename>(data|user|log)_[a-z_]+)\s*$/');
define('PATTORN_TABLE_BEGIN',    '/^\-+\s*\|\s*\-+\s*\|\s*\-+/');
define('PATTORN_TABLE_COMMENT',  '/^##+\s*(?P<comment>.*?)(:|:)/');
define('DEFAULT_NOT_NULL',       true);
$md_file = 'db-tables.md';
$create_sql_file = 'ibbd_bc_create_table.sql';
$lines = file($md_file);
$table_name = '';
$table_field_begin = false;
$table_sql = array();
$sql_field_begin = false;
$table_comment = '';
$indexs = array();
foreach ($lines as $line) {
    $line = trim($line);
    if ('' === $table_name) {
        
        $table_name = getTableName($line);
        
        if (!empty($table_name)) { 
            if (1 === preg_match(PATTORN_TABLE_COMMENT, $line, $matchs)) {
                $table_comment = trim($matchs['comment']);
            } else {
                $table_comment = '';
            }
        }
    } else {
        if (false === $table_field_begin) {
            
            $table_field_begin = checkTableFieldBegin($line);
            
            if (true === $table_field_begin) {
                $table_sql[$table_name] = "\nCREATE TABLE `{$table_name}` {";
            }
        } else {
            if ('' === $line) {
                
                if (!empty($indexs)) {
                    $index_sql = implode(",\n", $indexs);
                    $table_sql[$table_name] .= ",\n{$index_sql}";
                } 
                
                $table_sql[$table_name] .= "\n} ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='{$table_comment}';\n";
                
                $table_field_begin    = false;
                $table_name           = '';
                $sql_field_begin      = false;
                $indexs               = array();
            } else {
                
                if (true === $sql_field_begin) {
                    $table_sql[$table_name] .= ',';
                } else {
                    $sql_field_begin = true;
                }
                
                $arr = explode('|', $line);
                
                $field_name    = trim($arr[0]);
                $field_name    = str_replace("\\", '', $field_name);
                $field_type    = strtoupper(trim($arr[1]));
                $field_comment = trim($arr[3]);
                
                $ext = array();
                DEFAULT_NOT_NULL && $ext[] = 'NOT NULL';
                $arr[2] = trim($arr[2]);
                if (!empty($arr[2])) {
                    
                    $arr[2]  = strtoupper($arr[2]); 
                    $ext_arr = explode(',', $arr[2]);
                    foreach ($ext_arr as $attr) {
                        $attr = trim($attr);
                        $attr = str_replace("\\", '', $attr);
                        switch ($attr) {
                        case "PRIMARY":
                            $ext[] = 'PRIMARY KEY';
                            break;
                        case 'UNIQUE':
                            $ext[] = 'UNIQUE KEY';
                            break;
                        case 'AUTO_INCREMENT':
                            $ext[] = 'AUTO_INCREMENT';
                            break;
                        case 'INDEX':
                            $indexs[] = "    INDEX (`{$field_name}`)";
                            break;
                        default:
                            if ('DEFAULT' === substr($attr, 0, 7)) {
                                $ext[] = $attr;
                            }
                            break;
                        } 
                    } 
                } 
                $ext = empty($ext) ? '' : implode(' ', $ext);
                
                $table_sql[$table_name] .= "\n    `{$field_name}` {$field_type} {$ext} COMMENT '{$field_comment}'";
            }
        }
    }
} 
$sql  = "# md文件:http://git.ibbd.net/ibbd/ibbd-bc-py/blob/master/doc/db-tables.md\n";
$sql .= "# Create By http://git.ibbd.net/ibbd/ibbd-bc-py/blob/master/doc/markdown2sql.php\n";
$sql .= "# Create At " . date("Y-m-d H:i:s") . "\n\n\n";
$sql .= implode("", $table_sql);
echo $sql;
file_put_contents($create_sql_file, $sql);
function getTableName($line) 
{
    if (1 === preg_match(PATTORN_TABLE_NAME, $line, $matchs)) {
        return $matchs['tablename'];
    }
    return '';
}
function checkTableFieldBegin($line) {
    if (1 === preg_match(PATTORN_TABLE_BEGIN, $line)) {
        return true;
    }
    return false;
}