objects are turned into arrays by normalizers arrays are turned into various output formats by encoders $serializer->serialize($obj, 'xml') $serializer->decode($data, 'xml') $serializer->denormalize($data, 'Class', 'xml')
Author: Jordi Boggiano (j.boggiano@seld.be)
Author: Johannes M. Schmitt (schmittjoh@gmail.com)
Author: Lukas Kahwe Smith (smith@pooteeweet.org)
Inheritance: implements Symfony\Component\Serializer\SerializerInterface
 /**
  * @return JsonResponse
  *
  * @Route("/sync")
  */
 public function syncAction()
 {
     $youtube = new Youtube(['key' => $this->getParameter('youtube_api_key')]);
     $videos = $youtube->getPlaylistItemsByPlaylistId($this->getParameter('youtube_playlist_id'));
     $em = $this->getDoctrine()->getManager();
     foreach ($videos as $video) {
         $name = $video->snippet->title;
         $youtubeId = $video->snippet->resourceId->videoId;
         $description = $video->snippet->description;
         if (property_exists($video->snippet->thumbnails, 'maxres')) {
             $thumbnail = $video->snippet->thumbnails->maxres->url;
         } elseif (property_exists($video->snippet->thumbnails, 'high')) {
             $thumbnail = $video->snippet->thumbnails->high->url;
         } elseif (property_exists($video->snippet->thumbnails, 'medium')) {
             $thumbnail = $video->snippet->thumbnails->medium->url;
         } else {
             $thumbnail = $video->snippet->thumbnails->default->url;
         }
         $video = $em->getRepository('TGVideoBundle:Video')->findOneByYoutubeId($youtubeId);
         if ($video === null) {
             $video = new Video();
             $video->setYoutubeId($youtubeId);
             $em->persist($video);
         }
         $video->setName($name);
         $video->setDescription($description);
         $video->setThumbnail($thumbnail);
         $video->setUrl('https://www.youtube.com/embed/' . $youtubeId);
     }
     $em->flush();
     $videos = $this->getDoctrine()->getRepository('TGVideoBundle:Video')->findAll([], ['createdAt' => 'DESC']);
     $serializer = new Serializer([$this->get('tg_video.normalizer')]);
     return new JsonResponse(['videos' => $serializer->normalize($videos)]);
 }
 public function showAction()
 {
     $serializer = new Serializer([new ObjectNormalizer()], [new JsonEncode()]);
     $data = $this->productService->getAll();
     $jsonData = $serializer->serialize($data, 'json');
     return $this->templateEngine->renderResponse('AppBundle:admin:productList.html.twig', array('products' => $jsonData));
 }
Example #3
0
 public function setUp()
 {
     $serializer = new Serializer();
     $this->encoder = new XmlEncoder();
     $serializer->setEncoder('xml', $this->encoder);
     $serializer->addNormalizer(new CustomNormalizer());
 }
 /**
  * @param $object
  * @return mixed
  */
 public function getSerialize($object)
 {
     $encoders = array(new XmlEncoder(), new JsonEncoder());
     $normalizers = array(new ObjectNormalizer());
     $serializer = new Serializer($normalizers, $encoders);
     return $serializer->serialize($object, 'json');
 }
 public function updateAction(Request $request)
 {
     $ExamId = $request->get('id');
     $em = $this->getDoctrine()->getManager();
     $exam = $em->getRepository('ClassUserBundle:Exams')->find($ExamId);
     //under this condition edit form will filled with the existing data
     //when class being selected this mehtod will be invoked.
     if ($request->getMethod() == 'GET' && $exam != null) {
         $encoders = array(new JsonEncoder());
         $normalizers = array(new ObjectNormalizer());
         $serializer = new Serializer($normalizers, $encoders);
         $jsonContent = $serializer->serialize($exam, 'json');
         return new \Symfony\Component\HttpFoundation\Response($jsonContent);
     }
     //this conditon will work when data being submitted through the form
     if ($request->getMethod() == 'POST' && $exam != null) {
         if ($request->request->get('fees')) {
             $exam->setFees($request->request->get('fees'));
         }
         if ($request->request->get('conductDay')) {
             $exam->setConductDay($request->request->get('conductDay'));
         }
         if ($request->request->get('time')) {
             $exam->setTime($request->request->get('time'));
         }
         if ($request->request->get('teacher_id')) {
             $exam->setTeacherid($request->request->get('teacher_id'));
         }
         $em->flush();
         return new JsonResponse(array('message' => 'Updated Successfully'));
     }
     return new JsonResponse(array('message' => 'ERROR'));
 }
 /**
  * Deserializes a Json into readable datas
  * @param string $string
  *
  * @return RZ\Roadiz\Core\Entities\Group
  */
 public function deserialize($string)
 {
     if ($string == "") {
         throw new \Exception('File is empty.');
     }
     $encoder = new JsonEncoder();
     $nameConverter = new CamelCaseToSnakeCaseNameConverter(['name']);
     $normalizer = new GetSetMethodNormalizer(null, $nameConverter);
     $serializer = new Serializer([$normalizer], [$encoder]);
     $group = $serializer->deserialize($string, 'RZ\\Roadiz\\Core\\Entities\\Group', 'json');
     /*
      * Importing Roles.
      *
      * We need to extract roles from group and to re-encode them
      * to pass to RoleJsonSerializer.
      */
     $tempArray = json_decode($string, true);
     $data = [];
     if (!empty($tempArray['roles'])) {
         foreach ($tempArray['roles'] as $roleAssoc) {
             $role = $this->roleSerializer->deserialize(json_encode($roleAssoc));
             $role = $this->em->getRepository('RZ\\Roadiz\\Core\\Entities\\Role')->findOneByName($role->getName());
             $group->addRole($role);
         }
         $data[] = $group;
     }
     return $data;
 }
 /**
  * Generates the ajax response.
  *
  * @param Request                                                      $request      The request
  * @param AjaxChoiceLoaderInterface|FormBuilderInterface|FormInterface $choiceLoader The choice loader or form or array
  * @param string                                                       $format       The output format
  * @param string                                                       $prefix       The prefix of parameters
  *
  * @return Response
  *
  * @throws InvalidArgumentException When the format is not allowed
  */
 public static function generateResponse(Request $request, $choiceLoader, $format = 'json', $prefix = '')
 {
     $formats = array('xml', 'json');
     if (!in_array($format, $formats)) {
         $msg = "The '%s' format is not allowed. Try with '%s'";
         throw new InvalidArgumentException(sprintf($msg, $format, implode("', '", $formats)));
     }
     if ($choiceLoader instanceof FormBuilderInterface || $choiceLoader instanceof FormInterface) {
         $formatter = static::extractAjaxFormatter($choiceLoader);
         $choiceLoader = static::extractChoiceLoader($choiceLoader);
     } else {
         $formatter = static::createChoiceListFormatter();
     }
     if (!$choiceLoader instanceof AjaxChoiceLoaderInterface) {
         throw new UnexpectedTypeException($choiceLoader, 'Sonatra\\Bundle\\FormExtensionsBundle\\Form\\ChoiceList\\Loader\\AjaxChoiceLoaderInterface');
     }
     $data = static::getData($request, $choiceLoader, $formatter, $prefix);
     $encoders = array(new XmlEncoder(), new JsonEncoder());
     $normalizers = array(new GetSetMethodNormalizer());
     $serializer = new Serializer($normalizers, $encoders);
     $response = new Response();
     $response->headers->set('Content-Type', 'application/' . $format);
     $response->setContent($serializer->serialize($data, $format));
     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;
 }
 /**
  * Decode tha data
  * @param string $req_obj
  * @return array
  */
 public function decodeData($req_obj)
 {
     //get serializer instance
     $serializer = new Serializer(array(), array('json' => new \Symfony\Component\Serializer\Encoder\JsonEncoder(), 'xml' => new \Symfony\Component\Serializer\Encoder\XmlEncoder()));
     $jsonContent = $serializer->decode($req_obj, 'json');
     return $jsonContent;
 }
 /**
  * @test
  */
 public function itShouldCollect()
 {
     $this->serializer->normalize(Argument::any())->shouldBeCalled()->willReturn([]);
     $this->logger->pushHandler(Argument::any())->shouldBeCalled()->willReturn(true);
     $this->logger->info(Argument::type('string'), Argument::type('array'))->shouldBeCalled();
     $this->collector->collect($this->requestObject, ['logFile' => 'test.log']);
 }
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $output->writeln("CONECTANDO A WEBSERVICE VIA SOAP");
     try {
         $normalizer = new GetSetMethodNormalizer();
         $encoder = new JsonEncoder();
         $serializer = new Serializer(array($normalizer), array($encoder));
         //retrieve WSDL
         $this->client = new \nusoap_client("http://crm.cam-la.com/service/v4/soap.php?wsdl", 'true');
         $this->executeLogin($input, $output);
         //Obtengo todos los archivos que hay en la carpeta:
         $path = $this->getApplication()->getKernel()->getContainer()->get('kernel')->getRootDir() . '/Resources/data/';
         $files = scandir($path);
         foreach ($files as $file) {
             if (is_readable($path . $file) == false) {
                 continue;
             }
             if (is_file($path . $file) == false) {
                 continue;
             }
             $output->writeln("EJECUTANDO DATA " . $file);
             $content = file_get_contents($path . $file);
             $data = json_decode(json_encode($content), true);
             $obj = $serializer->deserialize($data, 'BcTic\\Bundle\\AtencionCrmCamBundle\\Entity\\CustomerCase', 'json');
             $this->uploadToDataBase($obj, $input, $output);
             //Ahora debo eliminar el archivo, pues con otro comando los obtengo y los voy actualizando para consulta cada 5 minutos.
             unlink($path . $file);
         }
     } catch (Exception $e) {
         $output->writeln("ERROR: " . $e->getMessage());
     }
     $output->writeln("EJECUCION FINALIZADA. Good Bye!");
 }
 function get(Request $req)
 {
     $resourceName = $req->get('resource');
     if (!isset($this->module["resourceEntityMappings"][$resourceName])) {
         throw new NotFoundHttpException();
     }
     $entityClass = $this->module["namespace"] . $this->module["resourceEntityMappings"][$resourceName];
     // Filterer entities queried?
     if ($req->getQueryString() != null) {
         $querystring = $req->getQueryString();
         $criteria = array();
         $queryParts = \explode('&', $querystring);
         foreach ($queryParts as $queryPart) {
             $key_value = \explode('=', $queryPart);
             $criteria[$key_value[0]] = urldecode($key_value[1]);
         }
         $entities = $this->em->getRepository($entityClass)->findBy($criteria);
         // Single entity queried?
     } elseif ($req->get('id') != null) {
         $id = $req->get('id');
         $entity = $this->em->getRepository($entityClass)->find($id);
         $entities = array($entity);
     } else {
         $entities = $this->em->getRepository($entityClass)->findAll();
     }
     return new Response($this->serializer->serialize(array($resourceName => $entities), 'json'), 200, array('Content-Type' => $req->getMimeType('json')));
 }
