<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use App\Entity as Entity;
use App\Entity\Exploitant;
use App\Entity\ExploitantIdentite;
use App\Entity\UserExploitant;
use App\Entity\User;
use Doctrine\ORM\Query\ResultSetMapping;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Encoder\XmlEncoder;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Normalizer\AbstractObjectNormalizer;
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Normalizer\ArrayDenormalizer;
use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;
use Symfony\Component\Serializer\Normalizer\DateTimeNormalizer;
/**
* @Route("/api/v1/", name="api_")
*/
class APIController extends AbstractController
{
/**
* @Route("", name="index")
*/
public function index()
{
return $this->render('api/index.html.twig', [
'controller_name' => 'APIController',
]);
}
/**
* @Route("sql/schema", name="sql_chema")
*/
/*
public function sql_chema()
{
$response =$this->render('sql/schema.txt', []);
$response->headers->set('Content-Type', 'text/html');
$response->headers->set('Access-Control-Allow-Origin', '*');
return $response;
}*/
/**
* @Route("ping", name="ping")
*/
public function ping()
{
$jsonContent = json_encode(["time" => new \DateTime() ]);
return $this->response200($jsonContent);
}
/**
* @Route("forms", name="forms")
*/
public function forms()
{
$entities = ["Exploitant","ExploitantIdentite","ExploitantSpeculation","Charge", "ChargeUpload", "Produit"];
$array = [];
foreach ($entities as $entity ) {
if ($entity == "ChargeUpload") {
$class_name = "App\Entity\\Charge";
$el = new $class_name();
$array[$entity] = $el->fields2();
} else {
$class_name = "App\Entity\\".$entity;
$el = new $class_name();
$array[$entity] = $el->fields();
}
}
//$itk = new Entity\Itk();
//$list = $itk->ItkList();
//$array["ItkInfos"] = [];
//itks
/*foreach ($list as $key => $value) {
$object_class = "App\Entity\\".$key;
$object = new $object_class();
$array[$key] = $object->fields();
//$array["ItkInfos"][$key] = $object->infos();
}*/
$jsonContent = json_encode($array);
return $this->response200($jsonContent);
}
/**
* @Route("login/{user_id}", name="login")
*/
public function login($user_id)
{
$em = $this->getDoctrine()->getManager();
$user = $em->getRepository(User::class)->find(trim($user_id));
if(!$user) return $this->error("user with id ".intval($user_id)." doesn't exist");
$user->setApiToken(sha1(random_bytes(10))); //generate token
$user->setApiTokenCreatedAt(new \DateTime()); //reference datetime for token expiration
$jsonContent = $this->serialize(User::class, ['username','password','email'], $user_id);
return $this->response200($jsonContent);
}
/**
* @Route("mobileApp", name="mobileApp")
*/
public function mobileApp()
{
return $this->response200(json_encode(
[
"versionName" => "2.4.0",
"versionCode" => "20400",
"name" => "E-Roso 2.4.0",
"whatsnew" => " "
]
));
}
/**
* @Route("debut/{user_id}/{string}", name="debut")
*/
public function debut($user_id, $string)
{
$jsonContent = json_encode("Debut User ".$user_id." avec : ".$string);
return $this->response200($jsonContent);
}
/**
* @Route("connect/{user_login}/{user_pass}", name="connect")
*/
public function connect($user_login, $user_pass)
{
$response["error"] = "";
if($user_login == "" && $user_pass== "") {
$jsonContent = json_encode(["status" => "KO" ]);
return $this->response200($jsonContent);
}
if($user_login != "" && $user_pass != ""){
$em = $this->getDoctrine()->getManager();
$user = $em->getRepository(User::class)->findOneBy(["username"=>trim($user_login), "password"=>$user_pass]);
if(!$user) {
$jsonContent = json_encode(["status" => "KO" ]);
return $this->response200($jsonContent);
//return $this->error("user doesn't exist");
}
$user->setApiToken(sha1(random_bytes(10))); //generate token
$user->setApiTokenCreatedAt(new \DateTime()); //reference datetime for token expiration
$jsonContent = $this->serialize(User::class, ['username','password','email'], $user->getId());
$jsonContent = json_encode(["status" => "OK", "id"=> $user->getId()]);
return $this->response200($jsonContent);
}else{
$jsonContent = json_encode(["status" => "KO" ]);
return $this->response200($jsonContent);
}
if($response["error"] != "") {
$jsonContent = json_encode(["status" => "KO" ]);
return $this->response200($jsonContent);
}
return $this->response200(json_encode($response));
}
/**
* @Route("farms/{user_id}", name="farms")
*/
public function farms($user_id)
{
$em = $this->getDoctrine()->getManager();
$user = $em->getRepository(User::class)->findOneBy(["id"=>$user_id]);
if(in_array('ROLE_ADMIN', $user->getRoles())){
$jsonContent = $this->serialize(Exploitant::class, ["docs"]);
return $this->response200($jsonContent);
}
if(in_array('ROLE_OPERATOR', $user->getRoles())){
$jsonContent = $this->serialize(Exploitant::class, ["docs"],$user_id, "filtreExp" );
return $this->response200($jsonContent);
}
if(in_array('ROLE_USER', $user->getRoles())){
$jsonContent = $this->serialize(Exploitant::class, ["docs"],$user_id, "filtreExp");
return $this->response200($jsonContent);
}
return $this->response200($jsonContent);
}
/**
* @Route("orphans_plots", name="orphans_plots")
*/
public function orphans_plots()
{
$jsonContent = $this->serialize(Plot::class, ["farm"], NULL, ["farm" => NULL]);
// TODO
return $this->response200($jsonContent);
}
/**
* @Route("lists/{user_id}", name="lists")
*/
public function lists($user_id)
{
$entities = [
"ListSexe" => [],
"ListProfil" => [],
"ListOuiNon" => [],
"ListProduit" => [],
"ListProduitAnimal" => [],
"ListTypeProductionVegetal" => [],
"ListTypeCharge" => [],
"ListSousCharge" => [],
"ListTypeProduit" => [],
"ListTypeDepense" => [],
"ListUnite" => [],
"ListMois" => [],
"ListTechnique" => [],
"ListTechnicien" => [],
"ListOrganisation" => [],
"ListElevage" => [],
"ListEau" => [],
"ListSaison" => [],
"ListPeriodeSoudure" => [],
"ListEconomieExploitation" => [],
"ListNiveauVie" => [],
"ListEAF" => [],
"ListProduction" => [],
"ListProjetPro" => [],
"ListCollege" => [],
"ListResponsabiliteOp" => [],
"ListTypeOp" => [],
"ListTypeCulture" => [],
"ListServicePaysan" => [],
"ListRegion" => [],
"ListDistrict" => [],
"ListCommune" => [],
];
$em = $this->getDoctrine()->getManager();
$array = [];
foreach ($entities as $key => $value ) {
$class_name = "App\Entity\\".$key;
if ($key == "ListCommune" || $key == "ListDistrict" || $key == "ListRegion") {
$array[$key] = json_decode($this->serialize($class_name, $value, null, ["isProjet" => true]));
} else {
$array[$key] = json_decode($this->serialize($class_name, $value));
}
}
$user = $em->getRepository(User::class)->findOneBy(["id"=>$user_id]);
if(in_array('ROLE_ADMIN', $user->getRoles())){
$array["lecteur"][0] = false;
}
if(in_array('ROLE_OPERATOR', $user->getRoles())){
$array["lecteur"][0] = false;
}
if(in_array('ROLE_USER', $user->getRoles())){
$array["lecteur"][0] = true;
}
$jsonContent = json_encode($array);
return $this->response200($jsonContent);
}
/**
* @Route("personal/export/{user_id}", name="export_personal")
*/
public function export_personal($user_id)
{
$jsonContent = $this->serialize(User::class, ['plotsLocked','cropsLocked','userItks','lockedJson'], $user_id);
return $this->response200($jsonContent);
}
/**
* @Route("farm/{farm_id}/lock/{user_id}", name="lock_farm")
*/
/*
public function lock_farm($farm_id, $user_id)
{
$em = $this->getDoctrine()->getManager();
$farm = $em->getRepository(Farm::class)->find($farm_id);
if(!$farm) return $this->error("farm not found");
// Change this with :
// $this->getUser();
$user = $em->getRepository(User::class)->find($user_id);
if(!$user) return $this->error("user not found");
if($farm->getLock()) return $this->error("farm already locked by ".$farm->getLock()->__toString());
$farm->setLock($user);
$json = [];
$json["farm"] = $farm->getLockedJson();
$em->flush();
return $this->response200(json_encode($json));
}
*/
/**
* @Route("farm/{farm_id}/unlock/{user_id}", name="unlock_farm")
*/
/*
public function unlock_farm($farm_id, $user_id)
{
$em = $this->getDoctrine()->getManager();
$farm = $em->getRepository(Farm::class)->find($farm_id);
if(!$farm) return $this->error("farm not found");
// Change this with :
// $this->getUser();
$user = $em->getRepository(User::class)->find($user_id);
if(!$user) return $this->error("user not found");
if(!$farm->getLock()) return $this->error("farm not locked");
$farm->unlock($user);
$json = [];
$json["farm"] = $farm->getLockedJson();
$em->flush();
return $this->response200(json_encode($json));
}*/
function response200($json){
$response = new Response($json, 200, [
'Content-Type' => 'application/json',
'Access-Control-Allow-Origin' => '*',
"Access-Control-Allow-Headers" => "Origin, x-requested-with, Content-Type, Accept",
]);
return $response;
}
function error($msg){
$response = new Response();
$response->setContent(json_encode([
"error" => [
'message' => $msg,
],
]));
$response->headers->set('Content-Type', 'application/json');
$response->setStatusCode(401);
return $response;
}
function get_serializer($only_normalizer=false){
$encoder = new JsonEncoder();
$defaultContext = [
AbstractNormalizer::CIRCULAR_REFERENCE_HANDLER => function ($object, $format, $context) {
return $object->getId();
},
AbstractObjectNormalizer::MAX_DEPTH_HANDLER => function ($innerObject, $outerObject, string $attributeName, string $format = null, array $context = []) {
return $innerObject->id;
},
];
$normalizer = new ObjectNormalizer(null, null, null, null, null, null, $defaultContext);
$serializer = new Serializer([new DateTimeNormalizer(),$normalizer], [$encoder]);
if($only_normalizer) return $normalizer;
return $serializer;
}
function serialize($class, $ignore=[], $id=NULL, $filter=NULL)
{
$serializer = $this->get_serializer();
$em = $this->getDoctrine()->getManager();
$objects = NULL;
if ($filter == "filtreExp") {
$user = $this->getUser();
$em = $this->getDoctrine()->getManager();
$listeExp = $em->getRepository(UserExploitant::class)->findBy(array('userId'=>$id));
$myLis = [];
foreach ($listeExp as $value) {
$myLis[] = $value->getExpId();
}
if (count($myLis) === 0 ){
$objects = [];
} else {
$objects = $em->getRepository(Exploitant::class)->findBy(array('id'=> $myLis));
}
/*if (isset($listeExp)){
foreach($listeExp as $list){
}
$objects = $em->getRepository(Exploitant::class)->findBy(array('expId'=> []));
} else {
return null;
}*/
} else {
if($id) $objects = $em->getRepository($class)->find($id);
else if ($filter) $objects = $em->getRepository($class)->findBy($filter);
else $objects = $em->getRepository($class)->findAll();
}
//if(!$objects) return $this->error("Nothing found !");
// Serialize your object in Json
$ignore[] = '__initializer__';
$ignore[] = '__cloner__';
$ignore[] = '__isInitialized__';
$ignore[] = 'currencyList';
if ($class == "App\Entity\ListRegion") {
$objects = $em->getRepository($class)->findBy([],["value"=>"asc"]);
return $serializer->serialize($objects, 'json', [
AbstractNormalizer::IGNORED_ATTRIBUTES => ["district"] ,
AbstractObjectNormalizer::ENABLE_MAX_DEPTH => true,
]);
}
if ($class == "App\Entity\ListDistrict") {
$objects = $em->getRepository($class)->findBy([],["value"=>"asc"]);
return $serializer->serialize($objects, 'json', [
AbstractNormalizer::IGNORED_ATTRIBUTES => ["commune","district"] ,
AbstractObjectNormalizer::ENABLE_MAX_DEPTH => true,
]);
}
if ($class == "App\Entity\ListCommune") {
$objects = $em->getRepository($class)->findBy([],["value"=>"asc"]);
return $serializer->serialize($objects, 'json', [
AbstractNormalizer::IGNORED_ATTRIBUTES => ["commune","region"] ,
AbstractObjectNormalizer::ENABLE_MAX_DEPTH => true,
]);
}
$ignore[] = 'commune';
$ignore[] = 'region';
$ignore[] = 'district';
return $serializer->serialize($objects, 'json', [
AbstractNormalizer::IGNORED_ATTRIBUTES => $ignore ,
AbstractObjectNormalizer::ENABLE_MAX_DEPTH => true,
]);
}
//transform objects relations to an array of ids
function relations_to_ids($objs_array){
$ids_array = [];
foreach ($objs_array as $obj) {
$ids_array[] = $obj->getId();
}
return $ids_array;
}
}