Skip to content

Commit e15c463

Browse files
Merge pull request #617 from components-web-app/fix/page-data-collection-associations
Leave to-many and non-resource associations out of page data properties
2 parents 2ef71ee + ef6a68f commit e15c463

9 files changed

Lines changed: 268 additions & 9 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,9 @@ Every change that reaches `main` adds a line under **Unreleased**. When a versio
44

55
## Unreleased
66

7+
### Fixed
8+
- A page data class's to-many associations, and associations to a class that is not an API resource, are no longer page data properties, so writing an entity such an association holds no longer 500s ("SingleValuedAssociationField expected" on flush) and the page data metadata no longer lists them ([#617](https://github.com/components-web-app/api-components-bundle/pull/617))
9+
710
## [2.0.0-alpha.47](https://github.com/components-web-app/api-components-bundle/compare/2.0.0-alpha.46...2.0.0-alpha.47) - 2026-11-25
811

912
### Added

‎CLAUDE.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -406,6 +406,7 @@ Resources are fetched and cached **individually**. Never embed related data outs
406406
- **`layout` names one layout, the lowest `reference`, even when a use reaches several through a shared container** (#535, by design): the module shows it as a label, and `renderedOn` is the complete answer for pages.
407407
- **A list inside a DTO that is not an API resource is normalized as a Hydra `Collection`** unless its property carries `#[Context(normalizationContext: ['api_sub_level' => true])]`, as `ComponentUsageMetadata::$locations` does.
408408
- **A component matches a page data property by class hierarchy, never by short name** (#345). `PageDataMetadata::findPropertiesByComponentClass()` uses `is_a()` against the property's Doctrine target, so a property typed `AbstractComponent` or a parent component class holds any subclass. `PageDataProvider::findPageDataComponentMetadata()` is the one lookup behind usage counts (`/usage` and the cascade on delete), `ComponentVoter`'s page data reachability and `PropagateUpdatesListener`'s purge and Mercure fan-out, so a component held only by such a property is used, public only when the page data is on a live route, and propagates to the page data on edit.
409+
- **Only a single-valued association to an API resource is a page data property** (`PageDataMetadataFactory`, #617). A to-many one put into `PageDataProvider`'s `pd.<property> = :component` is a DQL error on the flush of every write to its target, and a non-resource target has no resource metadata, so both are left out. `Page\PageDataCollectionAssociationTest` pins it.
409410
- **Publish now is `"publishedAt": "now"`, resolved by the server** (#407). `PublishableNormalizer::denormalize()` replaces the exact string `PublishableNormalizer::PUBLISH_NOW` with the current time (`RFC3339_EXTENDED`, so truncation can only make it earlier, never scheduled) after `unsetRestrictedData()`, so a caller who may not publish still cannot send it, and before the `?published=true` path, where any change is still a 422. Never rely on Symfony's loose date parsing for it: that fallback is deprecated in 8.1 and throws in 9.0. Send a raw body to test the server's `"now"`.
410411
- **A position never exposes a publishable component that is not active to a caller who is not granted** (#492), static or dynamic, and neither does `_metadata.staticComponent`. `ComponentPositionNormalizer` drops the `component` key from its output rather than nulling the entity (#389), so the key is absent, not `null`; the module treats a missing `component` as an empty position. A granted caller still gets the draft swapped in. The manifest follows, because it is built from the normalized position.
411412
- `createdAt` is restored in `TimestampedNormalizer::denormalize()` (#213). `OBJECT_TO_POPULATE` is not always an instance of `$type` (a `PersistentCollection` when denormalizing a collection property), so gate on `instanceof`; an object denormalized into anything that is not an instance of `$type` is new and gets a fresh `createdAt` (a position embedded in a component `PATCH`).

‎src/Metadata/Factory/PageDataMetadataFactory.php‎

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -36,41 +36,38 @@ public function __construct(
3636
*/
3737
public function create(string $resourceClass): PageDataMetadata
3838
{
39-
// needs to be a class
4039
if (!class_exists($resourceClass)) {
4140
throw new PageDataNotFoundException(\sprintf('`%s` was not found', $resourceClass));
4241
}
4342

44-
// Check it is page data
4543
$reflection = new \ReflectionClass($resourceClass);
4644
if (!$reflection->implementsInterface(PageDataInterface::class)) {
4745
throw new PageDataNotFoundException(\sprintf('Resource class `%s` is not a valid page data resource', $resourceClass));
4846
}
4947

50-
// Find the doctrine manager
5148
$manager = $this->registry->getManagerForClass($resourceClass);
5249
if (!$manager) {
5350
throw new PageDataNotFoundException(\sprintf('Cannot find manager for page data resource `%s`', $resourceClass));
5451
}
5552
$classMetadata = $manager->getClassMetadata($resourceClass);
5653

57-
// Get abstract prop names to exclude
5854
$abstractReflection = new \ReflectionClass(AbstractPageData::class);
5955
$reflProps = $abstractReflection->getProperties();
6056
$abstractProps = array_map(static function (\ReflectionProperty $prop) {
6157
return $prop->name;
6258
}, $reflProps);
6359

64-
// Get all fields with association
65-
$assocFields = array_filter($classMetadata->getAssociationNames(), static function ($name) use ($abstractProps) {
66-
return !\in_array($name, $abstractProps, true);
60+
$assocFields = array_filter($classMetadata->getAssociationNames(), static function ($name) use ($abstractProps, $classMetadata) {
61+
return !\in_array($name, $abstractProps, true) && !$classMetadata->isCollectionValuedAssociation($name);
6762
});
6863

69-
// Create metadata with relations
7064
$metadata = new PageDataMetadata($resourceClass);
7165
foreach ($assocFields as $assocField) {
7266
$targetClass = $classMetadata->getAssociationTargetClass($assocField);
7367
$metadataCollection = $this->resourceMetadataFactory->create($targetClass);
68+
if (0 === \count($metadataCollection)) {
69+
continue;
70+
}
7471
/** @var ApiResource $apiResource */
7572
$apiResource = $metadataCollection[0];
7673
$relationName = $apiResource->getShortName();
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the Silverback API Components Bundle Project
5+
*
6+
* (c) Daniel West <daniel@silverback.is>
7+
*
8+
* For the full copyright and license information, please view the LICENSE
9+
* file that was distributed with this source code.
10+
*/
11+
12+
namespace Silverback\ApiComponentsBundle\Tests\Functional\Page;
13+
14+
use Silverback\ApiComponentsBundle\Entity\Core\Page;
15+
use Silverback\ApiComponentsBundle\Tests\Functional\FunctionalTestCase;
16+
use Silverback\ApiComponentsBundle\Tests\Functional\TestBundle\Entity\DummyPageDataVariant;
17+
use Silverback\ApiComponentsBundle\Tests\Functional\TestBundle\Entity\PageDataWithVariants;
18+
use Silverback\ApiComponentsBundle\Tests\Functional\Trait\ApiRequestTrait;
19+
use Silverback\ApiComponentsBundle\Tests\Functional\Trait\SiteTrait;
20+
21+
final class PageDataCollectionAssociationTest extends FunctionalTestCase
22+
{
23+
use ApiRequestTrait;
24+
25+
use SiteTrait;
26+
27+
public function test_writing_an_entity_held_by_a_to_many_page_data_association_does_not_throw(): void
28+
{
29+
self::bootKernel();
30+
$page = self::newPage('variants page', true);
31+
self::persistAndFlush($page);
32+
$pageData = new PageDataWithVariants();
33+
$pageData->page = self::getEntityManager()->getReference(Page::class, $page->getId());
34+
self::persistAndFlush($pageData);
35+
$pageData = self::findByIri(self::iriOf($pageData));
36+
self::assertInstanceOf(PageDataWithVariants::class, $pageData);
37+
$manager = self::getEntityManager();
38+
39+
$variant = new DummyPageDataVariant();
40+
$variant->pageData = $pageData;
41+
$pageData->variants->add($variant);
42+
$manager->persist($variant);
43+
$manager->flush();
44+
$variant->stock = 5;
45+
$manager->flush();
46+
47+
$stored = self::findByIri(self::iriOf($variant));
48+
self::assertInstanceOf(DummyPageDataVariant::class, $stored);
49+
self::assertSame(5, $stored->stock);
50+
}
51+
52+
public function test_a_to_many_association_is_not_a_page_data_property(): void
53+
{
54+
self::assertNotContains('variants', self::pageDataPropertyNames());
55+
}
56+
57+
public function test_an_association_to_a_class_that_is_not_an_api_resource_is_not_a_page_data_property(): void
58+
{
59+
self::assertNotContains('supplier', self::pageDataPropertyNames());
60+
}
61+
62+
/**
63+
* @return list<string>
64+
*/
65+
private static function pageDataPropertyNames(): array
66+
{
67+
$client = static::createClient();
68+
69+
$response = self::requestJsonLd($client, 'GET', '/_/page_data_metadatas/' . rawurlencode(PageDataWithVariants::class));
70+
71+
self::assertResponseStatusCodeSame(200);
72+
73+
return array_column($response->toArray()['properties'], 'property');
74+
}
75+
}

‎tests/Functional/Page/PageDataMetadataTest.php‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ public function test_i_can_get_all_page_data_metadata(): void
2828

2929
self::assertResponseStatusCodeSame(200);
3030
self::assertJsonNodeSame('@context.properties', 'PageDataMetadata/properties');
31-
self::assertJsonNodeCount('member', 9);
31+
self::assertJsonNodeCount('member', 10);
3232
}
3333

3434
public function test_i_can_get_a_single_page_data_endpoint(): void
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the Silverback API Components Bundle Project
5+
*
6+
* (c) Daniel West <daniel@silverback.is>
7+
*
8+
* For the full copyright and license information, please view the LICENSE
9+
* file that was distributed with this source code.
10+
*/
11+
12+
namespace Silverback\ApiComponentsBundle\Tests\Functional\TestBundle\Entity;
13+
14+
use Doctrine\ORM\Mapping as ORM;
15+
use Silverback\ApiComponentsBundle\Entity\Utility\IdTrait;
16+
17+
#[ORM\Entity]
18+
class DummyPageDataSupplier
19+
{
20+
use IdTrait;
21+
}
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the Silverback API Components Bundle Project
5+
*
6+
* (c) Daniel West <daniel@silverback.is>
7+
*
8+
* For the full copyright and license information, please view the LICENSE
9+
* file that was distributed with this source code.
10+
*/
11+
12+
namespace Silverback\ApiComponentsBundle\Tests\Functional\TestBundle\Entity;
13+
14+
use ApiPlatform\Metadata\ApiResource;
15+
use Doctrine\ORM\Mapping as ORM;
16+
use Silverback\ApiComponentsBundle\Entity\Utility\IdTrait;
17+
18+
#[ApiResource]
19+
#[ORM\Entity]
20+
class DummyPageDataVariant
21+
{
22+
use IdTrait;
23+
24+
#[ORM\ManyToOne(targetEntity: PageDataWithVariants::class, inversedBy: 'variants')]
25+
#[ORM\JoinColumn(nullable: true, onDelete: 'CASCADE')]
26+
public ?PageDataWithVariants $pageData = null;
27+
28+
#[ORM\Column(type: 'integer')]
29+
public int $stock = 0;
30+
}
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the Silverback API Components Bundle Project
5+
*
6+
* (c) Daniel West <daniel@silverback.is>
7+
*
8+
* For the full copyright and license information, please view the LICENSE
9+
* file that was distributed with this source code.
10+
*/
11+
12+
namespace Silverback\ApiComponentsBundle\Tests\Functional\TestBundle\Entity;
13+
14+
use ApiPlatform\Metadata\ApiResource;
15+
use Doctrine\Common\Collections\ArrayCollection;
16+
use Doctrine\Common\Collections\Collection;
17+
use Doctrine\ORM\Mapping as ORM;
18+
use Silverback\ApiComponentsBundle\Entity\Core\AbstractPageData;
19+
20+
#[ApiResource]
21+
#[ORM\Entity]
22+
class PageDataWithVariants extends AbstractPageData
23+
{
24+
/** @var Collection<int, DummyPageDataVariant> */
25+
#[ORM\OneToMany(targetEntity: DummyPageDataVariant::class, mappedBy: 'pageData')]
26+
public Collection $variants;
27+
28+
#[ORM\ManyToOne(targetEntity: DummyPageDataSupplier::class)]
29+
#[ORM\JoinColumn(nullable: true, onDelete: 'SET NULL')]
30+
public ?DummyPageDataSupplier $supplier = null;
31+
32+
public function __construct()
33+
{
34+
$this->variants = new ArrayCollection();
35+
}
36+
}
Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the Silverback API Components Bundle Project
5+
*
6+
* (c) Daniel West <daniel@silverback.is>
7+
*
8+
* For the full copyright and license information, please view the LICENSE
9+
* file that was distributed with this source code.
10+
*/
11+
12+
namespace Silverback\ApiComponentsBundle\Tests\Metadata\Factory;
13+
14+
use ApiPlatform\Metadata\ApiResource;
15+
use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
16+
use ApiPlatform\Metadata\Resource\ResourceMetadataCollection;
17+
use Doctrine\ORM\EntityManagerInterface;
18+
use Doctrine\ORM\Mapping\ClassMetadata;
19+
use Doctrine\Persistence\ManagerRegistry;
20+
use PHPUnit\Framework\TestCase;
21+
use Silverback\ApiComponentsBundle\Metadata\Factory\PageDataMetadataFactory;
22+
use Silverback\ApiComponentsBundle\Metadata\PageDataMetadata;
23+
use Silverback\ApiComponentsBundle\Metadata\PageDataPropertyMetadata;
24+
use Silverback\ApiComponentsBundle\Tests\Functional\TestBundle\Entity\DummyComponent;
25+
use Silverback\ApiComponentsBundle\Tests\Functional\TestBundle\Entity\DummyPageDataSupplier;
26+
use Silverback\ApiComponentsBundle\Tests\Functional\TestBundle\Entity\DummyPageDataVariant;
27+
use Silverback\ApiComponentsBundle\Tests\Functional\TestBundle\Entity\PageDataWithVariants;
28+
29+
final class PageDataMetadataFactoryTest extends TestCase
30+
{
31+
public function test_a_to_many_association_is_left_out_of_the_metadata(): void
32+
{
33+
$classMetadata = $this->createStub(ClassMetadata::class);
34+
$classMetadata->method('getAssociationNames')->willReturn(['page', 'component', 'variants']);
35+
$classMetadata->method('isCollectionValuedAssociation')->willReturnMap([
36+
['page', false],
37+
['component', false],
38+
['variants', true],
39+
]);
40+
$classMetadata->method('getAssociationTargetClass')->willReturnMap([
41+
['component', DummyComponent::class],
42+
['variants', DummyPageDataVariant::class],
43+
]);
44+
$resourceMetadataFactory = $this->createStub(ResourceMetadataCollectionFactoryInterface::class);
45+
$resourceMetadataFactory->method('create')->willReturnCallback(
46+
static fn (string $class) => new ResourceMetadataCollection($class, [new ApiResource(shortName: (new \ReflectionClass($class))->getShortName())]),
47+
);
48+
49+
$metadata = (new PageDataMetadataFactory(self::registryFor($classMetadata), $resourceMetadataFactory))->create(PageDataWithVariants::class);
50+
51+
self::assertSame(PageDataWithVariants::class, $metadata->getResourceClass());
52+
self::assertSame([['component', DummyComponent::class, 'DummyComponent']], self::propertiesOf($metadata));
53+
}
54+
55+
public function test_an_association_to_a_class_that_is_not_an_api_resource_is_left_out_of_the_metadata(): void
56+
{
57+
$classMetadata = $this->createStub(ClassMetadata::class);
58+
$classMetadata->method('getAssociationNames')->willReturn(['supplier', 'component']);
59+
$classMetadata->method('isCollectionValuedAssociation')->willReturn(false);
60+
$classMetadata->method('getAssociationTargetClass')->willReturnMap([
61+
['supplier', DummyPageDataSupplier::class],
62+
['component', DummyComponent::class],
63+
]);
64+
$resourceMetadataFactory = $this->createStub(ResourceMetadataCollectionFactoryInterface::class);
65+
$resourceMetadataFactory->method('create')->willReturnCallback(
66+
static fn (string $class) => DummyComponent::class === $class
67+
? new ResourceMetadataCollection($class, [new ApiResource(shortName: 'DummyComponent')])
68+
: new ResourceMetadataCollection($class),
69+
);
70+
71+
$metadata = (new PageDataMetadataFactory(self::registryFor($classMetadata), $resourceMetadataFactory))->create(PageDataWithVariants::class);
72+
73+
self::assertSame([['component', DummyComponent::class, 'DummyComponent']], self::propertiesOf($metadata));
74+
}
75+
76+
private static function registryFor(ClassMetadata $classMetadata): ManagerRegistry
77+
{
78+
$manager = self::createStub(EntityManagerInterface::class);
79+
$manager->method('getClassMetadata')->willReturn($classMetadata);
80+
$registry = self::createStub(ManagerRegistry::class);
81+
$registry->method('getManagerForClass')->willReturn($manager);
82+
83+
return $registry;
84+
}
85+
86+
/**
87+
* @return list<array{string, string, string}>
88+
*/
89+
private static function propertiesOf(PageDataMetadata $metadata): array
90+
{
91+
return array_values(array_map(
92+
static fn (PageDataPropertyMetadata $property) => [$property->getProperty(), $property->getComponentClass(), $property->getComponentShortName()],
93+
$metadata->getProperties()->toArray(),
94+
));
95+
}
96+
}

0 commit comments

Comments
 (0)