Example #13
0
 /**
  * Serialize an object to json.
  *
  * @todo There is an issue while serializing the Country object in JSON.
  * The country has the Country object (name and code) instead to have the country name.
  *
  * @param BatchGeocoded $object The BatchGeocoded object to serialize.
  *
  * @return string The serialized object in json.
  */
 protected function serialize($object)
 {
     $serializer = new Serializer([new ObjectNormalizer()], [new JsonEncoder()]);
     $serialized = $serializer->serialize($object, 'json');
     // transform to array to fix the serialization issue
     $serialized = json_decode($serialized, true);
     return json_encode($this->fixSerialization($serialized));
 }
Example #14
0
 public function output($object)
 {
     $encoders = array(new XmlEncoder(), new JsonEncoder());
     $normalizers = array(new ObjectNormalizer());
     $serializer = new Serializer($normalizers, $encoders);
     $jsonContent = $serializer->serialize($object->getItems(), 'json');
     echo $jsonContent;
 }
 private function deserialize($json, $entityName)
 {
     $encoders = array(new XmlEncoder(), new JsonEncoder());
     $normalizers = array(new ObjectNormalizer());
     $serializer = new Serializer($normalizers, $encoders);
     $object = $serializer->deserialize($json, $entityName, 'json');
     return $object;
 }
 function it_returns_flat_data_without_media(ChannelInterface $channel, ChannelManager $channelManager, ProductInterface $product, Serializer $serializer)
 {
     $product->getValues()->willReturn([]);
     $serializer->normalize($product, 'flat', ['scopeCode' => 'foobar', 'localeCodes' => ''])->willReturn(['normalized_product']);
     $channelManager->getChannelByCode('foobar')->willReturn($channel);
     $this->setChannel('foobar');
     $this->process($product)->shouldReturn(['media' => [], 'product' => ['normalized_product']]);
 }
 public function save(Article $article)
 {
     $metadata = $this->entityManager->getClassMetadata(get_class($article));
     $type = "app." . $metadata->getTableName();
     $this->fluentLogger->post($type, array_filter($this->serializer->normalize($article), function ($idx) {
         return $idx != 'id';
     }, ARRAY_FILTER_USE_KEY));
 }
 private function serialize($object)
 {
     $encoders = array(new XmlEncoder(), new JsonEncoder());
     $normalizers = array(new ObjectNormalizer());
     $serializer = new Serializer($normalizers, $encoders);
     $jsonContent = $serializer->serialize($object, 'json');
     return $jsonContent;
 }
 /**
  * {@inheritdoc}
  */
 public function normalize($elements, $format = null, array $context = [])
 {
     $normalizedElements = [];
     foreach ($elements as $key => $element) {
         $normalizedElements[$key] = $this->serializer->normalize($element, $format, $context);
     }
     return $normalizedElements;
 }
 /**
  * Deserializes a json file into a readable array of datas.
  *
  * @param string $jsonString
  *
  * @return RZ\Roadiz\Core\Entities\NodeTypeField
  */
 public static function deserialize($jsonString)
 {
     $encoder = new JsonEncoder();
     $nameConverter = new CamelCaseToSnakeCaseNameConverter(['name', 'label', 'description', 'visible', 'type', 'indexed', 'virtual', 'default_values']);
     $normalizer = new GetSetMethodNormalizer(null, $nameConverter);
     $serializer = new Serializer([$normalizer], [$encoder]);
     return $serializer->deserialize($jsonString, 'RZ\\Roadiz\\Core\\Entities\\NodeTypeField', 'json');
 }
