<?php
namespace App\Controller\Api;
use App\Controller\Response;
use App\Entity\Objectives;
use App\Services\Objectives\ObjectiveSetter;
use App\Services\Objectives\Validator;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
/**
* @Route("/api/objective", name="api_objective_")
*/
class ObjectivesController extends AbstractController
{
use Response;
use \App\Controller\Request;
/**
* @Route("/set", name="set", methods={"POST"})
*/
public function setterAction(Request $request, Validator $validator, ObjectiveSetter $objectiveSetter)
{
try {
$user = $this->getUser(); // TOKEN
# get Request json
$content = $request->getContent();
# parse JSON to Array
$data = \json_decode($content, true);
# validate data
$validator->validate($data);
if ($validator->isValid()) {
if ($data['weight'] < $data['objective_weight']) {
throw new \Exception('Weight must be greater than objective weight');
}
$data['user_id'] = $user->getId(); // TOKEN
# set objective
$objectiveSetter->setData($data)->saveObjective();
}
return $this->jsonResponse();
} catch (\Exception $e) {
return $this->errorJsonResponse(['message' => $e->getMessage()]);
}
}
/**
* @Route("/get/{userid}", name="get", methods={"GET"})
*/
public function getterAction($userid, EntityManagerInterface $em)
{
try {
$user = $this->getUser(); // TOKEN
$objective = $em->getRepository(Objectives::class)->findOneByUser($user->getId()); // TOKEN
//$objective = $em->getRepository(Objectives::class)->findOneByUser($userid);
if ($objective) {
$addWeeks = $objective['weight'] - $objective['objectiveWeight'];
$endObjective = (clone $objective['createdAt'])->add(new \DateInterval('P' . $addWeeks . 'W'));
$days = $endObjective->diff(new \DateTime())->format('%a');
$objective['remainingDays'] = intval($days);
$objective['remainingWeeks'] = ceil($days / 7);
}
return $this->jsonResponse(
[
'data' => $objective,
]
);
} catch (\Exception $e) {
return $this->errorJsonResponse(['message' => $e->getMessage()]);
}
}
/**
* @Route("/cancel/{userid}", name="cancel", methods={"POST"})
*/
public function cancelAction($userid, EntityManagerInterface $em)
{
try {
$user = $this->getUser(); // TOKEN
$objective = $em->getRepository(Objectives::class)->findOneBy([
'userId' => $user->getId(), // TOKEN
//'userId' => $userid,
]);
if ($objective) {
$objective->setCancelledAt(new \DateTime());
$em->persist($objective);
$em->flush();
}
return $this->jsonResponse();
} catch (\Exception $e) {
return $this->errorJsonResponse(['message' => $e->getMessage()]);
}
}
}