Last active
August 29, 2015 14:25
-
-
Save rajiteh/9f26c69687c7280976d1 to your computer and use it in GitHub Desktop.
Quickly bootstrap your laravel database using an alternate .env file (Can be used with Codeception)
This file contains hidden or 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 | |
class LaravelTestDatabaseBootstrapper { | |
protected static $_instance; | |
protected $projectRoot; | |
protected $envFile; | |
protected $app = null; | |
protected function __construct($envFile, $projectRoot) { | |
$this->projectRoot = $projectRoot; | |
$this->envFile = $envFile; | |
} | |
public static function initOrGetInstance($envFile=null, $projectRoot=null) { | |
if ( !(self::$_instance instanceof self) ) { | |
if (is_null($envFile) || is_null($projectRoot)) { | |
throw new \InvalidArgumentException("Env file path and project root path are required."); | |
} | |
self::$_instance = new self($envFile, $projectRoot); | |
} | |
return self::$_instance; | |
} | |
public function bootstrap() { | |
$app = $this->getApp(); | |
$kernel = $app->make('Illuminate\Contracts\Console\Kernel'); | |
$kernel->call('migrate', ['--force' => true]); | |
foreach (explode("\n", $kernel->output()) as $line) { | |
$line = trim($line); | |
if (strlen($line) > 0) | |
$this->log($line); | |
}; | |
} | |
protected function getApp() { | |
if (is_null($this->app)) { | |
$this->log("Using env at (" . $this->projectRoot . $this->envFile . ")"); | |
Dotenv::load($this->projectRoot, $this->envFile); | |
$this->log("Initializing Laravel app."); | |
require($this->projectRoot . "bootstrap/autoload.php"); | |
$app = require($this->projectRoot . "bootstrap/app.php"); | |
// Set environment | |
$app->loadEnvironmentFrom($this->envFile); | |
$this->app = $app; | |
} | |
return $this->app; | |
} | |
protected function log($msg) { | |
echo "DatabaseBootstrapper : " . $msg . "\n"; | |
} | |
} | |
//running at tests/_bootstrap.php | |
LaravelTestDatabaseBootstrapper::initOrGetInstance('.env.testing', __DIR__ . '/../')->bootstrap(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment