terrarium-web/src/Controller/HygrometryApiController.php

80 lines
2.6 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;
use Symfony\Component\HttpFoundation\JsonResponse;
use App\Repository\HygrometryRepository;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
class HygrometryApiController extends AbstractController
{
/**
* @Route("/api/hygrometry/create", name="api_hygrometry_create", methods={"POST"})
*/
public function create(
Request $request,
ApiValidator $validator,
\Swift_Mailer $mailer,
HygrometryRepository $repository,
ParameterBagInterface $params
): JsonResponse
{
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();
$min = (float) $params->get('hygrometry_trigger_min');
$max = (float) $params->get('hygrometry_trigger_max');
if ($entity->getValue() < $min || $entity->getValue() > $max) {
$message = (new \Swift_Message('[Terrarium] Alerte hygométrie'))
->setFrom('terrarium@deblan.fr')
->setTo(['simon@deblan.fr', 'jennifer@derago.fr'])
->setBody(
$this->renderView(
'alert/hygrometry.txt.twig',
[
'entity' => $entity,
'entities' => $repository->findByDateRange(
new \DateTime('now - 1 hour'), new \DateTime('now'),
6,
'DESC'
),
'triggers' => [
'min' => $min,
'max' => $max,
],
]
)
);
$mailer->send($message);
}
return $this->json([], 201);
}
}