Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(attribute): add groups to map to / from attributes #82

Merged
merged 1 commit into from
Mar 20, 2024
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
2 changes: 2 additions & 0 deletions src/Attribute/MapFrom.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
* @param string|callable(mixed $value, object $object): mixed|null $transformer A transformer id or a callable that transform the value during mapping
* @param bool|null $ignore if true, the property will be ignored during mapping
* @param string|null $if The condition to map the property, using the expression language
* @param string[]|null $groups The groups to map the property
*/
public function __construct(
public ?string $source = null,
Expand All @@ -25,6 +26,7 @@ public function __construct(
public mixed $transformer = null,
public ?bool $ignore = null,
public ?string $if = null,
public ?array $groups = null,
) {
}
}
2 changes: 2 additions & 0 deletions src/Attribute/MapTo.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
* @param string|callable(mixed $value, object $object): mixed|null $transformer A transformer id or a callable that transform the value during mapping
* @param bool|null $ignore if true, the property will be ignored during mapping
* @param string|null $if The condition to map the property, using the expression language
* @param string[]|null $groups The groups to map the property
*/
public function __construct(
public ?string $target = null,
Expand All @@ -25,6 +26,7 @@ public function __construct(
public mixed $transformer = null,
public ?bool $ignore = null,
public ?string $if = null,
public ?array $groups = null,
) {
}
}
4 changes: 4 additions & 0 deletions src/Event/PropertyMetadataEvent.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@
*/
final class PropertyMetadataEvent
{
/**
* @param string[]|null $groups
*/
public function __construct(
public readonly MapperMetadata $mapperMetadata,
public readonly SourcePropertyMetadata $source,
Expand All @@ -22,6 +25,7 @@ public function __construct(
public ?TransformerInterface $transformer = null,
public ?bool $ignored = null,
public ?string $if = null,
public ?array $groups = null,
) {
}
}
1 change: 1 addition & 0 deletions src/EventListener/MapFromListener.php
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ private function addPropertyFromTarget(GenerateMapperEvent $event, MapFrom $mapF
transformer: $this->getTransformerFromMapAttribute($event->mapperMetadata->target, $mapFrom),
ignored: $mapFrom->ignore,
if: $mapFrom->if,
groups: $mapFrom->groups,
);

if (\array_key_exists($property->target->name, $event->properties)) {
Expand Down
1 change: 1 addition & 0 deletions src/EventListener/MapToListener.php
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ private function addPropertyFromSource(GenerateMapperEvent $event, MapTo $mapTo,
transformer: $this->getTransformerFromMapAttribute($event->mapperMetadata->source, $mapTo),
ignored: $mapTo->ignore,
if: $mapTo->if,
groups: $mapTo->groups,
);

if (\array_key_exists($property->target->name, $event->properties)) {
Expand Down
80 changes: 17 additions & 63 deletions src/Generator/PropertyConditionsGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,20 @@
use AutoMapper\Metadata\GeneratorMetadata;
use AutoMapper\Metadata\PropertyMetadata;
use PhpParser\Node\Arg;
use PhpParser\Node\ArrayItem as NewArrayItem;
use PhpParser\Node\ArrayItem;
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\ArrayItem as OldArrayItem;
use PhpParser\Node\Name;
use PhpParser\Node\Scalar;
use PhpParser\Node\Stmt;
use PhpParser\Parser;
use PhpParser\ParserFactory;
use Symfony\Component\ExpressionLanguage\ExpressionLanguage;

// compatibility with nikic/php-parser 4.x
if (!class_exists(ArrayItem::class) && class_exists(Expr\ArrayItem::class)) {
class_alias(Expr\ArrayItem::class, ArrayItem::class);
}

/**
* We generate a list of conditions that will allow the field to be mapped to the target.
*
Expand All @@ -41,8 +45,9 @@ public function generate(GeneratorMetadata $metadata, PropertyMetadata $property
$conditions[] = $this->propertyExistsForStdClass($metadata, $propertyMetadata);
$conditions[] = $this->propertyExistsForArray($metadata, $propertyMetadata);
$conditions[] = $this->isAllowedAttribute($metadata, $propertyMetadata);
$conditions[] = $this->sourceGroupsCheck($metadata, $propertyMetadata);
$conditions[] = $this->targetGroupsCheck($metadata, $propertyMetadata);
$conditions[] = $this->groupsCheck($metadata->variableRegistry, $propertyMetadata->groups); // Property groups
$conditions[] = $this->groupsCheck($metadata->variableRegistry, $propertyMetadata->source->groups); // Source groups
$conditions[] = $this->groupsCheck($metadata->variableRegistry, $propertyMetadata->target->groups); // Target groups
$conditions[] = $this->noGroupsCheck($metadata, $propertyMetadata);
$conditions[] = $this->maxDepthCheck($metadata, $propertyMetadata);
$conditions[] = $this->customCondition($metadata, $propertyMetadata);
Expand Down Expand Up @@ -132,71 +137,20 @@ private function isAllowedAttribute(GeneratorMetadata $metadata, PropertyMetadat
}

/**
* When there are groups associated to the source property we check if the context has the same groups.
* 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']))
* ```
*/
private function sourceGroupsCheck(GeneratorMetadata $metadata, PropertyMetadata $propertyMetadata): ?Expr
{
if (!$propertyMetadata->source->groups) {
return null;
}

$variableRegistry = $metadata->variableRegistry;

// compatibility with old versions of nikic/php-parser
if (class_exists(NewArrayItem::class)) {
$arrayItemClass = NewArrayItem::class;
} else {
$arrayItemClass = OldArrayItem::class;
}

return 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(function (string $group) use ($arrayItemClass) {
return new $arrayItemClass(new Scalar\String_($group));
}, $propertyMetadata->source->groups))),
])
);
}

