/**
  * @Route("/exportcsvpro", name="export_pro")
  */
 public function exportProCSVAction()
 {
     $now = new \DateTime('now');
     $em = $this->getDoctrine()->getManager();
     $response = new StreamedResponse();
     $response->setCallback(function () use($em) {
         $normalizer = new ObjectNormalizer();
         $count = $em->getRepository('AppBundle:Client')->getCount();
         $total = intval($count[1]);
         $header = array('NOM', 'PRENOM', 'EMAIL', 'SEXE');
         $handle = fopen('php://output', 'r+');
         fputcsv($handle, $header, ";");
         $row = 1;
         while ($total >= 0) {
             $clients = $em->getRepository('AppBundle:Client')->findAllClients(($row - 1) * 2, 2);
             foreach ($clients as $key => $obj) {
                 $clients[$key] = $normalizer->normalize($obj);
             }
             foreach ($clients as $client) {
                 fputcsv($handle, $client, ";");
             }
             $total = $total - 2;
             $row++;
         }
         fclose($handle);
     });
     $response->headers->set('Content-Type', 'application/force-download');
     $response->headers->set('Content-Disposition', 'attachment; filename="export.csv"');
     return $response;
 }
 /**
  * @Route("/player/ajax/get", name="team_player_ajax_get")
  */
 public function ajaxGetAction(Request $request)
 {
     if ($request->isXmlHttpRequest()) {
         try {
             $user = $this->getUser();
             $em = $this->getDoctrine()->getManager();
             $player = $em->getRepository('TeamBundle:Player')->findOneBy(array('id' => $request->get('id')));
             if ($user->getTeam() == $player->getTeam()) {
                 $normalizer = new ObjectNormalizer();
                 $normalizer->setCircularReferenceHandler(function ($object) {
                     return $object->getId();
                 });
                 $serializer = new Serializer(array($normalizer));
                 $player = $serializer->normalize($player);
                 $response = new Response(json_encode(array('status' => 'ok', 'player' => $player)));
             } else {
                 $response = new Response(json_encode(array('status' => 'ko', 'message' => 'Vous n\'avez pas la permission d\'éditer ce joueur', 'debug' => 'Utilisateur connecté != manager de l\'équipe du joueur')));
             }
         } catch (\Exception $e) {
             $response = new Response(json_encode(array('status' => 'ko', 'message' => 'Une erreur inconnue s\'est produite', 'debug' => $e->getMessage())));
         }
         $response->headers->set('Content-Type', 'application/json');
         return $response;
     }
     $response = new Response(json_encode(array('status' => 'ko', 'message' => 'Accès non autorisé', 'debug' => 'Bad request')));
     $response->headers->set('Content-Type', 'application/json');
     return $response;
 }
 public function testObjectToPopulateWithProxy()
 {
     $proxyDummy = new ProxyDummy();
     $context = array('object_to_populate' => $proxyDummy);
     $normalizer = new ObjectNormalizer();
     $normalizer->denormalize(array('foo' => 'bar'), 'Symfony\\Component\\Serializer\\Tests\\Fixtures\\ToBeProxyfiedDummy', null, $context);
     $this->assertSame('bar', $proxyDummy->getFoo());
 }
 /**
  * {@inheritdoc}
  */
 public function normalize($object, $format = null, array $context = array())
 {
     $encoder = new JsonEncoder();
     $normalizer = new ObjectNormalizer();
     $normalizer->setCircularReferenceHandler(function ($object) {
         return $object->getName();
     });
     $serializer = new Serializer(array($normalizer), array($encoder));
     return $serializer->normalize($object);
 }
 /**
  * Constructor
  */
 public function __construct()
 {
     $classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader()));
     $encoder = new JsonEncoder();
     $normalizer = new ObjectNormalizer($classMetadataFactory);
     $normalizer->setCircularReferenceHandler(function (ClassMetadata $object) {
         return $object->getName();
     });
     $this->serializer = new Serializer([$normalizer], [$encoder]);
 }
 private function getGalleryItems()
 {
     $encoders = array(new XmlEncoder(), new JsonEncoder());
     $normalizer = new ObjectNormalizer();
     $normalizer->setCircularReferenceHandler(function ($object) {
         return $object->getId();
     });
     $serializer = new Serializer(array($normalizer), $encoders);
     $em = $this->getDoctrine()->getManager();
     $galleryItems = $em->getRepository('BackendAdminBundle:GalleryItem')->findAll();
     return $galleryItems = $serializer->serialize($galleryItems, 'json');
 }
 public function indexAction()
 {
     $encoders = array(new XmlEncoder(), new JsonEncoder());
     $normalizer = new ObjectNormalizer();
     $normalizer->setIgnoredAttributes(array('username', 'password', 'salt', 'userRoles', 'roles', 'sobiratel', 'informator', 'userid', 'id', 'lazyPropertiesDefaults', '__initializer__', '__cloner__', '__isInitialized__'));
     $serializer = new Serializer(array($normalizer), $encoders);
     $user = $this->getUser();
     $jsonContent = $serializer->serialize($user, 'xml');
     $response = new Response($jsonContent);
     $response->headers->set('Content-Type', 'text/xml');
     $response->headers->set('Content-Disposition', 'attachment; filename="pasport.xml"');
     return $response;
 }
 public function testNormalizeNotSerializableContext()
 {
     $objectDummy = new ObjectDummy();
     $expected = array('foo' => null, 'baz' => null, 'fooBar' => '', 'camelCase' => null, 'object' => null, 'bar' => null);
     $this->assertEquals($expected, $this->normalizer->normalize($objectDummy, null, array('not_serializable' => function () {
     })));
 }
 /**
  * {@inheritdoc}
  */
 protected function getConstructor(array &$data, $class, array &$context, \ReflectionClass $reflectionClass, $allowedAttributes)
 {
     if (is_a($class, StaticConstructorDummy::class, true)) {
         return new \ReflectionMethod($class, 'create');
     }
     return parent::getConstructor($data, $class, $context, $reflectionClass, $allowedAttributes);
 }
 /**
  * Lists all Events entities.
  *
  */
 public function indexAction()
 {
     $em = $this->getDoctrine()->getManager();
     $entities = $em->getRepository('AgendaBundle:Events')->findAll();
     $normalizer = new ObjectNormalizer();
     $encoder = new JsonEncoder();
     $dateCallback = function ($dateTime) {
         return $dateTime instanceof \DateTime ? $dateTime->format(\DateTime::ISO8601) : '';
     };
     $userCallback = function ($user) {
         return array("email" => $user->getEmail(), "roles" => $user->getRoles(), "id_organisme" => $user->getIdOrganisme()->getId());
     };
     $normalizer->setCallbacks(array('start' => $dateCallback, 'end' => $dateCallback, 'idUser' => (object) $userCallback));
     $serializer = new Serializer(array($normalizer), array($encoder));
     $jsonObject = $serializer->serialize($entities, 'json');
     $response = new Response();
     $response->setContent($jsonObject);
     return $response;
 }
 /**
  * @Route("/exportexcel", requirements={"_format" = "excel"}, name="excel_export")
  */
 public function exportExcelAction()
 {
     if ($this->getRequest()->getMethod() == "POST") {
         $normalizer = new ObjectNormalizer();
         $now = new \DateTime();
         $day = $now->format('d');
         $month = $now->format('m');
         $year = $now->format('Y');
         $date = $day . '-' . $month . '-' . $year;
         $filename = 'export_articles_' . $date . '.xls';
         $em = $this->getDoctrine()->getManager();
         $data = $em->getRepository('AppBundle:Article')->findAll();
         foreach ($data as $key => $obj) {
             $data[$key] = $normalizer->normalize($obj);
         }
         return $this->get('excel_service')->array_to_excel($data, $filename);
         die;
     }
     return $this->render('AppBundle:Default:exportexcel.html.twig');
 }
 /**
  * Cette action permet de retourner les évenements en Json
  * @return Response
  */
 public function indexAction()
 {
     $em = $this->getDoctrine()->getManager();
     $entities = $em->getRepository('WcsWildResaBundle:Events')->findAll();
     $normalizer = new ObjectNormalizer();
     $encoder = new JsonEncoder();
     $dateCallback = function ($dateTime) {
         return $dateTime instanceof \DateTime ? $dateTime->format(\DateTime::ISO8601) : '';
     };
     // ne conserver que le type de la machine
     $machineCallback = function ($machines) {
         $result = [];
         foreach ($machines as $mach) {
             $result[] = $mach->getTypeMachine();
         }
         return $result;
     };
     $normalizer->setCallbacks(array('start' => $dateCallback, 'end' => $dateCallback, 'machines' => $machineCallback));
     $serializer = new Serializer(array($normalizer), array($encoder));
     $jsonObject = $serializer->serialize($entities, 'json');
     return new Response($jsonObject);
 }
 /**
  * @Route("/randonnee/{cleRando}")
  * @Template()
  */
 public function viewAction($cleRando, Request $request)
 {
     //if ($request->isXMLHttpRequest()) {
     $randonnee = $this->getDoctrine()->getRepository('AdherentsBundle:Randonnees')->find($cleRando);
     if (!$randonnee) {
         throw $this->createNotFoundException('Pas de randonnee pour la cle :' . $cleRando);
     }
     //see http://symfony.com/doc/current/components/serializer.html
     //$encoders = array(new XmlEncoder(), new JsonEncoder());
     $encoders = array(new JsonEncoder());
     $normalizer = new ObjectNormalizer();
     //http://symfony.com/doc/current/components/serializer.html see circulable references
     $normalizer->setCircularReferenceHandler(function ($object) {
         return $object->getCle();
     });
     $normalizers = array($normalizer);
     $serializer = new Serializer($normalizers, $encoders);
     $json_datas = $serializer->serialize($randonnee, 'json');
     return new Response($json_datas);
     //}
     //return new Response('This is not ajax!', 400);
 }
