2018-03-01 21:27:37 -06:00
|
|
|
<?php
|
|
|
|
|
|
2024-03-12 22:39:16 -04:00
|
|
|
namespace App\Services\Databases;
|
2018-03-01 21:27:37 -06:00
|
|
|
|
2025-09-24 13:34:19 +02:00
|
|
|
use App\Exceptions\Service\Database\NoSuitableDatabaseHostException;
|
2024-03-12 22:39:16 -04:00
|
|
|
use App\Models\Database;
|
|
|
|
|
use App\Models\DatabaseHost;
|
2025-09-24 13:34:19 +02:00
|
|
|
use App\Models\Server;
|
|
|
|
|
use Webmozart\Assert\Assert;
|
2018-03-01 21:27:37 -06:00
|
|
|
|
2025-01-16 14:53:50 -05:00
|
|
|
readonly class DeployServerDatabaseService
|
2018-03-01 21:27:37 -06:00
|
|
|
{
|
2024-11-22 09:27:57 +01:00
|
|
|
public function __construct(private DatabaseManagementService $managementService) {}
|
2018-03-01 21:27:37 -06:00
|
|
|
|
2025-03-03 14:41:19 -05:00
|
|
|
/**
|
|
|
|
|
* @param array{database?: string, remote?: string} $data
|
|
|
|
|
*/
|
2018-03-01 21:27:37 -06:00
|
|
|
public function handle(Server $server, array $data): Database
|
|
|
|
|
{
|
2020-10-11 11:59:46 -07:00
|
|
|
Assert::notEmpty($data['database'] ?? null);
|
|
|
|
|
Assert::notEmpty($data['remote'] ?? null);
|
2018-03-01 21:27:37 -06:00
|
|
|
|
2024-12-06 20:24:30 -05:00
|
|
|
$hosts = DatabaseHost::query()->get();
|
2020-10-11 11:59:46 -07:00
|
|
|
if ($hosts->isEmpty()) {
|
2021-01-23 12:33:34 -08:00
|
|
|
throw new NoSuitableDatabaseHostException();
|
2024-12-06 20:24:30 -05:00
|
|
|
}
|
2018-03-01 21:27:37 -06:00
|
|
|
|
2024-12-06 20:24:30 -05:00
|
|
|
$nodeHosts = $server->node->databaseHosts()->get();
|
|
|
|
|
// TODO: @areyouscared remove allow random feature for database hosts
|
|
|
|
|
if ($nodeHosts->isEmpty() && !config('panel.client_features.databases.allow_random')) {
|
|
|
|
|
throw new NoSuitableDatabaseHostException();
|
2018-03-01 21:27:37 -06:00
|
|
|
}
|
|
|
|
|
|
2020-06-23 20:07:37 -07:00
|
|
|
return $this->managementService->create($server, [
|
2020-10-11 11:59:46 -07:00
|
|
|
'database_host_id' => $nodeHosts->isEmpty()
|
|
|
|
|
? $hosts->random()->id
|
|
|
|
|
: $nodeHosts->random()->id,
|
|
|
|
|
'database' => DatabaseManagementService::generateUniqueDatabaseName($data['database'], $server->id),
|
|
|
|
|
'remote' => $data['remote'],
|
2018-03-01 21:27:37 -06:00
|
|
|
]);
|
|
|
|
|
}
|
|
|
|
|
}
|