コード例 #1
2
ファイル: HashHandlerTest.php プロジェクト: alebon/graviton
 /**
  * Test HashHandler::deserializeHashFromJson()
  *
  * @return void
  */
 public function testDeserializeHashFromJson()
 {
     $array = [__METHOD__];
     $hash = new Hash($array);
     $type = [__FILE__];
     $context = DeserializationContext::create();
     $deserializationVisitor = $this->getMockBuilder('JMS\\Serializer\\JsonDeserializationVisitor')->disableOriginalConstructor()->setMethods(['visitArray'])->getMock();
     $deserializationVisitor->expects($this->once())->method('visitArray')->with($array, $type, $context)->willReturn($array);
     $this->assertEquals($hash, (new HashHandler())->deserializeHashFromJson($deserializationVisitor, $array, $type, $context));
 }
コード例 #2
1
 /**
  * @Route("/api/equip/upgrade/category/{id}", methods={"PUT"}, requirements={"id"="^[0-9].*$"})
  * @param Request $request
  * @param EquipUpgradeCategory $equipUpgradeCategory
  * @return Response
  */
 public function updateEquipUpgradeCategoryAction(Request $request, EquipUpgradeCategory $equipUpgradeCategory)
 {
     $serializer = $this->get("jms_serializer");
     $data = $request->getContent();
     $context = new DeserializationContext();
     $context->setAttribute('target', $equipUpgradeCategory);
     $equipUpgradeCategory = $serializer->deserialize($data, 'AppBundle\\Entity\\EquipUpgradeCategory', 'json', $context);
     $em = $this->getDoctrine()->getManager();
     $em->persist($equipUpgradeCategory);
     $em->flush();
     $view = $this->view($equipUpgradeCategory, 200);
     return $this->handleView($view);
 }
コード例 #3
0
 /**
  * {@inheritdoc}
  */
 public function construct(VisitorInterface $visitor, ClassMetadata $metadata, $data, array $type, DeserializationContext $context)
 {
     if ($context->attributes->containsKey('target') && $context->getDepth() === 1) {
         return $context->attributes->get('target')->get();
     }
     return $this->fallbackConstructor->construct($visitor, $metadata, $data, $type, $context);
 }
コード例 #4
0
 public function construct(VisitorInterface $visitor, ClassMetadata $metadata, $data, array $type, DeserializationContext $context)
 {
     if ($context instanceof \Lemon\RestBundle\Serializer\DeserializationContext && $context->shouldUseDoctrineConstructor()) {
         $this->useDoctrine();
     }
     return $this->objectConstructor->construct($visitor, $metadata, $data, $type, $context);
 }
コード例 #5
0
 /**
  * @param SerializerInterface $serializer
  */
 public function __construct(SerializerInterface $serializer = null)
 {
     $this->serializer = $serializer ?: SerializerBuilder::create()->build();
     $this->serializationContext = new SerializationContext();
     $this->serializationContext->setSerializeNull(true);
     $this->deserializationContext = new DeserializationContext();
     $this->deserializationContext->setSerializeNull(true);
 }
コード例 #6
0
 protected function jmsDeserialization($content, $class, $groups, $type = 'json')
 {
     /** @var $serializer \JMS\Serializer\Serializer */
     $serializer = $this->get('jms_serializer');
     $serializerContext = DeserializationContext::create()->setGroups($groups);
     return $serializer->deserialize($content, $class, $type, $serializerContext);
 }
コード例 #7
0
 /**
  * @param Context $context
  * @param int     $direction {@see self} constants
  *
  * @return JMSContext
  */
 private function convertContext(Context $context, $direction)
 {
     if ($direction === self::SERIALIZATION) {
         $jmsContext = JMSSerializationContext::create();
     } else {
         $jmsContext = JMSDeserializationContext::create();
         if (null !== $context->getMaxDepth()) {
             for ($i = 0; $i < $context->getMaxDepth(); ++$i) {
                 $jmsContext->increaseDepth();
             }
         }
     }
     foreach ($context->getAttributes() as $key => $value) {
         $jmsContext->attributes->set($key, $value);
     }
     if (null !== $context->getVersion()) {
         $jmsContext->setVersion($context->getVersion());
     }
     $groups = $context->getGroups();
     if (!empty($groups)) {
         $jmsContext->setGroups($context->getGroups());
     }
     if (null !== $context->getMaxDepth()) {
         $jmsContext->enableMaxDepthChecks();
     }
     if (null !== $context->getSerializeNull()) {
         $jmsContext->setSerializeNull($context->getSerializeNull());
     }
     return $jmsContext;
 }
