terrarium-web/src/Controller/HygrometryApiController.php

80 lines
2.6 KiB
PHP
Raw Permalink Normal View History

2020-03-16 14:19:25 +01:00
<?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;
2020-03-24 23:47:46 +01:00
use Symfony\Component\HttpFoundation\JsonResponse;
2020-06-14 22:32:01 +02:00
use App\Repository\HygrometryRepository;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
2020-03-16 14:19:25 +01:00
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
2020-03-16 14:19:25 +01:00
{
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,
2020-06-14 22:32:01 +02:00
'entities' => $repository->findByDateRange(
2020-11-21 18:11:03 +01:00
new \DateTime('now - 1 hour'), new \DateTime('now'),
2020-06-14 22:32:01 +02:00
6,
'DESC'
),
'triggers' => [
'min' => $min,
'max' => $max,
],
]
)
);
$mailer->send($message);
}
2020-03-16 14:19:25 +01:00
return $this->json([], 201);
}
}