domovoy/app/Services/Inventory/DeviceService.php

93 lines
2.7 KiB
PHP

<?php
declare(strict_types=1);
namespace Domovoy\Services\Inventory;
use Domovoy\Models\Device;
use Domovoy\Repositories\DeviceRepository;
use Domovoy\Repositories\DiscoveredHostRepository;
class DeviceService
{
private DeviceRepository $deviceRepository;
private ?DiscoveredHostRepository $discoveredHostRepository;
public function __construct(
DeviceRepository $deviceRepository,
?DiscoveredHostRepository $discoveredHostRepository = null
)
{
$this->deviceRepository = $deviceRepository;
$this->discoveredHostRepository = $discoveredHostRepository;
}
public function createFromDiscoveredHost(
string $name,
string $ipAddress,
?string $macAddress = null,
?string $hostname = null,
?string $vendor = null
): Device {
$device = new Device();
$device->name = $name;
$device->primaryIp = $ipAddress;
$device->macAddress = $macAddress;
$device->hostname = $hostname;
$device->vendor = $vendor;
$device->type = 'unknown';
$device->status = 'active';
$device->importance = 'normal';
$this->deviceRepository->save($device);
return $device;
}
public function getAllDevices(): array
{
return $this->deviceRepository->findAll();
}
public function getDevice(int $id): ?Device
{
return $this->deviceRepository->findById($id);
}
public function updateDevice(Device $device): void
{
$this->deviceRepository->save($device);
}
public function deleteDevice(int $id): void
{
$this->deviceRepository->delete($id);
}
public function mergeDiscoveredHost(int $hostId, int $deviceId): void
{
if ($this->discoveredHostRepository === null) {
throw new \RuntimeException('DiscoveredHostRepository is required for merge');
}
$host = $this->discoveredHostRepository->findById($hostId);
if ($host === null) {
throw new \RuntimeException('Discovered host not found');
}
$device = $this->deviceRepository->findById($deviceId);
if ($device === null) {
throw new \RuntimeException('Device not found');
}
$device->primaryIp = $device->primaryIp ?: $host->ipAddress;
$device->macAddress = $device->macAddress ?: $host->macAddress;
$device->hostname = $device->hostname ?: $host->hostname;
$device->vendor = $device->vendor ?: $host->vendor;
$this->deviceRepository->save($device);
$host->status = 'merged';
$host->matchedDeviceId = (string)$device->id;
$this->discoveredHostRepository->save($host);
}
}