Skip to content

Instantly share code, notes, and snippets.

@tylerdiaz
Created July 23, 2011 23:58
Show Gist options
  • Save tylerdiaz/1102019 to your computer and use it in GitHub Desktop.
Save tylerdiaz/1102019 to your computer and use it in GitHub Desktop.
#!/usr/bin/env php
<?php
$db_connection_favorites = array(
'default' => array(
'host' => '127.0.0.1',
'user' => 'root',
'password' => 'root',
'db' => 'database_name'
),
);
$command_function = array(
'command' => NULL,
'command_key' => NULL,
'database' => NULL,
'database_table' => NULL,
'data' => array(),
);
$content = file_get_contents('php://stdin');
$str_sliced = str_split($content);
$auto_input = "";
$validate_fields = FALSE;
$field_to_validate = FALSE;
$hash_rocket_push = FALSE;
$command_array = explode(" ", ltrim(trim($content)));
$command_response = array($content);
$conserve_whitespace = "";
foreach($str_sliced as $char):
if(ctype_space($char)) $conserve_whitespace .= $char;
else break;
endforeach;
$response_string = '';
$command_number = 0;
foreach($command_array as $command):
$expected_response = explode('/', $command);
if($expected_response[0] == "respond" || $expected_response[0] == "result" || $expected_response[0] == "return"): // For now we'll only loop through the commands we're familiar with!
$command_function['command'] = $expected_response[0];
$command_function['command_key'] = $expected_response[1];
else:
$expected_response = explode(':', $command);
if(isset($expected_response[1])):
$command_function['data'][$expected_response[0]] = $expected_response[1];
else:
switch($command_number):
case 1:
$command_function['database'] = $command;
break;
case 2:
$command_function['database_table'] = $command;
break;
endswitch;
endif;
endif;
$command_number++;
endforeach;
if($command_function['command_key'] == "array" || $command_function['command_key'] == "insert" || $command_function['command_key'] == "update" || $command_function['command_key'] == "get"):
foreach($command_function['data'] as $command => $value):
if($value != "all" || $value != "true"):
$value = explode(",", $value);
endif;
// Lets go through the features the person wants to enable!
if($command == "input"): // Need to auto complete those $this->input->post('') tags? We got yah.
if($value == "all"):
$auto_input['all'] = TRUE;
else:
foreach($value as $input_value):
$auto_input[$input_value] = TRUE;
endforeach;
endif;
elseif($command == "push"):
$hash_rocket_push = TRUE;
elseif($command == "validation" || $command == "validate"):
// WORK IN PROGRESS! (...)
$response_string .= $conserve_whitespace."\$this->load->library('form_validation'); \n\n";
if($value == "all"):
$field_to_validate['all'] = TRUE;
else:
foreach($value as $input_value):
$field_to_validate[$input_value] = TRUE;
endforeach;
endif;
endif;
endforeach;
// Connecting to the database...
if(isset($db_connection_favorites[$command_function['database']])){
$conn = mysql_connect($db_connection_favorites[$command_function['database']]['host'],
$db_connection_favorites[$command_function['database']]['user'],
$db_connection_favorites[$command_function['database']]['password']) or die("Failed to connect: ".mysql_error());
} else {
// Here we could add some default fallback kind of thing...
$conn = mysql_connect($db_connection_favorites[$command_function['database']]['host'],
$db_connection_favorites[$command_function['database']]['user'],
$db_connection_favorites[$command_function['database']]['password']) or die("Failed to connect: ".mysql_error());
}
mysql_select_db($db_connection_favorites[$command_function['database']]['db'], $conn) or die("Failed to select DB: ".mysql_error());
// Now, getting the structure of the table!
if($command_function['database_table'] != NULL):
$table_info = mysql_query("DESCRIBE ".strtolower($command_function['database_table']));
$append_to_insert = "\n\n".$conserve_whitespace."\$this->db";
$longest_string = 2;
if($hash_rocket_push == TRUE || $validate_fields == TRUE):
while($row1 = mysql_fetch_assoc($table_info)):
if($hash_rocket_push == TRUE):
if(strlen($row1['Field']) > $longest_string):
$longest_string = strlen($row1['Field']);
endif;
elseif($validate_fields == TRUE):
$validation_rules = '';
if(isset($field_to_validate['all'])):
if($row1['Null'] == "NO") $validation_rules .= 'required|';
if(preg_match("/(int|float|decimal)/", $row1['Type'])) $validation_rules .= 'numeric';
if(preg_match("/(char|varchar)/", $row1['Type'])):
// Get whats the max character limit!
$amount_hack = explode("(", $row1['Type']);
$amount_hack = substr_replace($amount_hack[1], '', -1);
$validation_rules .= 'xss_clean|max_length['.$amount_hack.']';
if(preg_match("/(ip)/", $row1['Field'])) $validation_rules .= '|valid_ip'; // Kind of a bad guess sometimes but. Worth checking!
if(preg_match("/(email)/", $row1['Field'])) $validation_rules .= '|valid_email'; // Kind of a bad guess sometimes but. Worth checking!
endif;
if(preg_match("/(text|blob)/", $row1['Type'])) $validation_rules .= '|xss_clean|htmlspecialchars'; // Quick security patches
if($validation_rules == 'required|') $validation_rules = substr_replace($validation_rules, '', -1);
$response_string .= $conserve_whitespace."\$this->form_validation->set_rules('".$row1['Field']."', '".$command_function['database_table']." ".$row1['Field']."', '".$validation_rules."');\n";
elseif(isset($field_to_validate[$row1['Field']])):
if($row1['Null'] == "NO") $validation_rules .= 'required|';
if(preg_match("/(int|float|decimal)/", $row1['Type'])) $validation_rules .= 'numeric';
if(preg_match("/(char|varchar)/", $row1['Type'])):
// Get whats the max character limit!
$amount_hack = explode("(", $row1['Type']);
$amount_hack = substr_replace($amount_hack[1], '', -1);
$validation_rules .= 'xss_clean|max_length['.$amount_hack.']';
if(preg_match("/(ip)/", $row1['Field'])) $validation_rules .= '|valid_ip'; // Kind of a bad guess sometimes but. Worth checking!
if(preg_match("/(email)/", $row1['Field'])) $validation_rules .= '|valid_email'; // Kind of a bad guess sometimes but. Worth checking!
endif;
if(preg_match("/(text|blob)/", $row1['Type'])) $validation_rules .= '|xss_clean|htmlspecialchars'; // Quick security patches
if($validation_rules == 'required|') $validation_rules = substr_replace($validation_rules, '', -1);
$response_string .= $conserve_whitespace."\$this->form_validation->set_rules('".$row1['Field']."', '".$command_function['database_table']." ".$row1['Field']."', '".$validation_rules."');\n";
endif;
endif;
endwhile;
$table_info = mysql_query("DESCRIBE ".strtolower($command_function['database_table']));
endif;
if($validate_fields == TRUE) $response_string .= "\n";
if($command_function['command_key'] != "get") $response_string .= $conserve_whitespace.'$'.strtolower($command_function['database_table']).' = array('."\n";
while($row = mysql_fetch_array($table_info)):
$row['Type'] = strtolower($row['Type']);
if($command_function['command_key'] == "array"):
$value = $row['Default'];
if($hash_rocket_push == TRUE):
$hash_rockets = "";
$tabs = ceil(($longest_string-strlen($row['Field']))/4.5);
if(strlen($row['Field']) == 13 || strlen($row['Field']) == 11 || strlen($row['Field']) == 12 || strlen($row['Field']) > 18) $tabs++;
if(strlen($row['Field']) > 19) $tabs++;
$i = 0;
while($tabs > $i):
$hash_rockets .= "\t";
$i++;
endwhile;
$hash_rockets .= " => ";
else:
$hash_rockets = " => ";
endif;
// $hash_rocket_push;
if(isset($command_function['data']['input'])):
if(isset($auto_input['all']) == TRUE):
if(preg_match("/(ip)/", $row['Field'])):
$value = "\$this->input->ip_address()";
else:
$value = '$this->input->post(\''.$row['Field'].'\')';
endif;
elseif(isset($auto_input[$row['Field']]) == TRUE):
if(preg_match("/(ip)/", $row['Field'])):
$value = "\$this->input->ip_address()";
else:
$value = '$this->input->post(\''.$row['Field'].'\')';
endif;
endif;
endif;
if(preg_match("/(int|float|decimal)/", $row['Type'])):
$value = ($value != NULL ? $value : 0); // Still nothing? Let's add something to not leave that in blank
$response_string .= $conserve_whitespace."\t'".$row['Field']."'".$hash_rockets.$value.",\n";
else:
if( ! preg_match("/this/", $value) && ! is_numeric($value)) $value = "'".$value."'";
$response_string .= $conserve_whitespace."\t'".$row['Field']."'".$hash_rockets.$value.",\n";
endif;
elseif($command_function['command_key'] == "insert"):
if($row['Type'] == "timestamp" || $row['Type'] == "date" || $row['Type'] == "time" || $row['Type'] == "year" || $row['Type'] == "datetime"):
$append_to_insert .= "->set('".$row['Field']."', 'NOW()', false)";
elseif($row['Extra'] != "auto_increment"):
$value = $row['Default'];
if($hash_rocket_push == TRUE):
$hash_rockets = "";
$tabs = ceil(($longest_string-strlen($row['Field']))/4.5);
if(strlen($row['Field']) == 13 || strlen($row['Field']) == 11 || strlen($row['Field']) == 12 || strlen($row['Field']) > 18) $tabs++;
if(strlen($row['Field']) > 19) $tabs++;
$i = 0;
while($tabs > $i):
$hash_rockets .= "\t";
$i++;
endwhile;
$hash_rockets .= " => ";
else:
$hash_rockets = " => ";
endif;
// $hash_rocket_push;
if(isset($command_function['data']['input'])):
if(isset($auto_input['all']) == TRUE):
if(preg_match("/(ip)/", $row['Field'])):
$value = "\$this->input->ip_address()";
else:
$value = '$this->input->post(\''.$row['Field'].'\')';
endif;
elseif(isset($auto_input[$row['Field']]) == TRUE):
if(preg_match("/(ip)/", $row['Field'])):
$value = "\$this->input->ip_address()";
else:
$value = '$this->input->post(\''.$row['Field'].'\')';
endif;
endif;
endif;
if(preg_match("/(int|float|decimal)/", $row['Type'])):
$value = ($value != NULL ? $value : 0); // Still nothing? Let's add something to not leave that in blank
$response_string .= $conserve_whitespace."\t'".$row['Field']."'".$hash_rockets.$value.",\n";
else:
if( ! preg_match("/this/", $value) && ! is_numeric($value)) $value = "'".$value."'";
$response_string .= $conserve_whitespace."\t'".$row['Field']."'".$hash_rockets.$value.",\n";
endif;
endif;
elseif($command_function['command_key'] == "get"):
// It's a fair judgement to assume the main key is
// the one thats going to be used for searching the database
if($row['Key'] == "PRI"):
$response_string .= $conserve_whitespace.'$'.depluralize($command_function['database_table']).' = $this->db->get_where(\''.$command_function['database_table'].'\', array(\''.$row['Field'].'\' => $'.depluralize($command_function['database_table']).'_'.$row['Field'].'));'."\n\n";
$response_string .= $conserve_whitespace."if(\$".depluralize($command_function['database_table'])."->num_rows() > 0){\n".$conserve_whitespace."\t\$".depluralize($command_function['database_table'])."_data = \$".depluralize($command_function['database_table'])."->row_array();\n".$conserve_whitespace."\t\n".$conserve_whitespace."} else {\n".$conserve_whitespace."\t// ".depluralize($command_function['database_table'])." not found...\n".$conserve_whitespace."} ";
endif;
endif;
endwhile;
$response_string = substr_replace($response_string , '', -2)."\n";
if($command_function['command_key'] == "array"):
$response_string .= $conserve_whitespace.");";
elseif($command_function['command_key'] == "insert"):
$response_string .= $conserve_whitespace.");".$append_to_insert;
$response_string .= "->insert('".$command_function['database_table']."', \$".strtolower($command_function['database_table']).");";
endif;
else:
$table_info = mysql_query("SHOW TABLES");
echo strtoupper("Tables within ".$db_connection_favorites[$command_function['database']]['db']."\n========================\n");
while($row = mysql_fetch_array($table_info)):
echo $row['Tables_in_mino']."\n";
endwhile;
endif;
else: // This is for more generic purposes, and since I already built the other script, I had to have some way to extend it without getting in the codes way.
switch($command_function['command_key']):
case 'controller':
$new_function = "\n\t// --------------------------------------------------------------------\n\n\t/**\n\t * %2\$s page\n\t *\n\t * Function description\n\t *\n\t * @access public\n\t * @param\tstring\n\t * @return\tview\n\t * @route\tview/%1\$s/%2\$s\n\t */\n\n\tfunction %2\$s(){\n\t\t%3\$s\n\t}\n";
$response_string .= $conserve_whitespace.'<?php ';
$response_string .= $conserve_whitespace.'if ( ! defined(\'BASEPATH\')) exit(\'No direct script access allowed\');';
$response_string .= "\n\n/**\n * ".ucfirst($command_function['database_table'])." Controller\n *\n * author(s) ".exec('whoami')."\n * version 1.0\n * copyright Untitled - ".@date("F j, o")."\n * last_update: ".@date("F j, o")." by ".exec('whoami')."\n**/";
$response_string .= "\n\nclass ".ucfirst($command_function['database_table'])." extends Controller \n{\n";
$response_string .= "\tvar \$under_development = FALSE;\n";
$response_string .= "\n\tfunction __construct(){\n \t\tparent::Controller();\n\t}\n";
// Start functions
$functions = array('create', 'retrieve', 'update', 'delete');
foreach($functions as $function):
$function_data = "echo 'New function';";
if($function == "create" || $function == "compose" || $function == "build" || $function == "new" || $function == "make"):
$function_data = ""; // Coming soon!
elseif($function == "retrieve" || $function == "read" || $function == "fetch" || $function == "search" || $function == "view"):
$function_data = ""; // Coming soon!
elseif($function == "update" || $function == "edit"):
$function_data = ""; // Coming soon!
elseif($function == "delete" || $function == "destroy" || $function == "erase" || $function == "remove"):
$function_data = ""; // Coming soon!
endif;
$response_string .= sprintf($new_function, $command_function['database_table'], $function, $function_data);
endforeach;
// End of file
$response_string .= "\n\n} \n\n\n/* End of file ".$command_function['database_table'].".php */\n/* Location: ./system/application/controllers/".$command_function['database_table'].".php */";
break;
case 'model':
break;
case 'view':
break;
endswitch;
// This is a more sophisticated MVC generator, since it doesn't generate code for you as a solid block it kind of generates code based on your specific needs
endif;
function depluralize($word){
// https://sites.google.com/site/chrelad/notes-1/pluraltosingularwithphp
$rules = array(
'ss' => false,
'os' => 'o',
'ies' => 'y',
'xes' => 'x',
'oes' => 'o',
'ies' => 'y',
'ves' => 'f',
's' => '');
// Loop through all the rules and do the replacement.
foreach(array_keys($rules) as $key){
// If the end of the word doesn't match the key,
// it's not a candidate for replacement. Move on
// to the next plural ending.
if(substr($word, (strlen($key) * -1)) != $key) continue;
// If the value of the key is false, stop looping
// and return the original version of the word.
if($key === false) return $word;
// We've made it this far, so we can do the
// replacement.
return substr($word, 0, strlen($word) - strlen($key)) . $rules[$key];
}
return $word;
}
// Whew! All done, let's say what we need to say...
echo $response_string;
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment