Skip to content

Instantly share code, notes, and snippets.

@th3coop
Last active January 31, 2023 05:19
Show Gist options
  • Save th3coop/7b1e2ce758dd15da04c85c5da2f7e518 to your computer and use it in GitHub Desktop.
Save th3coop/7b1e2ce758dd15da04c85c5da2f7e518 to your computer and use it in GitHub Desktop.
Install fresh Laravel instance into randomly generated DB for CI envs
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Artisan;
class RunTestsCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'drivers:test {dbname} {connection?}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Run the drivers app tests!!!!!';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
try {
$name = $this->argument('dbname');
$dbname = $name . rand(1000, 9999);
$connection = $this->hasArgument('connection') && $this->argument('connection') ? $this->argument('connection') : DB::connection()->getPDO()->getAttribute(PDO::ATTR_DRIVER_NAME);
$hasDb = DB::connection($connection)->select('SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = ' . "'" . $dbname . "'");
while (DB::connection($connection)->select('SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = ' . "'" . $dbname . "'")) {
$dbname = $name . rand(1000, 9999);
$this->info('DB already exists. Trying new name: ' . $dbname);
}
if (empty($hasDb)) {
$this->info('Creating DB ' . $dbname);
DB::connection($connection)->select('CREATE DATABASE ' . $dbname);
$this->info("Database '$dbname' created for '$connection' connection");
} else {
$this->info("Database $dbname already exists for $connection connection");
}
// $_ENV['DB_DATABASE'] = $dbname;
// $this->getLaravel()->environment(['DB_DATABASE' => $dbname]);
// $this->info('env: ' . $this->getLaravel()->environment('DB_DATABASE'));
// \Illuminate\Support\Env::enablePutenv();
// putenv('DB_DATABASE=' . $dbname);
// $this->info('env: ' . json_encode($_ENV));
// $this->call('config:clear');
config(['database.connections.' . $connection . '.database' => $dbname]);
DB::reconnect($connection);
$this->info('config: ' . config('database.connections.' . $connection . '.database'));
$this->info('Installing site');
$this->call('install', ['--ready'=>true], $this->output);
} catch (\Exception $e) {
$this->error($e->getMessage());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment