コード例 #1
0
ファイル: RamseyUuidHandlerTest.php プロジェクト: pauci/cqrs
 public function testSerializeJson()
 {
     $uuid = Uuid::fromString('34ca79b8-6181-4b93-903a-ac658e0c5c35');
     $object = new ObjectWithUuid($uuid);
     $json = $this->serializer->serialize($object, 'json');
     $this->assertEquals('{"uuid":"34ca79b8-6181-4b93-903a-ac658e0c5c35"}', $json);
 }
コード例 #2
0
 /**
  * @test serialized xml has type attribute
  */
 public function xmlSerialization()
 {
     $container = new EventContainer(new SerializableEventStub('event.name', 'some data'));
     $this->namingStrategy->expects($this->once())->method('classToType')->with(get_class($container->getEvent()))->will($this->returnValue('stub'));
     $serialized = $this->serializer->serialize($container, 'xml');
     $this->assertEquals(file_get_contents(__DIR__ . '/Fixtures/container.xml'), $serialized);
 }
コード例 #3
0
 public function put($resource, $body, $type, $options = [])
 {
     $options['body'] = $this->serializer->serialize($body, 'json');
     $options['headers'] = ['Content-Type' => 'application/json'];
     $content = $this->client->put($resource, $options)->getBody()->getContents();
     return $this->deserialize($content, $type);
 }
コード例 #4
0
 /**
  * @param GetResponseForControllerResultEvent $event
  */
 public function serializeResponse(GetResponseForControllerResultEvent $event)
 {
     if ($this->doSerialize) {
         $data = $event->getControllerResult();
         $apiResponse = new ApiResponse(200, $data);
         $data = array_merge($apiResponse->toArray(), $this->data->all());
         $data = array_filter($data);
         if (!isset($data['data'])) {
             $data['data'] = [];
         }
         $context = new SerializationContext();
         $context->setSerializeNull(true);
         if (method_exists($context, 'enableMaxDepthChecks')) {
             $context->enableMaxDepthChecks();
         }
         if ($action = $this->getAction($event)) {
             $context->setGroups($action->getSerializationGroups());
         }
         if ($fields = $event->getRequest()->query->get('fields')) {
             $context->addExclusionStrategy(new FieldsListExclusionStrategy($fields));
         }
         $json = $this->serializer->serialize($data, 'json', $context);
         $response = new Response($json, 200, ['Content-Type' => 'application/json']);
         $event->setResponse($response);
         $event->stopPropagation();
     }
 }
コード例 #5
0
 /**
  * Render the view into a string and return for output
  *
  * @param mixed $input
  * @return string
  * @throws \Exception
  */
 public function render($input = null)
 {
     $context = new SerializationContext();
     $context->setSerializeNull(true);
     $context->enableMaxDepthChecks();
     FrontController::getInstance()->getResponse()->headers->set('Content-Type', 'application/json');
     return $this->serializer->serialize($input, $this->format, $context);
 }
コード例 #6
0
 /**
  *
  * @param \CSanquer\FakeryGenerator\Model\Config $config
  * @param string                                 $dir
  * @param string                                 $format
  * @return string filename
  */
 public function dump(Config $config, $dir, $format = 'json')
 {
     $format = in_array($format, ['json', 'xml']) ? $format : 'json';
     $serialized = $this->serializer->serialize($config, $format);
     $filename = $dir . '/' . $config->getClassName(true) . '_fakery_generator_config_' . date('Y-m-d_H-i-s') . '.' . $format;
     file_put_contents($filename, $serialized);
     return $filename;
 }
コード例 #7
0
ファイル: Controller.php プロジェクト: bakgat/notos
 public function json($data, $groups = null)
 {
     if ($groups) {
         $this->context->setGroups($groups);
     }
     $serializedData = $this->serializer->serialize($data, 'json', $this->context);
     return $serializedData;
 }
コード例 #8
0
ファイル: JmsSerializer.php プロジェクト: mnapoli/blackbox
 /**
  * {@inheritdoc}
  */
 public function transform($data)
 {
     try {
         return $this->serializer->serialize($data, $this->format);
     } catch (JMSException $e) {
         throw new StorageException('The JMS serializer failed serializing the data: ' . $e->getMessage(), 0, $e);
     }
 }
コード例 #9
0
 /**
  * @param mixed $content
  *
  * @return string
  */
 protected function serialize($content)
 {
     if (!empty($content)) {
         if (is_object($content)) {
             $content = $this->serializer->serialize($content, 'json');
         }
     }
     return $content;
 }
