Skip to content

Instantly share code, notes, and snippets.

@tomlankhorst
Created April 12, 2019 09:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomlankhorst/060a68101f654d11bf2e5b6b5d1dc6d6 to your computer and use it in GitHub Desktop.
Save tomlankhorst/060a68101f654d11bf2e5b6b5d1dc6d6 to your computer and use it in GitHub Desktop.
Laravel Migrations Compiler
<?php
namespace Tests;
/**
* This class fakes all migrations and builds a single SQL file that is stored in the /tests folder.
* Then, the corresponding SQL can be used to build a fresh new table.
*
* Simply run in your TestCase setup:
* ```
* $db = app('db')->connection();
* $db->getSchemaBuilder()->dropAllTables();
* $db->unprepared(MigrationsCompiler::get());
* ```
*/
class MigrationsCompiler
{
/**
* @var \Illuminate\Database\Migrations\Migrator
*/
protected $migrator;
/**
* @var \Illuminate\Database\Connection
*/
protected $db;
/**
* @var array
*/
protected $migrations;
public function __construct()
{
$this->migrator = app('migrator');
$this->db = $this->migrator->resolveConnection(null);
$this->migrations = $this->migrator->getMigrationFiles(base_path().'/database/migrations');
$this->migrator->requireFiles($this->migrations);
}
public static function get()
{
return (new static)->cached();
}
public function cached()
{
$driver = config('database.default');
$path = base_path("tests/migrations.$driver.cache.sql");
if (file_exists($path)) {
return file_get_contents($path);
}
file_put_contents($path, $sql = $this->sql());
return $sql;
}
public function sql()
{
$sql = '';
foreach ($this->migrations as $migration) {
$sql .="\n-- migration:".$migration." --\n";
$sql .= "{$this->migrationToSql($migration)}\n";
}
return $sql;
}
protected function migrationToSql($migration)
{
$sql = "";
$migration_name = $this->migrator->getMigrationName($migration);
$migration = $this->migrator->resolve($migration_name);
$name = "";
foreach ($this->db->pretend(function () use ($migration) {
$migration->up();
}) as $query) {
if ($name != $migration_name) {
$name = $migration_name;
$sql .="\n-- migration:".$name." --\n";
}
$sql .= $query['query'].";\n";
}
return $sql;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment