php Symfony-Component-Serializer-Serializer类(方法)实例源码

下面列出了php Symfony-Component-Serializer-Serializer 类(方法)源码代码实例,从而了解它的用法。

作者:tweedegol    项目:video-bundl   
/**
  * @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)]);
 }

作者:dev-learnin    项目:websho   
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));
 }

作者:rooste    项目:symfon   
public function setUp()
 {
     $serializer = new Serializer();
     $this->encoder = new XmlEncoder();
     $serializer->setEncoder('xml', $this->encoder);
     $serializer->addNormalizer(new CustomNormalizer());
 }

作者:Futrill    项目:iglesy   
/**
  * @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');
 }

作者:Nipuna-Sankalp    项目:sasip_student_online_management_syste   
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'));
 }

作者:QuangDang21    项目:roadi   
/**
  * 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;
 }

作者:mcdi    项目:SonatraFormExtensionsBundl   
/**
  * 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;
 }

作者:Jujuwa    项目:bruminator2.   
/**
  * @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;
 }

作者:yogendra989    项目:basi   
/**
  * 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;
 }

作者:ramiroavil    项目:SugarCRM-CAM-CHIL   
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!");
 }

作者:vanslambrouck    项目:geotool   
/**
  * 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));
 }

作者:sel    项目:scrape   
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;
 }

作者:RAFnu    项目:Competition-REFU.   
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;
 }

作者:umpirsk    项目:pim-community-de   
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']]);
 }

作者:RAFnu    项目:Competition-REFU.   
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;
 }

作者:bryanband    项目:roadi   
/**
  * 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');
 }

作者:tweedegol    项目:video-bundl   
/**
  * {@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)]);
 }

作者:tweedegol    项目:file-bundl   
/**
  * {@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']]);
 }

作者:kbsal    项目:sitemap-serialize   
/**
  * 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');
 }

作者:alexk    项目:travisintegrationtes   
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.');
 }


问题


面经


文章

微信
公众号

扫码关注公众号