terrarium-web/src/Controller/HygrometryApiController.php

43 lines
1.2 KiB
PHP

<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use App\Validator\ApiValidator;
use App\Entity\Hygrometry;
class HygrometryApiController extends AbstractController
{
/**
* @Route("/api/hygrometry/create", name="api_hygrometry_create", methods={"POST"})
*/
public function create(Request $request, ApiValidator $validator): Response
{
if ('application/json' === $request->getContentType()) {
return $this->json([], 400);
}
$content = $request->getContent();
if (!$validator->isValidContent($content)) {
return $this->json([], 400);
}
$data = json_decode($content, true);
$entity = new Hygrometry();
$entity
->setDate(new \DateTime($data['date']))
->setValue((float) $data['value']);
$manager = $this->getDoctrine()->getManager();
$manager->persist($entity);
$manager->flush();
return $this->json([], 201);
}
}