/** * {@inheritDoc} */ public function isListedPropertyCheck(PropertyMetadata $property, Context $navigatorContext) { if (empty($this->fields)) { return false; } $name = $property->serializedName ?: $property->name; switch (true) { case $property->type["name"] == "ArrayCollection": $this->classFields[$property->type["params"][0]["name"]] = $navigatorContext->getDepth() == 1 ? $name : $this->classFields[$property->class] . "." . $name; break; case strpos($property->type["name"], "\\"): $this->classFields[$property->type["name"]] = $navigatorContext->getDepth() == 1 ? $name : $this->classFields[$property->class] . "." . $name; break; default: break; } $data = $this->fields; if ($navigatorContext->getDepth() > 1) { $prefix = $this->classFields[$property->class]; $prefix_parts = explode(".", $prefix); foreach ($prefix_parts as $part) { $data = isset($data[$part]) ? $data[$part] : []; } } return isset($data[$name]); }
/** * @param AbstractVisitor $visitor * @param array $data * @param string $type * @param Context $context * @return Envelope */ public function deserializeMessage(AbstractVisitor $visitor, array $data, $type, Context $context) { $data['class'] = bernard_decode_class_string($data['class']); $type = ['name' => $data['class'], 'params' => null]; $message = new BernardTokenMessage($data['name'], $context->accept($data['args'], $type)); return $message; }
private function isTooDeep(Context $context) { $depth = $context->getDepth(); $groups = $context->attributes->get('groups')->get(); $metadataStack = $context->getMetadataStack(); $nthProperty = 0; // iterate from the first added items to the lasts for ($i = $metadataStack->count() - 1; $i > 0; $i--) { $metadata = $metadataStack[$i]; if ($metadata instanceof PropertyMetadata) { $maxDepth = null; if ($metadata->maxDepth) { if (!is_array($metadata->maxDepth)) { $maxDepth = (int) $metadata->maxDepth; } else { foreach ($groups as $group) { if (array_key_exists($group, $metadata->maxDepth) && $metadata->maxDepth[$group] > $maxDepth) { $maxDepth = $metadata->maxDepth[$group]; } } } } $nthProperty++; $relativeDepth = $depth - $nthProperty; if (null !== $maxDepth && $relativeDepth > $maxDepth) { return true; } } } return false; }
public function simpleListOfFromXml(XmlDeserializationVisitor $visitor, $node, array $type, Context $context) { $newType = array('name' => $type["params"][0]["name"], 'params' => array()); $ret = array(); foreach (explode(" ", (string) $node) as $v) { $ret[] = $context->accept($v, $newType); } return $ret; }
/** * {@inheritDoc} */ public function shouldSkipProperty(PropertyMetadata $property, Context $navigatorContext) { if (empty($this->fields)) { return false; } $name = $property->serializedName ?: $property->name; $this->trackDepth($name, $navigatorContext->getDepth()); return !in_array($name, $this->getFields()); }
/** * Transforms root of visitor with additional data based on the representation. * * @param PaginatedRepresentation $representation * @param JsonApiSerializationVisitor $visitor * @param Context $context * * @return mixed */ protected function transformRoot(PaginatedRepresentation $representation, JsonApiSerializationVisitor $visitor, Context $context) { // serialize items $data = $context->accept($representation->getItems()); $root = $visitor->getRoot(); $root['meta'] = array('page' => $representation->getPage(), 'limit' => $representation->getLimit(), 'pages' => $representation->getPages(), 'total' => $representation->getTotal()); $root['links'] = array('first' => $this->getUriForPage(1), 'last' => $this->getUriForPage($representation->getPages()), 'next' => $representation->hasNextPage() ? $this->getUriForPage($representation->getNextPage()) : null, 'previous' => $representation->hasPreviousPage() ? $this->getUriForPage($representation->getPreviousPage()) : null); $visitor->setRoot($root); return $data; }
/** * @param VisitorInterface $visitor * @param array $data * @param array $type * @param Context $context * * @return PageBridge */ public function doDeserialize(VisitorInterface $visitor, array $data, array $type, Context $context) { $document = $context->accept($data['document'], ['name' => PageDocument::class]); $structure = $this->structureFactory->getStructureMetadata('page', $data['structure']); $bridge = new PageBridge($structure, $this->inspector, $this->propertyFactory, $document); // filthy hack to set the Visitor::$result to null and force the // serializer to return the Bridge and not the Document $visitor->setNavigator($context->getNavigator()); return $bridge; }
/** * @param Context $context * @param array|string $groups * @param string|integer $version */ protected function applyExclusionStrategies(Context $context, $groups = null, $version = null) { $context->enableMaxDepthChecks(); if ($groups !== null) { $context->setGroups($groups); } if ($version !== null) { $context->setVersion($version); } }
/** * {@inheritDoc} */ public function shouldSkipProperty(PropertyMetadata $property, Context $navigatorContext) { $name = $property->serializedName ?: $property->name; if (!in_array($name, $this->fields)) { return false; } if ($navigatorContext->getDepth() == 1) { return false; } return true; }
public function serializeCollection(VisitorInterface $visitor, Collection $collection, array $type, Context $context) { // We change the base type, and pass through possible parameters. $type['name'] = 'array'; //don't include items that will produce null elements $dataArray = []; foreach ($collection->toArray() as $element) { if (!$context->isVisiting($element)) { $dataArray[] = $element; } } return $visitor->visitArray($dataArray, $type, $context); }
/** * @param PropertyMetadata $property * @param Context $context * @return bool */ public function shouldSkipProperty(PropertyMetadata $property, Context $context) { $plainFields = $this->transformToPlainArray($this->scope); if ($property->name == 'id') { return false; } $stack = $this->getStackAsString($context->getMetadataStack()); if ($stack) { $propertyInStack = $stack . '.' . $property->name; return !in_array($propertyInStack, $plainFields); } return !in_array($property->name, $plainFields); }
/** * {@inheritDoc} */ public function shouldSkipProperty(PropertyMetadata $property, Context $navigatorContext) { // name,{main_address:[zip_code,{point:[latitude,longitude]}]} $filteredMetadataStack = $this->filterMetadataStack($navigatorContext->getMetadataStack()); $filteredMetadataStack->push($property); $part = $this->fields; foreach ($filteredMetadataStack as $curKey) { $part = $this->findArrayPart($this->namingStrategy->translateName($curKey), $part); } if ($part != false) { return false; } return true; }
public function shouldSkipProperty(PropertyMetadata $property, Context $context) { if ($context instanceof DeserializationContext) { return false; } $data = $context->getObject(); if ($data instanceof \Staffim\DTOBundle\Hateoas\CollectionRepresentation) { return false; } if ($property->class == 'Hateoas\\Configuration\\Relation') { return false; } return is_object($data) && $property->getValue($data) === UnknownValue::create(); }
/** * @param \JMS\Serializer\VisitorInterface $visitor * @param \JMS\Serializer\Context $context * @return string */ private function getFieldPath(VisitorInterface $visitor, Context $context) { $path = ''; foreach ($context->getMetadataStack() as $element) { if ($element instanceof PropertyMetadata) { $name = $element->serializedName !== null ? $element->serializedName : $element->name; if ($visitor instanceof AbstractVisitor) { $name = $visitor->getNamingStrategy()->translateName($element); } $path = $name . self::PATH_FIELD_SEPARATOR . $path; } } $path = rtrim($path, self::PATH_FIELD_SEPARATOR); return $path; }
private function getGroupsFor(Context $navigatorContext) { $paths = $navigatorContext->getCurrentPath(); $groups = $this->groups; foreach ($paths as $index => $path) { if (!array_key_exists($path, $groups)) { if ($index > 0) { $groups = array('Default'); } break; } $groups = $groups[$path]; } return $groups; }
/** * {@inheritdoc} */ public function shouldSkipProperty(PropertyMetadata $property, Context $context) { if (!$context instanceof SerializationContext) { return false; } /** @var \Mango\Bundle\JsonApiBundle\Configuration\Metadata\ClassMetadata $metadata */ $metadata = $this->metadataFactory->getMetadataForClass(get_class($context->getObject())); if ($metadata) { foreach ($metadata->getRelationships() as $relationship) { if ($property->name === $relationship->getName()) { return true; } } } return false; }
/** * Whether the property should be skipped. * * @param PropertyMetadata $property * * @return boolean */ public function shouldSkipProperty(PropertyMetadata $property, Context $context) { switch ($context->getDirection()) { case GraphNavigator::DIRECTION_SERIALIZATION: if (isset($property->exposeToSerialize) && $property->exposeToSerialize !== true) { return true; } break; case GraphNavigator::DIRECTION_DESERIALIZATION: if (isset($property->exposeToDeserialize) && $property->exposeToDeserialize !== true) { return true; } break; } return false; }
public function resolveResponseContentType(XmlDeserializationVisitor $visitor, $data, array $type, Context $context) { $operation = $visitor->getCurrentObject()->getHead()->getOperation(); switch ($operation) { case OperationType::OPERATION_PAYMENT_INIT: $type['name'] = 'PHPCommerce\\Vendor\\RatePAY\\Service\\Payment\\Type\\Response\\PaymentInitResponseType'; return $context->accept($data, $type); break; case OperationType::OPERATION_PAYMENT_REQUEST: $type['name'] = 'PHPCommerce\\Vendor\\RatePAY\\Service\\Payment\\Type\\Response\\PaymentRequestResponseType'; return $context->accept($data, $type); break; case OperationType::OPERATION_PAYMENT_CONFIRM: $type['name'] = 'PHPCommerce\\Vendor\\RatePAY\\Service\\Payment\\Type\\Response\\PaymentConfirmResponseType'; return $context->accept($data, $type); break; case OperationType::OPERATION_PAYMENT_CHANGE: $type['name'] = 'PHPCommerce\\Vendor\\RatePAY\\Service\\Payment\\Type\\Response\\PaymentChangeResponseType'; return $context->accept($data, $type); break; case OperationType::OPERATION_CONFIRMATION_DELIVER: $type['name'] = 'PHPCommerce\\Vendor\\RatePAY\\Service\\Payment\\Type\\Response\\ConfirmationDeliverResponseType'; return $context->accept($data, $type); break; case OperationType::OPERATION_CONFIGURATION_REQUEST: $type['name'] = 'PHPCommerce\\Vendor\\RatePAY\\Service\\Payment\\Type\\Response\\ConfigurationResponseType'; return $context->accept($data, $type); break; default: throw new RuntimeException("Unknown Operation: " . $operation); break; } }
private function isTooDeep(Context $context) { $depth = $context->getDepth(); $metadataStack = $context->getMetadataStack(); $nthProperty = 0; // iterate from the first added items to the lasts for ($i = $metadataStack->count() - 1; $i > 0; $i--) { $metadata = $metadataStack[$i]; if ($metadata instanceof PropertyMetadata) { $nthProperty++; $relativeDepth = $depth - $nthProperty; if (null !== $metadata->maxDepth && $relativeDepth > $metadata->maxDepth) { return true; } } } return false; }
/** * @param JsonApiSerializationVisitor $visitor * @param Pagerfanta $pagerfanta * @param array $type * @param Context $context * @return Pagerfanta */ public function serializePagerfanta(JsonApiSerializationVisitor $visitor, Pagerfanta $pagerfanta, array $type, Context $context) { $request = $this->requestStack->getCurrentRequest(); $pagerfanta->setNormalizeOutOfRangePages(true); $pagerfanta->setAllowOutOfRangePages(true); $pagerfanta->setMaxPerPage($request->get('page[limit]', $this->paginationOptions['limit'], true)); $pagerfanta->setCurrentPage($request->get('page[number]', 1, true)); $results = $pagerfanta->getCurrentPageResults(); if ($results instanceof \ArrayIterator) { $results = $results->getArrayCopy(); } $data = $context->accept($results); $root = $visitor->getRoot(); $root['meta'] = array('page' => $pagerfanta->getCurrentPage(), 'limit' => $pagerfanta->getMaxPerPage(), 'pages' => $pagerfanta->getNbPages(), 'total' => $pagerfanta->getNbResults()); $root['links'] = array('first' => $this->getUriForPage(1), 'last' => $this->getUriForPage($pagerfanta->getNbPages()), 'prev' => $pagerfanta->hasPreviousPage() ? $this->getUriForPage($pagerfanta->getPreviousPage()) : null, 'next' => $pagerfanta->hasNextPage() ? $this->getUriForPage($pagerfanta->getNextPage()) : null); $visitor->setRoot($root); return $data; }
public function serializeFormViewToJson(JsonSerializationVisitor $visitor, FormView $formView, array $type, Context $context) { $output = array(); if (!$formView->vars['valid']) { if ($formView->vars['errors']) { foreach ($formView->vars['errors'] as $error) { $output['global'] = $error->getMessage(); } } foreach ($formView->children as $fieldName => $child) { if (!$child->vars['valid']) { foreach ($child->vars['errors'] as $error) { $output[$fieldName] = $error->getMessage(); } } } } return $context->accept($output); }
/** * @param AbstractVisitor $visitor * @param array $data * @param string $type * @param Context $context * @return Envelope */ public function deserializeToken(AbstractVisitor $visitor, array $data, $type, Context $context) { $token = new Token(); $token->setLocation($data['location']); foreach ($data['data'] as $datum) { $type = $datum['type']; if ($type['name'] === 'array') { $argsData = []; foreach ($datum['args'] as $arrayData) { $arrayKey = $arrayData['key']; $argsData[$arrayKey] = $context->accept($arrayData['args'], $arrayData['type']); } } else { $argsData = $context->accept($datum['args'], $type); } $token->setData($datum['key'], $argsData); } return $token; }
public function visitProperty(PropertyMetadata $metadata, $data, Context $context) { $name = $this->namingStrategy->translateName($metadata); $types = array('NULL', 'string', 'integer', 'boolean', 'double', 'float', 'array', 'ArrayCollection'); if (isset($data[$name]) && is_scalar($data[$name]) && !in_array($metadata->type['name'], $types)) { /** @var DeserializationContext $context */ $context->useDoctrineConstructor(); $data[$name] = array('id' => $data[$name]); } if (null === $data || is_array($data) && !array_key_exists($name, $data)) { return; } if (!$metadata->type) { throw new RuntimeException(sprintf('You must define a type for %s::$%s.', $metadata->reflection->class, $metadata->name)); } $v = $data[$name] !== null ? $this->getNavigator()->accept($data[$name], $metadata->type, $context) : null; if (null === $metadata->setter) { $metadata->reflection->setValue($this->getCurrentObject(), $v); return; } $this->getCurrentObject()->{$metadata->setter}($v); }
/** * @param VisitorInterface $visitor * @param mixed $data * @param array $type * @param Context $context * @return array|null * @throws RuntimeException If $data contains more elements than $type['params'] */ public function deserializeJobParameterArray(VisitorInterface $visitor, $data, array $type, Context $context) { /** * If $type['params'] is not set this most likely means, that a job is being deserialized, so we check if the JobDeserializationSubscriber set the type of params at the end of the $data array * * @see JobDeserializationSubscriber::onPreDeserialize() */ $deserializeJob = false; if (count($type['params']) == 0 && is_array($data) && is_array(end($data)) && in_array('abc.job.type', array_keys(end($data)))) { $jobType = $this->extractJobType($data); $type['params'] = $this->getParamTypes($jobType); $deserializeJob = true; } if (is_array($data) && count($data) > count($type['params'])) { throw new RuntimeException(sprintf('Invalid job parameters, the parameters contain more elements that defined (%s)', implode(',', $type['params']))); } $result = []; for ($i = 0; $i < count($type['params']); $i++) { if (!is_array($data) || !isset($data[$i]) || null == $data[$i]) { $result[$i] = null; } else { if (!is_array($type['params'][$i])) { $type['params'][$i] = ['name' => $type['params'][$i], 'params' => array()]; } $result[$i] = $context->accept($data[$i], $type['params'][$i]); } } if (count($data) > 0 && !$deserializeJob) { /** * Since serializer always returns the result of $context->accept unless visitor result is empty, * we have to make sure that the visitor result is null in case only root is type JobParameterArray::class * * @see Serializer::handleDeserializeResult() */ $visitor->setNavigator($context->getNavigator()); } return $result; }
private function visit(VisitorInterface $visitor, Context $context, $data, $format, array $type = null) { $context->initialize($format, $visitor, $this->navigator, $this->factory); $visitor->setNavigator($this->navigator); return $this->navigator->accept($data, $type, $context); }
public function visitProperty(PropertyMetadata $metadata, $object, Context $context) { $v = $metadata->getValue($object); if (null === $v && !$context->shouldSerializeNull()) { return; } if ($metadata->xmlAttribute) { $this->setCurrentMetadata($metadata); $node = $this->navigator->accept($v, $metadata->type, $context); $this->revertCurrentMetadata(); if (!$node instanceof \DOMCharacterData) { throw new RuntimeException(sprintf('Unsupported value for XML attribute for %s. Expected character data, but got %s.', $metadata->name, json_encode($v))); } $attributeName = $this->namingStrategy->translateName($metadata); $this->setAttributeOnNode($this->currentNode, $attributeName, $node->nodeValue, $metadata->xmlNamespace); return; } if ($metadata->xmlValue && $this->currentNode->childNodes->length > 0 || !$metadata->xmlValue && $this->hasValue) { throw new RuntimeException(sprintf('If you make use of @XmlValue, all other properties in the class must have the @XmlAttribute annotation. Invalid usage detected in class %s.', $metadata->class)); } if ($metadata->xmlValue) { $this->hasValue = true; $this->setCurrentMetadata($metadata); $node = $this->navigator->accept($v, $metadata->type, $context); $this->revertCurrentMetadata(); if ($node !== null) { if (!$node instanceof \DOMCharacterData) { throw new RuntimeException(sprintf('Unsupported value for property %s::$%s. Expected character data, but got %s.', $metadata->reflection->class, $metadata->reflection->name, is_object($node) ? get_class($node) : gettype($node))); } $this->currentNode->appendChild($node); } return; } if ($metadata->xmlAttributeMap) { if (!is_array($v)) { throw new RuntimeException(sprintf('Unsupported value type for XML attribute map. Expected array but got %s.', gettype($v))); } foreach ($v as $key => $value) { $this->setCurrentMetadata($metadata); $node = $this->navigator->accept($value, null, $context); $this->revertCurrentMetadata(); if (!$node instanceof \DOMCharacterData) { throw new RuntimeException(sprintf('Unsupported value for a XML attribute map value. Expected character data, but got %s.', json_encode($v))); } $this->setAttributeOnNode($this->currentNode, $key, $node->nodeValue, $metadata->xmlNamespace); } return; } if ($addEnclosingElement = (!$metadata->xmlCollection || !$metadata->xmlCollectionInline) && !$metadata->inline) { $elementName = $this->namingStrategy->translateName($metadata); if (null !== $metadata->xmlNamespace) { $element = $this->createElement($elementName, $metadata->xmlNamespace); } else { $defaultNamespace = $this->getClassDefaultNamespace($this->objectMetadataStack->top()); $element = $this->createElement($elementName, $defaultNamespace); } $this->setCurrentNode($element); } $this->setCurrentMetadata($metadata); if (null !== ($node = $this->navigator->accept($v, $metadata->type, $context))) { $this->currentNode->appendChild($node); } $this->revertCurrentMetadata(); if ($addEnclosingElement) { $this->revertCurrentNode(); if ($element->hasChildNodes() || $element->hasAttributes() || $node === null && $v !== null) { $this->currentNode->appendChild($element); } } $this->hasValue = false; }
/** * Normalize wrapper to serialize with xml * Event class name is added * * @param XmlSerializationVisitor $visitor * @param EventContainer $container * @param array $type * @param Context $context */ public function serializeContainerXml(XmlSerializationVisitor $visitor, EventContainer $container, array $type, Context $context) { if (!$visitor->getDocument()) { /** @var ClassMetadata $metadata */ $metadata = $context->getMetadataFactory()->getMetadataForClass(__NAMESPACE__ . '\\EventContainer'); $metadata->xmlRootName = 'event'; $visitor->startVisitingObject($metadata, $container, [], $context); // $visitor->visitArray([], ['name' => 'array'], $context); } $event = $container->getEvent(); $node = $visitor->getCurrentNode(); $node->setAttribute('type', $this->namingStrategy->classToType(get_class($event))); $data = $visitor->getDocument()->createElement('data'); $visitor->getCurrentNode()->appendChild($data); $visitor->setCurrentNode($data); $visitor->getNavigator()->accept($event, null, $context); $visitor->revertCurrentNode(); }
/** * @param $object * @param Relationship $relationship * @param Context $context * * @return array */ protected function processRelationship($object, Relationship $relationship, Context $context) { if (null === $object) { return null; } if (!is_object($object)) { throw new \RuntimeException(sprintf('Cannot process relationship "%s", because it is not an object but a %s.', $relationship->getName(), gettype($object))); } /** @var ClassMetadata $relationshipMetadata */ $relationshipMetadata = $this->hateoasMetadataFactory->getMetadataForClass(get_class($object)); if (null === $relationshipMetadata) { throw new \RuntimeException(sprintf('Metadata for class %s not found. Did you define at as a JSON-API resource?', ClassUtils::getRealClass(get_class($object)))); } $relationshipId = $this->getId($relationshipMetadata, $object); // contains the relations type and id $relationshipDataArray = $this->getRelationshipDataArray($relationshipMetadata, $relationshipId); // only include this relationship if it is needed if ($relationship->isIncludedByDefault() && $this->canIncludeRelationship($relationshipMetadata, $relationshipId)) { $includedRelationship = $relationshipDataArray; // copy data array so we do not override it with our reference $this->includedRelationships[] =& $includedRelationship; $includedRelationship = $context->accept($object); // override previous reference with the serialized data } // the relationship data can only contain one reference to another resource return $relationshipDataArray; }
/** * Fill a jms context. * * @param ContextInterface $context * @param JMSContext $newContext * * @return JMSContext */ private function fillContext(ContextInterface $context, JMSContext $newContext) { foreach ($context->getAttributes() as $key => $value) { $newContext->attributes->set($key, $value); } if ($context instanceof VersionableContextInterface && null !== $context->getVersion()) { $newContext->setVersion($context->getVersion()); } if ($context instanceof GroupableContextInterface) { $groups = $context->getGroups(); if (!empty($groups)) { $newContext->setGroups($context->getGroups()); } } if ($context instanceof MaxDepthContextInterface && null !== $context->getMaxDepth()) { $newContext->enableMaxDepthChecks(); } if ($context instanceof SerializeNullContextInterface && null !== $context->getSerializeNull()) { $newContext->setSerializeNull($context->getSerializeNull()); } return $newContext; }
private function leaveScope(Context $context, $data) { if ($context instanceof SerializationContext) { $context->stopVisiting($data); } elseif ($context instanceof DeserializationContext) { $context->decreaseDepth(); } }