Skip to content

Use composition for Normalizers #2579

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
"symfony/http-kernel": "^3.4 || ^4.0",
"symfony/property-access": "^3.4 || ^4.0",
"symfony/property-info": "^3.4 || ^4.0",
"symfony/serializer": "^4.1",
"symfony/serializer": "4.2.x-dev",
"symfony/web-link": "^4.1",
"willdurand/negotiation": "^2.0.3"
},
Expand Down
72 changes: 72 additions & 0 deletions src/Hal/Serializer/HalItemNormalizer.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
<?php

/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <dunglas@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

declare(strict_types=1);

namespace ApiPlatform\Core\Hal\Serializer;

use Symfony\Component\Serializer\Normalizer\CacheableSupportsMethodInterface;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;

final class HalItemNormalizer implements NormalizerInterface, DenormalizerInterface, CacheableSupportsMethodInterface
{
private $normalizer;

public function __construct(NormalizerInterface $normalizer)
{
if (!$normalizer instanceof DenormalizerInterface) {
throw new \TypeError('');
}

$this->normalizer = $normalizer;
}

/**
* {@inheritdoc}
*/
public function hasCacheableSupportsMethod(): bool
{
return true;
}

/**
* {@inheritdoc}
*/
public function denormalize($data, $class, $format = null, array $context = [])
{
return $this->normalizer->denormalize($data, $class, $format, $context);
}

/**
* {@inheritdoc}
*/
public function supportsDenormalization($data, $type, $format = null)
{
return $this->normalizer->supportsDenormalization($data, $type, $format);
}

/**
* {@inheritdoc}
*/
public function normalize($object, $format = null, array $context = [])
{
return $this->normalizer->normalize($object, $format, $context);
}

/**
* {@inheritdoc}
*/
public function supportsNormalization($data, $format = null)
{
return $this->normalizer->supportsNormalization($data, $format);
}
}
76 changes: 76 additions & 0 deletions src/JsonApi/Serializer/JsonApiItemNormalizer.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
<?php

/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <dunglas@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

declare(strict_types=1);

namespace ApiPlatform\Core\JsonApi\Serializer;

use Symfony\Component\Serializer\Exception\BadMethodCallException;
use Symfony\Component\Serializer\Exception\CircularReferenceException;
use Symfony\Component\Serializer\Exception\ExceptionInterface;
use Symfony\Component\Serializer\Exception\ExtraAttributesException;
use Symfony\Component\Serializer\Exception\InvalidArgumentException;
use Symfony\Component\Serializer\Exception\LogicException;
use Symfony\Component\Serializer\Exception\RuntimeException;
use Symfony\Component\Serializer\Exception\UnexpectedValueException;
use Symfony\Component\Serializer\Normalizer\CacheableSupportsMethodInterface;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;

class JsonApiItemNormalizer implements NormalizerInterface, DenormalizerInterface, CacheableSupportsMethodInterface
{
private $normalizer;

public function __construct(NormalizerInterface $normalizer)
{
$this->normalizer = $normalizer;
}

/**
* {@inheritdoc}
*/
public function hasCacheableSupportsMethod(): bool
{
// TODO: Implement hasCacheableSupportsMethod() method.
}

/**
* {@inheritdoc}
*/
public function denormalize($data, $class, $format = null, array $context = [])
{
// TODO: Implement denormalize() method.
}

/**
* {@inheritdoc}
*/
public function supportsDenormalization($data, $type, $format = null)
{
// TODO: Implement supportsDenormalization() method.
}

/**
* {@inheritdoc}
*/
public function normalize($object, $format = null, array $context = [])
{
// TODO: Implement normalize() method.
}

/**
* {@inheritdoc}
*/
public function supportsNormalization($data, $format = null)
{
// TODO: Implement supportsNormalization() method.
}
}
165 changes: 112 additions & 53 deletions src/JsonLd/Serializer/ItemNormalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,87 +20,145 @@
use ApiPlatform\Core\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
use ApiPlatform\Core\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface;
use ApiPlatform\Core\Serializer\AbstractItemNormalizer;
use ApiPlatform\Core\Serializer\ContextTrait;
use ApiPlatform\Core\Util\ClassInfoTrait;
use ApiPlatform\Core\Serializer\DataTransformerNormalizer;
use ApiPlatform\Core\Serializer\ObjectClassResolver;
use ApiPlatform\Core\Serializer\ResourceClassNormalizer;
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactoryInterface;
use Symfony\Component\Serializer\NameConverter\NameConverterInterface;
use Symfony\Component\Serializer\Normalizer\CacheableSupportsMethodInterface;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\SerializerAwareInterface;
use Symfony\Component\Serializer\SerializerInterface;

/**
* Converts between objects and array including JSON-LD and Hydra metadata.
*
* @author Kévin Dunglas <dunglas@gmail.com>
*/
final class ItemNormalizer extends AbstractItemNormalizer
final class ItemNormalizer implements NormalizerInterface, DenormalizerInterface, CacheableSupportsMethodInterface, SerializerAwareInterface
{
use ClassInfoTrait;
use ContextTrait;
use JsonLdContextTrait;
// use ClassInfoTrait;
// use ContextTrait;
// use JsonLdContextTrait;

const FORMAT = 'jsonld';

private $contextBuilder;
// private $contextBuilder;

private $objectNormalizer;

private $normalizer;

public function __construct(ResourceMetadataFactoryInterface $resourceMetadataFactory, PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, IriConverterInterface $iriConverter, ResourceClassResolverInterface $resourceClassResolver, ContextBuilderInterface $contextBuilder, PropertyAccessorInterface $propertyAccessor = null, NameConverterInterface $nameConverter = null, ClassMetadataFactoryInterface $classMetadataFactory = null, array $defaultContext = [], iterable $dataTransformers = [], bool $handleNonResource = false)
{
parent::__construct($propertyNameCollectionFactory, $propertyMetadataFactory, $iriConverter, $resourceClassResolver, $propertyAccessor, $nameConverter, $classMetadataFactory, null, false, $defaultContext, $dataTransformers, $resourceMetadataFactory, $handleNonResource);
// parent::__construct($propertyNameCollectionFactory, $propertyMetadataFactory, $iriConverter, $resourceClassResolver, $propertyAccessor, $nameConverter, $classMetadataFactory, null, false, $defaultContext, $dataTransformers, $resourceMetadataFactory, $handleNonResource);

// $this->contextBuilder = $contextBuilder;
$this->objectNormalizer = new ObjectNormalizer(
$classMetadataFactory,
$nameConverter,
$propertyAccessor,
null,
null,
new ObjectClassResolver(),
$defaultContext
);

$dataTransformerNormalizer = new DataTransformerNormalizer(
$this->objectNormalizer,
$resourceMetadataFactory,
$dataTransformers
);

$jsonLdItemNormalizer = new JsonLdItemNormalizer(
$dataTransformerNormalizer,
$iriConverter,
$resourceMetadataFactory,
$contextBuilder
);

$resourceClassNormalizer = new ResourceClassNormalizer(
$jsonLdItemNormalizer,
$resourceClassResolver,
$iriConverter
);

$this->normalizer = $resourceClassNormalizer;
}

$this->contextBuilder = $contextBuilder;
/**
* {@inheritdoc}
*/
public function setSerializer(SerializerInterface $serializer)
{
$this->objectNormalizer->setSerializer($serializer);
}

/**
* {@inheritdoc}
*/
public function hasCacheableSupportsMethod(): bool
{
return $this->normalizer->hasCacheableSupportsMethod();
}

/**
* {@inheritdoc}
*/
public function supportsNormalization($data, $format = null, array $context = [])
{
return self::FORMAT === $format && parent::supportsNormalization($data, $format, $context);
return $this->normalizer->supportsNormalization($data, $format, $context);
}

/**
* {@inheritdoc}
*/
public function normalize($object, $format = null, array $context = [])
{
if ($this->handleNonResource && ($context['api_normalize'] ?? false) || null !== $outputClass = $this->getOutputClass($this->getObjectClass($object), $context)) {
if (isset($outputClass)) {
$object = $this->transformOutput($object, $context);
}

$data = $this->createJsonLdContext($this->contextBuilder, $object, $context);
$rawData = parent::normalize($object, $format, $context);
if (!\is_array($rawData)) {
return $rawData;
}

return $data + $rawData;
}

$resourceClass = $this->resourceClassResolver->getResourceClass($object, $context['resource_class'] ?? null, true);
$resourceMetadata = $this->resourceMetadataFactory->create($resourceClass);
$data = $this->addJsonLdContext($this->contextBuilder, $resourceClass, $context);

// Use resolved resource class instead of given resource class to support multiple inheritance child types
$context['resource_class'] = $resourceClass;
$context['iri'] = $this->iriConverter->getIriFromItem($object);

$rawData = parent::normalize($object, $format, $context);
if (!\is_array($rawData)) {
return $rawData;
}

$data['@id'] = $context['iri'];
$data['@type'] = $resourceMetadata->getIri() ?: $resourceMetadata->getShortName();

return $data + $rawData;
return $this->normalizer->normalize($object, $format, $context);
// if ($this->handleNonResource && ($context['api_normalize'] ?? false) || null !== $outputClass = $this->getOutputClass($this->getObjectClass($object), $context)) {
// if (isset($outputClass)) {
// $object = $this->transformOutput($object, $context);
// }
//
// $data = $this->createJsonLdContext($this->contextBuilder, $object, $context);
// $rawData = parent::normalize($object, $format, $context);
// if (!\is_array($rawData)) {
// return $rawData;
// }
//
// return $data + $rawData;
// }
//
// $resourceClass = $this->resourceClassResolver->getResourceClass($object, $context['resource_class'] ?? null, true);
// $resourceMetadata = $this->resourceMetadataFactory->create($resourceClass);
// $data = $this->addJsonLdContext($this->contextBuilder, $resourceClass, $context);
//
// // Use resolved resource class instead of given resource class to support multiple inheritance child types
// $context['resource_class'] = $resourceClass;
// $context['iri'] = $this->iriConverter->getIriFromItem($object);
//
// $rawData = parent::normalize($object, $format, $context);
// if (!\is_array($rawData)) {
// return $rawData;
// }
//
// $data['@id'] = $context['iri'];
// $data['@type'] = $resourceMetadata->getIri() ?: $resourceMetadata->getShortName();
//
// return $data + $rawData;
}

/**
* {@inheritdoc}
*/
public function supportsDenormalization($data, $type, $format = null, array $context = [])
{
return self::FORMAT === $format && parent::supportsDenormalization($data, $type, $format, $context);
return $this->normalizer->supportsDenormalization($data, $type, $format, $context);
// return self::FORMAT === $format && parent::supportsDenormalization($data, $type, $format, $context);
}

/**
Expand All @@ -110,15 +168,16 @@ public function supportsDenormalization($data, $type, $format = null, array $con
*/
public function denormalize($data, $class, $format = null, array $context = [])
{
// Avoid issues with proxies if we populated the object
if (isset($data['@id']) && !isset($context[self::OBJECT_TO_POPULATE])) {
if (isset($context['api_allow_update']) && true !== $context['api_allow_update']) {
throw new InvalidArgumentException('Update is not allowed for this operation.');
}

$context[self::OBJECT_TO_POPULATE] = $this->iriConverter->getItemFromIri($data['@id'], $context + ['fetch_data' => true]);
}

return parent::denormalize($data, $class, $format, $context);
return $this->normalizer->denormalize($data, $class, $format, $context);
// // Avoid issues with proxies if we populated the object
// if (isset($data['@id']) && !isset($context[self::OBJECT_TO_POPULATE])) {
// if (isset($context['api_allow_update']) && true !== $context['api_allow_update']) {
// throw new InvalidArgumentException('Update is not allowed for this operation.');
// }
//
// $context[self::OBJECT_TO_POPULATE] = $this->iriConverter->getItemFromIri($data['@id'], $context + ['fetch_data' => true]);
// }
//
// return parent::denormalize($data, $class, $format, $context);
}
}
Loading