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

[FEATURE] add context mapping populator #47

Merged
merged 8 commits into from
Aug 10, 2023
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 README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,5 @@ This is important for preloading the default configuration of provided converter
and simplify your code and further updates.

## [Usage](docs/usage.md)

## [Development](docs/development.md)
11 changes: 11 additions & 0 deletions docs/development.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
## Development

### Running tests (incl. code coverage)

If you want to run the tests (incl. code coverage) you can do so by configuring Phpstorm in the following way:
![phpstorm-settings.png](images/phpstorm-settings.png)

You can see that we are using the image `pimcore/pimcore:php8.2-debug-latest` here. Of course this could be updated
after a while.
But with this image we can do code coverage by running all tests via phpunit.xml:
![img.png](images/phpstorm-run-configuration.png)
Binary file added docs/images/phpstorm-run-configuration.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added docs/images/phpstorm-settings.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
36 changes: 36 additions & 0 deletions docs/usage.md
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,39 @@ with `phone` (property of the source object).

> Note: the source and the target property must be of the same type for this to work.

#### Mapping context

If you just want to map a single property from the context to the target without transforming it in between, you don't
need to write a custom populator for this, as this bundle already contains the `ContextMappingPopulator` for this use
case.

You can use it in your converter config via the `context` keyword:

```yaml
# config/packages/neusta_converter.yaml
neusta_converter:
converter:
person.converter:
...
context:
group: ~
locale: language
```

Which will populate

`group` (property of the target object)

with `group` (property of the context object)

and

`locale` (property of the target object)

with `language` (property of the context object).

> Note: the context and the target property must be of the same type for this to work.

### Conversion

And now if you want to convert `User`s into `Person`s just type in your code:
Expand Down Expand Up @@ -189,3 +222,6 @@ if ($ctx && $ctx->hasKey('locale')) {

Internally the `GenericContext` is only an associative array but the interface allows you to adapt your own
implementation of a domain-oriented context and use it in your populators as you like.

You can use the context in factories and populators with custom implementation,
but it is also possible to use the simple property mapping like in section [mapping context](#mapping-context) described.
2 changes: 1 addition & 1 deletion src/Converter/Context/GenericContext.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
class GenericContext
{
/** @var array<string, mixed> */
protected array $values;
protected array $values = [];

public function hasKey(string $key): bool
{
Expand Down
2 changes: 1 addition & 1 deletion src/Converter/GenericConverter.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
namespace Neusta\ConverterBundle\Converter;

use Neusta\ConverterBundle\Converter;
use Neusta\ConverterBundle\TargetFactory;
use Neusta\ConverterBundle\Populator;
use Neusta\ConverterBundle\TargetFactory;

/**
* @template TSource of object
Expand Down
2 changes: 1 addition & 1 deletion src/Converter/StrategicConverter.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
namespace Neusta\ConverterBundle\Converter;

use Neusta\ConverterBundle\Converter;
use Neusta\ConverterBundle\Exception\ConverterException;
use Neusta\ConverterBundle\Converter\Strategy\ConverterSelector;
use Neusta\ConverterBundle\Exception\ConverterException;

/**
* @template TSource of object
Expand Down
8 changes: 7 additions & 1 deletion src/DependencyInjection/Configuration.php
Original file line number Diff line number Diff line change
Expand Up @@ -52,9 +52,15 @@ private function addConverterSection(ArrayNodeDefinition $rootNode): void
->useAttributeAsKey('target')
->prototype('scalar')->end()
->end()
->arrayNode('context')
->info('Mapping of context properties (value) to target properties (key)')
->normalizeKeys(false)
->useAttributeAsKey('target')
->prototype('scalar')->end()
->end()
->end()
->validate()
->ifTrue(fn (array $c) => empty($c['populators']) && empty($c['properties']))
->ifTrue(fn (array $c) => empty($c['populators']) && empty($c['properties']) && empty($c['context']))
->thenInvalid('At least one "populator" or "property" must be defined.')
->end()
->end()
Expand Down
17 changes: 14 additions & 3 deletions src/DependencyInjection/NeustaConverterExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
namespace Neusta\ConverterBundle\DependencyInjection;

use Neusta\ConverterBundle\Converter;
use Neusta\ConverterBundle\Populator\ContextMappingPopulator;
use Neusta\ConverterBundle\Populator\PropertyMappingPopulator;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
Expand All @@ -15,14 +16,14 @@
final class NeustaConverterExtension extends ConfigurableExtension
{
/**
* @param array<string, mixed> $config
* @param array<string, mixed> $mergedConfig
*/
public function loadInternal(array $config, ContainerBuilder $container): void
public function loadInternal(array $mergedConfig, ContainerBuilder $container): void
{
$loader = new YamlFileLoader($container, new FileLocator(dirname(__DIR__, 2) . '/config'));
$loader->load('services.yaml');

foreach ($config['converter'] as $converterId => $converter) {
foreach ($mergedConfig['converter'] as $converterId => $converter) {
$this->registerConverterConfiguration($converterId, $converter, $container);
}
}
Expand All @@ -42,6 +43,16 @@ private function registerConverterConfiguration(string $id, array $config, Conta
]);
}

foreach ($config['context'] ?? [] as $targetProperty => $sourceProperty) {
$config['populators'][] = $propertyContextPopulatorId = "{$id}.populator.context.{$targetProperty}";
$container->register($propertyContextPopulatorId, ContextMappingPopulator::class)
->setArguments([
'$targetProperty' => $targetProperty,
'$sourceProperty' => $sourceProperty ?? $targetProperty,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The parameter is named $contextProperty. I fixed it in #48.

'$accessor' => new Reference('property_accessor'),
]);
}

$container->registerAliasForArgument($id, Converter::class, $this->appendSuffix($id, 'Converter'));
$container->register($id, $config['converter'])
->setPublic(true)
Expand Down
58 changes: 58 additions & 0 deletions src/Populator/ContextMappingPopulator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
<?php

declare(strict_types=1);

namespace Neusta\ConverterBundle\Populator;

use Neusta\ConverterBundle\Converter\Context\GenericContext;
use Neusta\ConverterBundle\Exception\PopulationException;
use Neusta\ConverterBundle\Populator;
use Symfony\Component\PropertyAccess\PropertyAccess;
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;

/**
* @template TSource of object
* @template TTarget of object
* @template TContext of GenericContext|null
*
* @implements Populator<TSource, TTarget, TContext>
*/
final class ContextMappingPopulator implements Populator
{
/** @var \Closure(mixed, TContext=):mixed */
private \Closure $mapper;
private PropertyAccessorInterface $accessor;

/**
* @param \Closure(mixed, TContext=):mixed|null $mapper
*/
public function __construct(
private string $targetProperty,
private string $contextProperty,
?\Closure $mapper = null,
PropertyAccessorInterface $accessor = null,
) {
$this->mapper = $mapper ?? static fn ($v) => $v;
$this->accessor = $accessor ?? PropertyAccess::createPropertyAccessor();
}

/**
* @throws PopulationException
*/
public function populate(object $target, object $source, ?object $ctx = null): void
{
if (!$ctx || !$ctx->hasKey($this->contextProperty)) {
return;
}

try {
$this->accessor->setValue(
$target,
$this->targetProperty,
($this->mapper)($ctx->getValue($this->contextProperty), $ctx)
);
} catch (\Throwable $exception) {
throw new PopulationException($this->contextProperty, $this->targetProperty, $exception);
}
}
}
36 changes: 36 additions & 0 deletions tests/Converter/GenericConverterTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
use Neusta\ConverterBundle\Converter;
use Neusta\ConverterBundle\Converter\GenericConverter;
use Neusta\ConverterBundle\Converter\Context\GenericContext;
use Neusta\ConverterBundle\Populator\ContextMappingPopulator;
use Neusta\ConverterBundle\Populator\PropertyMappingPopulator;
use Neusta\ConverterBundle\Tests\Fixtures\Model\PersonFactory;
use Neusta\ConverterBundle\Tests\Fixtures\Model\Person;
use Neusta\ConverterBundle\Tests\Fixtures\Model\User;
Expand All @@ -27,8 +29,10 @@ public function testConvert(): void
{
// Test Fixture
$source = (new User())->setFirstname('Max')->setLastname('Mustermann');

// Test Execution
$target = $this->converter->convert($source);

// Test Assertion
self::assertEquals('Max Mustermann', $target->getFullName());
}
Expand All @@ -38,9 +42,41 @@ public function testConvertWithContext(): void
// Test Fixture
$source = (new User())->setFirstname('Max')->setLastname('Mustermann');
$ctx = (new GenericContext())->setValue('separator', ', ');

// Test Execution
$target = $this->converter->convert($source, $ctx);

// Test Assertion
self::assertEquals('Max, Mustermann', $target->getFullName());
}

public function testConvertWithSameContextPropertyNames(): void
{
$converter = new GenericConverter(new PersonFactory(), [new ContextMappingPopulator('locale', 'locale')]);

// Test Fixture
$source = new User();
$ctx = (new GenericContext())->setValue('locale', 'en');

// Test Execution
$target = $converter->convert($source, $ctx);

// Test Assertion
self::assertEquals('en', $target->getLocale());
}

public function testConvertWithDifferentContextPropertyNames(): void
{
$converter = new GenericConverter(new PersonFactory(), [new ContextMappingPopulator('locale', 'language')]);

// Test Fixture
$source = new User();
$ctx = (new GenericContext())->setValue('language', 'en');

// Test Execution
$target = $converter->convert($source, $ctx);

// Test Assertion
self::assertEquals('en', $target->getLocale());
}
}
41 changes: 41 additions & 0 deletions tests/DependencyInjection/NeustaConverterExtensionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
use Neusta\ConverterBundle\Converter\GenericConverter;
use Neusta\ConverterBundle\DependencyInjection\NeustaConverterExtension;
use Neusta\ConverterBundle\NeustaConverterBundle;
use Neusta\ConverterBundle\Populator\ContextMappingPopulator;
use Neusta\ConverterBundle\Populator\PropertyMappingPopulator;
use Neusta\ConverterBundle\Tests\Fixtures\Model\PersonFactory;
use Neusta\ConverterBundle\Tests\Fixtures\Populator\PersonNamePopulator;
Expand Down Expand Up @@ -82,6 +83,46 @@ public function test_with_mapped_properties(): void
self::assertSame('age', $ageInYearsPopulator->getArgument('$sourceProperty'));
}

public function test_with_mapped_context(): void
{
$container = $this->buildContainer([
'converter' => [
'foobar' => [
'target_factory' => PersonFactory::class,
'context' => [
'name' => null,
'ageInYears' => 'age',
],
],
],
]);

// converter
$converter = $container->getDefinition('foobar');
self::assertSame(GenericConverter::class, $converter->getClass());
self::assertTrue($converter->isPublic());
self::assertTrue($container->hasAlias(Converter::class . ' $foobarConverter'));
self::assertIsReference(PersonFactory::class, $converter->getArgument('$factory'));
self::assertIsArray($converter->getArgument('$populators'));
self::assertCount(2, $converter->getArgument('$populators'));
self::assertIsReference('foobar.populator.context.name', $converter->getArgument('$populators')[0]);
self::assertIsReference('foobar.populator.context.ageInYears', $converter->getArgument('$populators')[1]);

// name context populator
$namePopulator = $container->getDefinition('foobar.populator.context.name');
self::assertSame(ContextMappingPopulator::class, $namePopulator->getClass());
self::assertIsReference('property_accessor', $namePopulator->getArgument('$accessor'));
self::assertSame('name', $namePopulator->getArgument('$targetProperty'));
self::assertSame('name', $namePopulator->getArgument('$sourceProperty'));

// ageInYears context populator
$ageInYearsPopulator = $container->getDefinition('foobar.populator.context.ageInYears');
self::assertSame(ContextMappingPopulator::class, $ageInYearsPopulator->getClass());
self::assertIsReference('property_accessor', $ageInYearsPopulator->getArgument('$accessor'));
self::assertSame('ageInYears', $ageInYearsPopulator->getArgument('$targetProperty'));
self::assertSame('age', $ageInYearsPopulator->getArgument('$sourceProperty'));
}

private static function assertIsReference(string $expected, mixed $actual): void
{
self::assertInstanceOf(Reference::class, $actual);
Expand Down
Loading