本文整理汇总了PHP中Symfony\Component\Serializer\Serializer类的典型用法代码示例。如果您正苦于以下问题:PHP Serializer类的具体用法?PHP Serializer怎么用?PHP Serializer使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Serializer类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: syncAction
/**
* @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)]);
}
示例2: showAction
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));
}
示例3: setUp
public function setUp()
{
$serializer = new Serializer();
$this->encoder = new XmlEncoder();
$serializer->setEncoder('xml', $this->encoder);
$serializer->addNormalizer(new CustomNormalizer());
}
示例4: getSerialize
/**
* @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');
}
示例5: updateAction
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'));
}
开发者ID:Nipuna-Sankalpa,项目名称:sasip_student_online_management_system,代码行数:33,代码来源:ExamConfigController.php
示例6: deserialize
/**
* 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;
}
示例7: generateResponse
/**
* 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;
}
示例8: ajaxGetAction
/**
* @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;
}
示例9: decodeData
/**
* 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;
}
示例10: execute
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!");
}
示例11: serialize
/**
* 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));
}
示例12: output
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;
}
示例13: deserialize
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;
}
示例14:
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']]);
}
示例15: serialize
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;
}