Files
portal-api/app/Services/Plesk/PleskDomainService.php
T
2026-09-28 08:26:29 +07:00

111 lines
3.6 KiB
PHP

<?php
namespace App\Services\Plesk;
use App\Models\DnsServer;
use Illuminate\Http\Client\RequestException;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
/**
* Plesk `/domains` entry point — shared by the DNS module (ServerService)
* and the Hosting module (PleskHostingService). Extracted from
* ServerService so both stop drifting apart on the same Plesk call.
*/
class PleskDomainService
{
private ?string $lastError = null;
public function __construct(private PleskService $plesk)
{
}
/** Message from the most recent failed call — null if the last call succeeded or hasn't run yet. */
public function getLastError(): ?string
{
return $this->lastError;
}
public function createDomain(DnsServer $server, array $data = []): array|false
{
$this->lastError = null;
if (empty($data['domain_name'])) {
$this->lastError = 'Domain name is required';
return false;
}
$param = [
'name' => $data['domain_name'],
'description' => '',
'hosting_type' => 'virtual',
'hosting_settings' => [
'ftp_login' => $data['ftp_login'] ?? str_replace('.', '_', $data['domain_name']),
'ftp_password' => $data['ftp_password'] ?? Str::random(12),
],
'plan' => ['name' => $data['plan'] ?? 'Default Domain'],
];
// Omit ip_addresses/ipv4 unless explicitly given — Plesk assigns its
// own default IP for the domain, and a wrong hardcoded IP here gets
// rejected outright ("IP address 'x.x.x.x' is not available").
if (!empty($data['ip_addresses'])) {
$param['ip_addresses'] = $data['ip_addresses'];
$param['ipv4'] = $data['ip_addresses'];
}
if (!empty($data['owner_client_id'])) {
$param['owner_client'] = ['id' => $data['owner_client_id']];
}
try {
$response = $this->plesk->client($server, 30)
->post($this->plesk->url($server, 'domains'), $param);
$responseData = $response->json();
Log::info('Response Plesk API Created', ['data' => $responseData]);
if ($response->successful() && isset($responseData['id'], $responseData['guid'])) {
return $responseData + ['hosting_settings' => $param['hosting_settings']];
}
$this->lastError = $responseData['message'] ?? 'Plesk domain creation failed';
} catch (RequestException $e) {
$this->lastError = $e->response?->json('message') ?? $e->getMessage();
Log::error('Plesk domain creation failed', [
'error' => $e->getMessage(),
'response' => $e->response?->body(),
'data' => $param,
]);
}
return false;
}
public function getDomainInfo(DnsServer $server, string $domain = ''): array|false
{
if (empty($domain)) {
return false;
}
try {
$response = $this->plesk->client($server, 10)
->get($this->plesk->url($server, 'domains'), ['name' => $domain]);
if ($response->successful()) {
foreach ($response->json() ?? [] as $domainInfo) {
if (isset($domainInfo['name']) && $domainInfo['name'] === $domain) {
return $domainInfo;
}
}
}
return false;
} catch (RequestException $e) {
Log::error($e->getMessage());
return false;
}
}
}