Example #21
0
 /**
  * {@inheritdoc}
  */
 public function buildView(FormView $view, FormInterface $form, array $options)
 {
     $serializer = new Serializer([$this->normalizer]);
     $data = $form->getData();
     if ($data instanceof Video) {
         $data = new ArrayCollection([$data]);
     }
     $view->vars['options'] = json_encode(['multiple' => $options['multiple'], 'name' => $view->vars['full_name'], 'selected' => $serializer->normalize($data)]);
 }
Example #22
0
 /**
  * {@inheritdoc}
  */
 public function buildView(FormView $view, FormInterface $form, array $options)
 {
     $serializer = new Serializer([$this->normalizer]);
     $data = $form->getData();
     if ($data instanceof File) {
         $data = new ArrayCollection([$data]);
     }
     $view->vars['options'] = json_encode(['multiple' => $options['multiple'], 'name' => $view->vars['full_name'], 'images_only' => $options['images_only'], 'selected' => $serializer->normalize($data), 'allow_upload' => $options['allow_upload'], 'allow_delete' => $options['allow_delete'], 'allow_new_folder' => $options['allow_new_folder']]);
 }
Example #23
0
 /**
  * returns the xml sitemap
  * @return string sitemap in xml format
  */
 public function __toString()
 {
     // Missing attribute xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" in urlset node
     $encoders = array(new XmlEncoder('urlset'));
     // anyway to use setIgnoredAttributes() dynamicly on each Url object?
     $normalizers = array(new GetSetMethodNormalizer());
     $serializer = new Serializer($normalizers, $encoders);
     return (string) $serializer->serialize(array('url' => $this->urls), 'xml');
 }
 public function testStdClassNormalizer()
 {
     $normalizers = array(new StdClassNormalizer());
     $encoders = array();
     $serializer = new Serializer($normalizers, $encoders);
     $object = (object) array('foo' => 'bar', 'array' => array(1, 'foo' => (object) array('foo' => 'bar')));
     $normalized_object = $serializer->normalize($object);
     $this->assertEquals($object, $normalized_object, 'Normalizer accepted stdClass object.');
 }
 /**
  * @Route("/account/{url}/{appkey}")
  * 
  */
 public function accountAction($url, $appkey)
 {
     $encoder = new JsonEncoder();
     $normalizer = new GetSetMethodNormalizer();
     $serializer = new Serializer(array($normalizer), array($encoder));
     $account = $this->getDoctrine()->getRepository('AdminBundle:Account')->findByUrl($url);
     $serializer->serialize($account, 'json');
     return new Response($serializer->serialize($account, 'json'), 200, array('Content-Type' => 'application/json'));
 }
 public function getAction()
 {
     $normalizer = new ObjectNormalizer(new ClassMetadataFactory(new YamlFileLoader(CONFIG_PATH . 'test_entity.yml')), new CamelCaseToSnakeCaseNameConverter());
     $serializer = new Serializer([$normalizer], [new JsonEncoder(), new XmlEncoder()]);
     $test = new TestEntity();
     $test->setMessage('Test');
     $test = $serializer->deserialize('<test><id>1</id></test>', 'DG\\SymfonyCert\\Entity\\TestEntity', 'xml', ['object_to_populate' => $test]);
     return new Response($serializer->serialize($test, 'xml', ['groups' => ['group2']]), 200, ['Content-Type' => 'text/xml']);
 }
 public function toJson()
 {
     $encoders = array(new XmlEncoder(), new JsonEncoder());
     $normalizers = array(new ObjectNormalizer());
     $serializer = new Serializer($normalizers, $encoders);
     $data['result'] = array();
     $data['result'] = json_decode($serializer->serialize($this, 'json'), true);
     return json_encode($data);
 }
Example #28
0
 public function userDataAction()
 {
     $user = $this->get('security.context')->getToken()->getUser();
     $normalizer = new GetSetMethodNormalizer();
     $normalizer->setIgnoredAttributes(array('password', 'roles', 'salt'));
     $serializer = new Serializer(array($normalizer), array(new JsonEncoder()));
     $json = $serializer->serialize($user, 'json');
     return new Response($json);
 }
 /**
  * Compares given value object with value object data structure
  *
  * Returns set of value object attribute names. E.g.:
  *
  * [
  *      // Items that are missing in value object
  *      'add'    => ['field1', 'field2', ...]
  *      // Items that shuld not be present in value object
  *      'remove' => ['field3', 'field4', ...]
  * ]
  *
  * @param object $object
  * @param array $comparedData
  * @param string $propertyIdentifier
  * @return array
  */
 public function diff($object, $comparedData, $propertyIdentifier)
 {
     $objectData = $this->serilaizer->normalize($object);
     $comparingColumn = $this->getAttributesOfValueObjects($comparedData, $propertyIdentifier);
     $toAdd = array_diff($comparingColumn, array_column($objectData, $propertyIdentifier));
     $toRemove = array_diff(array_column($objectData, $propertyIdentifier), $comparingColumn);
     // @todo: add items to be updated
     return ['add' => $toAdd, 'remove' => $toRemove];
 }
Example #30
0
 /**
  * Response constructor.
  *
  * @param string $content
  * @param int    $status
  * @param array  $headers
  */
 public function __construct($content = '', $status = 200, $headers = array())
 {
     $encoders = [new XmlEncoder()];
     $normalizers = [new GetSetMethodNormalizer()];
     $serializer = new Serializer($normalizers, $encoders);
     $contents_xml = $serializer->serialize($content, 'xml');
     $headers['Content-Type'] = 'application/xml';
     parent::__construct($contents_xml, $status = 200, $headers);
 }