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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Apply the Symfony JsonStreamer `default_options` configuration when streaming JSON through the
AutoMapper, and allow to pass default options to its reader and writer
- Add an `ignored_groups` context option, also mapped from the serializer `AbstractNormalizer::IGNORED_GROUPS`, to exclude the properties belonging to the given groups
- Add an `enable_default_groups` context option, also mapped from the serializer `AbstractNormalizer::ENABLE_DEFAULT_GROUPS`, to put the properties without groups in the `Default` and class short name groups

### Fixed
- Fix the deprecation triggered by the bundle on Symfony 8.2 about the event dispatcher service alias
Expand Down
19 changes: 19 additions & 0 deletions docs/getting-started/context.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,25 @@ In this case a property flagged with both the `read` and `internal` groups will
property are checked, including the serializer `#[Groups]` overridden by the `groups` argument of `#[MapTo]` or `#[MapFrom]`. When used through the
Symfony Serializer, the `AbstractNormalizer::IGNORED_GROUPS` option is supported.

### Default groups

When the `enable_default_groups` option is set, properties without groups belong to the `Default` group and to the
group named after the short name of their class, like the Symfony Serializer does with the
`AbstractNormalizer::ENABLE_DEFAULT_GROUPS` option.

```php
$source = new User();
$target = $autoMapper->map($source, UserDTO::class, ['groups' => ['Default'], 'enable_default_groups' => true]);
```

In this case properties without groups are mapped. The serializer `#[Groups]` of each class are checked against the
default groups of that class only: a `User` property in the `Default` or `User` group is mapped, but a `User` property
in the `UserDTO` group is not (and the same goes for `UserDTO` properties with the `Default` and `UserDTO` groups).
The groups set with the `groups` argument of `#[MapTo]` or `#[MapFrom]` belong to the mapping of the property, so they
match `Default` and the short names of both classes.

Requesting only other groups still excludes the properties without groups.

### Allowed attributes

Allowed attributes allow you to define a subset of properties that should be mapped. This is
Expand Down
118 changes: 92 additions & 26 deletions src/Generator/PropertyConditionsGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -54,11 +54,15 @@ public function generate(GeneratorMetadata $metadata, PropertyMetadata $property
$conditions[] = $this->isAllowedAttribute($metadata, $propertyMetadata);

if (!$propertyMetadata->disableGroupsCheck) {
$conditions[] = $this->groupsCheck($metadata->variableRegistry, $propertyMetadata->groups); // Property groups
$sourceDefaultGroups = $this->defaultGroups($metadata->mapperMetadata->isSourceArrayLike() ? null : $metadata->mapperMetadata->source);
$targetDefaultGroups = $this->defaultGroups($metadata->mapperMetadata->isTargetArrayLike() ? null : $metadata->mapperMetadata->target);
$defaultGroups = array_values(array_unique([...$sourceDefaultGroups, ...$targetDefaultGroups]));

$conditions[] = $this->groupsCheck($metadata->variableRegistry, $propertyMetadata->groups, $defaultGroups); // Property groups

if ($propertyMetadata->groups === null) {
$conditions[] = $this->groupsCheck($metadata->variableRegistry, $propertyMetadata->source->groups); // Source groups
$conditions[] = $this->groupsCheck($metadata->variableRegistry, $propertyMetadata->target->groups); // Target groups
$conditions[] = $this->groupsCheck($metadata->variableRegistry, $propertyMetadata->source->groups, $sourceDefaultGroups); // Source groups
$conditions[] = $this->groupsCheck($metadata->variableRegistry, $propertyMetadata->target->groups, $targetDefaultGroups); // Target groups
}

// Ignored groups exclude the property whatever its groups come from, even the overridden ones
Expand All @@ -68,7 +72,7 @@ public function generate(GeneratorMetadata $metadata, PropertyMetadata $property
...$propertyMetadata->target->groups ?? [],
])));

$conditions[] = $this->noGroupsCheck($metadata, $propertyMetadata);
$conditions[] = $this->noGroupsCheck($metadata, $propertyMetadata, $defaultGroups);
}

