ogcore/src/Controller/OgDhcp/Subnet/PostAction.php

68 lines
2.4 KiB
PHP

<?php
namespace App\Controller\OgDhcp\Subnet;
use App\Controller\OgDhcp\AbstractOgDhcpController;
use App\Entity\Subnet;
use App\Entity\DhcpServer;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Attribute\AsController;
use Symfony\Component\Validator\Exception\ValidatorException;
use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;
#[AsController]
class PostAction extends AbstractOgDhcpController
{
/**
* @throws TransportExceptionInterface
* @throws ServerExceptionInterface
* @throws RedirectionExceptionInterface
* @throws ClientExceptionInterface
*/
public function __invoke(Subnet|string $dataOrUuid): JsonResponse
{
if ($dataOrUuid instanceof Subnet) {
$data = $dataOrUuid;
} else {
$data = $this->entityManager->getRepository(Subnet::class)->findOneBy(['uuid' => $dataOrUuid]);
}
if (!$data) {
throw new \Exception('Subred no encontrada.');
}
$dhcpServer = $data->getDhcpServer();
if (!$dhcpServer) {
throw new \Exception('La subred no tiene un servidor DHCP asociado.');
}
$params = [
'json' => [
'subnetId' => $data->getServerId() ?? rand(1, 1000),
'mask' => $data->getNetmask(),
'address' => $data->getIpAddress(),
'nextServer' => $data->getNextServer(),
'bootFileName' => $data->getBootFileName(),
'router' => $data->getRouter(),
'DNS' => $data->getDns()
]
];
$port = $dhcpServer->getApiPort() ?? 8081;
$url = sprintf('http://%s:%d/ogdhcp/v1/subnets', $dhcpServer->getIp(), $port);
$content = $this->createRequest('POST', $url, $params);
$data->setServerId($content['message']['id']);
$data->setSynchronized(true);
$this->entityManager->persist($data);
$this->entityManager->flush();
return new JsonResponse(data: $content, status: Response::HTTP_OK);
}
}