Skip to content

Allow blank nodes in JSON-LD #956

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
1 change: 1 addition & 0 deletions src/Bridge/Symfony/Bundle/Resources/config/api.xml
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@
<argument type="service" id="api_platform.property_accessor" />
<argument type="service" id="api_platform.name_converter" on-invalid="ignore" />
<argument type="service" id="serializer.mapping.class_metadata_factory" on-invalid="ignore" />
<argument type="service" id="api_platform.identifiers_extractor.cached" />

<tag name="serializer.normalizer" />
</service>
Expand Down
1 change: 1 addition & 0 deletions src/Bridge/Symfony/Bundle/Resources/config/hal.xml
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
<argument type="service" id="api_platform.property_accessor" />
<argument type="service" id="api_platform.name_converter" on-invalid="ignore" />
<argument type="service" id="serializer.mapping.class_metadata_factory" on-invalid="ignore" />
<argument type="service" id="api_platform.identifiers_extractor.cached" />

<tag name="serializer.normalizer" priority="8" />
</service>
Expand Down
1 change: 1 addition & 0 deletions src/Bridge/Symfony/Bundle/Resources/config/jsonld.xml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
<argument type="service" id="api_platform.property_accessor" />
<argument type="service" id="api_platform.name_converter" on-invalid="ignore" />
<argument type="service" id="serializer.mapping.class_metadata_factory" on-invalid="ignore" />
<argument type="service" id="api_platform.identifiers_extractor.cached" />

<tag name="serializer.normalizer" priority="8" />
</service>
Expand Down
2 changes: 1 addition & 1 deletion src/Bridge/Symfony/Routing/IriConverter.php
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ public function __construct(PropertyNameCollectionFactoryInterface $propertyName
$this->propertyAccessor = $propertyAccessor ?? PropertyAccess::createPropertyAccessor();

if (null === $identifiersExtractor) {
@trigger_error('Not injecting ItemIdentifiersExtractor is deprecated since API Platform 2.1 and will not be possible anymore in API Platform 3');
@trigger_error('Not injecting IdentifiersExtractorInterface is deprecated since API Platform 2.1 and will not be possible anymore in API Platform 3');
$this->identifiersExtractor = new IdentifiersExtractor($this->propertyNameCollectionFactory, $this->propertyMetadataFactory, $this->propertyAccessor);
} else {
$this->identifiersExtractor = $identifiersExtractor;
Expand Down
65 changes: 61 additions & 4 deletions src/JsonLd/Serializer/ItemNormalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,12 @@

namespace ApiPlatform\Core\JsonLd\Serializer;

use ApiPlatform\Core\Api\IdentifiersExtractorInterface;
use ApiPlatform\Core\Api\IriConverterInterface;
use ApiPlatform\Core\Api\ResourceClassResolverInterface;
use ApiPlatform\Core\Exception\InvalidArgumentException;
use ApiPlatform\Core\JsonLd\ContextBuilderInterface;
use ApiPlatform\Core\JsonLd\Util\BlankNodeIdentifiersGenerator;
use ApiPlatform\Core\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
use ApiPlatform\Core\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface;
Expand All @@ -40,13 +42,16 @@ final class ItemNormalizer extends AbstractItemNormalizer

private $resourceMetadataFactory;
private $contextBuilder;
private $blankNodeIdentifiersGenerator;

public function __construct(ResourceMetadataFactoryInterface $resourceMetadataFactory, PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, IriConverterInterface $iriConverter, ResourceClassResolverInterface $resourceClassResolver, ContextBuilderInterface $contextBuilder, PropertyAccessorInterface $propertyAccessor = null, NameConverterInterface $nameConverter = null, ClassMetadataFactoryInterface $classMetadataFactory = null)
public function __construct(ResourceMetadataFactoryInterface $resourceMetadataFactory, PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, IriConverterInterface $iriConverter, ResourceClassResolverInterface $resourceClassResolver, ContextBuilderInterface $contextBuilder, PropertyAccessorInterface $propertyAccessor = null, NameConverterInterface $nameConverter = null, ClassMetadataFactoryInterface $classMetadataFactory = null, IdentifiersExtractorInterface $identifiersExtractor = null)
{
parent::__construct($propertyNameCollectionFactory, $propertyMetadataFactory, $iriConverter, $resourceClassResolver, $propertyAccessor, $nameConverter, $classMetadataFactory);
parent::__construct($propertyNameCollectionFactory, $propertyMetadataFactory, $iriConverter, $resourceClassResolver, $propertyAccessor, $nameConverter, $classMetadataFactory, $identifiersExtractor);

$this->resourceMetadataFactory = $resourceMetadataFactory;
$this->contextBuilder = $contextBuilder;

$this->blankNodeIdentifiersGenerator = new BlankNodeIdentifiersGenerator();
}

/**
Expand All @@ -68,14 +73,20 @@ public function normalize($object, $format = null, array $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);

$context = $this->addJsonLdDocumentContext($object, $context);

$jsonLdIdentifier = $this->getJsonLdNodeIdentifier($object, $context);
if ($this->hasIri($object)) {
$context['iri'] = $jsonLdIdentifier;
}

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

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

return $data + $rawData;
Expand All @@ -96,6 +107,12 @@ public function supportsDenormalization($data, $type, $format = null)
*/
public function denormalize($data, $class, $format = null, array $context = [])
{
// Blank node identifiers cannot be used in denormalization
// Denormalize into new object
if (isset($data['@id']) && $this->isBlankNodeIdentifier($data['@id'])) {
unset($data['@id']);
}

// Avoid issues with proxies if we populated the object
if (isset($data['@id']) && !isset($context['object_to_populate'])) {
if (isset($context['api_allow_update']) && true !== $context['api_allow_update']) {
Expand All @@ -107,4 +124,44 @@ public function denormalize($data, $class, $format = null, array $context = [])

return parent::denormalize($data, $class, $format, $context);
}

/**
* Adds information related to the JSON-LD document to the serializer context.
*
* @param object $object
* @param array $context
*
* @return array
*/
private function addJsonLdDocumentContext($object, array $context)
{
$context['jsonld_document_root'] ?? $context['jsonld_document_root'] = spl_object_hash($object);

return $context;
}

/**
* Gets the identifier for a JSON-LD node.
*
* @param object $object
* @param array $context
*
* @return string
*/
private function getJsonLdNodeIdentifier($object, array $context): string
{
return $this->hasIri($object) ? $this->iriConverter->getIriFromItem($object) : $this->blankNodeIdentifiersGenerator->getBlankNodeIdentifier($object, $context['jsonld_document_root']);
}

/**
* Determines whether an IRI is a JSON-LD blank node identifier.
*
* @param string $iri
*
* @return bool
*/
private function isBlankNodeIdentifier(string $iri): bool
{
return '_:' === substr($iri, 0, 2);
}
}
51 changes: 51 additions & 0 deletions src/JsonLd/Util/BlankNodeIdentifiersGenerator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
<?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\JsonLd\Util;

/**
* Generates blank node identifiers scoped to each JSON-LD document.
*
* @author Teoh Han Hui <teohhanhui@gmail.com>
*
* @internal
*/
final class BlankNodeIdentifiersGenerator
{
const IDENTIFIER_PREFIX = '_:b';

private $blankNodeCounts = [];
private $identifiers = [];

/**
* Gets a blank node identifier for an object, scoped to a JSON-LD document.
*
* @param object $object
* @param string $documentRootHash
*
* @return string
*/
public function getBlankNodeIdentifier($object, string $documentRootHash): string
{
$objectHash = spl_object_hash($object);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not a fond of exposing such low level data from the system publicly. Is it really safe? Another potential problem is that this ID will be reused later by PHP. WDYT about using a UUID instead?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's not being exposed in any way. The hash is only used to keep track of which objects we've already generated a blank node identifier for, and always return that same identifier for the same object (the scope is the JSON-LD document).

We cannot use UUID for this, as the point is to detect the same object instance.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nevermind got it.


if (!isset($this->identifiers[$documentRootHash][$objectHash])) {
$this->blankNodeCounts[$documentRootHash] ?? $this->blankNodeCounts[$documentRootHash] = 0;
$this->identifiers[$documentRootHash] ?? $this->identifiers[$documentRootHash] = [];

$this->identifiers[$documentRootHash][$objectHash] = sprintf('%s%d', self::IDENTIFIER_PREFIX, $this->blankNodeCounts[$documentRootHash]++);
}

return $this->identifiers[$documentRootHash][$objectHash];
}
}
36 changes: 31 additions & 5 deletions src/Serializer/AbstractItemNormalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@

namespace ApiPlatform\Core\Serializer;

use ApiPlatform\Core\Api\IdentifiersExtractor;
use ApiPlatform\Core\Api\IdentifiersExtractorInterface;
use ApiPlatform\Core\Api\IriConverterInterface;
use ApiPlatform\Core\Api\OperationType;
use ApiPlatform\Core\Api\ResourceClassResolverInterface;
Expand Down Expand Up @@ -43,8 +45,9 @@ abstract class AbstractItemNormalizer extends AbstractObjectNormalizer
protected $iriConverter;
protected $resourceClassResolver;
protected $propertyAccessor;
protected $identifiersExtractor;

public function __construct(PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, IriConverterInterface $iriConverter, ResourceClassResolverInterface $resourceClassResolver, PropertyAccessorInterface $propertyAccessor = null, NameConverterInterface $nameConverter = null, ClassMetadataFactoryInterface $classMetadataFactory = null)
public function __construct(PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, IriConverterInterface $iriConverter, ResourceClassResolverInterface $resourceClassResolver, PropertyAccessorInterface $propertyAccessor = null, NameConverterInterface $nameConverter = null, ClassMetadataFactoryInterface $classMetadataFactory = null, IdentifiersExtractorInterface $identifiersExtractor = null)
{
parent::__construct($classMetadataFactory, $nameConverter);

Expand All @@ -54,8 +57,15 @@ public function __construct(PropertyNameCollectionFactoryInterface $propertyName
$this->resourceClassResolver = $resourceClassResolver;
$this->propertyAccessor = $propertyAccessor ?: PropertyAccess::createPropertyAccessor();

if (null === $identifiersExtractor) {
@trigger_error('Not injecting IdentifiersExtractorInterface is deprecated since API Platform 2.1 and will not be possible anymore in API Platform 3');
$this->identifiersExtractor = new IdentifiersExtractor($this->propertyNameCollectionFactory, $this->propertyMetadataFactory, $this->propertyAccessor);
} else {
$this->identifiersExtractor = $identifiersExtractor;
}

$this->setCircularReferenceHandler(function ($object) {
return $this->iriConverter->getIriFromItem($object);
return $this->hasIri($object) ? $this->iriConverter->getIriFromItem($object) : spl_object_hash($object);
});
}

Expand Down Expand Up @@ -86,7 +96,7 @@ public function normalize($object, $format = null, array $context = [])
$context = $this->initContext($resourceClass, $context);
$context['api_normalize'] = true;

if (isset($context['resources'])) {
if (isset($context['resources']) && $this->hasIri($object)) {
$resource = $context['iri'] ?? $this->iriConverter->getIriFromItem($object);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is the condition still needed? if it hasIri context['iri'] is defined no?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No. $context['iri'] is only set from the JsonLd ItemNormalizer (I think). I don't know what's the reasoning behind, but I did not change it...

$context['resources'][$resource] = $resource;
}
Expand Down Expand Up @@ -421,7 +431,7 @@ protected function getAttributeValue($object, $attribute, $format = null, array
}

/**
* Normalizes a relation as an URI if is a Link or as a JSON-LD object.
* Normalizes a relation.
*
* @param PropertyMetadata $propertyMetadata
* @param mixed $relatedObject
Expand All @@ -433,7 +443,7 @@ protected function getAttributeValue($object, $attribute, $format = null, array
*/
private function normalizeRelation(PropertyMetadata $propertyMetadata, $relatedObject, string $resourceClass, string $format = null, array $context)
{
if ($propertyMetadata->isReadableLink()) {
if ($propertyMetadata->isReadableLink() || !$this->hasIri($relatedObject)) {
return $this->serializer->normalize($relatedObject, $format, $this->createRelationSerializationContext($resourceClass, $context));
}

Expand All @@ -444,4 +454,20 @@ private function normalizeRelation(PropertyMetadata $propertyMetadata, $relatedO

return $iri;
}

/**
* Determines whether an item has an IRI.
*
* @param object $object
*
* @return bool
*
* @internal
*/
protected function hasIri($object): bool
{
$identifiers = $this->identifiersExtractor->getIdentifiersFromItem($object);

return (bool) array_filter($identifiers);
}
}
37 changes: 32 additions & 5 deletions tests/Hal/Serializer/ItemNormalizerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

namespace ApiPlatform\Core\Tests\Hal\Serializer;

use ApiPlatform\Core\Api\IdentifiersExtractorInterface;
use ApiPlatform\Core\Api\IriConverterInterface;
use ApiPlatform\Core\Api\ResourceClassResolverInterface;
use ApiPlatform\Core\Exception\InvalidArgumentException;
Expand All @@ -34,18 +35,24 @@ class ItemNormalizerTest extends \PHPUnit_Framework_TestCase
/**
* @expectedException \ApiPlatform\Core\Exception\RuntimeException
*/
public function testDonTSupportDenormalization()
public function testDontSupportDenormalization()
{
$propertyNameCollectionFactoryProphecy = $this->prophesize(PropertyNameCollectionFactoryInterface::class);
$propertyMetadataFactoryProphecy = $this->prophesize(PropertyMetadataFactoryInterface::class);
$iriConverterProphecy = $this->prophesize(IriConverterInterface::class);
$resourceClassResolverProphecy = $this->prophesize(ResourceClassResolverInterface::class);

$identifiersExtractorProphecy = $this->prophesize(IdentifiersExtractorInterface::class);

$normalizer = new ItemNormalizer(
$propertyNameCollectionFactoryProphecy->reveal(),
$propertyMetadataFactoryProphecy->reveal(),
$iriConverterProphecy->reveal(),
$resourceClassResolverProphecy->reveal()
$resourceClassResolverProphecy->reveal(),
null,
null,
null,
$identifiersExtractorProphecy->reveal()
);

$this->assertFalse($normalizer->supportsDenormalization('foo', ItemNormalizer::FORMAT));
Expand All @@ -66,11 +73,17 @@ public function testSupportNormalization()
$resourceClassResolverProphecy->getResourceClass($dummy)->willReturn(Dummy::class)->shouldBeCalled();
$resourceClassResolverProphecy->getResourceClass($std)->willThrow(new InvalidArgumentException())->shouldBeCalled();

$identifiersExtractorProphecy = $this->prophesize(IdentifiersExtractorInterface::class);

$normalizer = new ItemNormalizer(
$propertyNameCollectionFactoryProphecy->reveal(),
$propertyMetadataFactoryProphecy->reveal(),
$iriConverterProphecy->reveal(),
$resourceClassResolverProphecy->reveal()
$resourceClassResolverProphecy->reveal(),
null,
null,
null,
$identifiersExtractorProphecy->reveal()
);

$this->assertTrue($normalizer->supportsNormalization($dummy, 'jsonhal'));
Expand Down Expand Up @@ -98,6 +111,9 @@ public function testNormalize()
$resourceClassResolverProphecy->getResourceClass($dummy, null, true)->willReturn(Dummy::class)->shouldBeCalled();
$resourceClassResolverProphecy->getResourceClass($dummy, Dummy::class, true)->willReturn(Dummy::class)->shouldBeCalled();

$identifiersExtractorProphecy = $this->prophesize(IdentifiersExtractorInterface::class);
$identifiersExtractorProphecy->getIdentifiersFromItem($dummy)->willReturn(['id']);

$serializerProphecy = $this->prophesize(SerializerInterface::class);
$serializerProphecy->willImplement(NormalizerInterface::class);
$serializerProphecy->normalize('hello', null, Argument::type('array'))->willReturn('hello')->shouldBeCalled();
Expand All @@ -106,7 +122,11 @@ public function testNormalize()
$propertyNameCollectionFactoryProphecy->reveal(),
$propertyMetadataFactoryProphecy->reveal(),
$iriConverterProphecy->reveal(),
$resourceClassResolverProphecy->reveal()
$resourceClassResolverProphecy->reveal(),
null,
null,
null,
$identifiersExtractorProphecy->reveal()
);
$normalizer->setSerializer($serializerProphecy->reveal());

Expand Down Expand Up @@ -141,6 +161,9 @@ public function testNormalizeWithoutCache()
$resourceClassResolverProphecy->getResourceClass($dummy, null, true)->willReturn(Dummy::class)->shouldBeCalled();
$resourceClassResolverProphecy->getResourceClass($dummy, Dummy::class, true)->willReturn(Dummy::class)->shouldBeCalled();

$identifiersExtractorProphecy = $this->prophesize(IdentifiersExtractorInterface::class);
$identifiersExtractorProphecy->getIdentifiersFromItem($dummy)->willReturn(['id']);

$serializerProphecy = $this->prophesize(SerializerInterface::class);
$serializerProphecy->willImplement(NormalizerInterface::class);
$serializerProphecy->normalize('hello', null, Argument::type('array'))->willReturn('hello')->shouldBeCalled();
Expand All @@ -149,7 +172,11 @@ public function testNormalizeWithoutCache()
$propertyNameCollectionFactoryProphecy->reveal(),
$propertyMetadataFactoryProphecy->reveal(),
$iriConverterProphecy->reveal(),
$resourceClassResolverProphecy->reveal()
$resourceClassResolverProphecy->reveal(),
null,
null,
null,
$identifiersExtractorProphecy->reveal()
);
$normalizer->setSerializer($serializerProphecy->reveal());

Expand Down
Loading