/**
* When there is groups associated to the target property we check if the context has the same groups.
*
* ```php
* (null !== $context[MapperContext::GROUPS] ?? null && array_intersect($context[MapperContext::GROUPS] ?? [], ['group1', 'group2']))
* ```
* @param string[]|null $groups
*/
private function targetGroupsCheck(GeneratorMetadata $metadata, PropertyMetadata $propertyMetadata): ?Expr
private function groupsCheck(VariableRegistry $variableRegistry, ?array $groups = []): ?Expr
{
if (!$propertyMetadata->target->groups) {
if (!$groups) {
return null;
}

$variableRegistry = $metadata->variableRegistry;

// compatibility with old versions of nikic/php-parser
if (class_exists(NewArrayItem::class)) {
$arrayItemClass = NewArrayItem::class;
} else {
$arrayItemClass = OldArrayItem::class;
}

return new Expr\BinaryOp\BooleanAnd(
new Expr\BinaryOp\NotIdentical(
new Expr\ConstFetch(new Name('null')),
Expand All @@ -212,9 +166,9 @@ private function targetGroupsCheck(GeneratorMetadata $metadata, PropertyMetadata
new Expr\Array_()
)
),
new Arg(new Expr\Array_(array_map(function (string $group) use ($arrayItemClass) {
return new $arrayItemClass(new Scalar\String_($group));
}, $propertyMetadata->target->groups))),
new Arg(new Expr\Array_(array_map(function (string $group) {
return new ArrayItem(new Scalar\String_($group));
}, $groups))),
])
);
}
Expand All @@ -228,7 +182,7 @@ private function targetGroupsCheck(GeneratorMetadata $metadata, PropertyMetadata
*/
private function noGroupsCheck(GeneratorMetadata $metadata, PropertyMetadata $propertyMetadata): ?Expr
{
if ($propertyMetadata->target->groups || $propertyMetadata->source->groups) {
if ($propertyMetadata->groups || $propertyMetadata->target->groups || $propertyMetadata->source->groups) {
return null;
}

Expand Down
1 change: 1 addition & 0 deletions src/Metadata/MetadataRegistry.php
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,7 @@ private function createGeneratorMetadata(MapperMetadata $mapperMetadata): Genera
$propertyMappedEvent->ignored ?? false,
$propertyMappedEvent->maxDepth,
$propertyMappedEvent->if,
$propertyMappedEvent->groups,
);
}

Expand Down
4 changes: 4 additions & 0 deletions src/Metadata/PropertyMetadata.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@
*/
final class PropertyMetadata
{
/**
* @param string[]|null $groups
*/
public function __construct(
public readonly SourcePropertyMetadata $source,
public readonly TargetPropertyMetadata $target,
Expand All @@ -23,6 +26,7 @@ public function __construct(
public bool $ignored = false,
public ?int $maxDepth = null,
public ?string $if = null,
public ?array $groups = null,
) {
}
}
21 changes: 20 additions & 1 deletion tests/AutoMapperMapToTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
namespace AutoMapper\Tests;

use AutoMapper\Exception\BadMapDefinitionException;
use AutoMapper\MapperContext;
use AutoMapper\Tests\Fixtures\MapTo\BadMapTo;
use AutoMapper\Tests\Fixtures\MapTo\BadMapToTransformer;
use AutoMapper\Tests\Fixtures\MapTo\Bar;
Expand Down Expand Up @@ -41,7 +42,6 @@ public function testMapToArray()
$this->assertArrayNotHasKey('a', $bar);
$this->assertSame('foo', $bar['baz']);
$this->assertSame('foo', $bar['foo']);
$this->assertSame('external', $bar['externalProperty']);
$this->assertSame('transformFromIsCallable_foo', $bar['transformFromIsCallable']);
$this->assertSame('transformFromStringInstance_foo', $bar['transformFromStringInstance']);
$this->assertSame('transformFromStringStatic_foo', $bar['transformFromStringStatic']);
Expand Down Expand Up @@ -69,6 +69,25 @@ public function testMapToArray()
$this->assertSame('bar', $bar['transformFromCustomTransformerService']);
}

public function testMapToArrayGroups()
{
$this->buildAutoMapper(propertyTransformers: [new TransformerWithDependency(new FooDependency())]);

$foo = new FooMapTo('foo');
$bar = $this->autoMapper->map($foo, 'array');

self::assertArrayNotHasKey('externalProperty', $bar);

$bar = $this->autoMapper->map($foo, 'array', [MapperContext::GROUPS => ['group1']]);

self::assertArrayHasKey('externalProperty', $bar);
self::assertSame('external', $bar['externalProperty']);

$bar = $this->autoMapper->map($foo, 'array', [MapperContext::GROUPS => ['group2']]);

self::assertArrayNotHasKey('externalProperty', $bar);
}

public function testMapFromArray()
{
$foo = ['b' => 'foo', 'bar' => 'bar', 'baz' => 'baz', 'foo' => 'foo'];
Expand Down
2 changes: 1 addition & 1 deletion tests/Fixtures/MapTo/FooMapTo.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
use AutoMapper\Attribute\MapTo;
use AutoMapper\Tests\Fixtures\Transformer\CustomTransformer\TransformerWithDependency;

#[MapTo('array', name: 'externalProperty', transformer: 'transformExternalProperty')]
#[MapTo('array', name: 'externalProperty', transformer: 'transformExternalProperty', groups: ['group1'])]
class FooMapTo
{
public function __construct(
Expand Down
5 changes: 0 additions & 5 deletions tools/phpstan/phpstan-baseline.neon
Original file line number Diff line number Diff line change
Expand Up @@ -75,11 +75,6 @@ parameters:
count: 1
path: ../../src/Generator/CreateTargetStatementsGenerator.php

-
message: "#^Parameter \\#1 \\$items of class PhpParser\\\\Node\\\\Expr\\\\Array_ constructor expects array\\<PhpParser\\\\Node\\\\ArrayItem\\>, array\\<PhpParser\\\\Node\\\\ArrayItem\\|PhpParser\\\\Node\\\\Expr\\\\ArrayItem\\> given\\.$#"
count: 2
path: ../../src/Generator/PropertyConditionsGenerator.php

-
message: "#^Method AutoMapper\\\\Loader\\\\FileLoader\\:\\:addHashToRegistry\\(\\) has parameter \\$className with no type specified\\.$#"
count: 1
Expand Down
Loading