|
<?php |
|
/** |
|
* Put this file to "app/Console/EnvironmentInstaller.php" |
|
*/ |
|
namespace App\Console; |
|
|
|
use Dotenv\Dotenv; |
|
use Composer\Script\Event; |
|
use Illuminate\Support\Str; |
|
use Composer\IO\IOInterface; |
|
use Illuminate\Foundation\Application; |
|
|
|
/** |
|
* Class EnvironmentInstaller |
|
* @package App\Console |
|
*/ |
|
class EnvironmentInstaller |
|
{ |
|
/** |
|
* @var string |
|
*/ |
|
private $path; |
|
|
|
/** |
|
* @var string |
|
*/ |
|
private $file; |
|
|
|
/** |
|
* @var array |
|
*/ |
|
private $exists = []; |
|
|
|
/** |
|
* EnvironmentInstaller constructor. |
|
* @param Application $app |
|
* @param Event $event |
|
*/ |
|
public function __construct(Application $app, Event $event) |
|
{ |
|
$this->path = $app->environmentPath(); |
|
$this->file = $app->environmentFile(); |
|
$io = $event->getIO(); |
|
|
|
$this->loadDefaults(); |
|
|
|
$fp = fopen($this->file() , 'a+'); |
|
|
|
$io->write('Setup environment.'); |
|
|
|
foreach ($this->sync($app, $event->getIO()) as $key => $value) { |
|
if (!$this->has($key)) { |
|
$question = ' ' . $key . ' [' . $value . ']: '; |
|
$value = $io->ask($question, $value); |
|
} |
|
|
|
fwrite($fp, $key . '=' . $value . "\n"); |
|
} |
|
|
|
|
|
fclose($fp); |
|
} |
|
|
|
/** |
|
* @param string $suffix |
|
* @return string |
|
*/ |
|
private function file($suffix = '') |
|
{ |
|
return $this->path . '/' . $this->file . $suffix; |
|
} |
|
|
|
/** |
|
* @return void |
|
*/ |
|
private function loadDefaults() |
|
{ |
|
if (is_file($this->file())) { |
|
$env = new Dotenv($this->path, $this->file); |
|
|
|
foreach ($this->read($env) as $key => $value) { |
|
$this->exists[] = $key; |
|
} |
|
} |
|
} |
|
|
|
/** |
|
* @param Dotenv $env |
|
* @return \Generator |
|
*/ |
|
public function read(Dotenv $env) |
|
{ |
|
foreach ($env->load() as $field) { |
|
list($name, $value) = explode('=', $field); |
|
if (!Str::startsWith($name, '#')) { |
|
yield $name => $value; |
|
} |
|
} |
|
} |
|
|
|
/** |
|
* @param Application $app |
|
* @param IOInterface $io |
|
* @return \Generator |
|
*/ |
|
private function sync(Application $app, IOInterface $io) |
|
{ |
|
$variables = $this->read(new Dotenv($app->environmentPath(), $app->environmentFile() . '.example')); |
|
|
|
foreach ($variables as $key => $value) { |
|
yield $key => $value; |
|
} |
|
} |
|
|
|
/** |
|
* @param string $key |
|
* @return bool |
|
*/ |
|
private function has($key) |
|
{ |
|
return in_array($key, $this->exists, true); |
|
} |
|
|
|
/** |
|
* @param Event $event |
|
* @return static |
|
*/ |
|
public static function build(Event $event) |
|
{ |
|
return new static(app(), $event); |
|
} |
|
} |