add client from rest api

This commit is contained in:
2026-07-14 07:56:35 +02:00
parent 22da85872d
commit 4388a7ec93
@@ -3,6 +3,7 @@ namespace App\Controller\Api;
use App\Entity\Clients; use App\Entity\Clients;
use App\Repository\ClientsRepository; use App\Repository\ClientsRepository;
use App\Services\AddReports;
use Doctrine\ORM\EntityManagerInterface; use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\JsonResponse;
@@ -40,9 +41,45 @@ class ClientsController extends AbstractController
} }
#[Route('/add', name: 'add_client', methods: ['POST'])] #[Route('/add', name: 'add_client', methods: ['POST'])]
public function add(Request $request, EntityManagerInterface $entityManager): JsonResponse public function add(Request $request, EntityManagerInterface $entityManager, AddReports $addReports): JsonResponse
{ {
return $this->json($request->toArray(), context: ['groups' => ['client:add', 'client:read']]); $need = [
"strName" => $request->getPayload()->get('name'),
"strAddress" => $request->getPayload()->get('address'),
"dateLegitimacy" => $request->getPayload()->get('legitimacy'),
"dateProclamation" => $request->getPayload()->get('proclamation'),
"intNIP" => $request->getPayload()->get('nip'),
"intPhone" => $request->getPayload()->get('phone'),
"strEmail" => $request->getPayload()->get('email'),
];
$newClient = new Clients();
foreach ($need as $key => $value) {
$cleared = $this->clearType($key, $value);
$method = 'set'.ucfirst($key);
$newClient->{$method}($cleared);
}
$entityManager->persist($newClient);
$entityManager->flush();
$entityManager->getCache()->evictEntityRegion(Clients::class);
$addReports->setClient($newClient);
$addReports->init();
return $this->json(['success' => true]);
}
private function clearType(string $key, mixed $value)
{
if (str_contains($key, 'str')) {
return addslashes($value);
}
if (str_contains($key, 'int')) {
return intval($value);
}
if (str_contains($key, 'date')) {
return new \DateTime($value);
}
} }
// #[Route('/{id}', name: 'show', methods: ['GET'])] // #[Route('/{id}', name: 'show', methods: ['GET'])]