コード例 #10
0
 public function append(EventStream $events)
 {
     foreach ($events as $event) {
         $data = $this->serializer->serialize($event, 'json');
         $event = $this->serializer->serialize(['type' => get_class($event), 'created_on' => (new DateTimeImmutable('now', new DateTimeZone('UTC')))->getTimestamp(), 'data' => $data], 'json');
         $this->predis->rpush('events:' . $events->aggregateId(), $event);
         $this->predis->rpush('published_events', $event);
     }
 }
コード例 #11
0
 /**
  * @inheritDoc
  */
 public function getResponse($responseType, $view, $templateName, $params, $status = 200, $headers = [], $groups = ['Default'])
 {
     if ($responseType === 'html') {
         $response = $this->getHtml($view, $templateName, $params);
     } else {
         $response = $this->serializer->serialize($params, $responseType, SerializationContext::create()->setGroups($groups));
     }
     return new Response($response, $status, $headers);
 }
コード例 #12
0
 /**
  * @param array|object $data
  * @param string $dtoClassName
  * @param string $outputFormat
  * @return array
  */
 public function serialize($data, $dtoClassName, $outputFormat = 'json')
 {
     // TODO: check if $data is object or array
     $itemArray = [];
     foreach ($data as $item) {
         $dto = $this->shifter->toDto($item, new $dtoClassName());
         $serializedData = $this->serializer->serialize($dto, $outputFormat);
         $itemArray[] = (array) json_decode($serializedData);
     }
     return $itemArray;
 }
コード例 #13
0
 /**
  * @param object $entidad
  * @param string $contenido
  */
 public function store($entidad, $contenido)
 {
     if (!method_exists($entidad, 'getDetalles')) {
         throw new HttpException(400, "No el objeto no tiene detalles serializables");
     }
     $observacion = new Observacion();
     $observacion->setContenido($contenido);
     $observacion->setRelated($entidad->getId());
     $observacion->setLastState($this->serializer->serialize($entidad->getDetalles(), 'json'));
     $this->manager->persist($observacion);
 }
コード例 #14
0
 public function put($resource, $body, $type, $options = [])
 {
     $options['future'] = true;
     $options['body'] = $this->serializer->serialize($body, 'json');
     $options['headers'] = ['Content-Type' => 'application/json'];
     return $this->client->put($resource, $options)->then(function (Response $reponse) {
         return $reponse->getBody()->getContents();
     })->then(function ($content) use($type) {
         return $this->deserialize($content, $type);
     });
 }
コード例 #15
0
 /**
  * @param GetResponseForControllerResultEvent $event
  */
 public function onKernelView(GetResponseForControllerResultEvent $event)
 {
     $result = $event->getControllerResult();
     if ($result instanceof Response) {
         return $result;
     }
     $serialized = $this->serializer->serialize($result, 'json');
     $response = new Response();
     $response->setContent($serialized);
     $response->headers->add(array('Content-type' => 'application/json'));
     $event->setResponse($response);
 }
コード例 #16
0
ファイル: Api.php プロジェクト: dvelopment/fastbill
 /**
  * @param Request $requestModel
  * @param string $responseType
  *
  * @throws Exception\FastBillException
  * @return \DVelopment\FastBill\Model\FbApi
  */
 public function call(Request $requestModel, $responseType = 'DVelopment\\FastBill\\Model\\FbApi')
 {
     $request = new GetRequest(self::API_BASE_URL);
     $request->setUseAuthentication(true)->setUsername($this->username)->setPassword($this->apiKey)->setFormat('json')->setContentType('application/json');
     $request->setBody($this->serializer->serialize($requestModel, 'json'));
     /** @var FbApi $fbApi */
     $fbApi = $this->client->execute($request, null, $responseType)->getContent();
     if (count($fbApi->getResponse()->errors)) {
         throw new FastBillException($fbApi->getResponse()->errors);
     }
     return $fbApi;
 }
コード例 #17
0
 /**
  * Tests getting ident codes with XML response
  *
  * @param int    $expectedStatusCode
  * @param string $account
  * @param int    $serial
  * @param string $expectedResponse
  *
  * @dataProvider provideIdentCodeData
  */
 public function testIdentCodeXml($expectedStatusCode, $account, $serial, $expectedResponse)
 {
     $this->client->request('GET', sprintf('/dhl/b2b/identcode/%s/%d.xml', $account, $serial));
     // Assert if the response status code isn't equal to the expected one
     $this->assertEquals($expectedStatusCode, $this->client->getResponse()->getStatusCode(), $this->client->getResponse()->getContent());
     // Assert that the "Content-Type" header is "application/json"
     $this->assertTrue($this->client->getResponse()->headers->contains('Content-Type', 'text/xml; charset=UTF-8'), $this->client->getResponse()->headers->get('Content-Type'));
     // Check if it's a valid XML
     $doc = new DOMDocument();
     $this->assertTrue($doc->loadXML($this->client->getResponse()->getContent()), 'Is no valid XML');
     // Assert that the expected response is equal to the current one
     $this->assertEquals($this->serializer->serialize($expectedResponse, 'xml'), $this->client->getResponse()->getContent(), 'XML is not equal');
 }
