/** * @param array $data * @param string|null|array $serializationLevel * @return Response */ public function createResponse(array $data, $serializationLevel = null) { $responseData = [static::KEY_STATUS => static::STATUS_SUCCESS, static::KEY_DATA => $data]; $serializedData = $this->serializer->serialize($responseData, self::STANDARD_RESPONSE_FORMAT, $serializationLevel ? SerializationContext::create()->setGroups($serializationLevel) : SerializationContext::create()); $response = $this->getJsonResponse($serializedData); return $response; }
/** * @param $track * @param $debug * * @throws RussianPostApiException * @throws InvalidTrackException * * @return OperationHistoryData */ public function getTrackOperationHistory($track, &$debug, $language = "RUS") { if (!TrackValidator::validateTrack($track)) { throw new InvalidTrackException(); } $track = TrackValidator::filterTrack($track); $client = $this->initClient(); $AuthorizationHeader = self::createAuthorizationHeader($this->login, $this->password); $historyRequest = self::createOperationHistoryRequest($track, 0, $language); $parameters = ["AuthorizationHeader" => $this->serializer->serialize($AuthorizationHeader, 'array'), "historyRequest" => $this->serializer->serialize($historyRequest, 'array')]; //($operation, $params=array(), $namespace='http://tempuri.org', $soapAction='', $headers=false, $rpcParams=null, $style='rpc', $use='encoded') $result = $client->call('GetOperationHistory', $parameters, 'http://russianpost.org/operationhistory'); $debug = array("Request" => $client->request, "Response" => $client->response, "Debug" => $client->debug_str); if ($client->fault) { throw new RussianPostApiException(print_r($result, true)); } else { $err = $client->getError(); if ($err) { throw new RussianPostApiException($err); } else { /** @var OperationHistoryData $object */ $object = $this->serializer->deserialize($result, 'a3mg\\RussianPostBundle\\Model\\OperationHistoryData', 'array'); return $object; } } }
public function testSerializationToJson() { $subject = new Message('to', 'from', 'subject', 'message'); $data = $this->serializer->serialize($subject, 'json'); $object = $this->serializer->deserialize($data, get_class($subject), 'json'); $this->assertEquals($subject, $object); }
/** * @param $data * @param int $status * @param array $headers * @return \Symfony\Component\HttpFoundation\Response|static */ protected function success($data, $status = 200, $headers = []) { $serialized_data = $this->serializer->serialize($data, 'json'); $response = $this->jsonResponse; $response->setContent($serialized_data)->setStatusCode($status)->headers->add($headers); return $response; }
/** @test */ public function shouldSerializeDateTimesAsTimestamps() { $birthdayBoy = new BirthdayBoy(); $birthdayBoy->setBirthDate(self::FromTimestamp(1234567)); $json = $this->serializer->serialize($birthdayBoy, 'json'); $this->assertJsonStringEqualsJsonString($json, '{"birthDate": 1234567 }'); }
/** * {@inheritdoc} */ public function notifyCallback($callbackUrl, $statusResponse) { $requestBody = $this->serializer->serialize($statusResponse, 'json'); $request = new \cURL\Request($callbackUrl); $request->getOptions()->set(CURLOPT_FILE, fopen('/dev/null', 'w'))->set(CURLOPT_TIMEOUT, 5)->set(CURLOPT_RETURNTRANSFER, false)->set(CURLOPT_CUSTOMREQUEST, 'POST')->set(CURLOPT_POSTFIELDS, $requestBody)->set(CURLOPT_HTTPHEADER, array('Content-Type: application/json', sprintf('Content-Length: %d', strlen($requestBody)))); $request->send(); }
protected function jsonResponse($data) { $context = new SerializationContext(); $context->setSerializeNull(true); $content = $this->serializer->serialize($data, 'json', $context); $this->response->setContent($content); return $this->response; }
/** * {@inheritdoc} */ public function publish(Event $event) { try { $this->client->post(self::PUBLISH_URL, ['body' => $this->serializer->serialize($event, 'json')]); } catch (BadResponseException $exception) { throw new PublishException($exception->getMessage()); } }
/** * @param GameInterface $data * @param string $format * * @return array|string */ public function serialize($data, $format) { $serialized = $this->serializer->serialize($data, self::FORMAT_JSON, $this->serializationContext); if ($format === self::FORMAT_ARRAY) { $serialized = json_decode($serialized, true); } return $serialized; }
/** * @param ApiResponse $apiResponse to convert to a Symfony Response. * @param Request $request that needs this Response. * * @return Response */ public function toSymfonyResponse(ApiResponse $apiResponse, Request $request) { $format = $request->getRequestFormat($this->defaultResponseFormat); $serialized = $this->serializer->serialize($apiResponse->getData(), $format); $response = new Response($serialized, $apiResponse->getStatusCode(), $apiResponse->getHeaders()); $response->headers->set('Content-Type', $request->getMimeType($format)); return $response; }
public function testSerializationToJson() { $exception = new \Exception('foobar', 100); $subject = new ExceptionResponse($exception); $data = $this->serializer->serialize($subject, 'json'); $object = $this->serializer->deserialize($data, ExceptionResponse::class, 'json'); $this->assertEquals($subject, $object); }
/** * {@inheritdoc} */ public function post($uri, $data = null, array $options = array()) { if (is_array($data)) { $options = array_merge($data, $options); $data = new \StdClass(); } $this->request('post', $uri, array('body' => $this->serializer->serialize($data, 'json', SerializationContext::create()->setAttribute('options', $options)))); }
public function testSerialize() { $pageDocument = $this->createPage(); $managedPage = $this->contentMapper->load($pageDocument->getUuid(), 'sulu_io', 'fr'); $this->assertInstanceOf(StructureBridge::class, $managedPage); $result = $this->serializer->serialize($managedPage, 'json'); return $result; }
/** * @inheritdoc */ public function serialize($data, $format, $groups = null) { $context = null; if ($groups) { $context = SerializationContext::create()->setGroups($groups); } return $this->serializer->serialize($data, $format, $context); }
/** * @param Request $request * @param string $data * * @return string */ public function serializeRequest(Request $request, $data) { $format = $this->checkAcceptHeader($request); try { return $this->serializer->serialize($data, $format); } catch (\Exception $e) { throw new \RuntimeException('Could not serialize content to \'' . $format . '\' format.'); } }
/** * Send a request to fastbill. * * @param mixed $request The request to send. * @param string $responseClass The class that should be used to unserialize the response. * @return ApiResponseInterface */ protected function sendRequest(RequestInterface $request, $responseClass) { if (!in_array(ApiResponseInterface::class, class_implements($responseClass))) { throw new \InvalidArgumentException('The response class must implement "' . ApiResponseInterface::class . '".'); } $body = $this->serializer->serialize($request, 'json'); $response = $this->transport->sendRequest($body); return $this->serializer->deserialize($response, $responseClass, 'json'); }
/** * @param string $format * @dataProvider provideSupportedFormats */ public function testSerializeToJsonWithMemberType($format) { $subject = new MemberTest(); $subject->aString = 'foobar'; $subject->enum = TaggedTestType::VALUE1(); $data = $this->serializer->serialize($subject, $format); $object = $this->serializer->deserialize($data, MemberTest::class, $format); $this->assertEquals($subject, $object); }
/** * @param SerializableInterface $serializable * @param SerializationContext $serializationContext * * @return string */ public function toJson(SerializableInterface $serializable, SerializationContext $serializationContext = null) { if (null == $serializationContext) { $serializationContext = new SerializationContext(); } $serializationResult = $this->serializer->serialize($serializable, 'json', $this->getSerializationContext($serializable, $serializationContext)); $this->logSerializationResult($serializable, $serializationResult); return $serializationResult; }
/** * {@inheritdoc} */ public function serialize(DocumentInterface $object) { $context = SerializationContext::create(); if (!is_null($this->groupName)) { $context->setGroups(array($this->groupName)); $context->setSerializeNull($this->serializeNull); } return $this->jmsSerializer->serialize($object, 'json', $context); }
/** * @param string $title * @param object $object * * @return Event * * @throws LogicException */ private function buildEvent($title, $object) { if (!is_object($object)) { throw new LogicException(sprintf('Connector only allows publish objects, "%s" given', gettype($object))); } $event = new Event(); $event->setTitle($title)->setNamespace(get_class($object))->setPayload($this->serializer->serialize($object, 'json')); return $event; }
public function writeResponseContent(array $responseContent, $requestedContentType) { if (empty($responseContent)) { $serializedResponseContent = ""; } else { $serializedResponseContent = $this->serializer->serialize($responseContent, 'json'); } echo $serializedResponseContent; }
/** * @return array */ public function getTagsFunction() { return $this->memoizeCache->memoize(function () { $tags = $this->tagManager->findAll(); $context = SerializationContext::create(); $context->setSerializeNull(true); $context->setGroups(['partialTag']); return $this->serializer->serialize($tags, 'array', $context); }); }
/** * Returns a POST request if the object's identifier is null; a PUT request is returned otherwise. * * @param object $object * @param array $parameters * @param array $requirements * * @return Request */ public function createSaveRequest($object, array $parameters = [], array $requirements = []) { $metadata = $this->metadataRegistry->getMetadataForClass(get_class($object)); if (null === ($id = $metadata->getIdentifierValue($object))) { // Identifier is null so this is a new entity return new Request('POST', $this->urlGenerator->getCreateUrl($metadata->getResource(), $parameters, $requirements), ['Content-Type' => $this->getContentTypeHeader()], $this->serializer->serialize($object, $this->format, SerializationContext::create()->setGroups('Default'))); } // Identifier is set so we are modifying an exiting entity return new Request('PUT', $this->urlGenerator->getModifyUrl($metadata->getResource(), $id, $parameters, $requirements), ['Content-Type' => $this->getContentTypeHeader()], $this->serializer->serialize($object, $this->format, SerializationContext::create()->setGroups('Default'))); }
/** * Returns an array of serialized categories. * If parentKey is set, only the children of the category which is assigned to the given key are returned. * * @param string $locale * @param string $parentKey key of parent category * * @return array */ public function getCategoriesFunction($locale, $parentKey = null) { return $this->memoizeCache->memoize(function ($locale, $parentKey = null) { $entities = $this->categoryManager->findChildrenByParentKey($parentKey); $categories = $this->categoryManager->getApiObjects($entities, $locale); $context = SerializationContext::create(); $context->setSerializeNull(true); return $this->serializer->serialize($categories, 'array', $context); }); }
public function testSerializationToJson() { $definition = new Definition(); $definition->setType('LOCAL'); $definition->setPath('/path/to/filesystem'); $definition->setProperties(array('create' => true, 'mode' => 0755)); $data = $this->serializer->serialize($definition, 'json'); $object = $this->serializer->deserialize($data, 'Abc\\Filesystem\\Definition', 'json'); $this->assertEquals($definition, $object); $this->assertSame($definition->getProperties(), $object->getProperties()); }
/** * {@inheritdoc} */ public function serialize($data, array $groups = []) { $context = SerializationContext::create(); // Serialize null properties. $context->setSerializeNull(true); // Always serialize the default groups. This cannot be disabled. $groups[] = 'Default'; $context->setGroups($groups); $jsonString = $this->jmsSerializer->serialize($data, 'json', $context); return $jsonString; }
public function resourceAction($repositoryName, $path) { $repository = $this->registry->get($repositoryName); $resource = $repository->get('/' . $path); $context = SerializationContext::create(); $context->enableMaxDepthChecks(); $context->setSerializeNull(true); $json = $this->serializer->serialize($resource, 'json', $context); $response = new Response($json); $response->headers->set('Content-Type', 'application/json'); return $response; }
public function executeCommand($commandName, $args = array()) { $args = json_decode($this->serializer->serialize($args, 'json'), true); $command = $this->getCommand($commandName, (array) $args); $operation = $command->getOperation(); if ($command instanceof Collection && count($paramNames = $operation->getParamNames())) { $wireName = $operation->getParam($paramNames[0])->getWireName(); if (count($paramNames) == 1 && !$command->hasKey($wireName)) { $command->set($wireName, $args); } } return $command->execute(); }
/** * Adding extra user data to the JSON Web Token * @param AuthenticationSuccessEvent $event */ public function onAuthenticationSuccessResponse(AuthenticationSuccessEvent $event) { $data = $event->getData(); $user = $event->getUser(); if ($user instanceof UserInterface) { $this->updateUser($event, $user); $context = SerializationContext::create(); $context->setGroups(array('Default', 'full', 'userFull')); $data['user'] = json_decode($this->serializer->serialize($user, 'json', $context)); $event->setData($data); } return; }
/** * Send a request to fastbill. * * @param mixed $request The request to send. * @param string $responseClass The class that should be used to unserialize the response. * @return ApiResponseInterface * @throws ApiResponseException If the API response has errors. */ protected function sendRequest(RequestInterface $request, $responseClass) { if (!in_array(ApiResponseInterface::class, class_implements($responseClass))) { throw new \InvalidArgumentException('The response class must implement "' . ApiResponseInterface::class . '".'); } $body = $this->serializer->serialize($request, 'json'); $response = $this->transport->sendRequest($body); /** @var ApiResponseInterface $apiResponse */ $apiResponse = $this->serializer->deserialize($response, $responseClass, 'json'); if ($apiResponse->getResponse() !== null && $apiResponse->getResponse()->hasErrors()) { throw new ApiResponseException(sprintf('Error calling "%s"', $request->getService()), $apiResponse->getResponse()->getErrors()); } return $apiResponse; }