Example #14
0
 public function testMaxDepth()
 {
     $classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader()));
     $this->normalizer = new ObjectNormalizer($classMetadataFactory);
     $serializer = new Serializer(array($this->normalizer));
     $this->normalizer->setSerializer($serializer);
     $level1 = new MaxDepthDummy();
     $level1->foo = 'level1';
     $level2 = new MaxDepthDummy();
     $level2->foo = 'level2';
     $level1->child = $level2;
     $level3 = new MaxDepthDummy();
     $level3->foo = 'level3';
     $level2->child = $level3;
     $result = $serializer->normalize($level1, null, array(ObjectNormalizer::ENABLE_MAX_DEPTH => true));
     $expected = array('bar' => null, 'foo' => 'level1', 'child' => array('bar' => null, 'foo' => 'level2', 'child' => array('bar' => null, 'child' => null)));
     $this->assertEquals($expected, $result);
 }
 public function configure(ObjectNormalizer $normalizer)
 {
     $normalizer->setCircularReferenceHandler(function ($object) {
         return $object->getId();
     });
 }
 /**
  * pour rechercher des utilisateurs
  * @Route("/commenter", name="commenter")
  */
 public function commenter(Request $request)
 {
     $msg = $request->request->get('msg');
     $idAnnonce = $request->request->get('annonce');
     $user = $this->getConnectedUser();
     $commentaire = new comment();
     $commentaire->setIsVisible('YES');
     $commentaire->setUser($user);
     $commentaire->setMsg($msg);
     $now = new DateTime();
     $commentaire->setDate($now);
     $em = $this->getDoctrine()->getManager();
     $annonce = $em->getRepository("EntityBundle:annonce")->findOneById($idAnnonce);
     $commentaire->setAnnonce($annonce);
     $normalizer = new ObjectNormalizer();
     $normalizer->setIgnoredAttributes(array('password', 'comments', 'messages', 'username', 'role', 'roles', 'salt'));
     $serializer = new Serializer(array($normalizer), array(new JsonEncoder()));
     $em = $this->getDoctrine()->getManager();
     $em->persist($commentaire);
     $em->flush();
     $jsonContent = $serializer->serialize($commentaire, 'json');
     $response = new Response($jsonContent);
     $response->headers->set('Content-Type', 'application/json');
     return $response;
 }
