Example #1
2
 /**
  * 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));
 }
 /**
  * @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;
 }
 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);
 }
 public function testPreSerialize()
 {
     $listener = $this->getListener();
     $event = new PreSerializeEvent(DeserializationContext::create(), 'something', ['some type']);
     $listener->onSerializerPreSerialize($event);
     $this->assertArraySubset(['name' => 'ibrows_test'], $event->getType());
 }
 /**
  * @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);
 }
Example #6
0
 /**
  * @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));
 }
 /**
  * @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]);
 }
 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);
 }
Example #9
0
 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());
 }
Example #10
0
 /**
  * {@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);
 }
 /**
  * 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));
 }
 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());
     }
 }
 /**
  * {@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;
 }
 /**
  * @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;
 }
 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;
 }
 /**
  * [ВНИМАНИЕ]
  * Если у сущности генератор первичного ключа отсутствует, т.е. необходимо задать вручную ключ, то необходимо удалить
  * первичный ключ из структуры, чтобы не было попыток найти эту сущность. Ошибка описана в ссылке ниже
  * @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;
 }
Example #17
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;
 }
 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');
 }
 /**
  * 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;
 }
 /**
  * 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));
 }
 /**
  * @return DeserializationContext
  */
 protected function getDeserializationContext()
 {
     return DeserializationContext::create();
 }
Example #22
0
 /**
  * @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;
 }
 /**
  *
  * @param Object $content Обработанные данные из запроса
  * @return mixed
  */
 protected function mergeDataFromRequestWithEntity($content)
 {
     $dContext = DeserializationContext::create()->setGroups($this->serializationContextGroups);
     $dContext->attributes->set('related_action', 'merge');
     $entity = $this->serializer->deserialize(json_encode($content), $this->classMetadata->getName(), 'json', $dContext);
     if ($this->newPrimaryKeyValue !== null) {
         EntityHelper::changePKValue($this->em, $entity, $this->newPrimaryKeyValue);
     }
     return $entity;
 }
Example #24
0
 public static function deserialize($data)
 {
     return self::getSerializer()->fromArray($data, get_called_class(), DeserializationContext::create()->setGroups(['get']));
 }
 /**
  * This is the documentation description of your method, it will appear
  * on a specific pane. It will read all the text until the first
  * annotation.
  *
  * **Request content**
  *
  *      {
  *          "username": "******",
  *          "password": "******",
  *          "first_name":"Prueba",
  *          "last_name":"forlayo"
  *      }
  *
  *
  * @ApiDoc(
  *      resource=true,
  *      section = "Users",
  *      description="This is a description of your API method",     *
  *      statusCodes = {
  *          201 = "Returned when a new resource is created",
  *          400 = "Returned when the form has errors"
  *      }
  *  )
  *
  * @Rest\View
  */
 public function postUserAction(Request $request)
 {
     $json = $request->getContent();
     $serializer = $this->get("jms_serializer");
     $deSerializerGroup = array('Create');
     $user = new User();
     $dc = DeserializationContext::create();
     $dc->setGroups($deSerializerGroup);
     $dc->setAttribute('target', $user);
     $serializer->deserialize($json, 'OpenMarket\\APIBundle\\Entity\\User', 'json', $dc);
     $validator = $this->get('validator');
     $violations = $validator->validate($user, null, array('View'));
     if ($violations->count() == 0) {
         $userPasswordHandler = $this->get('user_password_handler');
         $userPasswordHandler->encode($user);
         $this->get('user_repository')->add($user);
     } else {
         throw new BadRequestHttpException(implode(PHP_EOL, array('violations' => $violations)));
     }
     return array('user' => $user);
 }
 public function testWillUseDeserializationContext()
 {
     $context = DeserializationContext::create();
     $restAdapter = $this->getRestAdapterBuilder()->setDeserializationContext($context);
     $this->assertAttributeEquals($context, 'deserializationContext', $restAdapter);
 }
Example #27
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;
 }
 /**
  * @param string $className
  * @param array  $groups
  * @param string $format
  *
  * @return mixed
  *
  * @throws BadRequestException
  */
 protected function deserializeRequest($className, $groups = array(SerializationGroup::EDIT), $format = 'json')
 {
     $context = DeserializationContext::create()->setGroups($groups);
     try {
         $object = $this->serializer->deserialize($this->requestStack->getCurrentRequest()->getContent(), $className, $format, $context);
     } catch (\Exception $e) {
         $exception = new BadRequestException();
         $exception->setInfo($e->getMessage());
         throw $exception;
     }
     return $object;
 }
Example #29
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'));
     }
 }
 public function testDeserializeValid()
 {
     $this->transformer->method('getResourceProxy')->willReturn($this);
     $listener = $this->getListener();
     $result = $listener->deserializeStrict($this->visitor, 'foobar', ['params' => ['originalType' => self::class]], DeserializationContext::create());
     $this->assertEquals($this, $result);
 }