Add some handy shortcuts for typical migration tasks

This will make it much easier for extension developers (and also less
error-prone) to create migrations for things like creating tables,
renaming columns and so on...
This commit is contained in:
Franz Liedke 2016-02-25 00:50:03 +09:00
parent ad95a44e7d
commit db7a03fbe5
2 changed files with 96 additions and 1 deletions

View File

@ -26,7 +26,7 @@
"illuminate/config": "5.1.*",
"illuminate/container": "5.1.*",
"illuminate/contracts": "5.1.*",
"illuminate/database": "5.1.*",
"illuminate/database": "^5.1.31",
"illuminate/events": "5.1.*",
"illuminate/filesystem": "5.1.*",
"illuminate/hashing": "5.1.*",

95
src/Database/Migration.php Executable file
View File

@ -0,0 +1,95 @@
<?php
/*
* This file is part of Flarum.
*
* (c) Toby Zerner <toby.zerner@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Flarum\Database;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Schema\Builder;
/**
* Migration factory.
*
* Implements some handy shortcuts for creating typical migrations.
*/
abstract class Migration
{
/**
* Create a table.
*/
public static function createTable($name, callable $definition)
{
return [
'up' => function (Builder $schema) use ($name, $definition) {
$schema->create($name, $definition);
},
'down' => function (Builder $schema) use ($name) {
$schema->drop($name);
}
];
}
/**
* Rename a table.
*/
public static function renameTable($from, $to)
{
return [
'up' => function (Builder $schema) use ($from, $to) {
$schema->rename($from, $to);
},
'down' => function (Builder $schema) use ($from, $to) {
$schema->rename($to, $from);
}
];
}
/**
* Add columns to a table.
*/
public static function addColumns($tableName, array $columnDefinitions)
{
return [
'up' => function (Builder $schema) use ($tableName, $columnDefinitions) {
$schema->table($tableName, function (Blueprint $table) use ($columnDefinitions) {
foreach ($columnDefinitions as $columnName => $options) {
$type = array_shift($options);
$table->addColumn($type, $columnName, $options);
}
});
},
'down' => function (Builder $schema) use ($tableName, $columnDefinitions) {
$schema->table($tableName, function (Blueprint $table) use ($columnDefinitions) {
$table->dropColumn(array_keys($columnDefinitions));
});
}
];
}
/**
* Rename a column.
*/
public static function renameColumn($tableName, $from, $to)
{
return [
'up' => function (Builder $schema) use ($tableName, $from, $to) {
$schema->table($tableName, function (Blueprint $table) use ($from, $to) {
$table->renameColumn($from, $to);
});
},
'down' => function (Builder $schema) use ($tableName, $from, $to) {
$schema->table($tableName, function (Blueprint $table) use ($from, $to) {
$table->renameColumn($to, $from);
});
}
];
}
}