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 @@ -31,6 +31,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
Symfony Uids are now read from any of these formats
- 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

### Fixed
- Fix the deprecation triggered by the bundle on Symfony 8.2 about the event dispatcher service alias
Expand Down
12 changes: 12 additions & 0 deletions docs/getting-started/context.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,18 @@ In this case only properties that have been flagged with the `read` group will b
> [!WARNING]
> Groups are checked on both the source and target objects, both must have one of the groups from the context to be mapped.

### Ignored groups

Ignored groups exclude the properties belonging to at least one of the given groups, whichever groups are allowed.

```php
$source = new User();
$target = $autoMapper->map($source, UserDTO::class, ['groups' => ['read'], 'ignored_groups' => ['internal']]);
```

In this case a property flagged with both the `read` and `internal` groups will not be mapped. All the groups of a
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.

### Allowed attributes

Expand Down
37 changes: 37 additions & 0 deletions src/Generator/PropertyConditionsGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,13 @@ public function generate(GeneratorMetadata $metadata, PropertyMetadata $property
$conditions[] = $this->groupsCheck($metadata->variableRegistry, $propertyMetadata->target->groups); // Target groups
}

// Ignored groups exclude the property whatever its groups come from, even the overridden ones
$conditions[] = $this->ignoredGroupsCheck($metadata->variableRegistry, array_values(array_unique([
...$propertyMetadata->groups ?? [],
...$propertyMetadata->source->groups ?? [],
...$propertyMetadata->target->groups ?? [],
])));

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

Expand Down Expand Up @@ -215,6 +222,36 @@ private function groupsCheck(VariableRegistry $variableRegistry, ?array $groups
);
}

