The normalization process looks at all public methods and calls the ones which have a name starting with get and take no parameters. The result is a map from property names (method name stripped of the get prefix and converted to lower case) to property values. Property values are normalized through the serializer. The denormalization first looks at the constructor of the given class to see if any of the parameters have the same name as one of the properties. The constructor is then called with all parameters or an exception is thrown if any required parameters were not present as properties. Then the denormalizer walks through the given map of property names to property values to see if a setter method exists for any of the properties. If a setter exists it is called with the property value. No automatic denormalization of the value takes place.
Author: Nils Adermann (naderman@naderman.de)
Inheritance: extends Symfony\Component\Serializer\Normalizer\SerializerAwareNormalizer, implements Symfony\Component\Serializer\Normalizer\NormalizerInterface, implements Symfony\Component\Serializer\Normalizer\DenormalizerInterface
Example #1
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);
 }
Example #2
0
 /**
  * @param Pool               $adminPool
  * @param EngineInterface    $templating
  * @param CategoryManager    $categoryManager
  * @param TransactionManager $transactionManager
  */
 public function __construct(Pool $adminPool, EngineInterface $templating, CategoryManager $categoryManager, TransactionManager $transactionManager)
 {
     parent::__construct($adminPool, $templating);
     $this->categoryManager = $categoryManager;
     $this->transactionManager = $transactionManager;
     $normalizer = new GetSetMethodNormalizer();
     $normalizer->setIgnoredAttributes(['category']);
     $this->serializer = new Serializer([$normalizer], [new JsonEncoder()]);
 }
 /**
  * {@inheritdoc}
  */
 public function normalize($object, $format = null, array $context = array())
 {
     if ($object instanceof \Exception) {
         return $this->normalizeException($object);
     }
     return parent::normalize($object, $format, $context);
 }
Example #4
0
 /**
  * Lists all Task entities.
  *
  */
 public function listAction()
 {
     $user = $this->get('security.context')->getToken()->getUser();
     $em = $this->getDoctrine()->getManager();
     $tasks = $em->getRepository('STMSBundle:Task')->findBy(array('user' => $user));
     $normalizer = new GetSetMethodNormalizer();
     $normalizer->setIgnoredAttributes(array('user'));
     $normalizer->setCallbacks(array('date' => function ($dateTime) {
         return $dateTime->format("Y-m-d");
     }));
     $serializer = new Serializer(array($normalizer), array(new JsonEncoder()));
     $json = $serializer->serialize($tasks, 'json');
     $response = new Response($json);
     $response->headers->set('Content-Type', 'application/json');
     return $response;
 }
 public function testIgnoredAttributes()
 {
     $this->normalizer->setIgnoredAttributes(array('foo', 'bar', 'camelCase'));
     $obj = new GetSetDummy();
     $obj->setFoo('foo');
     $obj->setBar('bar');
     $this->assertEquals(array('fooBar' => 'foobar'), $this->normalizer->normalize($obj, 'any'));
 }
 public function testObjectToPopulate()
 {
     $dummy = new GetSetDummy();
     $dummy->setFoo('foo');
     $obj = $this->normalizer->denormalize(array('bar' => 'bar'), __NAMESPACE__ . '\\GetSetDummy', null, array('object_to_populate' => $dummy));
     $this->assertEquals($dummy, $obj);
     $this->assertEquals('foo', $obj->getFoo());
     $this->assertEquals('bar', $obj->getBar());
 }
 /**
  * @expectedException \LogicException
  * @expectedExceptionMessage Cannot normalize attribute "object" because injected serializer is not a normalizer
  */
 public function testUnableToNormalizeObjectAttribute()
 {
     $serializer = $this->getMock('Symfony\\Component\\Serializer\\SerializerInterface');
     $this->normalizer->setSerializer($serializer);
     $obj = new GetSetDummy();
     $object = new \stdClass();
     $obj->setObject($object);
     $this->normalizer->normalize($obj, 'any');
 }
 public function testCircularReferenceHandler()
 {
     $serializer = new Serializer(array($this->normalizer));
     $this->normalizer->setSerializer($serializer);
     $this->normalizer->setCircularReferenceHandler(function ($obj) {
         return get_class($obj);
     });
     $obj = new CircularReferenceDummy();
     $expected = array('me' => 'Symfony\\Component\\Serializer\\Tests\\Fixtures\\CircularReferenceDummy');
     $this->assertEquals($expected, $this->normalizer->normalize($obj));
 }
 /**
  * {@inheritdoc}
  */
 public function normalize($object, $format = null, array $context = array())
 {
     $camelizedKeyAttributes = parent::normalize($object, $format, $context);
     $attributes = array();
     foreach ($camelizedKeyAttributes as $name => $value) {
         if (!isset($value)) {
             continue;
         }
         $attributes[$this->fromCamelCase($name)] = $value;
     }
     return $attributes;
 }