Example #17
0
 /**
  * @expectedException \Symfony\Component\Serializer\Exception\UnexpectedValueException
  */
 public function testThrowUnexpectedValueException()
 {
     $this->normalizer->denormalize(array('foo' => 'bar'), ObjectTypeHinted::class);
 }
 /**
  * @Route("/ajax/bookmark/create", name="ajax_create_bookmark")
  */
 public function ajaxCreateAction(Request $request)
 {
     $em = $this->getDoctrine()->getManager();
     $repository = $em->getRepository('AppBundle:Bookmark');
     $tagRepository = $em->getRepository('AppBundle:Tag');
     $openGraph = $this->container->get('open_graph');
     $url = $request->request->get('url');
     $tags = $request->request->get('tags');
     $user = $this->get('security.context')->getToken()->getUser();
     if (!$url) {
         $data = array('error' => 'invalid_url', 'errorMsg' => 'URL is required');
         $json = \json_encode($data);
         $response = new Response($json, 404);
         $response->headers->set('Content-Type', 'application/json');
         return $response;
     }
     $tags = explode(',', $tags);
     try {
         $data = $openGraph->read($url);
     } catch (RequestException $e) {
         $context = $e->getHandlerContext();
         $data = array('error' => 'invalid_url');
         if (isset($context['error'])) {
             $data['errorMsg'] = $context['error'];
         }
         $json = \json_encode($data);
         $response = new Response($json, 404);
         $response->headers->set('Content-Type', 'application/json');
         return $response;
     } catch (ConnectException $e) {
         $data = array('error' => 'invalid_page', 'exception' => $e->getMessage());
         $json = \json_encode($data);
         $response = new Response($json, 404);
         $response->headers->set('Content-Type', 'application/json');
         return $response;
     } catch (\Exception $e) {
         $data = array('error' => 'exception', 'exception' => $e->getMessage());
         $json = \json_encode($data);
         $response = new Response($json, 500);
         $response->headers->set('Content-Type', 'application/json');
         return $response;
     }
     $title = $data['title'];
     $description = $data['description'];
     if (isset($data['og:title']) && $data['og:title']) {
         $title = $data['og:title'];
     }
     if (isset($data['og:description']) && $data['og:description']) {
         $description = $data['og:description'];
     }
     $bookmark = new Bookmark();
     $bookmark->setUrl($url);
     $bookmark->setTitle($title);
     $bookmark->setUser($user);
     $bookmark->setDescription($description);
     if (isset($data['og:image'])) {
         $bookmark->setImage($data['og:image']);
     }
     $bookmarkTags = array();
     foreach ($tags as $tagName) {
         $tag = new Tag();
         $tag->setName($tagName);
         $tag->setUser($user);
         $em->persist($tag);
         $bookmarkTags[] = $tag;
     }
     $bookmark->setTags($bookmarkTags);
     $em->persist($bookmark);
     $em->flush();
     $normalizer = new ObjectNormalizer();
     $normalizer->setCircularReferenceHandler(function ($object) {
         return $object->getId();
     });
     $json = \json_encode($bookmark);
     $response = new Response($json);
     $response->headers->set('Content-Type', 'application/json');
     return $response;
 }
 public function benchSymfonyObjectNormalizer()
 {
     $normalizer = new ObjectNormalizer();
     $normalizer->setCallbacks(array('createdAt' => function (\DateTime $date) {
         return $date->format(\DateTime::RFC3339);
     }));
     $normalizers = array($normalizer);
     $encoders = array(new JsonEncoder());
     $symfony = new Serializer($normalizers, $encoders);
     return $symfony->serialize($this->data, 'json');
 }
