Last active
November 11, 2022 11:42
-
-
Save janyksteenbeek/1ca42f824636076247025b41cdc0e99f to your computer and use it in GitHub Desktop.
Laravel Cram Migration utility: This utility is used to cram a newly created Laravel migration file in between two migrations for correct order
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
<?php | |
/** | |
* Cram Migration utility | |
* ---------------------- | |
* | |
* This utility is used to cram a newly created Laravel migration file in between two migrations for correct order. | |
* It is useful when you have a lot of migrations and you want to insert a new one in between. | |
* | |
* Make sure your new migration file is named correctly, starting with 9999, e.g. 9999_create_users_table.php | |
* | |
* Usage: | |
* php ../../utils/cram-migration.php <migration-file> <desired-place> <last-in-order> | |
* | |
* @author Janyk Steenbeek <janyk@webmethod.nl> | |
* @license MIT | |
*/ | |
if (php_sapi_name() !== 'cli') { | |
die('This script can only be run from the command line.'); | |
} | |
if(basename(getcwd()) !== 'migrations') { | |
die('This script can only be run from the migrations directory.'); | |
} | |
if(count($argv) != 4) { | |
die("Usage: php cram-migration.php <migration-file> <desired-place> <last-in-order>"); | |
} | |
function pad($number) { | |
return str_pad($number, 4, '0', STR_PAD_LEFT); | |
} | |
$migration = $argv[1]; | |
if(! str_starts_with($migration, '9999_')) { | |
die("Migration file should start with 9999_."); | |
} | |
if(! file_exists($migration)) { | |
die("Migration file does not exist."); | |
} | |
$toPlace = intval($argv[2]); | |
$last = intval($argv[3]); | |
if(empty(glob(pad($last) . '_*.php'))) { | |
die("Migration file that starts with number " . $last . " does not exist."); | |
} | |
// Make place for the migration | |
for($i = $last; $i >= $toPlace; $i--) { | |
$prefixed = str_pad($i, 4, '0', STR_PAD_LEFT); | |
$filename = glob("{$prefixed}_*.php")[0]; | |
$newFile = str_replace(pad($i) . '_', pad($i + 1) . '_', $filename); | |
rename($filename, $newFile); | |
} | |
rename($migration, str_replace('9999_', pad($toPlace) . '_', $migration)); | |
echo "Migration file " . $migration . " has been crammed in between " . ($toPlace - 1) . " and " . ($toPlace + 1) . "."; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment