public function testCustomSubscribingHandler() { $fixture = file_get_contents(FIXTURE_ROOT . '/Unit/Serializer/JmsSerializer/test_entity_1.json'); $resultEntity = $this->realJms->deserialize($fixture, 'Elastification\\Client\\Serializer\\JmsSerializer\\SearchResponseEntity', 'json'); $this->assertInstanceOf('Elastification\\Client\\Serializer\\JmsSerializer\\SearchResponseEntity', $resultEntity); /* @var $resultEntity \Elastification\Client\Serializer\JmsSerializer\SearchResponseEntity */ $this->assertEquals(1, $resultEntity->took); $this->assertEquals(false, $resultEntity->timed_out); $this->assertInstanceOf('Elastification\\Client\\Serializer\\JmsSerializer\\Shards', $resultEntity->_shards); $this->assertEquals(1, $resultEntity->_shards->total); $this->assertEquals(1, $resultEntity->_shards->successful); $this->assertEquals(0, $resultEntity->_shards->failed); $this->assertInstanceOf('Elastification\\Client\\Serializer\\JmsSerializer\\Hits', $resultEntity->hits); $this->assertEquals(1, $resultEntity->hits->total); $this->assertEquals(0, $resultEntity->hits->maxScore); $this->assertCount(1, $resultEntity->hits->hits); $hit = $resultEntity->hits->hits[0]; $this->assertInstanceOf('Elastification\\Client\\Serializer\\JmsSerializer\\Hit', $hit); $this->assertEquals('4372-4412104-928-DL', $hit->_id); $this->assertEquals('elastification', $hit->_index); $this->assertEquals('test', $hit->_type); $this->assertEquals(1.993935, $hit->_score); $entity = $hit->_source; $this->assertInstanceOf('Elastification\\Client\\Tests\\Fixtures\\Unit\\Serializer\\JmsSerializer\\TestEntity', $entity); $this->assertEquals(123, $entity->a); }
/** * @param \Doctrine\ORM\Event\LifecycleEventArgs $args */ public function postPersist(LifecycleEventArgs $args) { $layoutBlock = $args->getEntity(); if ($layoutBlock instanceof LayoutBlock) { if ($contentObject = $layoutBlock->getSnapshotContent()) { $contentObject = $this->serializer->deserialize($contentObject, $layoutBlock->getClassType(), 'json'); $em = $args->getEntityManager(); try { $em->persist($contentObject); $contentObject = $em->merge($contentObject); $reflection = new \ReflectionClass($contentObject); foreach ($reflection->getProperties() as $property) { $method = sprintf('get%s', ucfirst($property->getName())); if ($reflection->hasMethod($method) && ($var = $contentObject->{$method}())) { if ($var instanceof ArrayCollection) { foreach ($var as $v) { $em->merge($v); } } } } } catch (EntityNotFoundException $e) { $em->detach($contentObject); $classType = $layoutBlock->getClassType(); $contentObject = new $classType(); $em->persist($contentObject); } $em->flush($contentObject); $layoutBlock->setObjectId($contentObject->getId()); $em->persist($layoutBlock); $em->flush($layoutBlock); } } }
/** * @param InputInterface $input * @param OutputInterface $output * * @return bool */ protected function execute(InputInterface $input, OutputInterface $output) { foreach ($this->sources as $name => $class) { $result = $this->serializer->deserialize(file_get_contents(getcwd() . '/tests/Common/Api/test_cases/protocols/output/fixtures/' . $name . '.xml'), $class, 'xml'); file_put_contents(getcwd() . '/tests/Common/Api/test_cases/protocols/output/fixtures/' . $name . '.serialized', serialize($result->getBody())); $output->writeln('Processed ' . $name . ' serialized file.'); } }
public function deserialize($data, $type) { $result = $this->serializer->deserialize($data, $type, 'json'); if (preg_match('/ArrayCollection/', $type)) { $result = new ArrayList($result); } return $result; }
public function testDeserializeJson() { $json = '{"foo":"bar","baz":[1,2,3]}'; /** @var Metadata $metadata */ $metadata = $this->serializer->deserialize($json, Metadata::class, 'json'); $this->assertInstanceOf(Metadata::class, $metadata); $this->assertEquals(['baz' => [1, 2, 3], 'foo' => 'bar'], $metadata->toArray()); }
/** * @param AbstractJsonEvent $event * * @return AbstractJsonEvent */ public function deserialize(AbstractJsonEvent $event) { $deSerialized = $this->serializer->deserialize($event->getJson(), get_class($event), self::JSON_FORMAT); $deSerialized->type = $event->type; $deSerialized->content = $event->content; $deSerialized->setName($event->getName()); return $deSerialized; }
/** * @param ServiceEvent $event */ public function onResponseEvent(ServiceEvent $event) { $service = $event->getService(); if ($service instanceof ServiceConfigurableInterface && null !== $service->getOption('response_type')) { /** @var Service $service */ $service->getResponse()->setDeserializedContent($this->serializer->deserialize($service->getResponse()->getContent(), $service->getOption('response_type'), $service->getOption('response_format'))); } }
public function testDiscriminatorIsInferredForGenericBaseClass() { $student = new Student(); $json = $this->serializer->serialize($student, 'json'); $this->assertEquals('{"type":"student"}', $json); $deserialized = $this->serializer->deserialize($json, Person::class, 'json'); $this->assertEquals($student, $deserialized); }
/** * @return \App\Satis\Model\ConfigLock|array|\JMS\Serializer\scalar|mixed|object * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException */ protected function getLockFile() { if ($this->filesystem->exists($this->lockFilename)) { $configLock = $this->serializer->deserialize($this->filesystem->get($this->lockFilename), 'App\\Satis\\Model\\ConfigLock', 'json'); } else { $configLock = new ConfigLock(); } return $configLock; }
/** * Deserializes request content. * * @param ResponseInterface $response * @param string $type * @param string $format * * @return mixed * * @throws \Exception */ protected function deserialize(ResponseInterface $response, $type, $format = 'json') { try { return $this->serializer->deserialize((string) $response->getBody(), $type, $format); } catch (\Exception $exception) { $this->logger->error('[WebServiceClient] Deserialization problem on webservice call.', array('response' => (string) $response->getBody(), 'exception' => $exception)); throw $exception; } }
public function testDeserializeJson() { $json = '{"uuid":"ed34c88e-78b0-11e3-9ade-406c8f20ad00"}'; /** @var ObjectWithUuid $object */ $object = $this->serializer->deserialize($json, ObjectWithUuid::class, 'json'); $uuid = $object->getUuid(); $this->assertInstanceOf(UuidInterface::class, $uuid); $this->assertEquals('ed34c88e-78b0-11e3-9ade-406c8f20ad00', (string) $uuid); }
/** * @test */ public function it_can_be_deserialized() { $modelData = $this->getModelData(); $modelClass = $this->getModelClass(); /** @var AbstractModel $model */ $model = $this->serializer->deserialize(json_encode($modelData), $modelClass, 'json'); $this->assertInstanceOf($modelClass, $model); $this->assertInstanceOf('CL\\Slack\\Model\\AbstractModel', $model); $this->assertModel($modelData, $model); }
public function test_CreateAnimal_success() { $this->testUtils->createUser()->toEleveur(); $this->client->request('POST', '/animal'); $this->assertEquals(Response::HTTP_OK, $this->client->getResponse()->getStatusCode()); /** @var PageAnimal $pageAnimal */ $pageAnimal = $this->serializer->deserialize($this->client->getResponse()->getContent(), PageAnimal::class, 'json'); $this->client->request('GET', '/animal/' . $pageAnimal->getId()); $this->assertEquals(Response::HTTP_OK, $this->client->getResponse()->getStatusCode()); }
/** * @param $data * @param $entityName * @return mixed */ public function hydrateEntity($data, $entityName) { if (empty($data)) { $data = array(); } if (is_string($data)) { $data = json_decode($data, true); } return $this->serializer->deserialize(json_encode($this->transformer->transformHydrateData($data)), $entityName, 'json'); }
/** * {@inheritdoc} */ public function reverseTransform($data) { if ($data === null) { return null; } try { return $this->serializer->deserialize($data, $this->class, $this->format); } catch (JMSException $e) { throw new StorageException('The JMS serializer failed deserializing the data: ' . $e->getMessage(), 0, $e); } }
/** * * @param string $filename * * @return \CSanquer\FakeryGenerator\Model\Config * * @throws \InvalidArgumentException */ public function load($filename) { $file = new \SplFileInfo($filename); if (!in_array($file->getExtension(), ['json', 'xml'])) { throw new \InvalidArgumentException('The config file must be an XML or a JSON file.'); } if (!file_exists($file->getRealPath())) { throw new \InvalidArgumentException('The config file must exist.'); } return $this->serializer->deserialize(file_get_contents($file->getRealPath()), 'CSanquer\\FakeryGenerator\\Model\\Config', $file->getExtension()); }
/** * @param AMQPMessage $msg * @return bool */ public function execute(AMQPMessage $msg) { $post = $this->serializer->deserialize($msg->body, 'AppBundle\\Entity\\Post', 'json'); $targetPath = $this->container->get('kernel')->getRootDir() . '/../web/downloads/pdf/' . $post->getPdfName() . '.pdf'; $this->container->get('knp_snappy.pdf')->generateFromHtml($this->templating->render('RabbitMQBundle::pdf_post_view.html.twig', array('post' => $post)), $targetPath); if (file_exists($targetPath)) { return true; } else { return false; } }
/** * Stores the object in the request. * * @param Request $request The request * @param ParamConverter $configuration Contains the name, class and options of the object * * @throws \InvalidArgumentException * * @return bool True if the object has been successfully set, else false */ public function apply(Request $request, ParamConverter $configuration) { $name = $configuration->getName(); $class = $configuration->getClass(); $options = $configuration->getOptions(); if (isset($options['query'])) { $content = new \stdClass(); $metadata = $this->serializer->getMetadataFactory()->getMetadataForClass($class); foreach ($metadata->propertyMetadata as $propertyMetadata) { if (!$propertyMetadata->readOnly) { $property = $propertyMetadata->name; $value = $request->query->get($propertyMetadata->name); if (!is_null($value)) { $content->{$property} = $request->query->get($propertyMetadata->name); } } } $content = json_encode($content); } else { $content = $request->getContent(); } if (!class_exists($class)) { throw new \InvalidArgumentException($class . ' class does not exist.'); } $success = false; try { $model = $this->serializer->deserialize($content, $class, 'json'); $success = true; } catch (\Exception $e) { $model = new $class(); } /** * Validate if possible */ if ($model instanceof ValidatableInterface) { $violations = $this->validator->validate($model); $valid = $success && !(bool) $violations->count(); $model->setViolations($violations); $model->setValid($valid); } /** * Adding transformed collection * to request attribute. */ $request->attributes->set($name, $model); /** * Alias to access current collection * Used by exception listener */ $request->attributes->set(Alias::DATA, $name); return true; }
public function getEventsFor($id) { if (!$this->predis->exists('events:' . $id)) { throw new AggregateDoesNotExist($id); } $serializedEvents = $this->predis->lrange('events:' . $id, 0, -1); $eventStream = []; foreach ($serializedEvents as $serializedEvent) { $eventData = $this->serializer->deserialize($serializedEvent, 'array', 'json'); $eventStream[] = $this->serializer->deserialize($eventData['data'], $eventData['type'], 'json'); } return new EventStream($id, $eventStream); }
/** * @test deserialize container data in proper event from xml */ public function xmlDeserialization() { $eventClass = __NAMESPACE__ . '\\SerializableEventStub'; $data = ['type' => $eventClass, 'data' => ['name' => 'event.name', 'foo' => 'some data']]; $this->namingStrategy->expects($this->once())->method('typeToClass')->with('stub')->will($this->returnValue($eventClass)); $containerClass = 'EventBand\\Serializer\\Jms\\EventContainer'; /** @var EventContainer $container */ $container = $this->serializer->deserialize(file_get_contents(__DIR__ . '/Fixtures/container.xml'), $containerClass, 'xml'); $this->assertInstanceOf($containerClass, $container); $this->assertInstanceOf($eventClass, $container->getEvent()); $this->assertEquals($data['data']['name'], $container->getEvent()->getName()); $this->assertEquals($data['data']['foo'], $container->getEvent()->getFoo()); }
/** * @param bool $deserialize * @return Post[]|null * @throws \Doctrine\DBAL\DBALException */ public function getAllInJson($deserialize = true) { $stmt = $this->getEntityManager()->getConnection()->prepare(file_get_contents(__DIR__ . self::RESOURCES_QUERY_PATH . 'get_all_posts_json.sql')); $stmt->execute(); $result = $stmt->fetchAll(); if ($deserialize) { if (!empty($result[0]['array_to_json'])) { return $this->serializer->deserialize($result[0]['array_to_json'], 'array<AppBundle\\Entity\\Post>', 'json'); } return null; } return $result[0]['array_to_json']; }
/** * Deserialize * * JMS Deserialized has been wrapped to allow looser typing of arguments. * @param string|array $data * @param string|\StdClass $object * @param string $format * @return mixed */ public function deserialize($data, $object, $format = 'json') { if (is_array($data)) { $data = json_encode($data); } if (is_object($object)) { $context = new DeserializationContext(); $context->attributes->set('target', $object); return $this->serializer->deserialize($data, get_class($object), $format, $context); } else { return $this->serializer->deserialize($data, $object, $format); } }
public function listen() { if ($this->closed) { throw new BadMethodCallException('This listener object is closed and cannot receive any more messages.'); } while ($envelope = $this->queue->get()) { $storedEvent = $this->serializer->deserialize($envelope->getBody(), 'Ddd\\Domain\\Event\\StoredEvent', 'json'); if ($this->listensTo($storedEvent->typeName())) { $this->handle(json_decode($storedEvent->eventBody())); } if ($this->stop) { return; } } }
/** * Creates and returns a template object based on the provided template definition. * * @param string $xml * * @return Template */ protected function createTemplateFromXml($xml) { /** @var Template $template */ $template = $this->serializer->deserialize($xml, 'phpDocumentor\\Transformer\\Template', 'xml'); $template->propagateParameters(); return $template; }
/** * @param array $data * @param Serializer $serializer * @return LegalEntity * @throws \Exception */ public static function create(array $data, Serializer $serializer) { $caseType = null; $data['caseType'] = isset($data['caseType']) ? $data['caseType'] : 'Lpa'; if (!empty($data['caseType'])) { switch ($data['caseType']) { case "Epa": $caseType = "Opg\\Core\\Model\\Entity\\CaseItem\\PowerOfAttorney\\Epa"; break; case "Order": $caseType = "Opg\\Core\\Model\\Entity\\CaseItem\\Deputyship\\Order"; break; default: $caseType = "Opg\\Core\\Model\\Entity\\CaseItem\\PowerOfAttorney\\Lpa"; break; } } else { throw new \Exception('Cannot build unknown case type.'); } try { /** @var CaseItem $case */ $case = $serializer->deserialize(json_encode($data), $caseType, 'json'); } catch (\Exception $e) { throw $e; } return $case; }
protected function deserializeUrl($content, $class) { $content['original_url'] = $content['url']; $parsedUrl = parse_url($content['url']); $urlParts = $parsedUrl; if (!empty($parsedUrl['query'])) { parse_str($parsedUrl['query'], $parsedQuery); if ($parsedQuery) { ksort($parsedQuery); $urlParts['query'] = http_build_query($parsedQuery); $content['query_param'] = $parsedQuery; } } $content['url'] = Helpers\Url::buildUrl($urlParts); /** @var Url $model */ return $this->serializer->deserialize(json_encode($content), $class, 'json'); }
/** * @param string $url * @param string $targetClass * * @return BaseResponse * * @throws RuntimeException */ protected function doGetObjectsRequest(string $url, string $targetClass) : BaseResponse { // TODO Do something on response error codes $rawResponse = $this->client->get($url); // TODO Catch error on malformatted json $deserializedResponse = $this->serializer->deserialize($rawResponse->getContent(), $targetClass, 'json'); return $deserializedResponse; }
/** * @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; }
/** * Save a listview * * @param ListView $view * * @return ListView */ public function save(ListView $view) { $data = $this->serializer->deserialize($view->getConditions(), 'Opifer\\RulesEngine\\Rule\\Rule', 'json'); $view->setConditions($data); // Transform column data to the correct format. // $columns = []; // foreach ($view->getColumns() as $column) { // $columns[] = [ // 'property' => $column, // 'type' => 'string' // Change to get the right type // ]; // } // $view->setColumns(json_encode($columns)); $this->em->persist($view); $this->em->flush(); return $view; }
/** * @param string $username * * @return Translations|null */ private function loadFromStorage($username) { $filename = $this->getInfoFilename($username); if (false == file_exists($filename)) { return null; } $content = file_get_contents($filename); $catalogue = $this->serializer->deserialize($content, Translations::class, 'json'); return $catalogue; }