Skip to content
Merged
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
7 changes: 6 additions & 1 deletion src/JsonApi/JsonSchema/SchemaFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -321,7 +321,12 @@ private function buildDefinitionPropertiesSchema(string $key, string $className,
}
$relatedDefinitions[$propertyName] = array_flip($refs);
if ($isOne) {
$relationships[$propertyName]['properties']['data'] = self::RELATION_PROPS;
$relationships[$propertyName]['properties']['data'] = [
'oneOf' => [
['type' => 'null'],
self::RELATION_PROPS,
],
];
continue;
}
$relationships[$propertyName]['properties']['data'] = [
Expand Down
24 changes: 16 additions & 8 deletions src/JsonApi/Serializer/ItemNormalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -460,23 +460,31 @@ private function getPopulatedRelations(object $object, ?string $format, array $c
$relationshipName = $this->nameConverter->normalize($relationshipName, $context['resource_class'], self::FORMAT, $context);
}

$data[$relationshipName] = [
'data' => [],
];

if (!$attributeValue) {
continue;
}

// Many to one relationship
if ('one' === $relationshipDataArray['cardinality']) {
$data[$relationshipName] = [
'data' => null,
];

if (!$attributeValue) {
continue;
}

unset($attributeValue['data']['attributes']);
$data[$relationshipName] = $attributeValue;

continue;
}

// Many to many relationship
$data[$relationshipName] = [
'data' => [],
];

if (!$attributeValue) {
continue;
}

foreach ($attributeValue as $attributeValueElement) {
if (!isset($attributeValueElement['data'])) {
throw new UnexpectedValueException(\sprintf('The JSON API attribute \'%s\' must contain a "data" key.', $relationshipName));
Expand Down
89 changes: 89 additions & 0 deletions src/JsonApi/Tests/Serializer/ItemNormalizerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -488,4 +488,93 @@ public function testDenormalizeRelationIsNotResourceLinkage(): void

$normalizer->denormalize($data, Dummy::class, ItemNormalizer::FORMAT);
}

public function testNormalizeWithNullToOneAndEmptyToManyRelationships(): void
{
$dummy = new Dummy();
$dummy->setId(1);
$dummy->setName('Dummy with relationships');

$propertyNameCollectionFactory = $this->createMock(PropertyNameCollectionFactoryInterface::class);
$propertyNameCollectionFactory->method('create')->willReturn(
new PropertyNameCollection(['id', 'name', 'relatedDummy', 'relatedDummies'])
);

$propertyMetadataFactory = $this->createMock(PropertyMetadataFactoryInterface::class);
$propertyMetadataFactory->method('create')->willReturnCallback(function ($class, $property) {
return match ($property) {
'id' => (new ApiProperty())->withReadable(true)->withIdentifier(true),
'name' => (new ApiProperty())->withReadable(true),
'relatedDummy' => (new ApiProperty())
->withReadable(true)
->withReadableLink(true)
->withNativeType(Type::nullable(Type::object(RelatedDummy::class))),
'relatedDummies' => (new ApiProperty())
->withReadable(true)
->withReadableLink(true)
->withNativeType(Type::collection(Type::object(ArrayCollection::class), Type::object(RelatedDummy::class))),
default => new ApiProperty(),
};
});

$iriConverter = $this->createMock(IriConverterInterface::class);
$iriConverter->method('getIriFromResource')->willReturn('/dummies/1');

$resourceClassResolver = $this->createMock(ResourceClassResolverInterface::class);
$resourceClassResolver->method('getResourceClass')->willReturn(Dummy::class);
$resourceClassResolver->method('isResourceClass')->willReturnCallback(fn ($class) => \in_array($class, [Dummy::class, RelatedDummy::class], true));

$propertyAccessor = $this->createMock(PropertyAccessorInterface::class);
$propertyAccessor->method('getValue')->willReturnCallback(function ($object, $property) {
return match ($property) {
'id' => 1,
'name' => 'Dummy with relationships',
'relatedDummy' => null,
'relatedDummies' => [],
default => null,
};
});

$resourceMetadataCollectionFactory = $this->createMock(ResourceMetadataCollectionFactoryInterface::class);
$resourceMetadataCollectionFactory->method('create')->willReturn(
new ResourceMetadataCollection('Dummy', [
(new ApiResource())
->withShortName('Dummy')
->withOperations(new Operations(['get' => (new Get())->withShortName('Dummy')])),
])
);

$serializer = $this->createStub(Serializer::class);

$normalizer = new ItemNormalizer(
$propertyNameCollectionFactory,
$propertyMetadataFactory,
$iriConverter,
$resourceClassResolver,
$propertyAccessor,
null,
null,
[],
$resourceMetadataCollectionFactory,
);

$normalizer->setSerializer($serializer);

$result = $normalizer->normalize($dummy, ItemNormalizer::FORMAT, [
'resources' => [],
'resource_class' => Dummy::class,
]);

$this->assertIsArray($result);
$this->assertArrayHasKey('data', $result);
$this->assertArrayHasKey('relationships', $result['data']);

// Verify to-one relationship with null value returns {"data": null}
$this->assertArrayHasKey('relatedDummy', $result['data']['relationships']);
$this->assertSame(['data' => null], $result['data']['relationships']['relatedDummy']);

// Verify to-many relationship with empty array returns {"data": []}
$this->assertArrayHasKey('relatedDummies', $result['data']['relationships']);
$this->assertSame(['data' => []], $result['data']['relationships']['relatedDummies']);
}
}