コード例 #8
0
 public function testPreSerialize()
 {
     $listener = $this->getListener();
     $event = new PreSerializeEvent(DeserializationContext::create(), 'something', ['some type']);
     $listener->onSerializerPreSerialize($event);
     $this->assertArraySubset(['name' => 'ibrows_test'], $event->getType());
 }
コード例 #9
0
ファイル: Util.php プロジェクト: phprest/phprest
 /**
  * @param string $type
  * @param Request $request
  *
  * @throws Exception\UnsupportedMediaType
  *
  * @return mixed
  */
 protected function deserialize($type, Request $request)
 {
     $mimeProcResult = $this->processMime($request->headers->get('Content-Type'));
     if (is_null($mimeProcResult->format)) {
         throw new Exception\UnsupportedMediaType();
     }
     return $this->serviceHateoas()->getSerializer()->deserialize($request->getContent(), $type, $mimeProcResult->format, DeserializationContext::create()->setVersion($mimeProcResult->apiVersion));
 }
コード例 #10
0
ファイル: Serializer.php プロジェクト: axelmdev/ecommerce
 public function deserialize($data, $type, $format, DeserializationContext $context = null)
 {
     if (!$this->deserializationVisitors->containsKey($format)) {
         throw new UnsupportedFormatException(sprintf('The format "%s" is not supported for deserialization.', $format));
     }
     if (null === $context) {
         $context = new DeserializationContext();
     }
     $context->initialize($format, $visitor = $this->deserializationVisitors->get($format)->get(), $this->navigator, $this->factory);
     $visitor->setNavigator($this->navigator);
     $navigatorResult = $this->navigator->accept($visitor->prepare($data), $this->typeParser->parse($type), $context);
     // This is a special case if the root is handled by a callback on the object iself.
     if (null === ($visitorResult = $visitor->getResult()) && null !== $navigatorResult) {
         return $navigatorResult;
     }
     return $visitorResult;
 }
コード例 #11
0
 /**
  * @inheritdoc
  */
 public function deserialize($data, $type, $format, $groups = null)
 {
     $context = null;
     if ($groups) {
         $context = DeserializationContext::create()->setGroups($groups);
     }
     return $this->serializer->deserialize($data, $type, $format, $context);
 }
コード例 #12
0
ファイル: Serializer.php プロジェクト: toiine/couchbasebundle
 /**
  * {@inheritdoc}
  */
 public function deserialize($json)
 {
     $context = DeserializationContext::create();
     if (!is_null($this->groupName)) {
         $context->setGroups(array($this->groupName));
         $context->setSerializeNull($this->serializeNull);
     }
     return $this->jmsSerializer->deserialize($json, $this->documentClass, 'json', $context);
 }
コード例 #13
0
 public function testValidationIsOnlyPerformedOnRootObject()
 {
     $this->validator->expects($this->once())->method('validate')->with($this->isInstanceOf('JMS\\Serializer\\Tests\\Fixtures\\AuthorList'), array('Foo'))->will($this->returnValue(new ConstraintViolationList()));
     $subscriber = $this->subscriber;
     $list = SerializerBuilder::create()->configureListeners(function (EventDispatcher $dispatcher) use($subscriber) {
         $dispatcher->addSubscriber($subscriber);
     })->build()->deserialize('{"authors":[{"full_name":"foo"},{"full_name":"bar"}]}', 'JMS\\Serializer\\Tests\\Fixtures\\AuthorList', 'json', DeserializationContext::create()->setAttribute('validation_groups', array('Foo')));
     $this->assertCount(2, $list);
 }
コード例 #14
0
ファイル: SerializerTest.php プロジェクト: nawrasg/tvguide
 public function testDeserializeXmlTv()
 {
     $data = file_get_contents(__DIR__ . '/../Data/xmltv-file1.xml');
     $context = DeserializationContext::create()->setGroups(['xmltv']);
     $program = $this->app['serializer']->deserialize($data, 'Domora\\TvGuide\\Data\\Program', 'xml', $context);
     $this->assertEquals("Esprits criminels", $program->getTitle());
     $this->assertEquals(1398636900, $program->getStart()->getTimestamp());
     $this->assertEquals(1398639900, $program->getStop()->getTimestamp());
 }
コード例 #15
0
 /**
  * @expectedException \Ibrows\JsonPatch\Exception\ResolvePathException
  * @expectedExceptionMessage Could not resolve path "subject" on current address.
  */
 public function testJMSGroups()
 {
     $operations = $this->getPatchConverter()->convert([['op' => 'replace', 'path' => '/subject', 'value' => 'something']]);
     $comment = new Comment();
     $comment->setSubject('subject before');
     $context = DeserializationContext::create();
     $context->setGroups(['emptyGroup']);
     $this->getExecutioner()->execute($operations, $comment, ['jms_context' => $context]);
 }
コード例 #16
0
 /**
  * Test ArrayObjectHandler::deserializeArrayObjectFromJson()
  *
  * @return void
  */
 public function testDeserializeArrayObjectFromJson()
 {
     $serialized = ['a' => __LINE__, 'b' => __LINE__];
     $deserialized = new \ArrayObject(['c' => __LINE__, 'd' => __LINE__]);
     $type = [__METHOD__];
     $context = DeserializationContext::create();
     $deserializationVisitor = $this->getMockBuilder('JMS\\Serializer\\JsonDeserializationVisitor')->disableOriginalConstructor()->setMethods(['visitArray'])->getMock();
     $deserializationVisitor->expects($this->once())->method('visitArray')->with($serialized, $type, $context)->willReturn($deserialized->getArrayCopy());
     $this->assertEquals($deserialized, (new ArrayObjectHandler())->deserializeArrayObjectFromJson($deserializationVisitor, $serialized, $type, $context));
 }
コード例 #17
0
 public function getResource(WarehouseResource $entity)
 {
     try {
         $guzzleResponse = $this->guzzle->get($entity->getResource());
         $response = $this->convertResponse($guzzleResponse);
         $response->setEntity($this->serializer->deserialize((string) $guzzleResponse->getBody(), get_class($entity), 'json', DeserializationContext::create()->setGroups(['Default', 'get'])));
         return $response;
     } catch (RequestException $e) {
         return $this->convertResponse($e->getResponse());
     }
 }
コード例 #18
0
 /**
  * {@inheritdoc}
  */
 public function convertDeserializationContext(ContextInterface $context)
 {
     if (!$this->supportsDeserialization($context)) {
         throw new \LogicException(sprintf('%s can\'t convert this deserialization context.', get_class($this)));
     }
     $newContext = JMSDeserializationContext::create();
     if ($context instanceof MaxDepthContextInterface && null !== $context->getMaxDepth()) {
         for ($i = 0; $i < $context->getMaxDepth(); ++$i) {
             $newContext->increaseDepth();
         }
     }
     $this->fillContext($context, $newContext);
     return $newContext;
 }
コード例 #19
0
 /**
  * @inheritdoc
  */
 public function apply(Request $request, ParamConverter $configuration)
 {
     $context = DeserializationContext::create();
     $context->setGroups(['query']);
     try {
         $object = $this->serializer->deserialize($request->attributes->get($configuration->getName()), $configuration->getClass(), 'json', $context);
     } catch (UnsupportedFormatException $e) {
         throw new UnsupportedMediaTypeHttpException($e->getMessage(), $e);
     } catch (JMSSerializerException $e) {
         throw new BadRequestHttpException($e->getMessage(), $e);
     } catch (SymfonySerializerException $e) {
         throw new BadRequestHttpException($e->getMessage(), $e);
     }
     $request->attributes->set($configuration->getName(), $object);
     return true;
 }
コード例 #20
0
 public static function toDeserialize($serialization, $namespace = "", $format = self::_FormatXML, $group = array())
 {
     $context = count($group) > 0 ? SRL\DeserializationContext::create()->setGroups($group) : null;
     if (is_array($serialization) || is_object($serialization)) {
         $serialization = json_encode($serialization);
     }
     $dados = json_encode($serialization);
     $serializer = SRL\SerializerBuilder::create()->build();
     if (is_array($dados)) {
         $result = $serializer->deserialize($serialization, sprintf('ArrayCollection<%s>', $namespace), $format, $context);
     } else {
         $result = $serializer->deserialize($serialization, $namespace, $format, $context);
     }
     if (count($result) == 0) {
         return null;
     }
     return $result;
 }
コード例 #21
0
 /**
  * [ВНИМАНИЕ]
  * Если у сущности генератор первичного ключа отсутствует, т.е. необходимо задать вручную ключ, то необходимо удалить
  * первичный ключ из структуры, чтобы не было попыток найти эту сущность. Ошибка описана в ссылке ниже
  * @link https://github.com/jamesmoey/extjs-bundle/issues/17
  * @inheritdoc
  */
 public function run()
 {
     $this->checkIsInit();
     $obj = json_decode($this->requestContent, false, 512, JSON_BIGINT_AS_STRING);
     $response = new RestResponse();
     $savedPKValueFromRequestData = null;
     $PKFieldName = $this->getPKFieldName();
     $entityNotHaveIdGenerator = $this->classMetadata->generatorType == ClassMetadata::GENERATOR_TYPE_NONE;
     if ($entityNotHaveIdGenerator) {
         if (!$this->isObjectHasPKField($obj) && !$this->isObjectHasNewPKField($obj)) {
             $response->setSuccess(false)->setStatusCode(RestResponse::STATUS_CODE_WRONG_INPUT_DATA)->setMessage(sprintf("Не указан первичный ключ (%s)", $PKFieldName));
             return $response;
         } elseif (!$this->isObjectHasPKField($obj) && $this->isObjectHasNewPKField($obj)) {
             $savedPKValueFromRequestData = $this->getNewPKValueFromObject($obj);
             unset($obj->{$this->getNewPKValueFromObject($obj)});
         } elseif ($this->isObjectHasPKField($obj) && !$this->isObjectHasNewPKField($obj)) {
             $savedPKValueFromRequestData = $obj->{$PKFieldName};
             unset($obj->{$PKFieldName});
         }
     }
     $serializedObj = json_encode($obj);
     $entity = $this->serializer->deserialize($serializedObj, $this->classMetadata->getName(), 'json', DeserializationContext::create()->setGroups([Action::GROUP_DEFAULT, Action::GROUP_POST]));
     if ($entityNotHaveIdGenerator) {
         EntityHelper::changePKValue($this->em, $entity, $savedPKValueFromRequestData);
     }
     $validator = $this->validator;
     /** @var ConstraintViolationList $validations */
     $validations = $validator->validate($entity);
     if (sizeof($validations) === 0) {
         try {
             $this->em->persist($entity);
             $this->em->flush();
             $this->em->refresh($entity);
             $response->setSuccess(true)->setData($entity)->setStatusCode(RestResponse::STATUS_CODE_OK);
         } catch (DBALException $e) {
             $response->setSuccess(false)->setMessage($e->getMessage())->setStatusCode(RestResponse::STATUS_CODE_WRONG_INPUT_DATA);
         }
     } else {
         $response->setSuccess(false)->setStatusCode(RestResponse::STATUS_CODE_WRONG_INPUT_DATA)->setErrors($validations);
     }
     return $response;
 }
コード例 #22
0
 /**
  * @param ServiceReference $service
  * @param string           $name
  * @return DeserializationContext
  */
 protected function createDeserializationContext(ServiceReference $service, $name)
 {
     $context = DeserializationContext::create();
     $groups = $service->getParameterSerializationGroups($name);
     $attributes = $service->getParameterSerializationAttributes($name);
     $version = $service->getParameterSerializationVersion($name);
     if (!empty($groups)) {
         $context->setGroups($groups);
     }
     if (!empty($attributes)) {
         foreach ($attributes as $k => $v) {
             $context->setAttribute($k, $v);
         }
     }
     if ($version !== null) {
         $context->setVersion($version);
         return $context;
     }
     return $context;
 }
コード例 #23
0
 public function testDeserializeContextConfiguration()
 {
     $expectedContext = DeserializationContext::create();
     $expectedContext->setGroups('group');
     $expectedContext->setVersion(1);
     $expectedContext->enableMaxDepthChecks();
     $operation = $this->getMock('Guzzle\\Service\\Description\\OperationInterface');
     $operation->expects($this->any())->method('getResponseType')->will($this->returnValue(OperationInterface::TYPE_CLASS));
     $operation->expects($this->any())->method('getResponseClass')->will($this->returnValue('ResponseClass'));
     $dataMap = array(array('jms_serializer.groups', 'group'), array('jms_serializer.version', 1), array('jms_serializer.max_depth_checks', true));
     $operation->expects($this->any())->method('getData')->will($this->returnValueMap($dataMap));
     $command = $this->getMock('Guzzle\\Service\\Command\\CommandInterface');
     $command->expects($this->any())->method('getOperation')->will($this->returnValue($operation));
     $response = new Response(200);
     $response->setBody('body');
     $serializer = $this->getMock('JMS\\Serializer\\SerializerInterface');
     $serializer->expects($this->once())->method('deserialize')->with('body', 'ResponseClass', 'json', $this->equalTo($expectedContext));
     $parser = new JMSSerializerResponseParser($serializer, $this->getMock('Guzzle\\Service\\Command\\ResponseParserInterface'));
     $ref = new \ReflectionMethod($parser, 'deserialize');
     $ref->setAccessible(true);
     return $ref->invoke($parser, $command, $response, 'json');
 }
コード例 #24
0
 public function testDeserializingNull()
 {
     $objectConstructor = new InitializedBlogPostConstructor();
     $this->serializer = new Serializer($this->factory, $this->handlerRegistry, $objectConstructor, $this->serializationVisitors, $this->deserializationVisitors, $this->dispatcher);
     $post = new BlogPost('This is a nice title.', $author = new Author('Foo Bar'), new \DateTime('2011-07-30 00:00', new \DateTimeZone('UTC')), new Publisher('Bar Foo'));
     $this->setField($post, 'author', null);
     $this->setField($post, 'publisher', null);
     $this->assertEquals($this->getContent('blog_post_unauthored'), $this->serialize($post, SerializationContext::create()->setSerializeNull(true)));
     if ($this->hasDeserializer()) {
         $deserialized = $this->deserialize($this->getContent('blog_post_unauthored'), get_class($post), DeserializationContext::create()->setSerializeNull(true));
         $this->assertEquals('2011-07-30T00:00:00+0000', $this->getField($deserialized, 'createdAt')->format(\DateTime::ISO8601));
         $this->assertAttributeEquals('This is a nice title.', 'title', $deserialized);
         $this->assertAttributeSame(false, 'published', $deserialized);
         $this->assertAttributeEquals(new ArrayCollection(), 'comments', $deserialized);
         $this->assertEquals(null, $this->getField($deserialized, 'author'));
     }
 }
コード例 #25
0
 /**
  * @param int           $facilityId
  * @param int           $doctorId
  * @param DoctorService $doctorService
  *
  * @return DoctorService
  */
 public function patchDoctorService($facilityId, $doctorId, $doctorService)
 {
     $request = $this->client->patch(['facilities/{facilityId}/doctors/{doctorId}/services/{doctorServiceId}', ['facilityId' => $facilityId, 'doctorId' => $doctorId, 'doctorServiceId' => $doctorService->getId()]], [], $this->serializer->serialize($doctorService, 'json', SerializationContext::create()->setGroups(['patch'])));
     /** @var DoctorService $newDoctorService */
     $newDoctorService = $this->authorizedRequest($request, DoctorService::class, DeserializationContext::create()->setGroups(['get']));
     return $newDoctorService;
 }
