Skip to content
Open
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
60 changes: 60 additions & 0 deletions docs/UPGRADE-2.0.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,17 @@ final class SkillNormalizer implements Normalizer
}
}
```
### Documents with a class level normalizer

Hydrator 2 uses a normalizer on a class, on one of its parents or on an implemented interface for the whole
object, and a guesser that matches the class has the same effect. Documents are stored field by field, so a
document class must not end up with such a normalizer. The `StackHydratorFieldMappingResolver`, which the
repository managers' `create()` sets up, now throws `Patchlevel\ODM\Metadata\DocumentHasClassNormalizer`
when it builds the metadata of such a document.

Remove the normalizer from the document class, its parents and its interfaces, and make sure no guesser
matches a document class. Put normalizers on the value objects inside the document instead.

### Custom hydrators

The repository managers and repositories now take a `Patchlevel\Hydrator\Hydrator` instead of a
Expand Down Expand Up @@ -135,3 +146,52 @@ final class LoggingHydrator implements Hydrator

`Patchlevel\ODM\Hydrator\DocumentHydrator` is internal now and no longer implements the `Hydrator`
interface. Load and store documents through the repository instead of using it directly.

## Field Mapping

### FieldMappingResolver

`FieldMappingResolver::resolve()` now works per class instead of per property. It receives a document class
and returns the field mappings of all its properties, keyed by property name. With inheritance it is called
for the root and for every class in the discriminator map. Properties you leave out are not mapped, except
the id and version properties, which always are.

before:

```php
use Patchlevel\ODM\Metadata\FieldMapping;
use Patchlevel\ODM\Metadata\FieldMappingResolver;

final class PropertyNameFieldMappingResolver implements FieldMappingResolver
{
public function resolve(ReflectionProperty $reflectionProperty): FieldMapping|null
{
return new FieldMapping($reflectionProperty->getName());
}
}
```
after:

```php
use Patchlevel\ODM\Metadata\FieldMapping;
use Patchlevel\ODM\Metadata\FieldMappingResolver;

final class PropertyNameFieldMappingResolver implements FieldMappingResolver
{
/**
* @param class-string $className
*
* @return array<string, FieldMapping>
*/
public function resolve(string $className): array
{
$fields = [];

foreach ((new ReflectionClass($className))->getProperties() as $property) {
$fields[$property->getName()] = new FieldMapping($property->getName());
}

return $fields;
}
}
```
5 changes: 5 additions & 0 deletions docs/field-mapping.md
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,11 @@ final readonly class Skill
}
}
```
A document itself must not end up with a normalizer, neither on its class, a parent or an interface it
implements, nor through a guesser, because documents are always stored field by field. The
`StackHydratorFieldMappingResolver`, which `create()` sets up, throws `DocumentHasClassNormalizer` when it
builds the metadata of such a document.

:::tip
The hydrator ships normalizers for enums, dates and arrays out of the box. See the
[hydrator documentation](https://patchlevel.dev/docs/hydrator/latest) for the full list.
Expand Down
2 changes: 2 additions & 0 deletions docs/inheritance.md
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,8 @@ $images->insert(new Video('m-3', 'Clip', 30)); // throws WrongClass
collection. Declare hierarchy-wide indexes there.
* Discriminator values are stored in every document, so keep them short and never change one once data
exists.
* No class in the hierarchy may have a class level normalizer, otherwise the metadata factory throws
`DocumentHasClassNormalizer`.

:::warning
The discriminator map is validated when the metadata is built. Mapping a value to a class that does
Expand Down
23 changes: 9 additions & 14 deletions src/Metadata/AttributeDocumentMetadataFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -53,13 +53,13 @@

$fieldClasses = $discriminatorMap === []
? [$className]
: array_values(array_unique([$rootReflection->getName(), ...array_values($discriminatorMap)]));

Check warning on line 56 in src/Metadata/AttributeDocumentMetadataFactory.php

View workflow job for this annotation

GitHub Actions / Mutation tests (locked, 8.5, ubuntu-latest)

Escaped Mutant for Mutator "UnwrapArrayValues": @@ @@ $fieldClasses = $discriminatorMap === [] ? [$className] - : array_values(array_unique([$rootReflection->getName(), ...array_values($discriminatorMap)])); + : array_values(array_unique([$rootReflection->getName(), ...$discriminatorMap])); $discriminatorValues = [];

$discriminatorValues = [];

foreach ($discriminatorMap as $value => $mappedClass) {
if (!is_a($mappedClass, $className, true)) {
continue;

Check warning on line 62 in src/Metadata/AttributeDocumentMetadataFactory.php

View workflow job for this annotation

GitHub Actions / Mutation tests (locked, 8.5, ubuntu-latest)

Escaped Mutant for Mutator "Continue_": @@ @@ foreach ($discriminatorMap as $value => $mappedClass) { if (!is_a($mappedClass, $className, true)) { - continue; + break; } $discriminatorValues[] = $value;
}

$discriminatorValues[] = $value;
Expand Down Expand Up @@ -147,20 +147,9 @@
$fields = [];

foreach ($classNames as $className) {
$reflection = new ReflectionClass($className);

foreach ($reflection->getProperties() as $reflectionProperty) {
$name = $reflectionProperty->getName();
$field = $this->fieldResolver?->resolve($reflectionProperty);

if ($idProperty === $name) {
$mapping = new FieldMapping('_id', [], $field?->fieldName);
} elseif ($versionProperty === $name) {
$mapping = $field ?? new FieldMapping($name);
} elseif ($field !== null) {
$mapping = $field;
} else {
continue;
foreach ($this->fieldResolver?->resolve($className) ?? [] as $name => $mapping) {
if ($name === $idProperty) {
$mapping = new FieldMapping('_id', [], $mapping->fieldName);
}

if (isset($fields[$name])) {
Expand All @@ -173,13 +162,19 @@
);
}

continue;

Check warning on line 165 in src/Metadata/AttributeDocumentMetadataFactory.php

View workflow job for this annotation

GitHub Actions / Mutation tests (locked, 8.5, ubuntu-latest)

Escaped Mutant for Mutator "Continue_": @@ @@ ); } - continue; + break; } $fields[$name] = $mapping;
}

$fields[$name] = $mapping;
}
}

$fields[$idProperty] ??= new FieldMapping('_id');

if ($versionProperty !== null) {
$fields[$versionProperty] ??= new FieldMapping($versionProperty);
}

return $fields;
}

Expand Down
26 changes: 26 additions & 0 deletions src/Metadata/DocumentHasClassNormalizer.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?php

declare(strict_types=1);

namespace Patchlevel\ODM\Metadata;

use Patchlevel\Hydrator\Normalizer\Normalizer;
use RuntimeException;

use function sprintf;

final class DocumentHasClassNormalizer extends RuntimeException
{
/**
* @param class-string $className
* @param class-string<Normalizer> $normalizerClass
*/
public function __construct(string $className, string $normalizerClass)
{
parent::__construct(sprintf(
'The document "%s" has the class level normalizer "%s". Documents are stored field by field and can not be normalized as a whole.',
$className,
$normalizerClass,
));
}
}
9 changes: 6 additions & 3 deletions src/Metadata/FieldMappingResolver.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,12 @@

namespace Patchlevel\ODM\Metadata;

use ReflectionProperty;

interface FieldMappingResolver
{
public function resolve(ReflectionProperty $reflectionProperty): FieldMapping|null;
/**
* @param class-string $className
*
* @return array<string, FieldMapping> keyed by property name
*/
public function resolve(string $className): array;
}
39 changes: 28 additions & 11 deletions src/Metadata/StackHydratorFieldMappingResolver.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,13 @@

namespace Patchlevel\ODM\Metadata;

use Patchlevel\Hydrator\Metadata\ClassMetadata;
use Patchlevel\Hydrator\Metadata\PropertyMetadata;
use Patchlevel\Hydrator\Normalizer\ArrayNormalizer;
use Patchlevel\Hydrator\Normalizer\ArrayShapeNormalizer;
use Patchlevel\Hydrator\Normalizer\Normalizer;
use Patchlevel\Hydrator\Normalizer\ObjectNormalizer;
use Patchlevel\Hydrator\StackHydrator;
use ReflectionProperty;

