-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Juan Rodríguez
committed
Sep 19, 2018
0 parents
commit 67555bd
Showing
15 changed files
with
576 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
/vendor/ | ||
composer.lock | ||
/.idea |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
MIT License | ||
|
||
Copyright (c) 2018 PcComponentes | ||
|
||
Permission is hereby granted, free of charge, to any person obtaining a copy | ||
of this software and associated documentation files (the "Software"), to deal | ||
in the Software without restriction, including without limitation the rights | ||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
copies of the Software, and to permit persons to whom the Software is | ||
furnished to do so, subject to the following conditions: | ||
|
||
The above copyright notice and this permission notice shall be included in all | ||
copies or substantial portions of the Software. | ||
|
||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
SOFTWARE. |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,108 @@ | ||
# Migration | ||
Entendemos como migración a la ejecución de todas las tareas relacionadas con la preparación de la infrastructura. Por ejemlo, crear tablas en una BD, alterarlas, insertas datos iniciales, crear colas en un sistema de mensajería, etc. | ||
|
||
Esta librería proporciona la base para ejecutar esas migraciones mediante comandos de consola [con el componente de symfony](https://symfony.com/doc/current/components/console.html). | ||
|
||
## Crear una migración | ||
Se recomienda crear un directorio ```migrations``` en la raíz del proyecto, y un subdirectorio con el tipo de migración que contendrá, por ejemplo ```mysql```, ```rabbitmq```, o similares. | ||
Por cada migración, creamos un fichero PHP con la declaración de una clase, que por convenio, debe llamarse igual que el fichero. Dicha clase __no debe estar en un namespace__. | ||
|
||
Tu clase migración necesitará como dependencias en su constructor, lo mínimo necesario para hacer el trabajo. Por ejemplo, veámos como sería una migración de \PDO, para crear o borrar una tabla ```ejemlo```. | ||
Deberá implementar la interfaz ```Pccomponentes\Migration\Migration```, con las tareas a realizar. | ||
|
||
```php | ||
<?php | ||
declare(strict_types=1); | ||
|
||
use Pccomponentes\Migration\Migration; | ||
|
||
class PdoMigration implements Migration | ||
{ | ||
private $connection; | ||
|
||
public function __construct(\PDO $connection) | ||
{ | ||
$this->connection = $connection; | ||
} | ||
|
||
public function upOperation(): void | ||
{ | ||
$this->connection->exec(' | ||
CREATE TABLE example ( | ||
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, | ||
name VARCHAR(30) NOT NULL | ||
) | ||
'); | ||
} | ||
|
||
public function downOperation(): void | ||
{ | ||
$this->connection->exec('DROP TABLE example'); | ||
} | ||
} | ||
|
||
``` | ||
|
||
## Ejecutar una migración | ||
Para ejecutar la migración, tenemos dos caminos: Usando el framework de symfony, o creando nuestra propia aplicación symfony de consola. | ||
|
||
### Con el framework symfony | ||
Si nuestro proyecto cuenta con el framework de symfony, podemos meter el comando directamente al contenedor de dependencias, y marcarlo con el tag correspondiente, para que el kernel y el ejecutable ```console``` de symfony lo ejecute directamente. | ||
Para añadirlo, sería modificar el fichero ```config/services.yml``` con esta información: | ||
```yaml | ||
pdo.connection: | ||
class: \PDO | ||
arguments: | ||
- 'mysql:dbname=testdb;host=localhost;port=3306' | ||
- 'user' | ||
- 'password' | ||
|
||
pdo_migration_command: | ||
class: Pccomponentes\Migration\MigrationCommand | ||
arguments: | ||
- 'pdo' # nombre del comando, que se concatenará a "migration:" | ||
- '%kernel.root_dir%/../migrations/pdo' # Ruta al directorio de las migraciones para este comando | ||
- ['@pdo.connection'] # Dependencias para construir nuestra migración | ||
tags: | ||
- { name: console.command } | ||
``` | ||
### Creando nuestra propia aplicación | ||
Para poder ejecutar el comando, previamente tenemos que generar una aplicación. Para ello, deberíamos crear un fichero PHP con el siguiente contenido, modificado lo necesario para adaptarlo a tu nuestro proyecto. | ||
Como será un ejecutable de consola, lo llamaremos ```console``` sin extensión, y lo pondremos en un directorio ```bin``` en la raíz de tu proyecto. | ||
```php | ||
#!/usr/bin/env php | ||
<?php | ||
require __DIR__ . '/../vendor/autoload.php'; | ||
use Symfony\Component\Console\Application; | ||
use Pccomponentes\Migration\MigrationCommand; | ||
$application = new Application(); | ||
$application->addCommands( | ||
[ | ||
new MigrationCommand( | ||
'pdo', | ||
__DIR__ . '/../migration/pdo', | ||
[ | ||
new \PDO('mysql:dbname=testdb;host=localhost;port=3306', 'user', 'password') | ||
] | ||
) | ||
] | ||
); | ||
$application->run(); | ||
``` | ||
|
||
## Ejecutar el comando | ||
|
||
Para ejecutar el comando en modo UP, sería: | ||
```$> bin/console migration:pdo --operation=up PdoMigration``` | ||
|
||
Si queremos ejecutar un DOWN: | ||
```$> bin/console migration:pdo --operation=down PdoMigration``` | ||
|
||
Además es posible ejecutar múltiples ficheros del mismo tipo, en orden. Por ejemplo: | ||
|
||
```$> bin/console migration:pdo --operation=up PdoMigration1 PdoMigration2 PdoMigration3``` |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
{ | ||
"name": "pccomponentes/migration", | ||
"description": "Simple migration system with symfony console commands", | ||
"authors": [ | ||
{ | ||
"name": "Juan G. Rodríguez Carrión", | ||
"email": "[email protected]" | ||
} | ||
], | ||
"license": "MIT", | ||
"type": "library", | ||
"autoload": { | ||
"psr-4": { | ||
"Pccomponentes\\Migration\\": "src/" | ||
} | ||
}, | ||
"autoload-dev": { | ||
"psr-4": { | ||
"Pccomponentes\\Migration\\Tests\\": "tests/" | ||
} | ||
}, | ||
"require": { | ||
"php": "^7.1", | ||
"symfony/console": "^4.1" | ||
}, | ||
"require-dev": { | ||
"pccomponentes/ganchudo": "^1.0", | ||
"phpunit/phpunit": "^7.3", | ||
"squizlabs/php_codesniffer": "^3.3" | ||
} | ||
} |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
ganchudo: | ||
inspectors: | ||
- name: 'Composer Validation' | ||
command: 'composer.phar validate --strict' | ||
- name: 'Php Linter' | ||
command: 'php -l <iterator>' | ||
iterator: | ||
in: ['src', 'tests'] | ||
exclude: [] | ||
file: '*.php' | ||
- name: 'Php Code Sniffer' | ||
command: 'vendor/bin/phpcs --standard=phpcs.xml.dist' | ||
- name: 'PhpUnit' | ||
command: 'vendor/bin/phpunit --configuration phpunit.xml.dist --no-coverage --colors=always' | ||
timeout: 3600 |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
<?php | ||
/** | ||
* This disaster was designed by | ||
* @author Juan G. Rodríguez Carrión <[email protected]> | ||
*/ | ||
declare(strict_types=1); | ||
|
||
use Pccomponentes\Migration\Migration; | ||
|
||
class MigrationTested implements Migration | ||
{ | ||
private $constructorArgs; | ||
private $upOperationCalled; | ||
private $downOperationCalled; | ||
|
||
public function __construct() | ||
{ | ||
$this->constructorArgs = \func_get_args(); | ||
$this->upOperationCalled = false; | ||
$this->downOperationCalled = false; | ||
} | ||
|
||
public function constructorArgs(): array | ||
{ | ||
return $this->constructorArgs; | ||
} | ||
|
||
public function upOperationCalled(): bool | ||
{ | ||
return $this->upOperationCalled; | ||
} | ||
|
||
public function downOperationCalled(): bool | ||
{ | ||
return $this->downOperationCalled; | ||
} | ||
|
||
public function upOperation(): void | ||
{ | ||
$this->upOperationCalled = true; | ||
} | ||
|
||
public function downOperation(): void | ||
{ | ||
$this->downOperationCalled = true; | ||
} | ||
} |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
<?xml version="1.0"?> | ||
<ruleset name="Project rules"> | ||
<description>Project rules.</description> | ||
<file>src</file> | ||
<file>tests</file> | ||
<rule ref="PSR2"/> | ||
<rule ref="PSR1.Methods.CamelCapsMethodName.NotCamelCaps"> | ||
<exclude-pattern>tests/*</exclude-pattern> | ||
</rule> | ||
<rule ref="Generic.Files.LineLength.TooLong"> | ||
<exclude-pattern>tests/*</exclude-pattern> | ||
</rule> | ||
<arg name="colors" /> | ||
</ruleset> |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,17 @@ | ||
<?xml version="1.0" encoding="UTF-8"?> | ||
|
||
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" | ||
xsi:noNamespaceSchemaLocation="http://schema.phpunit.de/5.7/phpunit.xsd" | ||
bootstrap="vendor/autoload.php" | ||
colors="true" | ||
convertErrorsToExceptions="true" | ||
convertNoticesToExceptions="true" | ||
convertWarningsToExceptions="true" | ||
> | ||
|
||
<testsuites> | ||
<testsuite name="Test Suite"> | ||
<directory>tests</directory> | ||
</testsuite> | ||
</testsuites> | ||
</phpunit> |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
<?php | ||
/** | ||
* This disaster was designed by | ||
* @author Juan G. Rodríguez Carrión <[email protected]> | ||
*/ | ||
declare(strict_types=1); | ||
namespace Pccomponentes\Migration; | ||
|
||
interface Migration | ||
{ | ||
public function upOperation(): void; | ||
public function downOperation(): void; | ||
} |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,70 @@ | ||
<?php | ||
/** | ||
* This disaster was designed by | ||
* @author Juan G. Rodríguez Carrión <[email protected]> | ||
*/ | ||
declare(strict_types=1); | ||
namespace Pccomponentes\Migration; | ||
|
||
use Symfony\Component\Console\Command\Command; | ||
use Symfony\Component\Console\Input\InputArgument; | ||
use Symfony\Component\Console\Input\InputInterface; | ||
use Symfony\Component\Console\Input\InputOption; | ||
use Symfony\Component\Console\Output\OutputInterface; | ||
|
||
final class MigrationCommand extends Command | ||
{ | ||
private $loader; | ||
|
||
private const OPERATION_UP = 'up'; | ||
private const OPERTATION_DOWN = 'down'; | ||
|
||
public function __construct(string $commandName, string $migrationDir, array $migrationArgs) | ||
{ | ||
parent::__construct("migration:{$commandName}"); | ||
$this->loader = new MigrationLoader($migrationDir, $migrationArgs); | ||
} | ||
|
||
protected function configure(): void | ||
{ | ||
$this | ||
->setDescription('Do "UP" operation over a specified migration files.') | ||
->addOption( | ||
'operation', | ||
'op', | ||
InputOption::VALUE_REQUIRED, | ||
sprintf('Available operations: %s, %s', self::OPERATION_UP, self::OPERTATION_DOWN) | ||
) | ||
->addArgument( | ||
'migrations', | ||
InputArgument::IS_ARRAY | InputArgument::REQUIRED, | ||
'Who migration classes do you want to migrate (separate multiple names with a space)?' | ||
); | ||
} | ||
|
||
protected function execute(InputInterface $input, OutputInterface $output): int | ||
{ | ||
try { | ||
$operation = $input->getOption('operation'); | ||
$executor = new MigrationExecutor( | ||
$this->loader->load($input->getArgument('migrations')) | ||
); | ||
switch ($operation) { | ||
case self::OPERATION_UP: | ||
$executor->upOperation(); | ||
return 0; | ||
case self::OPERTATION_DOWN: | ||
$executor->downOperation(); | ||
return 0; | ||
default: | ||
$output->writeln(sprintf('<error>Invalid operation %s</error>', $operation)); | ||
$output->write('<comment>Available operations: </comment>'); | ||
$output->writeln(sprintf('<options=bold>%s, %s</>', self::OPERATION_UP, self::OPERTATION_DOWN)); | ||
return 1; | ||
} | ||
} catch (\Exception $e) { | ||
$output->writeln(sprintf('<error>Exception: %s</error>', $e->getMessage())); | ||
return 1; | ||
} | ||
} | ||
} |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
<?php | ||
/** | ||
* This disaster was designed by | ||
* @author Juan G. Rodríguez Carrión <[email protected]> | ||
*/ | ||
declare(strict_types=1); | ||
namespace Pccomponentes\Migration; | ||
|
||
final class MigrationExecutor | ||
{ | ||
private $migrations; | ||
|
||
public function __construct(array $migrations) | ||
{ | ||
$this->migrations = $migrations; | ||
} | ||
|
||
public function migrations(): array | ||
{ | ||
return $this->migrations; | ||
} | ||
|
||
public function upOperation(): void | ||
{ | ||
\array_walk( | ||
$this->migrations, | ||
function (Migration $migration) { | ||
$migration->upOperation(); | ||
} | ||
); | ||
} | ||
|
||
public function downOperation(): void | ||
{ | ||
\array_walk( | ||
$this->migrations, | ||
function (Migration $migration) { | ||
$migration->downOperation(); | ||
} | ||
); | ||
} | ||
} |
Oops, something went wrong.