domovoy/app/Controllers/NetworkRangeController.php

95 lines
2.6 KiB
PHP

<?php
declare(strict_types=1);
namespace Domovoy\Controllers;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
class NetworkRangeController
{
private \Domovoy\Repositories\NetworkRangeRepository $repository;
public function __construct(\Domovoy\Repositories\NetworkRangeRepository $repository)
{
$this->repository = $repository;
}
public function create(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
{
$data = $request->getParsedBody();
$name = trim($data['name'] ?? '');
$cidr = trim($data['cidr'] ?? '');
if ($name === '' || $cidr === '') {
$response->getBody()->write('Name and CIDR are required');
return $response->withStatus(400);
}
// Basic CIDR validation
if (!$this->isValidCidr($cidr)) {
$response->getBody()->write('Invalid CIDR format');
return $response->withStatus(400);
}
$range = new \Domovoy\Models\NetworkRange();
$range->name = $name;
$range->cidr = $cidr;
$range->enabled = true;
$this->repository->save($range);
return $response
->withHeader('Location', '/discovery')
->withStatus(302);
}
public function toggle(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
{
$data = $request->getParsedBody();
$id = $data['id'] ?? null;
if ($id !== null) {
$range = $this->repository->findById((int)$id);
if ($range !== null) {
$range->enabled = !$range->enabled;
$this->repository->save($range);
}
}
return $response
->withHeader('Location', '/discovery')
->withStatus(302);
}
public function delete(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
{
$data = $request->getParsedBody();
$id = $data['id'] ?? null;
if ($id !== null) {
$this->repository->delete((int)$id);
}
return $response
->withHeader('Location', '/discovery')
->withStatus(302);
}
private function isValidCidr(string $cidr): bool
{
if (!str_contains($cidr, '/')) {
return false;
}
[$ip, $mask] = explode('/', $cidr, 2);
if (!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
return false;
}
$maskInt = (int)$mask;
return $maskInt >= 8 && $maskInt <= 32;
}
}