final readonly class StackHydratorFieldMappingResolver implements FieldMappingResolver
{
Expand All @@ -19,12 +19,34 @@ public function __construct(
) {
}

public function resolve(ReflectionProperty $reflectionProperty): FieldMapping
/**
* @param class-string $className
*
* @return array<string, FieldMapping>
*
* @throws DocumentHasClassNormalizer
*/
public function resolve(string $className): array
{
$metadata = $this->hydrator->metadata($reflectionProperty->getDeclaringClass()->getName());
$property = $metadata->properties[$reflectionProperty->getName()];
$metadata = $this->hydrator->metadata($className);

return $this->resolvePropertyMetadata($property);
if ($metadata->normalizer !== null) {
throw new DocumentHasClassNormalizer($className, $metadata->normalizer::class);
}

return $this->resolveProperties($metadata);
}

/** @return array<string, FieldMapping> */
private function resolveProperties(ClassMetadata $metadata): array
{
$fields = [];

foreach ($metadata->properties as $property) {
$fields[$property->propertyName] = $this->resolvePropertyMetadata($property);
}

return $fields;
}

private function resolvePropertyMetadata(PropertyMetadata $property): FieldMapping
Expand Down Expand Up @@ -56,15 +78,10 @@ private function resolveNormalizer(string $fieldName, Normalizer $normalizer): F
private function resolveObjectNormalizer(string $fieldName, ObjectNormalizer $objectNormalizer): FieldMapping
{
$metadata = $this->hydrator->metadata($objectNormalizer->className());
$children = [];

foreach ($metadata->properties as $property) {
$children[$property->propertyName] = $this->resolvePropertyMetadata($property);
}

return new FieldMapping(
$fieldName,
$children,
$this->resolveProperties($metadata),
);
}

Expand Down
13 changes: 13 additions & 0 deletions tests/Unit/Fixtures/Circle.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?php

declare(strict_types=1);

namespace Patchlevel\ODM\Tests\Unit\Fixtures;

final class Circle extends Shape
{
public function __construct(string $id, public int $radius)
{
parent::__construct($id);
}
}
16 changes: 16 additions & 0 deletions tests/Unit/Fixtures/DocumentBase.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?php

declare(strict_types=1);

namespace Patchlevel\ODM\Tests\Unit\Fixtures;

use Patchlevel\ODM\Attribute\Id;

abstract class DocumentBase
{
public function __construct(
#[Id]
public string $id,
) {
}
}
10 changes: 10 additions & 0 deletions tests/Unit/Fixtures/NormalizedContract.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php

declare(strict_types=1);

namespace Patchlevel\ODM\Tests\Unit\Fixtures;

#[SkillNormalizer]
interface NormalizedContract
{
}
10 changes: 10 additions & 0 deletions tests/Unit/Fixtures/NormalizedDocumentBase.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php

declare(strict_types=1);

namespace Patchlevel\ODM\Tests\Unit\Fixtures;

#[SkillNormalizer]
abstract class NormalizedDocumentBase extends DocumentBase
{
}
28 changes: 28 additions & 0 deletions tests/Unit/Fixtures/Shape.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

declare(strict_types=1);

namespace Patchlevel\ODM\Tests\Unit\Fixtures;

use Patchlevel\ODM\Attribute\DiscriminatorMap;
use Patchlevel\ODM\Attribute\Document;
use Patchlevel\ODM\Attribute\Id;

#[Document('shapes')]
#[DiscriminatorMap([
'circle' => Circle::class,
'square' => Square::class,
])]
abstract class Shape
{
public function __construct(
#[Id]
private string $id,
) {
}

public function id(): string
{
return $this->id;
}
}
11 changes: 11 additions & 0 deletions tests/Unit/Fixtures/Square.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?php

declare(strict_types=1);

namespace Patchlevel\ODM\Tests\Unit\Fixtures;

/** Has no visible properties of its own, its only property is the private id of Shape. */
#[SkillNormalizer]
final class Square extends Shape
{
}
Loading
Loading