コード例 #18
0
 /**
  *  Returns md5 of serialized object for objects and md5 for string values
  *
  * @param mixed $object
  * @return string
  */
 public function objectMd5($object)
 {
     $hash = '';
     if (is_object($object)) {
         try {
             $hash = md5($this->serializer->serialize($object, 'json'));
         } catch (RuntimeException $e) {
             $hash = '';
         }
     } elseif (is_string($object)) {
         $hash = md5($object);
     }
     return $hash;
 }
 public function onPlainResponse(ViewEvent $event)
 {
     $request = $event->getRequest();
     $response = $event->getResponse();
     // No need to perform JSON-RPC serialization here
     if (!$request instanceof JsonRpcRequestInterface || $request->isNotification()) {
         return;
     }
     // Response is already properly formatted
     if ($response instanceof JsonRpcResponseInterface) {
         return;
     }
     $response = new JsonRpcResponse($request->getId(), json_decode($this->serializer->serialize($event->getResponse(), 'json', $this->createSerializerContext($event))));
     $event->setResponse($response);
 }
コード例 #20
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;
 }
コード例 #21
0
 /**
  * @param UserCreatedEvent $userCreatedEvent
  */
 public function onUserCreated(UserCreatedEvent $userCreatedEvent)
 {
     $user = $userCreatedEvent->getUser();
     $data = array('event' => ApiEvent::USER_CREATED, 'user' => $user->getId(), 'userFullName' => $user->getFullName(), 'image' => $user->getAvatar());
     $message = $this->serializer->serialize($data, 'json', $this->serializationContext);
     $this->sqsClient->send($message);
 }
コード例 #22
0
 /**
  * @param Request $request
  * @return Response
  */
 public function indexAction(Request $request)
 {
     $format = $this->negotiator->getBestFormat($request->headers->get('Accept'));
     if ($format == 'html') {
         $format = 'json';
     }
     $data = array();
     foreach ($this->registry->all() as $definition) {
         $data[$definition->getName() . '_url'] = $this->router->generate('lemon_rest_list', array('resource' => $definition->getName()), RouterInterface::ABSOLUTE_URL);
     }
     $output = $this->serializer->serialize($data, $format);
     $response = new Response();
     $response->headers->set('Content-Type', $request->headers->get('Accept'));
     $response->setContent($output);
     return $response;
 }
コード例 #23
0
ファイル: AbstractWorker.php プロジェクト: gloubster/worker
 private function getTechnicalInformations(Result $data)
 {
     $availableHashAlgos = hash_algos();
     if ($data->isPath()) {
         $result = json_decode($this->serializer->serialize($this->mediavorus->guess($data->getData()), 'json'), true);
         if (in_array('sha256', $availableHashAlgos)) {
             $result['sha256'] = hash_file('sha256', $data->getData());
         }
         if (in_array('sha256', $availableHashAlgos)) {
             $result['sha1'] = hash_file('sha1', $data->getData());
         }
         if (in_array('sha256', $availableHashAlgos)) {
             $result['md5'] = hash_file('md5', $data->getData());
         }
     } elseif ($data->isBinary()) {
         $temp = $this->filesystem->createEmptyFile(sys_get_temp_dir());
         file_put_contents($temp, $data->getData());
         $tcData = json_decode($this->serializer->serialize($this->mediavorus->guess($temp), 'json'), true);
         unlink($temp);
         if (in_array('sha256', $availableHashAlgos)) {
             $result['sha256'] = hash('sha256', $data->getData());
         }
         if (in_array('sha256', $availableHashAlgos)) {
             $result['sha1'] = hash('sha1', $data->getData());
         }
         if (in_array('sha256', $availableHashAlgos)) {
             $result['md5'] = hash('md5', $data->getData());
         }
         return $tcData;
     } else {
         throw new RuntimeException('Unable to extract technical informations');
     }
     return $result;
 }
