Created
August 25, 2025 17:27
-
-
Save agusvama/462868e56fe0295487ea6d2a7fa7b46a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| // Uso: $ php sql_to_seeder.php archivo.sql NombreDelSeeder nombre_tabla | |
| if ($argc < 4) { | |
| echo "Uso: php sql_to_seeder.php archivo.sql NombreDelSeeder nombre_tabla\n"; | |
| exit(1); | |
| } | |
| $sqlFile = $argv[1]; | |
| $seederName = $argv[2]; | |
| $tableName = $argv[3]; | |
| if (!file_exists($sqlFile)) { | |
| echo "No existe el archivo: $sqlFile\n"; | |
| exit(1); | |
| } | |
| $sql = file_get_contents($sqlFile); | |
| // Busca sentencias tipo: INSERT INTO `tabla` (...) VALUES (...), (...); | |
| preg_match_all('/INSERT (?:IGNORE )?INTO .*? \((.*?)\) VALUES\s*(.*?);/is', $sql, $matches, PREG_SET_ORDER); | |
| echo "<?php\n\n"; | |
| echo "use Illuminate\\Database\\Seeder;\n"; | |
| echo "use Illuminate\\Support\\Facades\\DB;\n\n"; | |
| echo "class {$seederName} extends Seeder\n"; | |
| echo "{\n"; | |
| echo " public function run(): void\n"; | |
| echo " {\n"; | |
| echo " \$datos = [\n"; | |
| foreach ($matches as $match) { | |
| $columns = array_map('trim', explode(',', str_replace('`', '', $match[1]))); | |
| $rows = preg_split('/\),\s*\(/', trim($match[2], '() ')); | |
| foreach ($rows as $row) { | |
| $values = str_getcsv($row, ',', "'", "\\"); // maneja comillas | |
| $assoc = array_combine($columns, $values); | |
| echo " ["; | |
| $pairs = []; | |
| foreach ($assoc as $col => $val) { | |
| $val = trim($val); | |
| if ($val === 'NULL') { | |
| $pairs[] = "'$col' => null"; | |
| } else { | |
| $pairs[] = "'$col' => '$val'"; | |
| } | |
| } | |
| echo implode(', ', $pairs) . "],\n"; | |
| } | |
| } | |
| echo " ];\n\n"; | |
| echo " DB::table('{$tableName}')->insert(\$datos);\n"; | |
| echo " }\n"; | |
| echo "}\n"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment