88 lines
2.6 KiB
PHP
88 lines
2.6 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Services\VirtualMachine;
|
|
|
|
use App\Repositories\Setting\SettingRepositoryInterface;
|
|
|
|
/**
|
|
* Reads / writes the provisioning "provider" config stored in setting table
|
|
* under the single key `provider`.
|
|
*
|
|
* Shape:
|
|
* {
|
|
* "active_vcenter_id": 1, // mirror of module_vcenter.status=1
|
|
* "default_folder": "group-v1008",
|
|
* "default_resource_pool": "resgroup-3002",
|
|
* "default_datastore": "datastore-3004", // fallback if active host has no active datastore
|
|
* "name": "Acme Cloud",
|
|
* "region": "HCM",
|
|
* "tags": ["prod"]
|
|
* }
|
|
*
|
|
* The active_vcenter_id field is mirrored from module_vcenter — module_vcenter
|
|
* remains the source of truth, this is just a convenience view for the UI.
|
|
*/
|
|
class VmProviderSettingsService
|
|
{
|
|
public const KEY = 'provider';
|
|
|
|
public const DEFAULTS = [
|
|
'active_vcenter_id' => null,
|
|
'default_folder' => 'group-v1008',
|
|
'default_resource_pool' => 'resgroup-3002',
|
|
'default_datastore' => 'datastore-3004',
|
|
'name' => null,
|
|
'region' => null,
|
|
'tags' => [],
|
|
];
|
|
|
|
public function __construct(private readonly SettingRepositoryInterface $settings)
|
|
{
|
|
}
|
|
|
|
/** @return array<string,mixed> */
|
|
public function all(): array
|
|
{
|
|
$raw = $this->settings->getByKey(self::KEY);
|
|
$data = is_string($raw) ? json_decode($raw, true) : [];
|
|
return array_merge(self::DEFAULTS, is_array($data) ? $data : []);
|
|
}
|
|
|
|
public function get(string $field, mixed $default = null): mixed
|
|
{
|
|
return $this->all()[$field] ?? $default;
|
|
}
|
|
|
|
/** Merge-write a subset of fields. */
|
|
public function merge(array $patch): array
|
|
{
|
|
$merged = array_merge($this->all(), $patch);
|
|
$this->settings->updateOrCreateByKey(self::KEY, [
|
|
'value' => json_encode($merged, JSON_UNESCAPED_UNICODE),
|
|
]);
|
|
return $merged;
|
|
}
|
|
|
|
public function setActiveVcenterId(?int $id): void
|
|
{
|
|
$this->merge(['active_vcenter_id' => $id]);
|
|
}
|
|
|
|
public function defaultFolder(): string
|
|
{
|
|
return (string) $this->get('default_folder', self::DEFAULTS['default_folder']);
|
|
}
|
|
|
|
public function defaultResourcePool(): string
|
|
{
|
|
return (string) $this->get('default_resource_pool', self::DEFAULTS['default_resource_pool']);
|
|
}
|
|
|
|
public function defaultDatastore(): string
|
|
{
|
|
return (string) $this->get('default_datastore', self::DEFAULTS['default_datastore']);
|
|
}
|
|
}
|