Update "tools" directory to be compliant with the php-cs-fixer

This commit is contained in:
2023-04-13 21:53:13 +02:00
parent ba83207264
commit e719b3e11c
5 changed files with 791 additions and 715 deletions

View File

@@ -1,14 +1,18 @@
#!/usr/bin/php5 #!/usr/bin/php5
<?php <?php
if (! isset ($argv[1])) if (! isset($argv[1])) {
die("No file to decode provided\n"); die("No file to decode provided\n");
}
$file = $argv[1]; $file = $argv[1];
if (! file_exists ($file)) if (! file_exists($file)) {
die("File $file not found\n"); die("File $file not found\n");
if (! is_readable ($file)) }
if (! is_readable($file)) {
die("File $file not readable\n"); die("File $file not readable\n");
if (! is_writeable ($file)) }
if (! is_writeable($file)) {
die("File $file not writeable\n"); die("File $file not writeable\n");
}
print_r(json_decode(file_get_contents($file))); print_r(json_decode(file_get_contents($file)));

View File

@@ -3,24 +3,27 @@
require_once(__DIR__ . "/../src/markdown.php"); require_once(__DIR__ . "/../src/markdown.php");
if (! isset ($argv[1])) if (! isset($argv[1])) {
{ file_put_contents(
file_put_contents ("php://stderr", "php://stderr",
"No file to convert in markdown provided\n"); "No file to convert in markdown provided\n"
);
exit(1); exit(1);
} }
if (! file_exists ($argv[1])) if (! file_exists($argv[1])) {
{ file_put_contents(
file_put_contents ("php://stderr", "php://stderr",
"The file to convert in markdown doesn't exists\n"); "The file to convert in markdown doesn't exists\n"
);
exit(2); exit(2);
} }
if (! is_readable ($argv[1])) if (! is_readable($argv[1])) {
{ file_put_contents(
file_put_contents ("php://stderr", "php://stderr",
"The file to convert in markdown is not readable\n"); "The file to convert in markdown is not readable\n"
);
exit(3); exit(3);
} }
$md = new markdown (); $md = new Domframework\Markdown();
echo $md->html(file_get_contents($argv[1])); echo $md->html(file_get_contents($argv[1]));

View File