コード例 #24
0
 public function processForm(WebsiteOptions $options, array $parameters, $method = 'PUT')
 {
     $form = $this->formFactory->create(new WebsiteOptionsType(), $options, array('method' => $method));
     $form->submit($parameters, 'PATCH' !== $method);
     if ($form->isValid()) {
         $options = $form->getData();
         $this->om->persist($options);
         $this->om->flush();
         $serializationContext = new SerializationContext();
         $serializationContext->setSerializeNull(true);
         return json_decode($this->serializer->serialize($options, 'json', $serializationContext));
     }
     /*else {
           return $this->getErrorMessages($form);
       }*/
     throw new \InvalidArgumentException();
 }
コード例 #25
0
ファイル: OrderEmailManager.php プロジェクト: sulu/sulu-sales
 /**
  * @param ApiOrderInterface $apiOrder
  *
  * @return \Swift_Mime_Attachment
  */
 protected function createXMLAttachment(ApiOrderInterface $apiOrder)
 {
     $xmlFilename = 'PA_OrderConfirmation-' . $apiOrder->getNumber() . '.xml';
     $context = SerializationContext::create()->setGroups(['xmlOrder']);
     $context->setSerializeNull(true);
     $serialized = $this->serializer->serialize($apiOrder, 'xml', $context);
     return \Swift_Attachment::newInstance($serialized, $xmlFilename, 'application/xml');
 }
コード例 #26
0
 public function testCommit_dateNaissance_nom()
 {
     $pageAnimal = $this->testUtils->createUser()->toEleveur()->addAnimal()->getPageEleveur()->getAnimaux()[0];
     $pageAnimal->setDateNaissance(null);
     // Modification du nom et de la description de la page
     $this->client->request('POST', '/animal/' . $pageAnimal->getId(), array(), array(), array(), $this->serializer->serialize($pageAnimal, 'json'));
     $this->assertEquals(Response::HTTP_NOT_ACCEPTABLE, $this->client->getResponse()->getStatusCode());
 }
コード例 #27
0
 /**
  * @param Request $request
  * @param $exception
  * @param $httpCode
  * @return Response
  */
 protected function getFormattedResponse(Request $request, $exception, $httpCode)
 {
     if (Codes::HTTP_MOVED_PERMANENTLY == $httpCode) {
         $response = new Response(null, $httpCode);
         $response->headers->set('X-Location', $this->container->get('router')->generate('diamante_ticket_api_service_diamante_load_ticket_by_key', ['key' => $exception->getTicketKey()]));
         return $response;
     }
     return new Response($this->serializer->serialize(['error' => $exception->getMessage()], $request->getRequestFormat()), $httpCode);
 }
コード例 #28
0
ファイル: Serializer.php プロジェクト: aliebing/JsonApiBundle
 /**
  * {@inheritdoc}
  */
 public function serialize($data, $format, SerializationContext $context = null)
 {
     if ($format === 'json') {
         foreach ($this->exclusionStrategies as $exclusionStrategy) {
             $context->addExclusionStrategy($exclusionStrategy);
         }
     }
     return parent::serialize($data, $format, $context);
 }
コード例 #29
0
 /**
  * @return string
  */
 public function save()
 {
     $satisConfig = $this->serializer->serialize($this->satis, 'json');
     $this->configPersister->updateWith($satisConfig);
     if ($this->disableBuild === false) {
         return $this->configBuilder->build();
     }
     return true;
 }
コード例 #30
-8
 /**
  * @param RequestType $request
  * @return ResponseType
  */
 public function postRequest(RequestType $request)
 {
     $xmlContent = $this->serializer->serialize($request, 'xml');
     if ($this->logger) {
         $this->logger->debug("RatePAY Gateway Client posting XML content to {endpoint}\n\n{request}\n", ['endpoint' => $this->endpoint, 'request' => $xmlContent]);
     }
     $res = $this->client->request('POST', $this->endpoint, ['body' => $xmlContent, 'headers' => ['Content-Type' => 'text/xml; charset=UTF-8']]);
     $rawResponse = $res->getBody()->getContents();
     if ($this->logger) {
         $this->logger->debug("RatePAY Gateway Client received XML response with status code {statuscode}\n\n{response}", ['statuscode' => $res->getStatusCode(), 'response' => $rawResponse]);
     }
     if ($res->getStatusCode() != 200) {
         throw new \RuntimeException("Remote Server returned status code != 200");
     }
     $response = $this->serializer->deserialize($rawResponse, 'PHPCommerce\\Vendor\\RatePAY\\Service\\Payment\\Type\\Response\\ResponseType', 'xml');
     return $response;
 }