$conditions[] = $this->maxDepthCheck($metadata, $propertyMetadata);
Expand Down Expand Up @@ -185,41 +189,60 @@ private function isAllowedAttribute(GeneratorMetadata $metadata, PropertyMetadat
]);
}

/**
* The groups an ungrouped property belongs to when the `enable_default_groups` option is set: `Default` and the
* short name of the class.
*
* @return string[]
*/
private function defaultGroups(?string $class): array
{
if (null === $class) {
return ['Default'];
}

return ['Default', (false !== $nsSep = strrpos($class, '\\')) ? substr($class, $nsSep + 1) : $class];
}

/**
* When there is groups associated we check if the context has the same groups.
*
* ```php
* (null !== $context[MapperContext::GROUPS] ?? null && array_intersect($context[MapperContext::GROUPS] ?? [], ['group1', 'group2']))
* ```
*
* When some of the groups are default groups, the `enable_default_groups` option also allows them through any
* default group in the context.
*
* ```php
* || (($context[MapperContext::ENABLE_DEFAULT_GROUPS] ?? false) && array_intersect($context[MapperContext::GROUPS] ?? [], ['Default', 'ClassName']))
* ```
*
* @param string[]|null $groups
* @param string[] $defaultGroups
*/
private function groupsCheck(VariableRegistry $variableRegistry, ?array $groups = []): ?Expr
private function groupsCheck(VariableRegistry $variableRegistry, ?array $groups = [], array $defaultGroups = []): ?Expr
{
if (!$groups) {
return null;
}

return new Expr\BinaryOp\BooleanAnd(
$condition = new Expr\BinaryOp\BooleanAnd(
new Expr\BinaryOp\NotIdentical(
new Expr\ConstFetch(new Name('null')),
new Expr\BinaryOp\Coalesce(
new Expr\ArrayDimFetch($variableRegistry->getContext(), new Scalar\String_(MapperContext::GROUPS)),
new Expr\Array_()
)
),
new Expr\FuncCall(new Name('array_intersect'), [
new Arg(
new Expr\BinaryOp\Coalesce(
new Expr\ArrayDimFetch($variableRegistry->getContext(), new Scalar\String_(MapperContext::GROUPS)),
new Expr\Array_()
)
),
new Arg(new Expr\Array_(array_map(static function (string $group) {
return create_expr_array_item(new Scalar\String_($group));
}, $groups))),
])
$this->contextGroupsIntersect($variableRegistry, $groups),
);

if (!array_intersect($groups, $defaultGroups)) {
return $condition;
}

return new Expr\BinaryOp\BooleanOr($condition, $this->defaultGroupsCheck($variableRegistry, $defaultGroups));
}

/**
Expand Down Expand Up @@ -258,26 +281,69 @@ private function ignoredGroupsCheck(VariableRegistry $variableRegistry, ?array $
* ```php
* (!array_key_exists(MapperContext::GROUPS, $context) || !$context[MapperContext::GROUPS])
* ```
*
* With the `enable_default_groups` option, the property is in the default groups.
*
* ```php
* || (($context[MapperContext::ENABLE_DEFAULT_GROUPS] ?? false) && array_intersect($context[MapperContext::GROUPS] ?? [], ['Default', 'ClassName']))
* ```
*
* @param string[] $defaultGroups
*/
private function noGroupsCheck(GeneratorMetadata $metadata, PropertyMetadata $propertyMetadata): ?Expr
private function noGroupsCheck(GeneratorMetadata $metadata, PropertyMetadata $propertyMetadata, array $defaultGroups): ?Expr
{
if ($propertyMetadata->groups || $propertyMetadata->target->groups || $propertyMetadata->source->groups) {
return null;
}

return new Expr\BinaryOp\BooleanOr(
new Expr\BooleanNot(
new Expr\FuncCall(new Name('array_key_exists'), [
new Arg(new Scalar\String_(MapperContext::GROUPS)),
new Arg($metadata->variableRegistry->getContext()),
])
new Expr\BinaryOp\BooleanOr(
new Expr\BooleanNot(
new Expr\FuncCall(new Name('array_key_exists'), [
new Arg(new Scalar\String_(MapperContext::GROUPS)),
new Arg($metadata->variableRegistry->getContext()),
])
),
new Expr\BooleanNot(
new Expr\ArrayDimFetch($metadata->variableRegistry->getContext(), new Scalar\String_(MapperContext::GROUPS))
)
),
new Expr\BooleanNot(
new Expr\ArrayDimFetch($metadata->variableRegistry->getContext(), new Scalar\String_(MapperContext::GROUPS))
)
$this->defaultGroupsCheck($metadata->variableRegistry, $defaultGroups),
);
}

/**
* @param string[] $defaultGroups
*/
private function defaultGroupsCheck(VariableRegistry $variableRegistry, array $defaultGroups): Expr
{
return new Expr\BinaryOp\BooleanAnd(
new Expr\BinaryOp\Coalesce(
new Expr\ArrayDimFetch($variableRegistry->getContext(), new Scalar\String_(MapperContext::ENABLE_DEFAULT_GROUPS)),
new Expr\ConstFetch(new Name('false'))
),
$this->contextGroupsIntersect($variableRegistry, $defaultGroups),
);
}

/**
* @param string[] $groups
*/
private function contextGroupsIntersect(VariableRegistry $variableRegistry, array $groups): Expr
{
return new Expr\FuncCall(new Name('array_intersect'), [
new Arg(
new Expr\BinaryOp\Coalesce(
new Expr\ArrayDimFetch($variableRegistry->getContext(), new Scalar\String_(MapperContext::GROUPS)),
new Expr\Array_()
)
),
new Arg(new Expr\Array_(array_map(static function (string $group) {
return create_expr_array_item(new Scalar\String_($group));
}, $groups))),
]);
}

/**
* When there is a max depth for this property we check if the context has a depth lower or equal to the max depth.
*
Expand Down
13 changes: 13 additions & 0 deletions src/MapperContext.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
* @phpstan-type MapperContextArray array{
* "groups"?: string[]|null,
* "ignored_groups"?: string[]|null,
* "enable_default_groups"?: bool,
* "allowed_attributes"?: string[]|array<string, string[]>|null,
* "ignored_attributes"?: string[]|array<string, string[]>|null,
* "circular_reference_limit"?: int|null,
Expand Down Expand Up @@ -50,6 +51,11 @@ class MapperContext
* Exclude the properties belonging to any of these groups, whichever groups are allowed.
*/
public const string IGNORED_GROUPS = 'ignored_groups';

/**
* Put the properties without explicit groups in the `Default` and class short name groups.
*/
public const string ENABLE_DEFAULT_GROUPS = 'enable_default_groups';
public const string ALLOWED_ATTRIBUTES = 'allowed_attributes';
public const string IGNORED_ATTRIBUTES = 'ignored_attributes';
public const string CIRCULAR_REFERENCE_LIMIT = 'circular_reference_limit';
Expand Down Expand Up @@ -113,6 +119,13 @@ public function setGroups(?array $groups): self
return $this;
}

public function setEnableDefaultGroups(bool $enableDefaultGroups): self
{
$this->context[self::ENABLE_DEFAULT_GROUPS] = $enableDefaultGroups;

return $this;
}

/**
* @param string[]|null $ignoredGroups
*/
Expand Down
1 change: 1 addition & 0 deletions src/Normalizer/AutoMapperNormalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
private const array SERIALIZER_CONTEXT_MAPPING = [
AbstractNormalizer::GROUPS => MapperContext::GROUPS,
'ignored_groups' => MapperContext::IGNORED_GROUPS, // AbstractNormalizer::IGNORED_GROUPS, Symfony >= 8.2
'enable_default_groups' => MapperContext::ENABLE_DEFAULT_GROUPS, // AbstractNormalizer::ENABLE_DEFAULT_GROUPS, Symfony >= 8.2
AbstractNormalizer::ATTRIBUTES => MapperContext::ALLOWED_ATTRIBUTES,
AbstractNormalizer::IGNORED_ATTRIBUTES => MapperContext::IGNORED_ATTRIBUTES,
AbstractNormalizer::OBJECT_TO_POPULATE => MapperContext::TARGET_TO_POPULATE,
Expand Down
5 changes: 5 additions & 0 deletions tests/AutoMapperTest/DefaultGroups/expected.custom.data
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
AutoMapper\Tests\AutoMapperTest\DefaultGroups\AuthorDTO {
+name: null
+email: "email"
+bio: null
}
5 changes: 5 additions & 0 deletions tests/AutoMapperTest/DefaultGroups/expected.default.data
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
AutoMapper\Tests\AutoMapperTest\DefaultGroups\AuthorDTO {
+name: "name"
+email: null
+bio: "bio"
}
5 changes: 5 additions & 0 deletions tests/AutoMapperTest/DefaultGroups/expected.disabled.data
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
AutoMapper\Tests\AutoMapperTest\DefaultGroups\AuthorDTO {
+name: null
+email: null
+bio: null
}
5 changes: 5 additions & 0 deletions tests/AutoMapperTest/DefaultGroups/expected.source-class.data
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
AutoMapper\Tests\AutoMapperTest\DefaultGroups\AuthorDTO {
+name: "name"
+email: null
+bio: "bio"
}
5 changes: 5 additions & 0 deletions tests/AutoMapperTest/DefaultGroups/expected.target-class.data
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
AutoMapper\Tests\AutoMapperTest\DefaultGroups\AuthorDTO {
+name: "name"
+email: null
+bio: "bio"
}
41 changes: 41 additions & 0 deletions tests/AutoMapperTest/DefaultGroups/map.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<?php

declare(strict_types=1);

namespace AutoMapper\Tests\AutoMapperTest\DefaultGroups;

use AutoMapper\Attribute\MapTo;
use AutoMapper\Tests\AutoMapperBuilder;
use Symfony\Component\Serializer\Attribute\Groups;

class Author
{
public string $name = 'name';

#[Groups(['custom'])]
public string $email = 'email';

#[MapTo(groups: ['AuthorDTO'])]
public string $bio = 'bio';
}

class AuthorDTO
{
public ?string $name = null;
public ?string $email = null;
public ?string $bio = null;
}

return (static function () {
$autoMapper = AutoMapperBuilder::buildAutoMapper();

yield 'disabled' => $autoMapper->map(new Author(), AuthorDTO::class, ['groups' => ['Default']]);

yield 'default' => $autoMapper->map(new Author(), AuthorDTO::class, ['groups' => ['Default'], 'enable_default_groups' => true]);

yield 'source-class' => $autoMapper->map(new Author(), AuthorDTO::class, ['groups' => ['Author'], 'enable_default_groups' => true]);

yield 'target-class' => $autoMapper->map(new Author(), AuthorDTO::class, ['groups' => ['AuthorDTO'], 'enable_default_groups' => true]);

yield 'custom' => $autoMapper->map(new Author(), AuthorDTO::class, ['groups' => ['custom'], 'enable_default_groups' => true]);
})();
16 changes: 16 additions & 0 deletions tests/Fixtures/Normalizer/DefaultGroupsConferenceDummy.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?php

declare(strict_types=1);

namespace AutoMapper\Tests\Fixtures\Normalizer;

use Symfony\Component\Serializer\Attribute\Groups;

class DefaultGroupsConferenceDummy
{
public string $name = 'SymfonyCon';

/** @var DefaultGroupsTalkDummy[] */
#[Groups(['detail'])]
public array $talks = [];
}
21 changes: 21 additions & 0 deletions tests/Fixtures/Normalizer/DefaultGroupsDummy.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php

declare(strict_types=1);

namespace AutoMapper\Tests\Fixtures\Normalizer;

use Symfony\Component\Serializer\Attribute\Groups;

class DefaultGroupsDummy
{
public string $noGroup = 'noGroup';

#[Groups(['custom'])]
public string $customGroup = 'customGroup';

#[Groups(['Default'])]
public string $defaultGroup = 'defaultGroup';

#[Groups(['DefaultGroupsDummy'])]
public string $classGroup = 'classGroup';
}
10 changes: 10 additions & 0 deletions tests/Fixtures/Normalizer/DefaultGroupsTalkDummy.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php

declare(strict_types=1);

namespace AutoMapper\Tests\Fixtures\Normalizer;

class DefaultGroupsTalkDummy
{
public string $title = 'Keynote';
}
Loading