@@ -1,174 +1,213 @@
#!/usr/bin/php #!/usr/bin/php
<?php <?php
/** DomFramework
@package domframework /**
@author Dominique Fournier <dominique@fournier38.fr> */ * DomFramework
* @package domframework
* @author Dominique Fournier <dominique@fournier38.fr>
*/
require_once(__DIR__ . "/../src/Getopts.php"); require_once(__DIR__ . "/../src/Getopts.php");
require_once(__DIR__ . "/../src/Dblayeroo.php"); require_once(__DIR__ . "/../src/Dblayeroo.php");
/** Generate the model files from an existing database /**
* Generate the model files from an existing database
* Provide the DSN to connect to the database, and the program will generate * Provide the DSN to connect to the database, and the program will generate
* the models/table.php files * the models/table.php files
*/ */
class modelGenerator class ModelGenerator
{ {
/** The DSN provided by the user /**
* The DSN provided by the user
*/ */
private $dsn; private $dsn;
/** The modelsDir provided by the user /**
* The modelsDir provided by the user
*/ */
private $modelsDir; private $modelsDir;
/** The namespace name provided by the user /**
* The namespace name provided by the user
*/ */
private $namespaceName; private $namespaceName;
/** The dblayer object /**
* The dblayer object
*/ */
private $db; private $db;
/** The constructor /**
* The constructor
*/ */
public function __construct() public function __construct()
{ {
$getopts = new Domframework\Getopts(); $getopts = new Domframework\Getopts();
$getopts->add("Help", "?h", "help", "Help of the software"); $getopts->add("Help", "?h", "help", "Help of the software");
$getopts->add ("DSN", "", "dsn:", "DSN - Data Source Name\n". $getopts->add(
"DSN",
"",
"dsn:",
"DSN - Data Source Name\n" .
" Exemple : --dsn \"mysql:dbname=DBNAME\"", " Exemple : --dsn \"mysql:dbname=DBNAME\"",
"dsn"); "dsn"
$getopts->add ("Output", "o:", "output:", );
"Output directory, ./models by default", "dir"); $getopts->add(
$getopts->add ("Namespace", "n:", "namespace:", "Output",
"o:",
"output:",
"Output directory, ./models by default",
"dir"
);
$getopts->add(
"Namespace",
"n:",
"namespace:",
"The namespace (if '', not added), models by default", "The namespace (if '', not added), models by default",
"namespaceName"); "namespaceName"
$getopts->add ("Username", "u:", "username:", "Username to connect", );
"username"); $getopts->add(
$getopts->add ("Password", "p:", "password:", "Password to connect", "Username",
"password"); "u:",
if ($getopts->get ("Help")) "username:",
"Username to connect",
"username"
);
$getopts->add(
"Password",
"p:",
"password:",
"Password to connect",
"password"
);
if ($getopts->get("Help")) {
die($getopts->help()); die($getopts->help());
if ($getopts->get ("DSN") === false) }
{ if ($getopts->get("DSN") === false) {
file_put_contents("php://stderr", "ERROR: The DSN is not provided\n"); file_put_contents("php://stderr", "ERROR: The DSN is not provided\n");
exit(1); exit(1);
} }
$dsn = $getopts->get("DSN"); $dsn = $getopts->get("DSN");
$modelsDir = $getopts->get("Output"); $modelsDir = $getopts->get("Output");
if ($modelsDir === false) if ($modelsDir === false) {
$modelsDir = "./models"; $modelsDir = "./models";
if (! file_exists ($modelsDir) || ! is_dir ($modelsDir)) }
{ if (! file_exists($modelsDir) || ! is_dir($modelsDir)) {
file_put_contents ("php://stderr", file_put_contents(
"ERROR: The modelsDir '$modelsDir' doesn't exists or is not a directory\n"); "php://stderr",
"ERROR: The modelsDir '$modelsDir' doesn't exists or is not a directory\n"
);
exit(1); exit(1);
} }
$this->dsn = $dsn; $this->dsn = $dsn;
$this->modelsDir = $modelsDir; $this->modelsDir = $modelsDir;
$this->namespaceName = $getopts->get("Namespace"); $this->namespaceName = $getopts->get("Namespace");
try try {
{ $this->db = new Domframework\Dblayeroo(
$this->db = new Domframework\Dblayeroo ($dsn, $dsn,
$getopts->get("Username"), $getopts->get("Username"),
$getopts->get ("Password")); $getopts->get("Password")
} );
catch (\Exception $e) } catch (\Exception $e) {
{
file_put_contents("php://stderr", $e->getMessage() . "\n"); file_put_contents("php://stderr", $e->getMessage() . "\n");
exit(3); exit(3);
} }
} }
/** List all the existing tables in the database /**
* List all the existing tables in the database
*/ */
public function listTables() public function listTables()
{ {
return $this->db->listTables(); return $this->db->listTables();
} }
/** Create the model file from the $tableName /**
* Create the model file from the $tableName
* @param string $tableName The table to examine * @param string $tableName The table to examine
*/ */
public function createModel($tableName) public function createModel($tableName)
{ {
if (file_exists ($this->modelsDir."/$tableName".".php")) if (file_exists($this->modelsDir . "/$tableName" . ".php")) {
{ file_put_contents(
file_put_contents ("php://stderr", "php://stderr",
"WARNING: File " . $this->modelsDir . "/$tableName" . ".php already exists. " . "WARNING: File " . $this->modelsDir . "/$tableName" . ".php already exists. " .
"SKIP\n"); "SKIP\n"
);
return; return;
} }
echo "Create File " . $this->modelsDir . "/$tableName" . ".php\n"; echo "Create File " . $this->modelsDir . "/$tableName" . ".php\n";
$schema = $this->db->getTableSchema($tableName); $schema = $this->db->getTableSchema($tableName);
$f = ""; $f = "";
$f .= "<" . "?" . "php\n\n"; $f .= "<" . "?" . "php\n\n";
if ($this->namespaceName === false) if ($this->namespaceName === false) {
$f .= "namespace models;\n\n"; $f .= "namespace models;\n\n";
elseif ($this->namespaceName !== "") } elseif ($this->namespaceName !== "") {
$f .= "namespace $this->namespaceName;\n\n"; $f .= "namespace $this->namespaceName;\n\n";
}
$f .= "require_once (\"domframework/dblayeroo.php\");\n\n"; $f .= "require_once (\"domframework/dblayeroo.php\");\n\n";
$f .= "/** The model for $tableName table in the database\n */\n"; $f .= "/**
* The model for $tableName table in the database\n
*/\n";
$f .= "class $tableName extends \dblayeroo\n"; $f .= "class $tableName extends \dblayeroo\n";
$f .= "{\n"; $f .= "{\n";
$f .= " /** The constructor connect to database\n */\n"; $f .= " /**
* The constructor connect to database\n
*/\n";
$f .= " public function __construct ()\n {\n"; $f .= " public function __construct ()\n {\n";
$f .= " // The table name\n"; $f .= " // The table name\n";
$f .= " \$this->table (\"$tableName\");\n\n"; $f .= " \$this->table (\"$tableName\");\n\n";
$f .= " // The fields name and parameters\n"; $f .= " // The fields name and parameters\n";
$f .= " \$this->fields (array (\n"; $f .= " \$this->fields (array (\n";
foreach ($schema["fields"] as $field=>$params) foreach ($schema["fields"] as $field => $params) {
{
$f .= " \"$field\" => array (\"" . implode("\", \"", $params) . $f .= " \"$field\" => array (\"" . implode("\", \"", $params) .
"\"),\n"; "\"),\n";
} }
$f .= " ));\n\n"; $f .= " ));\n\n";
$f .= " // The primary key\n"; $f .= " // The primary key\n";
$f .= " \$this->primary (\"" . $schema["primary"] . "\");\n"; $f .= " \$this->primary (\"" . $schema["primary"] . "\");\n";
if (count ($schema["unique"])) if (count($schema["unique"])) {
{
$f .= "\n"; $f .= "\n";
$f .= " // The unique constraints\n"; $f .= " // The unique constraints\n";
$f .= " \$this->unique (array (\n"; $f .= " \$this->unique (array (\n";
foreach ($schema["unique"] as $unique) foreach ($schema["unique"] as $unique) {
{ if (is_array($unique)) {
if (is_array ($unique))
$f .= " array (\"" . implode("\", \"", $unique) . "\"),\n"; $f .= " array (\"" . implode("\", \"", $unique) . "\"),\n";
else } else {
$f .= " array (\"$unique\"),\n"; $f .= " array (\"$unique\"),\n";
} }
}
$f .= " ));\n"; $f .= " ));\n";
} }
$f .= "\n"; $f .= "\n";
$f .= " // The titles\n"; $f .= " // The titles\n";
$f .= " \$this->titles (array (\n"; $f .= " \$this->titles (array (\n";
foreach ($schema["fields"] as $field=>$params) foreach ($schema["fields"] as $field => $params) {
{
$f .= " \"$field\" => _(\"$field\"),\n"; $f .= " \"$field\" => _(\"$field\"),\n";
} }
$f .= " ));\n"; $f .= " ));\n";
if (count ($schema["foreign"])) if (count($schema["foreign"])) {
{
$f .= "\n"; $f .= "\n";
$f .= " // The foreign constraints\n"; $f .= " // The foreign constraints\n";
$f .= " \$this->foreign (array (\n"; $f .= " \$this->foreign (array (\n";
foreach ($schema["foreign"] as $field=>$params) foreach ($schema["foreign"] as $field => $params) {
$f .= " \"$field\" => array (\n \"" . $f .= " \"$field\" => array (\n \"" .
implode("\", \"", $params) . implode("\", \"", $params) .
"\"),\n"; "\"),\n";
}
$f .= " ));\n"; $f .= " ));\n";
$f .= "\n"; $f .= "\n";
$f .= " // And the associated objects\n"; $f .= " // And the associated objects\n";
if ($this->namespaceName === false) if ($this->namespaceName === false) {
$path = "\\models\\"; $path = "\\models\\";
elseif ($this->namespaceName !== "") } elseif ($this->namespaceName !== "") {
$path = "\\$this->namespaceName\\"; $path = "\\$this->namespaceName\\";
else } else {
$path = ""; $path = "";
foreach ($schema["foreign"] as $field=>$params) }
{ foreach ($schema["foreign"] as $field => $params) {
$objName = $params[0]; $objName = $params[0];
$f .= " \$this->foreign_$objName = new $path$objName ();\n"; $f .= " \$this->foreign_$objName = new $path$objName ();\n";
$f .= " \$this->setForeignObj (\$this->foreign_$objName);\n"; $f .= " \$this->setForeignObj (\$this->foreign_$objName);\n";
@@ -181,7 +220,8 @@ class modelGenerator
} }
} }
$modelGenerator = new modelGenerator (); $modelGenerator = new ModelGenerator();
$tables = $modelGenerator->listTables(); $tables = $modelGenerator->listTables();
foreach ($tables as $tableName) foreach ($tables as $tableName) {
$modelGenerator->createModel($tableName); $modelGenerator->createModel($tableName);
}

View File

@@ -1,50 +1,53 @@
#!/usr/bin/php #!/usr/bin/php
<?php <?php
/** DomFramework
/**
* DomFramework
* @package domframework * @package domframework
* @author Dominique Fournier <dominique@fournier38.fr> * @author Dominique Fournier <dominique@fournier38.fr>
*/ */
require_once(__DIR__ . "/../src/Dblayeroo.php"); require_once(__DIR__ . "/../src/Dblayeroo.php");
/** modelGraph /**
* modelGraph
* Allow to create the relational graph of an existing database * Allow to create the relational graph of an existing database
* Use GraphViz to generate the graph * Use GraphViz to generate the graph
* Request the database DSN to operate * Request the database DSN to operate
*/ */
class modelgraph class Modelgraph
{ {
// PROPERTIES // PROPERTIES
/** The connected object dblayeroo /**
* The connected object dblayeroo
*/ */
private $db; private $db;
/** The output file /**
* The output file
*/ */
private $output; private $output;
/** The constructor wait for $dsn /**
* The constructor wait for $dsn
* @param string $dsn The DSN to connect to database * @param string $dsn The DSN to connect to database
* @param string $username The username to connect to database * @param string $username The username to connect to database
* @param string $password The password to connect to database * @param string $password The password to connect to database
* @param string $output The output file to generate * @param string $output The output file to generate
*/ */
public function __construct($dsn, $username, $password, $output) public function __construct($dsn, $username, $password, $output)
// {{{
{ {
$this->output = $output; $this->output = $output;
$this->db = new Domframework\Dblayeroo($dsn, $username, $password); $this->db = new Domframework\Dblayeroo($dsn, $username, $password);
$this->graphvizCommande(); $this->graphvizCommande();
} }
// }}}
/** Generate the output file /**
* Generate the output file
*/ */
public function generate() public function generate()
// {{{
{
$tables = array ();
foreach ($this->db->listTables () as $table)
{ {
$tables = [];
foreach ($this->db->listTables() as $table) {
$tables[$table] = $this->db->getTableSchema($table); $tables[$table] = $this->db->getTableSchema($table);
} }
$d = "digraph G {\n"; $d = "digraph G {\n";
@@ -61,9 +64,10 @@ class modelgraph
$d .= " rankdir=RL\n"; $d .= " rankdir=RL\n";
// Generate the tables objects with the fields // Generate the tables objects with the fields
foreach ($tables as $table => $schema) foreach ($tables as $table => $schema) {
{ $d .= " /**
$d .= " /** TABLE '$table' */\n"; * TABLE '$table'
*/\n";
$d .= " \"$table\" [\n"; $d .= " \"$table\" [\n";
$d .= " shape = \"plaintext\"\n"; $d .= " shape = \"plaintext\"\n";
$d .= " label = <\n"; $d .= " label = <\n";
@@ -73,22 +77,24 @@ class modelgraph
$d .= "$table</TD></TR>\n"; $d .= "$table</TD></TR>\n";
// Display the fields // Display the fields
$i = 0; $i = 0;
foreach ($schema["fields"] as $field => $params) foreach ($schema["fields"] as $field => $params) {
{
$d .= " <TR>\n"; $d .= " <TR>\n";
$d .= " <TD SIDES=\"TBL\" PORT=\"OUT-$field\">"; $d .= " <TD SIDES=\"TBL\" PORT=\"OUT-$field\">";
if (key_exists ($field, $schema["foreign"])) if (key_exists($field, $schema["foreign"])) {
{
// Foreign Key // Foreign Key
$d .= "<FONT COLOR=\"#F02020\">!</FONT>"; $d .= "<FONT COLOR=\"#F02020\">!</FONT>";
} } elseif (
elseif (key_exists ("primary", $schema) && key_exists("primary", $schema) &&
$field === $schema["primary"]) $field === $schema["primary"]
$d .= "&#128273;"; // Primary key found ) {
elseif (in_array ("not null", $params)) $d .= "&#128273;";
$d .= "<FONT COLOR=\"#00B0E0\">&#9670;</FONT>"; // NOT NULL } elseif (in_array("not null", $params)) {
else // Primary key found
$d .= "<FONT COLOR=\"#00B0E0\">&#9670;</FONT>";
} else {
// NOT NULL
$d .= "&#9671;"; $d .= "&#9671;";
}
$d .= "</TD>\n"; $d .= "</TD>\n";
$d .= " <TD ALIGN=\"LEFT\" SIDES=\"TB\">"; $d .= " <TD ALIGN=\"LEFT\" SIDES=\"TB\">";
$d .= $field; $d .= $field;
@@ -103,11 +109,9 @@ class modelgraph
$d .= " ];\n"; $d .= " ];\n";
} }
// Generate the links between the tables // Generate the links between the tables
foreach ($tables as $table => $schema) foreach ($tables as $table => $schema) {
{
// "node1":"f2" -> "node5":"f0" []; // "node1":"f2" -> "node5":"f0" [];
foreach ($schema["foreign"] as $field => $params) foreach ($schema["foreign"] as $field => $params) {
{
$d .= "\"$table\":\"OUT-$field\" -> \"" . $params[0] . $d .= "\"$table\":\"OUT-$field\" -> \"" . $params[0] .
"\":\"IN-" . $params[1] . "\" "; "\":\"IN-" . $params[1] . "\" ";
$d .= "[];\n"; $d .= "[];\n";
@@ -117,29 +121,29 @@ class modelgraph
//echo $d; //echo $d;
$this->createJPG($d); $this->createJPG($d);
} }
// }}}
/** Look for the dot command /**
* Look for the dot command
* @return the full path of 'dot' command * @return the full path of 'dot' command
*/ */
private function graphvizCommande() private function graphvizCommande()
// {{{
{ {
foreach (explode (":", getenv ("PATH")) as $path) foreach (explode(":", getenv("PATH")) as $path) {
{ if (file_exists("$path/dot")) {
if (file_exists ("$path/dot"))
return "$path/dot"; return "$path/dot";
} }
throw new \Exception ("Can not find 'dot' executable. Install graphviz",
500);
} }
// }}} throw new \Exception(
"Can not find 'dot' executable. Install graphviz",
500
);
}
/** Generate the JPEG file with graphviz /**
* Generate the JPEG file with graphviz
* @param string $content The content of the GV file * @param string $content The content of the GV file
*/ */
private function createJPG($content) private function createJPG($content)
// {{{
{ {
$tmp = tempnam("/tmp", "modelgraph_"); $tmp = tempnam("/tmp", "modelgraph_");
file_put_contents($tmp, $content); file_put_contents($tmp, $content);
@@ -147,31 +151,32 @@ class modelgraph
"-o " . escapeshellarg($this->output) . " 2>&1"; "-o " . escapeshellarg($this->output) . " 2>&1";
exec($cmd, $output); exec($cmd, $output);
unlink($tmp); unlink($tmp);
if (!empty ($output)) if (!empty($output)) {
{
echo "ERROR : " . implode("\n", $output); echo "ERROR : " . implode("\n", $output);
exit(2); exit(2);
} }
} }
// }}}
} }
// MAIN PROGRAM // MAIN PROGRAM
if (isset ($argv[1]) && $argv[1] === "-h") if (isset($argv[1]) && $argv[1] === "-h") {
{
echo "Create the ER Diagram of a SQL database\n"; echo "Create the ER Diagram of a SQL database\n";
echo "Usage : \n"; echo "Usage : \n";
echo $argv[0] . " DSN username password outputfile.jpg\n"; echo $argv[0] . " DSN username password outputfile.jpg\n";
echo "DSN Examples : 'mysql:dbname=databaseName'\n"; echo "DSN Examples : 'mysql:dbname=databaseName'\n";
} }
if (! isset ($argv[1])) if (! isset($argv[1])) {
die("No DSN provided\n"); die("No DSN provided\n");
if (! isset ($argv[2])) }
if (! isset($argv[2])) {
die("No username provided\n"); die("No username provided\n");
if (! isset ($argv[3])) }
if (! isset($argv[3])) {
die("No password provided\n"); die("No password provided\n");
if (! isset ($argv[4])) }
if (! isset($argv[4])) {
die("No output file provided\n"); die("No output file provided\n");
}
$modelgraph = new modelgraph($argv[1], $argv[2], $argv[3], $argv[4]); $modelgraph = new modelgraph($argv[1], $argv[2], $argv[3], $argv[4]);
$modelgraph->generate(); $modelgraph->generate();

View File

@@ -1,6 +1,8 @@
#!/usr/bin/php #!/usr/bin/php
<?php <?php
/** DomFramework
/**
* DomFramework
* @package domframework * @package domframework
* @author Dominique Fournier <dominique@fournier38.fr> * @author Dominique Fournier <dominique@fournier38.fr>
* *
@@ -19,67 +21,86 @@ require_once (__DIR__."/../src/Dblayeroo.php");
require_once(__DIR__ . "/../src/Getopts.php"); require_once(__DIR__ . "/../src/Getopts.php");
require_once(__DIR__ . "/../src/Config.php"); require_once(__DIR__ . "/../src/Config.php");
/** Manage the configuration file /**
* Manage the configuration file
*/ */
class configuration extends \config class Configuration extends \Domframework\Config
{ {
/** The constructor of the configuration set the differents params /**
* The constructor of the configuration set the differents params
*/ */
function __construct () public function __construct()
{ {
$this->default = array ( $this->default = [
"db" => array ( "db" => [
"srcDSN" => "", "srcDSN" => "",
"srcUser" => null, "srcUser" => null,
"srcPassword" => null, "srcPassword" => null,
"dstDSN" => "", "dstDSN" => "",
"dstUser" => null, "dstUser" => null,
"dstPassword" => null, "dstPassword" => null,
), ],
"tables" => array ( "tables" => [
), ],
"tablesRel" => array ( "tablesRel" => [
), ],
"fields" => array ( "fields" => [
), ],
"tablesOrder" => array ( "tablesOrder" => [
), ],
"deleteContent" => null, "deleteContent" => null,
); ];
} }
} }
/** The main class /**
* The main class
*/ */
class main class Main
{ {
/** The constructor of the class do the main job /**
* The constructor of the class do the main job
*/ */
public function __construct() public function __construct()
{ {
// Manage the Getopts // Manage the Getopts
$getopts = new Domframework\Getopts(); $getopts = new Domframework\Getopts();
$getopts->add ("Help", "?h", array ("help"), "Help of the software"); $getopts->add("Help", "?h", ["help"], "Help of the software");
$getopts->add ("Step", "", array ("step:"), "Restart at provided step", $getopts->add(
"StepIdentifier"); "Step",
$getopts->add ("Debug", "", array ("debug"), "Display the SQL requests"); "",
$getopts->add ("Execute", "", array ("execute"), ["step:"],
"Execute the configuration without requesting data (start at step 5)"); "Restart at provided step",
if ($getopts->get ("Help")) "StepIdentifier"
);
$getopts->add("Debug", "", ["debug"], "Display the SQL requests");
$getopts->add(
"Execute",
"",
["execute"],
"Execute the configuration without requesting data (start at step 5)"
);
if ($getopts->get("Help")) {
die($getopts->help()); die($getopts->help());
if ($getopts->get ("Step")) }
{ if ($getopts->get("Step")) {
if (intval ($getopts->get ("Step")) < 0 || if (
intval ($getopts->get ("Step")) > 6) intval($getopts->get("Step")) < 0 ||
intval($getopts->get("Step")) > 6
) {
die("Invalid Step provided (Must be between 0 and 6)\n"); die("Invalid Step provided (Must be between 0 and 6)\n");
} }
if (empty ($getopts->restOfLine ())) }
if (empty($getopts->restOfLine())) {
throw new \Exception("No configuration file provided"); throw new \Exception("No configuration file provided");
if (count ($getopts->restOfLine ()) > 1) }
if (count($getopts->restOfLine()) > 1) {
throw new \Exception("Too much configuration file provided"); throw new \Exception("Too much configuration file provided");
}
$configurationFile = current($getopts->restOfLine()); $configurationFile = current($getopts->restOfLine());
if (! file_exists ($configurationFile)) if (! file_exists($configurationFile)) {
touch($configurationFile); touch($configurationFile);
}
$config = new Domframework\Configuration(); $config = new Domframework\Configuration();
$config->confFile = $configurationFile; $config->confFile = $configurationFile;
@@ -89,28 +110,30 @@ class main
$fields = $config->get("fields"); $fields = $config->get("fields");
$tablesOrder = $config->get("tablesOrder"); $tablesOrder = $config->get("tablesOrder");
$deleteContent = $config->get("deleteContent"); $deleteContent = $config->get("deleteContent");
if ($db["srcDSN"] === "" || $db["dstDSN"] === "") if ($db["srcDSN"] === "" || $db["dstDSN"] === "") {
$step = 0; $step = 0;
elseif (empty ($tables)) } elseif (empty($tables)) {
$step = 1; $step = 1;
elseif (empty ($tablesRel)) } elseif (empty($tablesRel)) {
$step = 2; $step = 2;
elseif (empty ($fields)) } elseif (empty($fields)) {
$step = 3; $step = 3;
elseif (empty ($tablesOrder)) } elseif (empty($tablesOrder)) {
$step = 4; $step = 4;
elseif ($deleteContent === null) } elseif ($deleteContent === null) {
$step = 5; $step = 5;
else } else {
$step = 6; $step = 6;
}
if ($getopts->get ("Step")) if ($getopts->get("Step")) {
$step = intval($getopts->get("Step")); $step = intval($getopts->get("Step"));
if ($getopts->get ("Execute")) }
if ($getopts->get("Execute")) {
$step = 5; $step = 5;
}
if ($step === 0) if ($step === 0) {
{
// Step 0: ask the connection parameters // Step 0: ask the connection parameters
echo "#### Entering step 0 : ask the connection parameters\n"; echo "#### Entering step 0 : ask the connection parameters\n";
$srcDSN = $this->ask("Enter SRC DSN"); $srcDSN = $this->ask("Enter SRC DSN");
@@ -119,71 +142,81 @@ class main
$dstDSN = $this->ask("Enter DST DSN"); $dstDSN = $this->ask("Enter DST DSN");
$dstUser = $this->ask("Enter DST User"); $dstUser = $this->ask("Enter DST User");
$dstPassword = $this->ask("Enter DST Password"); $dstPassword = $this->ask("Enter DST Password");
if ($srcUser === "") if ($srcUser === "") {
{
$srcUser = null; $srcUser = null;
$srcPassword = null; $srcPassword = null;
} }
if ($dstUser === "") if ($dstUser === "") {
{
$dstUser = null; $dstUser = null;
$dstPassword = null; $dstPassword = null;
} }
$value = array ( $value = [
"srcDSN" => $srcDSN, "srcDSN" => $srcDSN,
"srcUser" => $srcUser, "srcUser" => $srcUser,
"srcPassword" => $srcPassword, "srcPassword" => $srcPassword,
"dstDSN" => $dstDSN, "dstDSN" => $dstDSN,
"dstUser" => $dstUser, "dstUser" => $dstUser,
"dstPassword" => $dstPassword,); "dstPassword" => $dstPassword,];
$config->set("db", $value); $config->set("db", $value);
$db = $config->get("db"); $db = $config->get("db");
$step++; $step++;
} }
if ($step === 1) if ($step === 1) {
{
echo "#### Entering step 1: read the existing databases schemes\n"; echo "#### Entering step 1: read the existing databases schemes\n";
$srcDB = new Domframework\Dblayeroo ($db["srcDSN"], $db["srcUser"], $srcDB = new Domframework\Dblayeroo(
$db["srcPassword"]); $db["srcDSN"],
$db["srcUser"],
$db["srcPassword"]
);
$srcTables = $srcDB->listTables(); $srcTables = $srcDB->listTables();
$dstDB = new Domframework\Dblayeroo ($db["dstDSN"], $db["dstUser"], $dstDB = new Domframework\Dblayeroo(
$db["dstPassword"]); $db["dstDSN"],
$db["dstUser"],
$db["dstPassword"]
);
$dstTables = $dstDB->listTables(); $dstTables = $dstDB->listTables();
$value = array ( $value = [
"srcTables" => $srcTables, "srcTables" => $srcTables,
"dstTables" => $dstTables, "dstTables" => $dstTables,
); ];
$config->set("tables", $value); $config->set("tables", $value);
$step++; $step++;
echo "\n"; echo "\n";
} }
echo "#### Connect to the defined databases\n"; echo "#### Connect to the defined databases\n";
$srcDB = new Domframework\Dblayeroo ($db["srcDSN"], $db["srcUser"], $srcDB = new Domframework\Dblayeroo(
$db["srcPassword"]); $db["srcDSN"],
$dstDB = new Domframework\Dblayeroo ($db["dstDSN"], $db["dstUser"], $db["srcUser"],
$db["dstPassword"]); $db["srcPassword"]
);
$dstDB = new Domframework\Dblayeroo(
$db["dstDSN"],
$db["dstUser"],
$db["dstPassword"]
);
echo "\n"; echo "\n";
if ($step == 2) if ($step == 2) {
{
echo "#### Entering step 2: ask the relations between tables\n"; echo "#### Entering step 2: ask the relations between tables\n";
$tables = $config->get("tables"); $tables = $config->get("tables");
echo "# For each destination table, please provide the source table\n"; echo "# For each destination table, please provide the source table\n";
sort($tables["srcTables"]); sort($tables["srcTables"]);
echo "# Allowed source tables : " . implode(", ", $tables["srcTables"]) . echo "# Allowed source tables : " . implode(", ", $tables["srcTables"]) .
"\n"; "\n";
$value = array (); $value = [];
natsort($tables["dstTables"]); natsort($tables["dstTables"]);
foreach ($tables["dstTables"] as $table) foreach ($tables["dstTables"] as $table) {
{ while (1) {
while (1)
{
$value[$table] = $this->ask( $value[$table] = $this->ask(
"Destination Table '$table' filled by source table"); "Destination Table '$table' filled by source table"
if (in_array ($value[$table], $tables["srcTables"]) || );
$value[$table] === "") if (
in_array($value[$table], $tables["srcTables"]) ||
$value[$table] === ""
) {
continue 2; continue 2;
}
$this->error("The table '" . $value[$table] . " doesn't exists"); $this->error("The table '" . $value[$table] . " doesn't exists");
echo "# Allowed source tables : " . echo "# Allowed source tables : " .
implode(", ", $tables["srcTables"]) . "\n"; implode(", ", $tables["srcTables"]) . "\n";
@@ -195,21 +228,19 @@ class main
} }
$tablesRel = $config->get("tablesRel"); $tablesRel = $config->get("tablesRel");
if ($step === 3) if ($step === 3) {
{
echo "#### Entering step 3: ask the relation between fields\n"; echo "#### Entering step 3: ask the relation between fields\n";
echo "# For each destination table, if a source table is provided,\n" . echo "# For each destination table, if a source table is provided,\n" .
"# for each field, provide the source SQL request (can be field,\n" . "# for each field, provide the source SQL request (can be field,\n" .
"# CONCAT(), text between simple quotes, null...)\n"; "# CONCAT(), text between simple quotes, null...)\n";
if ($config->get("fields")) if ($config->get("fields")) {
$value = $config->get("fields"); $value = $config->get("fields");
else } else {
$value = array (); $value = [];
foreach ($tablesRel as $dstTable=>$srcTable) }
{ foreach ($tablesRel as $dstTable => $srcTable) {
echo "- Destination Table '$dstTable': "; echo "- Destination Table '$dstTable': ";
if ($srcTable === "") if ($srcTable === "") {
{
echo "No source table. SKIPPED\n"; echo "No source table. SKIPPED\n";
continue; continue;
} }
@@ -218,21 +249,24 @@ class main
$srcSchema = $srcDB->getTableSchema($srcTable); $srcSchema = $srcDB->getTableSchema($srcTable);
echo " List of the allowed fields: " . echo " List of the allowed fields: " .
implode(", ", array_keys($srcSchema["fields"])) . "\n"; implode(", ", array_keys($srcSchema["fields"])) . "\n";
foreach (array_keys ($dstSchema["fields"]) as $field) foreach (array_keys($dstSchema["fields"]) as $field) {
{ if (! key_exists($dstTable, $value)) {
if (! key_exists ($dstTable, $value)) $value[$dstTable] = [];
$value[$dstTable] = array (); }
if (! key_exists ($field, $value[$dstTable])) if (! key_exists($field, $value[$dstTable])) {
$value[$dstTable][$field] = ""; $value[$dstTable][$field] = "";
while (1) }
{ while (1) {
$oldval = (isset($config->get("fields")[$dstTable][$field])) ? $oldval = (isset($config->get("fields")[$dstTable][$field])) ?
$config->get("fields")[$dstTable][$field] : ""; $config->get("fields")[$dstTable][$field] : "";
$answer = $this->ask( $answer = $this->ask(
"Destination Table '$dstTable' field '$field'", $oldval); "Destination Table '$dstTable' field '$field'",
$oldval
);
$value[$dstTable][$field] = $answer; $value[$dstTable][$field] = $answer;
if (trim ($value[$dstTable][$field]) !== "") if (trim($value[$dstTable][$field]) !== "") {
break; break;
}
// TODO : Check if the field is valid (think about function) // TODO : Check if the field is valid (think about function)
$this->error("The field source must be defined !"); $this->error("The field source must be defined !");
} }
@@ -243,25 +277,24 @@ class main
echo "\n"; echo "\n";
} }
$fields = $config->get("fields"); $fields = $config->get("fields");
if ($step === 4) if ($step === 4) {
{
echo "#### Entering step 4: Order the tables by foreign keys\n"; echo "#### Entering step 4: Order the tables by foreign keys\n";
echo "# The tables with foreign keys constraint must be populated \n" . echo "# The tables with foreign keys constraint must be populated \n" .
"# after the tables depending of them\n"; "# after the tables depending of them\n";
$tablesToOrder = array (); $tablesToOrder = [];
foreach ($tablesRel as $dstTable=>$srcTable) foreach ($tablesRel as $dstTable => $srcTable) {
{ if ($srcTable !== "") {
if ($srcTable !== "")
$tablesToOrder[] = $dstTable; $tablesToOrder[] = $dstTable;
} }
while (1) }
{ while (1) {
echo "# Here are the tables to order: " . implode(",", $tablesToOrder) . echo "# Here are the tables to order: " . implode(",", $tablesToOrder) .
"\n"; "\n";
$tablesOrder = $this->ask("Order the tables, separated by commas"); $tablesOrder = $this->ask("Order the tables, separated by commas");
$tablesOrder = explode(",", $tablesOrder); $tablesOrder = explode(",", $tablesOrder);
if (count ($tablesToOrder) === count ($tablesOrder)) if (count($tablesToOrder) === count($tablesOrder)) {
break; break;
}
$this->error("Not all the tables are ordered"); $this->error("Not all the tables are ordered");
} }
$config->set("tablesOrder", $tablesOrder); $config->set("tablesOrder", $tablesOrder);
@@ -270,17 +303,15 @@ class main
} }
$tablesOrder = $config->get("tablesOrder"); $tablesOrder = $config->get("tablesOrder");
if ($step === 5) if ($step === 5) {
{ if ($deleteContent === null) {
if ($deleteContent === null)
{
echo "# The content of the destination tables can be deleted before\n" . echo "# The content of the destination tables can be deleted before\n" .
"# adding the source data.\n"; "# adding the source data.\n";
echo "# Attention: the order is important if there is foreign keys!\n" . echo "# Attention: the order is important if there is foreign keys!\n" .
"# Remove the most constraint tables before deleting the less\n" . "# Remove the most constraint tables before deleting the less\n" .
"# constraint ones\n"; "# constraint ones\n";
echo "# List of the destination tables: " . echo "# List of the destination tables: " .
implode (",", array_keys (array_diff ($tablesRel, array ("")))). implode(",", array_keys(array_diff($tablesRel, [""]))) .
"\n"; "\n";
$deleteContent = $this->ask("Get the list of the tables to be " . $deleteContent = $this->ask("Get the list of the tables to be " .
"cleaned, separated by comas"); "cleaned, separated by comas");
@@ -288,38 +319,32 @@ class main
$deleteContent = $config->get("deleteContent"); $deleteContent = $config->get("deleteContent");
} }
} }
if ($deleteContent !== "") if ($deleteContent !== "") {
{
echo "#### Entering step 5: delete tables content\n"; echo "#### Entering step 5: delete tables content\n";
foreach (explode (",", $deleteContent) as $table) foreach (explode(",", $deleteContent) as $table) {
{
$table = trim($table); $table = trim($table);
echo "- Delete content of table '$table'\n"; echo "- Delete content of table '$table'\n";
$dstDB->table ($table)->unique (array ())->delete ()->execute (); $dstDB->table($table)->unique([])->delete()->execute();
} }
$step = 6; $step = 6;
echo "\n"; echo "\n";
} } else {
else
{
echo "#### Entering step5: Skipped delete tables content\n"; echo "#### Entering step5: Skipped delete tables content\n";
$step = 6; $step = 6;
} }
if ($step === 6) if ($step === 6) {
{
echo "#### Entering step 6: populate the destination database with the " . echo "#### Entering step 6: populate the destination database with the " .
"configured data\n"; "configured data\n";
foreach ($tablesOrder as $dstTable) foreach ($tablesOrder as $dstTable) {
{
echo "- Populate table $dstTable:\n"; echo "- Populate table $dstTable:\n";
// Create the source SQL request. Add the alias name of the destination // Create the source SQL request. Add the alias name of the destination
// table to allow to import directely in the destination // table to allow to import directely in the destination
$sql = "SELECT "; $sql = "SELECT ";
$i = 0; $i = 0;
foreach ($fields[$dstTable] as $key=>$val) foreach ($fields[$dstTable] as $key => $val) {
{ if ($i > 0) {
if ($i > 0)
$sql .= ","; $sql .= ",";
}
$sql .= "$val AS $key"; $sql .= "$val AS $key";
$i++; $i++;
} }
@@ -331,16 +356,16 @@ class main
$dstDB->table($dstTable); $dstDB->table($dstTable);
$dstDB->fields($dstSchema["fields"]); $dstDB->fields($dstSchema["fields"]);
$dstDB->primary($dstSchema["primary"]); $dstDB->primary($dstSchema["primary"]);
foreach ($srcDB->directQuery ($sql) as $row) foreach ($srcDB->directQuery($sql) as $row) {
{
//print_r ($row); //print_r ($row);
$dstDB->clearRequest(); $dstDB->clearRequest();
$dstDB->insert() $dstDB->insert()
->setValues($row); ->setValues($row);
if (! $getopts->get ("Debug")) if (! $getopts->get("Debug")) {
echo "."; echo ".";
else } else {
echo $dstDB->getDisplayQuery(); echo $dstDB->getDisplayQuery();
}
$dstDB->execute(); $dstDB->execute();
} }
echo "\n"; echo "\n";
@@ -351,7 +376,8 @@ class main
echo "#### Entering step $step: End of process\n"; echo "#### Entering step $step: End of process\n";
} }
/** Ask a question to the user and return the answer /**
* Ask a question to the user and return the answer
* @param string $question the question message * @param string $question the question message
* @param string|null $proposal The optional pre-filled proposal * @param string|null $proposal The optional pre-filled proposal
* @return string The answer * @return string The answer
@@ -363,7 +389,8 @@ class main
return trim($console->readline($proposal)); return trim($console->readline($proposal));
} }
/** Display an error to the user /**
* Display an error to the user
* @param string $msg The error message to display * @param string $msg The error message to display
*/ */
public function error($msg) public function error($msg)
@@ -372,12 +399,9 @@ class main
} }
} }
try try {
{
$main = new \main(); $main = new \main();
} } catch (Exception $e) {
catch (Exception $e)
{
file_put_contents("php://stderr", $e->getMessage() . "\n"); file_put_contents("php://stderr", $e->getMessage() . "\n");
exit(4); exit(4);
} }