diff --git a/samples/Migration.php.sample b/samples/Migration.php.sample new file mode 100644 index 0000000..34a792d --- /dev/null +++ b/samples/Migration.php.sample @@ -0,0 +1,31 @@ +db()->tableExists('mi_tabla')) { + // return; + // } + } +} diff --git a/src/Command/Migration/MigrationCommand.php b/src/Command/Migration/MigrationCommand.php new file mode 100644 index 0000000..ad090b2 --- /dev/null +++ b/src/Command/Migration/MigrationCommand.php @@ -0,0 +1,74 @@ +requirePlugin()) { + return Command::FAILURE; + } + + $name = Utils::prompt( + label: 'Nombre de la migración', + placeholder: 'Ej: FixTablaUsuarios', + hint: 'El nombre debe empezar por mayúscula y solo puede contener letras, números y guiones bajos.', + regex: '/^[A-Z][a-zA-Z0-9_]*$/', + errorMessage: 'Inválido, debe empezar por mayúscula y solo puede contener letras, números y guiones bajos.' + ); + + $this->createMigration($name); + + return Command::SUCCESS; + } + + private function createMigration(string $name): void + { + $folder = 'Migration/'; + Utils::createFolder($folder); + + $fileName = $folder . $name . '.php'; + if (file_exists($fileName)) { + Utils::echo("* La migración " . $name . " YA EXISTE.\n"); + return; + } + + $samplePath = dirname(__DIR__, 3) . "/samples/Migration.php.sample"; + $sample = file_get_contents($samplePath); + + $migrationNameConst = strtolower(preg_replace('/(? OK.\n"); + + $newContentUse = InitEditor::addUse('use FacturaScripts\Core\Migrations;'); + if ($newContentUse) { + InitEditor::setInitContent($newContentUse); + } + + $newContentFunc = InitEditor::addToFunction('update', 'Migrations::runPluginMigration(new Migration\\' . $name . '());', true); + if ($newContentFunc) { + InitEditor::setInitContent($newContentFunc); + } + } +} diff --git a/src/Console/Application.php b/src/Console/Application.php index b7e1afc..8714193 100644 --- a/src/Console/Application.php +++ b/src/Console/Application.php @@ -167,6 +167,7 @@ private function getCommands(): array new \fsmaker\Command\Generator\ZipCommand(), new \fsmaker\Command\Init\InitCommand(), new \fsmaker\Command\List\ListCommand(), + new \fsmaker\Command\Migration\MigrationCommand(), new \fsmaker\Command\Model\ModelCommand(), new \fsmaker\Command\Plugin\PluginCommand(), new \fsmaker\Command\Test\TestCommand(), diff --git a/src/InitEditor.php b/src/InitEditor.php index 3a6ab31..782b49c 100644 --- a/src/InitEditor.php +++ b/src/InitEditor.php @@ -63,16 +63,17 @@ public static function addUse(string $useInstruction): ?string } /** - * Devuelve el contenido del fichero agregandole la linea introducida por `str`. Si quieres agregarla solo si no existe puedes colocar a true `checkIfNotExists` + * Devuelve el contenido del fichero agregandole la linea introducida por `str` a la función indicada. Si quieres agregarla solo si no existe puedes colocar a true `checkIfNotExists` * - Esta función si que escribe comentarios en la terminal + * @param string $functionName * @param string $instructionStr * @param bool $checkIfNotExists revisa si existe esa linea de código * @return ?string Si no ha sido exitosa la operación devuelve false si no pues el string modificado */ - public static function addToInitFunction(string $instructionStr, bool $checkIfNotExists = false): ?string + public static function addToFunction(string $functionName, string $instructionStr, bool $checkIfNotExists = false): ?string { // obtener el diagnostico general - $analysis = self::detectValidInitFunction(); + $analysis = self::detectValidFunction($functionName); // si algo va mal if (!$analysis['isValid']) { @@ -114,11 +115,24 @@ public static function addToInitFunction(string $instructionStr, bool $checkIfNo return mb_substr($info['initContent'], 0, $info['functionStart']) . $body . mb_substr($info['initContent'], $info['functionEnd']); } + /** + * Devuelve el contenido del fichero agregandole la linea introducida por `str` a la función `init`. Si quieres agregarla solo si no existe puedes colocar a true `checkIfNotExists` + * - Esta función si que escribe comentarios en la terminal + * @param string $instructionStr + * @param bool $checkIfNotExists revisa si existe esa linea de código + * @return ?string Si no ha sido exitosa la operación devuelve false si no pues el string modificado + */ + public static function addToInitFunction(string $instructionStr, bool $checkIfNotExists = false): ?string + { + return self::addToFunction('init', $instructionStr, $checkIfNotExists); + } + /** * Esta función analiza el fichero y detecta si está correcto y se puede agregar funciones. Devuelve información útil. + * @param string $functionName * @return array {isValid: bool, info: string|array} */ - public static function detectValidInitFunction(): array + public static function detectValidFunction(string $functionName): array { $str = self::getInitContent(); @@ -130,16 +144,16 @@ public static function detectValidInitFunction(): array } $error = ''; - $words = ['public', 'function', 'init', '(', ')', ':', 'void', '{']; + $words = ['public', 'function', $functionName, '(', ')', ':', 'void', '{']; // comprobar si solo existe una función init $matches = self::getSentenceMatches(self::removeSpaces($str), implode($words)); if (count($matches) !== 1) { if (count($matches) > 1) { - $error = '* Error(Init.php): Init mal formado. Existe más de una coincidencia de: "public function init(): void{".\n'; + $error = '* Error(Init.php): Init mal formado. Existe más de una coincidencia de: "public function ' . $functionName . '(): void{".\n'; } else {// $matches < 1 - $error = '* Error(Init.php): Init mal formado. No se ha podido encontrar "public function init(): void{".\n'; + $error = '* Error(Init.php): Init mal formado. No se ha podido encontrar "public function ' . $functionName . '(): void{".\n'; } return [ 'isValid' => false,