/** * Create serializer * * @throws \Exception */ private function createSerializer() { $sb = SerializerBuilder::create(); if ($this->serializationVisitor) { $sb->setSerializationVisitor($this->format, $this->serializationVisitor); } else { // set format if ('json' === $this->format) { $sv = new JsonSerializationVisitor(new SerializedNameAnnotationStrategy(new IdenticalPropertyNamingStrategy())); $sv->setOptions($this->jsonOptions); $sb->setSerializationVisitor($this->format, $sv); } else { if ('xml' === $this->format) { $sb->setSerializationVisitor('xml', new XmlSerializationVisitor(new SerializedNameAnnotationStrategy(new IdenticalPropertyNamingStrategy()))); } else { throw new \Exception('Format "' . $this->format . '"is not supported and serializationVisitor is not net'); } } } // chache dir if ($this->cacheDir) { $sb->setCacheDir($this->cacheDir); } // debugging $sb->setDebug($this->debug); $this->serializer = $sb->build(); }
/** * {@inheritdoc} */ public function serializeEmbedded(array $embeds, JsonSerializationVisitor $visitor, SerializationContext $context) { $serializedEmbeds = array(); foreach ($embeds as $embed) { $serializedEmbeds[$embed->getRel()] = $context->accept($embed->getData()); } $visitor->addData('_embedded', $serializedEmbeds); }
/** * Serialize extref to JSON * * @param JsonSerializationVisitor $visitor Visitor * @param ExtReference $extReference Extref * @param array $type Type * @param Context $context Context * @return string|null */ public function serializeExtReferenceToJson(JsonSerializationVisitor $visitor, ExtReference $extReference, array $type, Context $context) { try { return $visitor->visitString($this->converter->getUrl($extReference), $type, $context); } catch (\InvalidArgumentException $e) { return $visitor->visitNull(null, $type, $context); } }
public function serializeViolationToJson(JsonSerializationVisitor $visitor, ConstraintViolation $violation, array $type = null) { $data = array('property_path' => $violation->getPropertyPath(), 'message' => $violation->getMessage()); if (null === $visitor->getRoot()) { $visitor->setRoot($data); } return $data; }
/** * @param JsonSerializationVisitor $visitor * @param ConstraintViolationInterface $violation * @return array */ public function serializeToJson(JsonSerializationVisitor $visitor, ConstraintViolationInterface $violation) { $data = array('propertyPath' => $this->transformPropertyPath($violation->getPropertyPath()), 'message' => $violation->getMessage(), 'code' => $violation->getCode(), 'value' => $violation->getInvalidValue()); if (null === $visitor->getRoot()) { $visitor->setRoot($data); } return $data; }
/** * Serialize the Enum object to json. * * @param JsonSerializationVisitor $visitor The visitor * @param EnumInterface $data A EnumInterface instance * @param array $type The type parameters * * @return mixed */ public function serializeEnumToJson(JsonSerializationVisitor $visitor, EnumInterface $data, array $type) { $value = $data->getValue(); if ($visitor->getRoot() === null) { $visitor->setRoot($value); } return $value; }
public function userSerializeToJson(JsonSerializationVisitor $visitor, UserInterface $user, array $type) { $isRoot = null === $visitor->getRoot(); $json = self::$subHandler['user']->serializeToJson($visitor, $user, $type); if ($isRoot) { $visitor->setRoot($json); } return $json; }
/** * * @param * @param * @param * @return */ public function serializeToJson(JsonSerializationVisitor $visitor, MessageText $messageText, array $type) { $isRoot = null === $visitor->getRoot(); $json = array(); $json['message'] = utf8_encode($messageText->getMessage()); if ($isRoot) { $visitor->setRoot($json); } return $json; }
public function serializeToJson(JsonSerializationVisitor $visitor, UserInterface $user, array $type) { $isRoot = null === $visitor->getRoot(); $tt = array(); $tt['pseudo'] = $user->getPseudo(); if ($isRoot) { $visitor->setRoot($tt); } return $tt; }
/** * Test ExtReferenceHandler::serializeExtReferenceToJson() * * @return void */ public function testSerializeExtReferenceToJson() { $type = [__LINE__]; $context = SerializationContext::create(); $url = __FUNCTION__; $extref = ExtReference::create(__METHOD__, __FILE__); $this->converter->expects($this->once())->method('getUrl')->with($extref)->willReturn($url); $this->serializationVisitor->expects($this->once())->method('visitString')->with($url, $type, $context)->willReturn($url); $handler = new ExtReferenceHandler($this->converter); $this->assertEquals($url, $handler->serializeExtReferenceToJson($this->serializationVisitor, $extref, $type, $context)); }
public function deserializeEntity(JsonSerializationVisitor $visitor, $properties, array $type, Context $context) { /** @var EntityAccessor $entityAccessor */ $entityAccessor = $GLOBALS['container']['doctrine.orm.entityAccessor']; $entityClassName = $properties['__ENTITY_CLASS__']; $entityClass = new \ReflectionClass($entityClassName); $entity = $entityClass->newInstance(); unset($properties['__ENTITY_CLASS__']); $properties = $visitor->visitArray($properties, $type, $context); $entityAccessor->setRawProperties($entity, $properties); return $entity; }
public function write(OutputInterface $output, $fileCollection) { $commentedFiles = $fileCollection->getCommentedFiles(); $jsonVisitor = new JsonSerializationVisitor(new SerializedNameAnnotationStrategy(new CamelCaseNamingStrategy())); $jsonVisitor->setOptions(JSON_PRETTY_PRINT); $xmlVisitor = new XmlSerializationVisitor(new SerializedNameAnnotationStrategy(new CamelCaseNamingStrategy())); $serializer = SerializerBuilder::create()->setSerializationVisitor('json', $jsonVisitor)->setSerializationVisitor('xml', $xmlVisitor)->build(); if (!empty($this->outputFile)) { file_put_contents($this->outputFile, $serializer->serialize($commentedFiles, $this->outputFormat)); return; } $output->write($serializer->serialize($commentedFiles, $this->outputFormat)); }
public function serializeDateReferenceToJson(JsonSerializationVisitor $visitor, $obj, array $type, SerializationContext $context) { $this->LOGGER->debug("Serializing DateReference: " . print_r($obj, true)); $type['name'] = 'array'; if (get_class($obj) == "UR\\DB\\NewBundle\\Utils\\DateRange") { //date range found $dateRangeArray = array(); $dateRangeArray['from'] = $this->dateToArray($obj->getFrom()); $dateRangeArray['to'] = $this->dateToArray($obj->getTo()); return $visitor->visitArray($dateRangeArray, $type, $context); } else { $dateArray = $this->dateToArray($obj); return $visitor->visitArray($dateArray, $type, $context); } }
/** * {@inheritdoc} */ public function serializeEmbeddeds(array $embeddeds, JsonSerializationVisitor $visitor, SerializationContext $context) { $serializedEmbeddeds = array(); $multiple = array(); foreach ($embeddeds as $embedded) { if (!isset($serializedEmbeddeds[$embedded->getRel()])) { $serializedEmbeddeds[$embedded->getRel()] = $context->accept($embedded->getData()); } elseif (!isset($multiple[$embedded->getRel()])) { $multiple[$embedded->getRel()] = true; $serializedEmbeddeds[$embedded->getRel()] = array($serializedEmbeddeds[$embedded->getRel()], $context->accept($embedded->getData())); } else { $serializedEmbeddeds[$embedded->getRel()][] = $context->accept($embedded->getData()); } } $visitor->addData('_embedded', $serializedEmbeddeds); }
/** * * @param string $cacheDir * @param string $metadataDir * @param bool $debug */ public function __construct($cacheDir, $metadataDir, $debug = false) { $serializerBuilder = SerializerBuilder::create(); $serializerBuilder->setCacheDir($cacheDir)->setDebug($debug)->addMetadataDir($metadataDir); $propertyNamingStrategy = new SerializedNameAnnotationStrategy(new CamelCaseNamingStrategy()); $serializerBuilder->setPropertyNamingStrategy($propertyNamingStrategy); $serializerBuilder->addDefaultSerializationVisitors(); $serializerBuilder->addDefaultDeserializationVisitors(); $jsonSerializationVisitor = new JsonSerializationVisitor($propertyNamingStrategy); $jsonSerializationVisitor->setOptions(JSON_PRETTY_PRINT); $xmlSerializationVisitor = new XmlSerializationVisitor($propertyNamingStrategy); $xmlSerializationVisitor->setDefaultRootName('config'); $serializerBuilder->setSerializationVisitor('json', $jsonSerializationVisitor); $serializerBuilder->setSerializationVisitor('xml', $xmlSerializationVisitor); $this->serializer = $serializerBuilder->build(); }
public function getResult() { if(!defined('JSON_UNESCAPED_SLASHES')) { return str_replace('\/', '/', parent::getResult()); } else { return parent::getResult(); } }
public function endVisitingObject(JMSClassMetadata $metadata, $data, array $type, Context $context) { $rs = parent::endVisitingObject($metadata, $data, $type, $context); if (empty($rs)) { return null; } $isSaveChanges = $context instanceof SaveChangesContextInterface; if ($this->isProxyObject($data) && ($isSaveChanges || !$data->__isInitialized())) { return null; } try { $doctrineMeta = $this->entityManager->getClassMetadata($metadata->name); if ($doctrineMeta) { $rs['$type'] = strtr($type['name'], '\\', '.'); foreach ($doctrineMeta->associationMappings as $associationMapping) { $foreignKey = $associationMapping['fieldName'] . 'Id'; if (isset($rs[$foreignKey])) { continue; } $isScalar = in_array((int) $associationMapping['type'], array(ClassMetadata::ONE_TO_ONE, ClassMetadata::MANY_TO_ONE)); $isOwningSide = isset($associationMapping['isOwningSide']) ? $associationMapping['isOwningSide'] : false; if (!($isScalar && $isOwningSide)) { continue; } try { $getter = 'get' . $associationMapping['fieldName']; if (method_exists($data, $getter)) { $association = $data->{$getter}(); } else { $refl = new \ReflectionClass($data); if ($this->isProxyObject($data)) { $refl = $refl->getParentClass(); } try { $prop = $refl->getProperty($associationMapping['fieldName']); $prop->setAccessible(true); $association = $prop->getValue($data); } catch (\ReflectionException $e) { } } if ($association) { try { $id = $association->getId(); $rs[$foreignKey] = $id; } catch (\Exception $e) { } } } catch (\ReflectionException $e) { // continue; } } } } catch (\Exception $e) { return $rs; } return $rs; }
/** * @return Serializer */ private function getSerializer() { if ($this->serializer) { return $this->serializer; } $propertyNamingStrategy = new SerializedNameAnnotationStrategy(new CamelCaseNamingStrategy()); $visitor = new JsonSerializationVisitor($propertyNamingStrategy); $visitor->setOptions(JSON_UNESCAPED_UNICODE); return $this->serializer = SerializerBuilder::create()->setPropertyNamingStrategy($propertyNamingStrategy)->configureHandlers(function (HandlerRegistryInterface $registry) { $registry->registerSubscribingHandler(new CarbonHandler()); $registry->registerSubscribingHandler(new RecurringHandler()); $registry->registerSubscribingHandler(new DependsHandler($this)); })->addDefaultHandlers()->setSerializationVisitor('json', $visitor)->addDefaultDeserializationVisitors()->build(); }
/** * @param JsonSerializationVisitor $visitor * @param Comment $comment * @param array $type * @param Context $context * * @return array|\ArrayObject */ public function serializeToJson(JsonSerializationVisitor $visitor, Comment $comment, array $type, Context $context) { $data = $this->getCommentData($comment); return $visitor->visitArray($data, $type, $context); }
/** * Serialize ArrayObject * * @param JsonSerializationVisitor $visitor Visitor * @param \ArrayObject $data Data * @param array $type Type * @param Context $context Context * @return \ArrayObject */ public function serializeArrayObjectToJson(JsonSerializationVisitor $visitor, \ArrayObject $data, array $type, Context $context) { return new \ArrayObject($visitor->visitArray($data->getArrayCopy(), $type, $context)); }
/** * @param JsonSerializationVisitor $visitor * @param Tag $tag * @param array $type * @param Context $context * * @return array|\ArrayObject */ public function serializeToJson(JsonSerializationVisitor $visitor, Tag $tag, array $type, Context $context) { $data = $this->getTagData($tag); return $visitor->visitArray($data, $type, $context); }
/** * {@inheritdoc} */ public function endVisitingObject(ClassMetadata $metadata, $data, array $type, Context $context) { $rs = parent::endVisitingObject($metadata, $data, $type, $context); if ($rs instanceof \ArrayObject) { $rs = []; $this->setRoot($rs); return $rs; } /** @var JsonApiClassMetadata $jsonApiMetadata */ $jsonApiMetadata = $this->metadataFactory->getMetadataForClass(get_class($data)); if (null === $jsonApiMetadata) { return $rs; } $result = array(); if (isset($rs[JsonEventSubscriber::EXTRA_DATA_KEY]['type'])) { $result['type'] = $rs[JsonEventSubscriber::EXTRA_DATA_KEY]['type']; } if (isset($rs[JsonEventSubscriber::EXTRA_DATA_KEY]['id'])) { $result['id'] = $rs[JsonEventSubscriber::EXTRA_DATA_KEY]['id']; } $idField = $jsonApiMetadata->getIdField(); $result['attributes'] = array_filter($rs, function ($key) use($idField) { switch ($key) { case $idField: case 'relationships': case 'links': return false; } if ($key === JsonEventSubscriber::EXTRA_DATA_KEY) { return false; } return true; }, ARRAY_FILTER_USE_KEY); if (isset($rs['relationships'])) { $result['relationships'] = $rs['relationships']; } if (isset($rs['links'])) { $result['links'] = $rs['links']; } return $result; }
public function getResult() { return str_replace('\\/', '/', parent::getResult()); }
/** * @param JsonSerializationVisitor $visitor * @param ExceptionWrapper $wrapper * @param array $type * @param Context $context * * @return array */ public function serializeToJson(JsonSerializationVisitor $visitor, ExceptionWrapper $wrapper, array $type, Context $context) { $data = $this->convertToArray($wrapper); return $visitor->visitArray($data, $type, $context); }
/** * Extract custom-url and add them to serialization. * * @param Webspace $webspace * @param Context $context * @param JsonSerializationVisitor $visitor */ private function appendCustomUrls(Webspace $webspace, Context $context, JsonSerializationVisitor $visitor) { $customUrls = []; foreach ($webspace->getPortals() as $portal) { $customUrls = array_merge($customUrls, $this->getCustomUrlsForEnvironment($portal, $portal->getEnvironment($this->environment), $context)); } $customUrls = $context->accept($customUrls); $visitor->addData('customUrls', $customUrls); }
public function serializePagerfantaToJson(JsonSerializationVisitor $visitor, Pagerfanta $pagerfanta, array $type, Context $context) { $type['name'] = 'array'; return ['items' => $visitor->visitArray((array) $pagerfanta->getCurrentPageResults(), $type, $context), 'pages_count' => $pagerfanta->getNbPages(), 'current_page' => $pagerfanta->getCurrentPage(), 'max_per_page' => $pagerfanta->getMaxPerPage(), 'items_count' => $pagerfanta->count()]; }
/** * @param JsonSerializationVisitor $visitor * @param RollingUpdateDeployment $rollingUpdateDeployment * @param array $type * @param Context $context * * @return array */ public function serializeRollingUpdateDeployment(JsonSerializationVisitor $visitor, RollingUpdateDeployment $rollingUpdateDeployment, array $type, Context $context) { $representation = ['maxUnavailable' => $this->castToStringOrInteger($rollingUpdateDeployment->getMaxUnavailable()), 'maxSurge' => $this->castToStringOrInteger($rollingUpdateDeployment->getMaxSurge())]; return $visitor->visitArray($representation, $type, $context); }
/** @HandlerCallback("json", direction = "serialization") */ public function serializeToJson(JsonSerializationVisitor $visitor) { $visitor->setRoot(array($this->element => $this->value)); }
/** * {@inheritDoc} */ public function getServiceConfig() { return array('aliases' => array('jms_serializer.metadata_driver' => 'jms_serializer.metadata.chain_driver', 'jms_serializer.object_constructor' => 'jms_serializer.unserialize_object_constructor'), 'factories' => array('jms_serializer.handler_registry' => new HandlerRegistryFactory(), 'jms_serializer.datetime_handler' => function (ServiceManager $sm) { $options = $sm->get('Configuration'); $options = new Handlers($options['jms_serializer']['handlers']); $dateTimeOptions = $options->getDatetime(); return new DateHandler($dateTimeOptions['default_format'], $dateTimeOptions['default_timezone']); }, 'jms_serializer.event_dispatcher' => new EventDispatcherFactory(), 'jms_serializer.metadata.cache' => new MetadataCacheFactory(), 'jms_serializer.metadata.yaml_driver' => new MetadataDriverFactory('JMS\\Serializer\\Metadata\\Driver\\YamlDriver'), 'jms_serializer.metadata.xml_driver' => new MetadataDriverFactory('JMS\\Serializer\\Metadata\\Driver\\XmlDriver'), 'jms_serializer.metadata.php_driver' => new MetadataDriverFactory('JMS\\Serializer\\Metadata\\Driver\\PhpDriver'), 'jms_serializer.metadata.file_locator' => function (ServiceManager $sm) { $options = $sm->get('Configuration'); $options = new Metadata($options['jms_serializer']['metadata']); $directories = array(); foreach ($options->getDirectories() as $directory) { if (!isset($directory['path'], $directory['namespace_prefix'])) { throw new \RuntimeException(sprintf('The directory must have the attributes "path" and "namespace_prefix, "%s" given.', implode(', ', array_keys($directory)))); } $directories[rtrim($directory['namespace_prefix'], '\\')] = rtrim($directory['path'], '\\/'); } return new FileLocator($directories); }, 'jms_serializer.metadata.annotation_driver' => function (ServiceManager $sm) { $options = $sm->get('Configuration'); $options = new Metadata($options['jms_serializer']['metadata']); $reader = new AnnotationReader(); $reader = new CachedReader(new IndexedReader($reader), $sm->get($options->getAnnotationCache())); return new AnnotationDriver($reader); }, 'jms_serializer.metadata.chain_driver' => function (ServiceManager $sm) { $annotationDriver = $sm->get('jms_serializer.metadata.annotation_driver'); $phpDriver = $sm->get('jms_serializer.metadata.php_driver'); $xmlDriver = $sm->get('jms_serializer.metadata.xml_driver'); $yamlDriver = $sm->get('jms_serializer.metadata.yaml_driver'); return new DriverChain(array($yamlDriver, $xmlDriver, $phpDriver, $annotationDriver)); }, 'jms_serializer.metadata.lazy_loading_driver' => function (ServiceManager $sm) { return new LazyLoadingDriver($sm, 'jms_serializer.metadata_driver'); }, 'jms_serializer.metadata_factory' => function (ServiceManager $sm) { $options = $sm->get('Configuration'); $options = new Metadata($options['jms_serializer']['metadata']); $lazyLoadingDriver = $sm->get('jms_serializer.metadata.lazy_loading_driver'); return new MetadataFactory($lazyLoadingDriver, 'Metadata\\ClassHierarchyMetadata', $options->getDebug()); }, 'jms_serializer.camel_case_naming_strategy' => function (ServiceManager $sm) { $options = $sm->get('Configuration'); $options = new PropertyNaming($options['jms_serializer']['property_naming']); return new CamelCaseNamingStrategy($options->getSeparator(), $options->getLowercase()); }, 'jms_serializer.identical_naming_strategy' => function (ServiceManager $sm) { return new IdenticalPropertyNamingStrategy(); }, 'jms_serializer.serialized_name_annotation_strategy' => function (ServiceManager $sm) { $options = $sm->get('Configuration'); if (isset($options['jms_serializer']['naming_strategy'])) { if ($options['jms_serializer']['naming_strategy'] == 'identical') { return new SerializedNameAnnotationStrategy($sm->get('jms_serializer.identical_naming_strategy')); } } return new SerializedNameAnnotationStrategy($sm->get('jms_serializer.camel_case_naming_strategy')); }, 'jms_serializer.naming_strategy' => 'JMSSerializerModule\\Service\\NamingStrategyFactory', 'jms_serializer.json_serialization_visitor' => function (ServiceManager $sm) { $options = $sm->get('Configuration'); $options = new Visitors($options['jms_serializer']['visitors']); $jsonOptions = $options->getJson(); $vistor = new JsonSerializationVisitor($sm->get('jms_serializer.naming_strategy')); $vistor->setOptions($jsonOptions['options']); return $vistor; }, 'jms_serializer.json_deserialization_visitor' => function (ServiceManager $sm) { return new JsonDeserializationVisitor($sm->get('jms_serializer.naming_strategy'), $sm->get('jms_serializer.object_constructor')); }, 'jms_serializer.xml_serialization_visitor' => function (ServiceManager $sm) { return new XmlSerializationVisitor($sm->get('jms_serializer.naming_strategy')); }, 'jms_serializer.xml_deserialization_visitor' => function (ServiceManager $sm) { $options = $sm->get('Configuration'); $options = new Visitors($options['jms_serializer']['visitors']); $xmlOptions = $options->getXml(); $visitor = new XmlDeserializationVisitor($sm->get('jms_serializer.naming_strategy'), $sm->get('jms_serializer.object_constructor')); $visitor->setDoctypeWhitelist($xmlOptions['doctype_whitelist']); return $visitor; }, 'jms_serializer.yaml_serialization_visitor' => function (ServiceManager $sm) { return new YamlSerializationVisitor($sm->get('jms_serializer.naming_strategy')); }, 'jms_serializer.serializer' => 'JMSSerializerModule\\Service\\SerializerFactory'), 'invokables' => array('jms_serializer.unserialize_object_constructor' => 'JMS\\Serializer\\Construction\\UnserializeObjectConstructor', 'jms_serializer.array_collection_handler' => 'JMS\\Serializer\\Handler\\ArrayCollectionHandler', 'jms_serializer.doctrine_proxy_subscriber' => 'JMS\\Serializer\\EventDispatcher\\Subscriber\\DoctrineProxySubscriber')); }
/** * {@inheritdoc} */ public function endVisitingObject(ClassMetadata $metadata, $data, array $type, Context $context) { $rs = parent::endVisitingObject($metadata, $data, $type, $context); /** @var JsonApiClassMetadata $jsonApiMetadata */ $jsonApiMetadata = $this->metadataFactory->getMetadataForClass(get_class($data)); if (null === $jsonApiMetadata) { return $rs; } $idField = $jsonApiMetadata->getIdField(); if (empty($rs)) { $rs = new \ArrayObject(); if (array() === $this->getRoot()) { $this->setRoot(clone $rs); } return $rs; } $result = array(); if (isset($rs['type'])) { $result['type'] = $rs['type']; } if (isset($rs[$idField])) { $result['id'] = $rs[$idField]; } $result['attributes'] = array_filter($rs, function ($key) use($idField) { switch ($key) { case $idField: case 'type': case 'relationships': case 'links': return false; } return true; }, ARRAY_FILTER_USE_KEY); if (isset($rs['relationships'])) { $result['relationships'] = $rs['relationships']; } if (isset($rs['links'])) { $result['links'] = $rs['links']; } return $result; }