src/Controller/APIController.php line 60

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  4. use Symfony\Component\Routing\Annotation\Route;
  5. use Symfony\Component\HttpFoundation\Request;
  6. use Symfony\Component\HttpFoundation\Response;
  7. use App\Entity as Entity;
  8. use App\Entity\Exploitant;
  9. use App\Entity\ExploitantIdentite;
  10. use App\Entity\UserExploitant;
  11. use App\Entity\User;
  12. use Doctrine\ORM\Query\ResultSetMapping;
  13. use Symfony\Component\Serializer\Encoder\JsonEncoder;
  14. use Symfony\Component\Serializer\Encoder\XmlEncoder;
  15. use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
  16. use Symfony\Component\Serializer\Normalizer\AbstractObjectNormalizer;
  17. use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
  18. use Symfony\Component\Serializer\Serializer;
  19. use Symfony\Component\Serializer\Normalizer\ArrayDenormalizer;
  20. use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;
  21. use Symfony\Component\Serializer\Normalizer\DateTimeNormalizer;
  22. /**
  23.  * @Route("/api/v1/", name="api_")
  24.  */
  25. class APIController extends AbstractController
  26. {
  27.     /**
  28.      * @Route("", name="index")
  29.      */
  30.     public function index()
  31.     {
  32.         return $this->render('api/index.html.twig', [
  33.             'controller_name' => 'APIController',
  34.         ]);
  35.     }
  36.     /**
  37.      * @Route("sql/schema", name="sql_chema")
  38.      */
  39.      /*
  40.     public function sql_chema()
  41.     {
  42.       $response =$this->render('sql/schema.txt', []);
  43.       $response->headers->set('Content-Type', 'text/html');
  44.       $response->headers->set('Access-Control-Allow-Origin', '*');
  45.       return $response;
  46.     }*/
  47.     /**
  48.      * @Route("ping", name="ping")
  49.      */
  50.     public function ping()
  51.     {
  52.       $jsonContent json_encode(["time" => new \DateTime() ]);
  53.       return $this->response200($jsonContent);
  54.     }
  55.     /**
  56.      * @Route("forms", name="forms")
  57.      */
  58.     public function forms()
  59.     {
  60.       $entities = ["Exploitant","ExploitantIdentite","ExploitantSpeculation","Charge""ChargeUpload""Produit"];
  61.       $array = [];
  62.       foreach ($entities as $entity ) {
  63.         if ($entity == "ChargeUpload") {
  64.             $class_name "App\Entity\\Charge";
  65.             $el = new $class_name();
  66.             $array[$entity] = $el->fields2();
  67.         } else {
  68.             $class_name "App\Entity\\".$entity;
  69.             $el = new $class_name();
  70.             $array[$entity] = $el->fields();
  71.         }
  72.       }
  73.       //$itk = new Entity\Itk();
  74.       //$list = $itk->ItkList();
  75.       //$array["ItkInfos"] = [];
  76.       //itks
  77.       /*foreach ($list as $key => $value) {
  78.         $object_class = "App\Entity\\".$key;
  79.         $object = new $object_class();
  80.         $array[$key] = $object->fields();
  81.         //$array["ItkInfos"][$key] = $object->infos();
  82.       }*/
  83.       $jsonContent json_encode($array);
  84.       return $this->response200($jsonContent);
  85.     }
  86.     /**
  87.      * @Route("login/{user_id}", name="login")
  88.      */
  89.     public function login($user_id)
  90.     {
  91.       $em $this->getDoctrine()->getManager();
  92.       $user $em->getRepository(User::class)->find(trim($user_id));
  93.       if(!$user) return $this->error("user with id ".intval($user_id)." doesn't exist");
  94.       $user->setApiToken(sha1(random_bytes(10))); //generate token
  95.       $user->setApiTokenCreatedAt(new \DateTime()); //reference datetime for token expiration
  96.       $jsonContent $this->serialize(User::class,  ['username','password','email'], $user_id);
  97.       return $this->response200($jsonContent);
  98.     }
  99.     
  100.     /**
  101.      * @Route("mobileApp", name="mobileApp")
  102.      */
  103.     public function mobileApp()
  104.     {
  105.       return $this->response200(json_encode(
  106.         [
  107.           "versionName" => "2.4.0",
  108.           "versionCode" => "20400",
  109.           "name" => "E-Roso 2.4.0",
  110.           "whatsnew" => " "
  111.         ]
  112.       ));
  113.     }
  114.     
  115.     /**
  116.      * @Route("debut/{user_id}/{string}", name="debut")
  117.      */
  118.     public function debut($user_id$string)
  119.     {
  120.       $jsonContent json_encode("Debut User ".$user_id." avec : ".$string);
  121.       return $this->response200($jsonContent);
  122.     }
  123.     /**
  124.      * @Route("connect/{user_login}/{user_pass}", name="connect")
  125.      */
  126.     public function connect($user_login$user_pass)
  127.     {
  128.         $response["error"] = "";
  129.         if($user_login == "" && $user_pass== "") {
  130.             $jsonContent json_encode(["status" => "KO" ]);
  131.             return $this->response200($jsonContent);
  132.         }
  133.         if($user_login != "" && $user_pass != ""){
  134.             $em $this->getDoctrine()->getManager();
  135.             $user $em->getRepository(User::class)->findOneBy(["username"=>trim($user_login), "password"=>$user_pass]);
  136.             if(!$user) {
  137.                 $jsonContent json_encode(["status" => "KO" ]);
  138.                 return $this->response200($jsonContent);
  139.                 //return $this->error("user  doesn't exist");
  140.             }
  141.             $user->setApiToken(sha1(random_bytes(10))); //generate token
  142.             $user->setApiTokenCreatedAt(new \DateTime()); //reference datetime for token expiration
  143.             $jsonContent $this->serialize(User::class,  ['username','password','email'], $user->getId());
  144.             $jsonContent json_encode(["status" => "OK""id"=> $user->getId()]);
  145.             return $this->response200($jsonContent);
  146.         }else{
  147.           $jsonContent json_encode(["status" => "KO" ]);
  148.             return $this->response200($jsonContent);
  149.         }
  150.         if($response["error"] != "") {
  151.             $jsonContent json_encode(["status" => "KO" ]);
  152.             return $this->response200($jsonContent);
  153.         }
  154.         return $this->response200(json_encode($response));
  155.       
  156.       
  157.     }    
  158.     /**
  159.      * @Route("farms/{user_id}", name="farms")
  160.      */
  161.     public function farms($user_id)
  162.     {
  163.         $em $this->getDoctrine()->getManager();
  164.         $user $em->getRepository(User::class)->findOneBy(["id"=>$user_id]);
  165.         
  166.         if(in_array('ROLE_ADMIN'$user->getRoles())){
  167.             $jsonContent $this->serialize(Exploitant::class, ["docs"]); 
  168.             return $this->response200($jsonContent);
  169.         }
  170.         
  171.         if(in_array('ROLE_OPERATOR'$user->getRoles())){
  172.             $jsonContent $this->serialize(Exploitant::class, ["docs"],$user_id"filtreExp" ); 
  173.             return $this->response200($jsonContent);
  174.         }
  175.         if(in_array('ROLE_USER'$user->getRoles())){
  176.              $jsonContent $this->serialize(Exploitant::class, ["docs"],$user_id"filtreExp"); 
  177.             return $this->response200($jsonContent);
  178.         }
  179.       return $this->response200($jsonContent);
  180.     }
  181.     /**
  182.      * @Route("orphans_plots", name="orphans_plots")
  183.      */
  184.     public function orphans_plots()
  185.     {
  186.       $jsonContent $this->serialize(Plot::class, ["farm"], NULL, ["farm" => NULL]);
  187.       // TODO
  188.       return $this->response200($jsonContent);
  189.     }
  190.     /**
  191.      * @Route("lists/{user_id}", name="lists")
  192.      */
  193.     public function lists($user_id)
  194.     {
  195.       $entities = [
  196.         "ListSexe" => [],
  197.         "ListProfil" => [],
  198.         "ListOuiNon" => [],
  199.         "ListProduit" => [],
  200.         "ListProduitAnimal" => [],
  201.         "ListTypeProductionVegetal" => [],
  202.         "ListTypeCharge" => [],
  203.         "ListSousCharge" => [],
  204.         "ListTypeProduit" => [],
  205.         "ListTypeDepense" => [],
  206.         "ListUnite" => [],
  207.         "ListMois" => [],
  208.         "ListTechnique" => [],
  209.         "ListTechnicien" => [],
  210.         "ListOrganisation" => [],
  211.         "ListElevage" => [],
  212.         "ListEau" => [],
  213.         "ListSaison" => [],
  214.         "ListPeriodeSoudure" => [],
  215.         "ListEconomieExploitation" => [],
  216.         "ListNiveauVie" => [],
  217.         "ListEAF" => [],
  218.         "ListProduction" => [],
  219.         "ListProjetPro" => [],
  220.         "ListCollege" => [],
  221.         "ListResponsabiliteOp" => [],
  222.         "ListTypeOp" => [],
  223.         "ListTypeCulture" => [],
  224.         "ListServicePaysan" => [],
  225.         "ListRegion" => [],
  226.         "ListDistrict" => [],
  227.         "ListCommune" => [],
  228.         
  229.         
  230.       ];
  231.       $em $this->getDoctrine()->getManager();
  232.       
  233.       $array = [];
  234.       foreach ($entities as $key => $value ) {
  235.         $class_name "App\Entity\\".$key;
  236.         if ($key == "ListCommune" || $key == "ListDistrict" || $key == "ListRegion") {
  237.            $array[$key] = json_decode($this->serialize($class_name$valuenull, ["isProjet" => true])); 
  238.         } else {
  239.            $array[$key] = json_decode($this->serialize($class_name$value));
  240.         }
  241.         
  242.       }
  243.       $user $em->getRepository(User::class)->findOneBy(["id"=>$user_id]);
  244.         
  245.         if(in_array('ROLE_ADMIN'$user->getRoles())){
  246.             $array["lecteur"][0] = false;
  247.         }
  248.         if(in_array('ROLE_OPERATOR'$user->getRoles())){
  249.             $array["lecteur"][0] = false;
  250.         }
  251.         if(in_array('ROLE_USER'$user->getRoles())){
  252.             $array["lecteur"][0] = true;
  253.         }
  254.         
  255.       $jsonContent json_encode($array);
  256.       return $this->response200($jsonContent);
  257.     }
  258.     /**
  259.      * @Route("personal/export/{user_id}", name="export_personal")
  260.      */
  261.     public function export_personal($user_id)
  262.     {
  263.       $jsonContent $this->serialize(User::class, ['plotsLocked','cropsLocked','userItks','lockedJson'], $user_id);
  264.       return $this->response200($jsonContent);
  265.     }
  266.     /**
  267.      * @Route("farm/{farm_id}/lock/{user_id}", name="lock_farm")
  268.      */
  269.      /*
  270.     public function lock_farm($farm_id, $user_id)
  271.     {
  272.       $em = $this->getDoctrine()->getManager();
  273.       $farm = $em->getRepository(Farm::class)->find($farm_id);
  274.       if(!$farm) return $this->error("farm not found");
  275.       // Change this with :
  276.       // $this->getUser();
  277.       $user = $em->getRepository(User::class)->find($user_id);
  278.       if(!$user) return $this->error("user not found");
  279.       if($farm->getLock())  return $this->error("farm already locked by ".$farm->getLock()->__toString());
  280.       $farm->setLock($user);
  281.       $json = [];
  282.       $json["farm"] = $farm->getLockedJson();
  283.       $em->flush();
  284.       return $this->response200(json_encode($json));
  285.     }
  286. */
  287.     /**
  288.      * @Route("farm/{farm_id}/unlock/{user_id}", name="unlock_farm")
  289.      */
  290.      /*
  291.     public function unlock_farm($farm_id, $user_id)
  292.     {
  293.       $em = $this->getDoctrine()->getManager();
  294.       $farm = $em->getRepository(Farm::class)->find($farm_id);
  295.       if(!$farm) return $this->error("farm not found");
  296.       // Change this with :
  297.       // $this->getUser();
  298.       $user = $em->getRepository(User::class)->find($user_id);
  299.       if(!$user) return $this->error("user not found");
  300.       if(!$farm->getLock())  return $this->error("farm not locked");
  301.       $farm->unlock($user);
  302.       $json = [];
  303.       $json["farm"] = $farm->getLockedJson();
  304.       $em->flush();
  305.       return $this->response200(json_encode($json));
  306.     }*/
  307.     function response200($json){
  308.       $response = new Response($json200, [
  309.         'Content-Type' => 'application/json',
  310.         'Access-Control-Allow-Origin' => '*',
  311.         "Access-Control-Allow-Headers" => "Origin, x-requested-with, Content-Type, Accept",
  312.       ]);
  313.       return $response;
  314.     }
  315.     function error($msg){
  316.       $response = new Response();
  317.       $response->setContent(json_encode([
  318.         "error" => [
  319.           'message' => $msg,
  320.         ],
  321.       ]));
  322.       $response->headers->set('Content-Type''application/json');
  323.       $response->setStatusCode(401);
  324.       return $response;
  325.     }
  326.     function get_serializer($only_normalizer=false){
  327.       $encoder = new JsonEncoder();
  328.       $defaultContext = [
  329.           AbstractNormalizer::CIRCULAR_REFERENCE_HANDLER => function ($object$format$context) {
  330.               return $object->getId();
  331.           },
  332.           AbstractObjectNormalizer::MAX_DEPTH_HANDLER => function ($innerObject$outerObjectstring $attributeNamestring $format null, array $context = []) {
  333.               return $innerObject->id;
  334.           },
  335.       ];
  336.       $normalizer = new ObjectNormalizer(nullnullnullnullnullnull$defaultContext);
  337.       $serializer = new Serializer([new DateTimeNormalizer(),$normalizer], [$encoder]);
  338.       if($only_normalizer) return $normalizer;
  339.       return $serializer;
  340.     }
  341.     function serialize($class$ignore=[], $id=NULL$filter=NULL)
  342.     {
  343.       $serializer $this->get_serializer();
  344.       $em $this->getDoctrine()->getManager();
  345.       $objects NULL;
  346.       if ($filter == "filtreExp") {
  347.             $user $this->getUser();
  348.             $em $this->getDoctrine()->getManager();
  349.             $listeExp $em->getRepository(UserExploitant::class)->findBy(array('userId'=>$id));
  350.             $myLis = [];
  351.             foreach ($listeExp as $value) {
  352.                     $myLis[] = $value->getExpId();
  353.             }
  354.             
  355.             if (count($myLis) === ){
  356.                 $objects =  [];
  357.             } else {
  358.                 $objects $em->getRepository(Exploitant::class)->findBy(array('id'=> $myLis));               
  359.             }
  360.             /*if (isset($listeExp)){
  361.                 foreach($listeExp as $list){
  362.                     
  363.                 }
  364.                 $objects = $em->getRepository(Exploitant::class)->findBy(array('expId'=> []));
  365.             } else {
  366.                 return null;
  367.             }*/
  368.       } else {
  369.         if($id$objects $em->getRepository($class)->find($id);
  370.         else if ($filter$objects $em->getRepository($class)->findBy($filter);
  371.         else $objects $em->getRepository($class)->findAll();
  372.       }
  373.       
  374.       //if(!$objects) return $this->error("Nothing found !");
  375.       // Serialize your object in Json
  376.       $ignore[] = '__initializer__';
  377.       $ignore[] = '__cloner__';
  378.       $ignore[] = '__isInitialized__';
  379.       $ignore[] = 'currencyList';
  380.       if ($class == "App\Entity\ListRegion") {
  381.         $objects $em->getRepository($class)->findBy([],["value"=>"asc"]);
  382.         return $serializer->serialize($objects'json', [
  383.           AbstractNormalizer::IGNORED_ATTRIBUTES => ["district"] ,
  384.           AbstractObjectNormalizer::ENABLE_MAX_DEPTH => true,
  385.         ]);
  386.       }
  387.       if ($class == "App\Entity\ListDistrict") {
  388.           $objects $em->getRepository($class)->findBy([],["value"=>"asc"]);
  389.             return $serializer->serialize($objects'json', [
  390.                 AbstractNormalizer::IGNORED_ATTRIBUTES => ["commune","district"] ,
  391.                 AbstractObjectNormalizer::ENABLE_MAX_DEPTH => true,
  392.             ]);
  393.         }
  394.          if ($class == "App\Entity\ListCommune") {
  395.             $objects $em->getRepository($class)->findBy([],["value"=>"asc"]);
  396.             return $serializer->serialize($objects'json', [
  397.                 AbstractNormalizer::IGNORED_ATTRIBUTES => ["commune","region"] ,
  398.                 AbstractObjectNormalizer::ENABLE_MAX_DEPTH => true,
  399.             ]);
  400.         }
  401.         $ignore[] = 'commune';
  402.         $ignore[] = 'region';
  403.         $ignore[] = 'district';
  404.       return $serializer->serialize($objects'json', [
  405.           AbstractNormalizer::IGNORED_ATTRIBUTES => $ignore ,
  406.           AbstractObjectNormalizer::ENABLE_MAX_DEPTH => true,
  407.       ]);
  408.     }
  409.    //transform objects relations to an array of ids
  410.    function relations_to_ids($objs_array){
  411.      $ids_array = [];
  412.      foreach ($objs_array as $obj) {
  413.        $ids_array[] = $obj->getId();
  414.      }
  415.      return $ids_array;
  416.    }
  417. }