コード例 #26
0
 /**
  * Deserialize the response.
  *
  * @param CommandInterface $command     Command.
  * @param Response         $response    Response.
  * @param string           $contentType Content type.
  *
  * @return mixed|null Deserialized response, or `null`.
  */
 protected function deserialize(CommandInterface $command, Response $response, $contentType)
 {
     if ($this->serializer) {
         if (false !== stripos($contentType, 'json')) {
             $serializerContentType = 'json';
         } elseif (false !== stripos($contentType, 'xml')) {
             $serializerContentType = 'xml';
         } else {
             $serializerContentType = null;
         }
         if (null !== $serializerContentType && OperationInterface::TYPE_CLASS === $command->getOperation()->getResponseType()) {
             $context = DeserializationContext::create();
             $operation = $command->getOperation();
             if (null !== ($groups = $operation->getData('jms_serializer.groups'))) {
                 $context->setGroups($groups);
             }
             if (null !== ($version = $operation->getData('jms_serializer.version'))) {
                 $context->setVersion($version);
             }
             if (true === $operation->getData('jms_serializer.max_depth_checks')) {
                 $context->enableMaxDepthChecks();
             }
             return $this->serializer->deserialize($response->getBody(), $command->getOperation()->getResponseClass(), $serializerContentType, $context);
         }
     }
     return null;
 }
コード例 #27
0
 /**
  * Test ExtReferenceHandler::deserializeExtReferenceFromJson()
  *
  * @return void
  */
 public function testDeserializeExtReferenceFromJson()
 {
     $type = [__LINE__];
     $context = DeserializationContext::create();
     $url = __FUNCTION__;
     $extref = ExtReference::create(__METHOD__, __FILE__);
     $this->converter->expects($this->once())->method('getExtReference')->with($url)->willReturn($extref);
     $this->deserializationVisitor->expects($this->once())->method('visitString')->with($url, $type, $context)->willReturn($url);
     $handler = new ExtReferenceHandler($this->converter);
     $this->assertEquals($extref, $handler->deserializeExtReferenceFromJson($this->deserializationVisitor, $url, $type, $context));
 }
コード例 #28
0
 /**
  * @param DeserializationContext $context
  * @param array                  $options
  *
  * @return DeserializationContext
  */
 protected function configureDeserializationContext(DeserializationContext $context, array $options)
 {
     if (isset($options['groups'])) {
         $context->setGroups($options['groups']);
     }
     if (isset($options['version'])) {
         $context->setVersion($options['version']);
     }
     return $context;
 }
コード例 #29
0
ファイル: ParamConverter.php プロジェクト: alexjobs/Aisel
 /**
  * @param $resolvedClass
  * @param $rawPayload
  *
  * @throws \Doctrine\ORM\ORMException
  * @throws \Doctrine\ORM\OptimisticLockException
  * @throws \Doctrine\ORM\TransactionRequiredException
  * @throws \Doctrine\ORM\TransactionRequiredException
  * @throws NotFoundHttpException
  *
  * @return mixed $entity
  */
 protected function updateEntity($resolvedClass, $rawPayload)
 {
     $serializerGroups = isset($options['serializerGroups']) ? $options['serializerGroups'] : null;
     $deserializationContext = DeserializationContext::create();
     if ($serializerGroups) {
         $deserializationContext->setGroups($serializerGroups);
     }
     $convertedValue = $this->serializer->deserialize($rawPayload, $resolvedClass, 'json');
     $violations = $this->validator->validate($convertedValue);
     if ($violations->count()) {
         throw new ValidationFailedException($violations);
     }
     return $convertedValue;
 }
コード例 #30
-1
 /**
  * @Route("/api/monster/{id}", methods={"PUT"}, requirements={"id"="^[0-9].*$"})
  * @param Request $request
  * @param Monster $monster
  * @return Response
  */
 public function updateMonsterAction(Request $request, Monster $monster)
 {
     $serializer = $this->get("jms_serializer");
     $data = $request->getContent();
     $context = new DeserializationContext();
     $context->setAttribute('target', $monster);
     $monster = $serializer->deserialize($data, 'AppBundle\\Entity\\Monster', 'json', $context);
     $em = $this->getDoctrine()->getManager();
     $em->persist($monster);
     $em->flush();
     $view = $this->view($monster, 200);
     return $this->handleView($view);
 }