Game-Jaming/Backend/setup.php

111 lines
2.7 KiB
PHP

<?php
//use Illuminate\Support\Facades\DB;
use \Backend\Models\AdminUser;
use JetBrains\PhpStorm\ArrayShape;
/**
* @param string $servername
* @param string $username
* @param string $password
* @param string $DBName
* @return string[]
*/
function myDB(string $servername, string $username, string $password, string $DBName): array
{
$conn = new mysqli($servername, $username, $password);
if ($conn->connect_error) {
http_response_code(400);
echo json_encode(["message" => $conn->connect_error]);
exit();
}
$sql = "CREATE DATABASE ".$DBName;
if ($conn->query($sql) === FALSE) {
http_response_code(400);
echo json_encode(["message" => $conn->error]);
exit();
}
$conn->close();
return array(
"driver" => "mysql",
"host" => $servername,
"database" => $DBName,
"username" => $username,
"password" => $password
);
}
/**
* @param string $DBName
* @return string[]
*/
function liteDB(string $DBName): array
{
$DBName = $DBName.".sqlite";
if(file_exists($DBName)){
http_response_code(400);
echo json_encode(["message" => "database already exits"]);
exit();
}
New SQLite3($DBName);
return array(
'driver' => 'sqlite',
'database' => realpath(dirname(__FILE__)."/".$DBName)
);
}
$conFilePath = '../config/database.json';
if(!file_exists($conFilePath)){
$confile = fopen($conFilePath, "w");
fclose($confile);
}
if (0 !== filesize($conFilePath)){
http_response_code(400);
echo json_encode(["message" => "already have database connection"]);
exit();
}
if(isset($_POST["dbSetup"])){
switch($_POST["dbType"]){
case "mysql":
$dbCon = myDB($_POST["dbServername"],$_POST["dbUsername"],$_POST["dbPassword"], $_POST["dbName"]);
break;
case "sqlite":
$dbCon = liteDB($_POST["dbName"]);
break;
default:
http_response_code(400);
echo json_encode(["message" => "database type is wrong"]);
exit();
}
file_put_contents($conFilePath, json_encode($dbCon));
try{
require_once('../bootstrap.php');
} catch (\Exception $e) {
file_put_contents($conFilePath, NULL);
http_response_code(400);
echo json_encode(["message" => "Could not connect to the database. Please check your configuration. error:" . $e]);
exit();
}
require_once ('Database/databaseMigration.php');
AdminUser::firstOrCreate([
'user_name' => $_POST["AdminUsername"], 'password' => password_hash($_POST["AdminPassword"],PASSWORD_DEFAULT)
]);
http_response_code(201);
}else{
http_response_code(400);
}