Example #10
0
 /**
  * @param string $bundleComposer
  *
  * @return bool|Bundle
  */
 private function getBundle($bundleComposer)
 {
     if (!file_exists($bundleComposer)) {
         return false;
     }
     $bundleComposerData = file_get_contents($bundleComposer);
     $normalizer = new GetSetMethodNormalizer();
     $normalizer->setIgnoredAttributes(array('require', 'keywords'));
     $encoder = new JsonEncoder();
     $serializer = new Serializer(array($normalizer), array($encoder));
     $bundle = $serializer->deserialize($bundleComposerData, 'CampaignChain\\CoreBundle\\Entity\\Bundle', 'json');
     // Set the version of the installed bundle.
     $version = $this->packageService->getVersion($bundle->getName());
     /*
      * If version does not exist, this means two things:
      *
      * 1) Either, it is a package in require-dev of composer.json, but
      * CampaignChain is not in dev mode. Then we don't add this package.
      *
      * 2) Or it is a bundle in Symfony's src/ directory. Then we want to
      * add it.
      */
     if (!$version) {
         // Check if bundle is in src/ dir.
         $bundlePath = str_replace($this->rootDir . DIRECTORY_SEPARATOR, '', $bundleComposer);
         if (strpos($bundlePath, 'src' . DIRECTORY_SEPARATOR) !== 0) {
             // Not in src/ dir, so don't add this bundle.
             return false;
         } else {
             $version = 'dev-master';
         }
     }
     $bundle->setVersion($version);
     // Set relative path of bundle.
     $bundle->setPath(str_replace($this->rootDir . DIRECTORY_SEPARATOR, '', str_replace(DIRECTORY_SEPARATOR . 'composer.json', '', $bundleComposer)));
     return $bundle;
 }
 public function normalize($object, $format = null, array $context = array())
 {
     // Look for setters with non-primitive parameters
     $reflectionObject = new \ReflectionObject($object);
     $reflectionMethods = $reflectionObject->getMethods(\ReflectionMethod::IS_PUBLIC);
     $attributes = array();
     foreach ($reflectionMethods as $method) {
         $params = $method->getParameters();
         if (0 === strpos($method->name, 'set') && 3 < strlen($method->name) && 1 === $method->getNumberOfParameters() && $params[0]->getClass() !== NULL) {
             $attributeName = lcfirst(substr($method->name, 3));
             $attributes[] = $attributeName;
         }
     }
     $this->setIgnoredAttributes($attributes);
     return parent::normalize($object, $format, $context);
 }
 public function testMaxDepth()
 {
     $classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader()));
     $this->normalizer = new GetSetMethodNormalizer($classMetadataFactory);
     $serializer = new Serializer(array($this->normalizer));
     $this->normalizer->setSerializer($serializer);
     $level1 = new MaxDepthDummy();
     $level1->bar = 'level1';
     $level2 = new MaxDepthDummy();
     $level2->bar = 'level2';
     $level1->child = $level2;
     $level3 = new MaxDepthDummy();
     $level3->bar = 'level3';
     $level2->child = $level3;
     $level4 = new MaxDepthDummy();
     $level4->bar = 'level4';
     $level3->child = $level4;
     $result = $serializer->normalize($level1, null, array(GetSetMethodNormalizer::ENABLE_MAX_DEPTH => true));
     $expected = array('bar' => 'level1', 'child' => array('bar' => 'level2', 'child' => array('bar' => 'level3', 'child' => array('child' => null))));
     $this->assertEquals($expected, $result);
 }
 /**
  * @Route("/dossier/{id}/prequalified/list", name="contracting_dossier_prequalified_loader")
  * @Template()
  * @Security("has_role('ROLE_CONTRACTING')")
  */
 public function dossierPrequalifiedListAction($id)
 {
     $em = $this->getDoctrine()->getManager();
     $query = $em->createQuery('SELECT p,c FROM AppBundle:PreQualified p JOIN p.contract c WHERE p.contract=:id')->setParameter('id', $id);
     $prequalified = $query->getResult();
     $encoder = new JsonEncoder();
     $normalizer = new GetSetMethodNormalizer();
     $normalizer->setCircularReferenceHandler(function ($object) {
         return $object->getId();
     });
     $serializer = new Serializer(array($normalizer), array($encoder));
     $jsonContent = $serializer->serialize(array('data' => $prequalified), 'json');
     //Audit
     $contract = $em->getRepository('AppBundle:Contract')->findOneBy(array('id' => $id));
     if ($prequalified) {
         $audit = new Audit();
         $user = $this->get('security.token_storage')->getToken()->getUser();
         $audit->setUsername($user->getUsername());
         $audit->setName($user->getFirstname() . " " . $user->getLastname());
         $audit->setFunctionType("Contracting");
         $audit->setEventType("View pre-qualified suppliers");
         $audit->setDossier($contract);
         $em->persist($audit);
         $em->flush();
     }
     return new Response($jsonContent);
 }
 public function testPrivateSetter()
 {
     $obj = $this->normalizer->denormalize(array('foo' => 'foobar'), __NAMESPACE__ . '\\ObjectWithPrivateSetterDummy');
     $this->assertEquals('bar', $obj->getFoo());
 }
 public function testDenormalizeNonExistingAttribute()
 {
     $this->assertEquals(new PropertyDummy(), $this->normalizer->denormalize(array('non_existing' => true), __NAMESPACE__ . '\\PropertyDummy'));
 }
 public function testNoTraversableSupport()
 {
     $this->assertFalse($this->normalizer->supportsNormalization(new \ArrayObject()));
 }
 /**
  * The raw response from the api must be mapped to a correctly typed object.
  * This method does the job flattening the result and by using a GetSetMethodNormalizer.
  * What does that mean? This means that if your response has a key $entry['id_str'] the
  * setter setIdStr($entry['id_str']) is used. If the response has a key
  * $entry['media'][0]['media_url'] the setter setMedia0MediaUrl(..) is used. Therefore
  * you can persist whatever information you want to persist from the direct response
  * by using the correct name for the entity-field (and then also for the setter).
  *
  * @param  object $object     the json decoded object response by the api
  * @param  array  $dateFields fields that should be formatted as datetime object
  * @return YoutubeEntityInterface
  */
 protected function deserializeRawObject($object, $dateFields = array())
 {
     // flatten object
     $object = self::flatten($object);
     foreach ($dateFields as $df) {
         if (array_key_exists($df, $object)) {
             $object[$df] = new \DateTime($object[$df]);
         }
     }
     $normalizer = new GetSetMethodNormalizer();
     $normalizer->setCamelizedAttributes(array_keys($object));
     return $normalizer->denormalize($object, $this->socialEntityClass);
 }
 public function benchSymfonyGetSetNormalizer()
 {
     $normalizer = new GetSetMethodNormalizer();
     $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');
 }
 /**
  * @param ClassMetadataFactoryInterface $classMetadataFactory
  * @param NameConverterInterface        $nameConverter
  * @param PropertyInfoExtractor         $propertyInfoExtractor
  */
 public function __construct(ClassMetadataFactoryInterface $classMetadataFactory = null, NameConverterInterface $nameConverter = null, PropertyInfoExtractor $propertyInfoExtractor = null)
 {
     parent::__construct($classMetadataFactory, $nameConverter);
     $this->propertyInfoExtractor = $propertyInfoExtractor;
 }
 private function getMessages($fileName, $numberOfLines)
 {
     $normalizer = new GetSetMethodNormalizer();
     $encoder = new JsonEncoder();
     $serializer = new Serializer(array($normalizer), array($encoder));
     $normalizer->setCamelizedAttributes(array('level_name'));
     $messages = [];
     $file = array_reverse(file($fileName));
     foreach ($file as $line) {
         $messages[] = $serializer->deserialize($line, 'Sopinet\\Bundle\\LogBundle\\Entities\\Message', 'json');
         if (count($messages) == $numberOfLines) {
             break;
         }
     }
     return $messages;
 }
 /**
  * @Route("/client/clone/{idClient}", requirements={"idClient" = "\d+"}, defaults={"id" = "-1"}, name="cloneClient")
  * @Method("POST")
  * @Template()
  */
 public function cloneClientAction(Request $request, $idClient)
 {
     $t = $this->get('translator');
     $idoriginal = $idClient;
     if (null == $idClient) {
         throw $this->createNotFoundException($t->trans('Unable to find Client entity:', array(), 'BinovoElkarBackup') . $idClient);
     }
     $clientrow = array();
     try {
         // CLONE CLIENT
         $repository = $this->getDoctrine()->getRepository('BinovoElkarBackupBundle:Client');
         $client = $repository->find($idoriginal);
         if (null == $client) {
             throw $this->createNotFoundException($t->trans('Unable to find Client entity:', array(), 'BinovoElkarBackup') . $client);
         }
         $newname = $client->getName() . "-cloned1";
         while ($repository->findOneByName($newname)) {
             $newname++;
         }
         $new = clone $client;
         $new->setName($newname);
         $newem = $this->getDoctrine()->getManager();
         $newem->persist($new);
         $newem->flush();
         $newem->detach($new);
         $idnew = $new->getId();
         // CLONE JOBS
         $repository = $this->getDoctrine()->getRepository('BinovoElkarBackupBundle:Job');
         $jobs = $repository->findBy(array('client' => $idoriginal));
         foreach ($jobs as $job) {
             $repository = $this->getDoctrine()->getRepository('BinovoElkarBackupBundle:Client');
             $client = $repository->find($idnew);
             $newjob = clone $job;
             $newjob->setClient($client);
             $newjob->setDiskUsage(0);
             $newjob->setStatus('');
             $newem = $this->getDoctrine()->getManager();
             $newem->persist($newjob);
             $newem->flush();
             $newem->detach($newjob);
         }
     } catch (Exception $e) {
         $this->get('session')->getFlashBag()->add('clone', $t->trans('Unable to clone your client: %extrainfo%', array('%extrainfo%' => $e->getMessage()), 'BinovoElkarBackup'));
     }
     //$response = new Response($t->trans('Client cloned successfully', array(), 'BinovoElkarBackup'));
     //$response->headers->set('Content-Type', 'text/plain');
     // Custom normalizer
     //$normalizers[] = new ClientNormalizer();
     //$normalizer = new ObjectNormalizer();
     $normalizer = new GetSetMethodNormalizer();
     $normalizer->setCircularReferenceHandler(function ($object) {
         return $object->getId();
     });
     $normalizers[] = $normalizer;
     $encoders[] = new JsonEncoder();
     $encoders[] = new XmlEncoder();
     $serializer = new Serializer($normalizers, $encoders);
     $repository = $this->getDoctrine()->getRepository('BinovoElkarBackupBundle:Client');
     $client = $repository->find($idnew);
     //syslog(LOG_ERR, "Obtaining first job: ".$client->getJobs()[0]->getId());
     syslog(LOG_ERR, "Serializing object: " . $client->getName());
     $json = $serializer->serialize($client, 'json');
     syslog(LOG_ERR, "Output: " . print_r($json, TRUE));
     $response = new JsonResponse(array('msg' => $t->trans('Client cloned successfully', array(), 'BinovoElkarBackup'), 'action' => 'callbackClonedClient', 'data' => array($json)));
     return $response;
 }
 /**
  * @Route("/profile_attachment/list", name="user_profile_attachment_list")
  * @Template()
  * @Security("has_role('ROLE_ECONOMIC')")
  */
 public function profileAttachmentListAction()
 {
     $user = $this->get('security.token_storage')->getToken()->getUser();
     $em = $this->getDoctrine()->getManager();
     $query = $em->createQuery('SELECT p
                                 FROM AppBundle:Portfolio p WHERE p.economicUser=:id')->setParameter('id', $user->getId());
     $profileAttachments = $query->getResult();
     $encoder = new JsonEncoder();
     $normalizer = new GetSetMethodNormalizer();
     $normalizer->setCircularReferenceHandler(function ($object) {
         return $object->getId();
     });
     if ($profileAttachments) {
         //Audit
         $audit = new Audit();
         $audit->setUsername($user->getUsername());
         $audit->setName($user->getFirstname() . " " . $user->getLastname());
         $audit->setFunctionType("Economic");
         $audit->setEventType("Load profile attachment");
         $em->persist($audit);
         $em->flush();
     }
     $serializer = new Serializer(array($normalizer), array($encoder));
     $jsonContent = $serializer->serialize(array('data' => $profileAttachments), 'json');
     return new Response($jsonContent);
 }