blue-twilight/app/Http/Controllers/InstallController.php

130 lines
4.0 KiB
PHP

<?php
namespace App\Http\Controllers;
use App\Configuration;
use App\Helpers\MiscHelper;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;
class InstallController extends Controller
{
public function start(Request $request)
{
if (!$this->isDatabaseWorking())
{
return $this->databaseConnection($request);
}
else if (!$this->isAdministratorAccountCreated())
{
return $this->administratorAccount($request);
}
}
protected function administratorAccount(Request $request)
{
if (strtolower($request->method()) == 'post')
{
$user = new User();
$user->name = $request->get('name');
$user->email = $request->get('email');
$user->password = bcrypt($request->get('password'));
$user->is_admin = true;
$user->is_activated = true;
$user->save();
$request->session()->flash('', '');
return redirect(route('home'));
}
return view('install/administrator');
}
protected function databaseConnection(Request $request)
{
if (strtolower($request->method()) == 'post')
{
$baseDirectory = dirname(dirname(dirname(__DIR__)));
$data = [
'APP_KEY=' . config('app.key'),
'DB_CONNECTION=mysql',
'DB_HOST=' . $request->get('mysql-server'),
'DB_PORT=' . intval($request->get('mysql-port')),
'DB_DATABASE=' . $request->get('mysql-database'),
'DB_USERNAME=' . $request->get('mysql-username'),
'DB_PASSWORD=' . $request->get('mysql-password')
];
file_put_contents(sprintf('%s/.env', $baseDirectory), join(PHP_EOL, $data) . PHP_EOL);
// Update the in-memory configuration ready for Artisan :)
$configData = [
'connections' => [
'mysql' => [
'driver' => 'mysql',
'host' => $request->get('mysql-server'),
'port' => intval($request->get('mysql-port')),
'database' => $request->get('mysql-database'),
'username' => $request->get('mysql-username'),
'password' => $request->get('mysql-password')
]
]
];
config(['database' => array_replace_recursive(config('database'), $configData)]);
DB::reconnect();
try
{
Artisan::call('cache:clear');
Artisan::call('migrate', ['--force' => true]);
$result = Configuration::where('key', 'install_date')->first();
if (is_null($result))
{
$result = new Configuration();
$result->key = 'install_completed';
$result->value = true;
$result->save();
}
return redirect('/install');
}
catch (\Exception $ex)
{
$request->session()->flash('database_error', $ex->getMessage());
return redirect('/install')
->withInput($request->input());
}
}
return view('install/database', [
'database_error' => $request->session()->get('database_error')
]);
}
private function isAdministratorAccountCreated()
{
return (count(User::administrators()) > 0);
}
private function isDatabaseWorking()
{
try
{
if (!Configuration::installCompleted())
{
throw new \Exception(sprintf('install_completed configuration record is not present!'));
}
return true;
}
catch (\Exception $ex)
{
return false;
}
}
}