/**
* When there is groups associated we check that none of them is ignored by the context.
*
* ```php
* !array_intersect($context[MapperContext::IGNORED_GROUPS] ?? [], ['group1', 'group2'])
* ```
*
* @param string[]|null $groups
*/
private function ignoredGroupsCheck(VariableRegistry $variableRegistry, ?array $groups = []): ?Expr
{
if (!$groups) {
return null;
}

return new Expr\BooleanNot(
new Expr\FuncCall(new Name('array_intersect'), [
new Arg(
new Expr\BinaryOp\Coalesce(
new Expr\ArrayDimFetch($variableRegistry->getContext(), new Scalar\String_(MapperContext::IGNORED_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 no groups associated to the target property or source property we check if the context has the same groups.
*
Expand Down
16 changes: 16 additions & 0 deletions src/MapperContext.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
*
* @phpstan-type MapperContextArray array{
* "groups"?: string[]|null,
* "ignored_groups"?: string[]|null,
* "allowed_attributes"?: string[]|array<string, string[]>|null,
* "ignored_attributes"?: string[]|array<string, string[]>|null,
* "circular_reference_limit"?: int|null,
Expand Down Expand Up @@ -44,6 +45,11 @@
class MapperContext
{
public const string GROUPS = 'groups';

/**
* Exclude the properties belonging to any of these groups, whichever groups are allowed.
*/
public const string IGNORED_GROUPS = 'ignored_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 @@ -107,6 +113,16 @@ public function setGroups(?array $groups): self
return $this;
}

/**
* @param string[]|null $ignoredGroups
*/
public function setIgnoredGroups(?array $ignoredGroups): self
{
$this->context[self::IGNORED_GROUPS] = $ignoredGroups;

return $this;
}

/**
* @param string[]|array<string, string[]>|null $allowedAttributes
*/
Expand Down
5 changes: 5 additions & 0 deletions src/Normalizer/AutoMapperNormalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
{
private const array SERIALIZER_CONTEXT_MAPPING = [
AbstractNormalizer::GROUPS => MapperContext::GROUPS,
'ignored_groups' => MapperContext::IGNORED_GROUPS, // AbstractNormalizer::IGNORED_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 Expand Up @@ -169,6 +170,10 @@ private function createAutoMapperContext(?string $format = null, array $serializ
unset($serializerContext[$serializerContextName]);
}

if (\is_scalar($context[MapperContext::IGNORED_GROUPS] ?? null)) {
$context[MapperContext::IGNORED_GROUPS] = (array) $context[MapperContext::IGNORED_GROUPS];
}

if (\array_key_exists(AbstractNormalizer::DEFAULT_CONSTRUCTOR_ARGUMENTS, $serializerContext) && is_iterable($serializerContext[AbstractNormalizer::DEFAULT_CONSTRUCTOR_ARGUMENTS])) {
/**
* @var string $class
Expand Down
4 changes: 4 additions & 0 deletions tests/AutoMapperTest/IgnoredGroups/expected.groups.data
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
[
"admin" => "admin"
"id" => "id"
]
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
[
"id" => "id"
"overridden" => "overridden"
"secret" => "secret"
]
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
[
"admin" => "admin"
"id" => "id"
]
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
AutoMapper\Tests\AutoMapperTest\IgnoredGroups\Bar {
+id: "id"
+secret: ? string
}
51 changes: 51 additions & 0 deletions tests/AutoMapperTest/IgnoredGroups/map.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
<?php

declare(strict_types=1);

namespace AutoMapper\Tests\AutoMapperTest\IgnoredGroups;

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

class Foo
{
#[Groups(['read'])]
public string $id = 'id';

#[Groups(['read', 'internal'])]
public string $secret = 'secret';

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

#[MapTo(target: 'array', groups: ['read', 'admin'])]
public string $admin = 'admin';

#[Groups(['internal'])]
#[MapTo(target: 'array', groups: ['read'])]
public string $overridden = 'overridden';

public string $ungrouped = 'ungrouped';
}

class Bar
{
#[Groups(['read'])]
public string $id;

#[Groups(['read', 'internal'])]
public string $secret;
}

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

yield 'groups' => $autoMapper->map(new Foo(), 'array', ['groups' => ['read', 'internal'], 'ignored_groups' => ['internal']]);

yield 'overridden-groups' => $autoMapper->map(new Foo(), 'array', ['groups' => ['read'], 'ignored_groups' => ['internal']]);

yield 'map-to-groups' => $autoMapper->map(new Foo(), 'array', ['groups' => ['read'], 'ignored_groups' => ['admin']]);

yield 'target-groups' => $autoMapper->map(['id' => 'id', 'secret' => 'secret'], Bar::class, ['groups' => ['read'], 'ignored_groups' => ['internal']]);
})();
34 changes: 34 additions & 0 deletions tests/Normalizer/Features/GroupsTestTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -89,4 +89,38 @@ public function testNormalizeNoPropertyInGroup(): void

$this->assertEquals([], $normalizer->normalize($obj, null, ['groups' => ['notExist']]));
}

public function testNormalizeWithIgnoredGroups(): void
{
$normalizer = $this->getNormalizerForGroups();

$obj = new GroupDummy();
$obj->setFoo('foo');
$obj->setBar('bar');
$obj->setFooBar('fooBar');

$this->assertEquals([
'bar' => 'bar',
], $normalizer->normalize($obj, null, ['groups' => ['a', 'c'], 'ignored_groups' => ['a']]));

$normalized = $normalizer->normalize($obj, null, ['groups' => ['a', 'c'], 'ignored_groups' => 'b']);
$this->assertSame('foo', $normalized['foo']);
$this->assertArrayNotHasKey('bar', $normalized);
$this->assertArrayNotHasKey('fooBar', $normalized);
}

public function testDenormalizeWithIgnoredGroups(): void
{
$normalizer = $this->getDenormalizerForGroups();

$obj = new GroupDummy();
$obj->setFoo('foo');

$this->assertEquals($obj, $normalizer->denormalize(
['foo' => 'foo', 'bar' => 'bar', 'fooBar' => 'fooBar'],
GroupDummy::class,
null,
['groups' => ['a', 'b'], 'ignored_groups' => ['b']]
));
}
}