Example #20
0
 /**
  * @param string $class
  * @param array  $data
  *
  * @return object
  */
 public static function fromArray($class, array $data)
 {
     $normalizer = new ObjectNormalizer();
     return $normalizer->denormalize($data, $class);
 }
 public function testNormalizeStatic()
 {
     $this->assertEquals(array('foo' => 'K'), $this->normalizer->normalize(new ObjectWithStaticPropertiesAndMethods()));
 }
Example #22
0
 /**
  * @Route("/news/ajax/get", name="admin_news_ajax_get")
  */
 public function ajaxGetAction(Request $request)
 {
     if ($request->isXmlHttpRequest()) {
         try {
             $em = $this->getDoctrine()->getManager();
             $news = $em->getRepository('MainBundle:News')->findOneBy(array('id' => $request->get('id')));
             $normalizer = new ObjectNormalizer();
             $normalizer->setCircularReferenceHandler(function ($object) {
                 return $object->getId();
             });
             $serializer = new Serializer(array($normalizer));
             $news = $serializer->normalize($news);
             $response = new Response(json_encode(array('status' => 'ok', 'news' => $news)));
         } catch (\Exception $e) {
             $response = new Response(json_encode(array('status' => 'ko', 'message' => 'Une erreur inconnue s\'est produite', 'debug' => $e->getMessage())));
         }
         $response->headers->set('Content-Type', 'application/json');
         return $response;
     }
     $response = new Response(json_encode(array('status' => 'ko', 'message' => 'Accès refusé', 'debug' => 'Bad request')));
     $response->headers->set('Content-Type', 'application/json');
     return $response;
 }