Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit 81039a8

Browse filesBrowse files
fabpotsoyuka
authored andcommitted
feature #51741 [ObjectMapper] Object to Object mapper component (soyuka)
This PR was squashed before being merged into the 7.3 branch. Discussion ---------- [ObjectMapper] Object to Object mapper component | Q | A | ------------- | --- | Branch? | 7.3 | Bug fix? | no | New feature? | yes | Deprecations? | no | License | MIT | Doc PR | TBD this description will be used as docs ## Why ? In the train back from [API Platform Con](https://api-platform.com/con/2023/) and after watching `@weaverryan` conference about API Platform's feature that helps [separating Doctrine Entities from POPOs](https://symfonycasts.com/screencast/api-platform-extending/state-options), we had the feeling that such a component is definitely missing from the Symfony ecosystem. Current implementations (automapper-plus, janephp/automapper) are good but feel to complicated when you want something accessible (DX and complexity). Here we're not trying to have exceptional performance, we just want an accessible API with few mandatory features. Basically those are: - map properties from a class/object to another class/object (`Map(target: A::class)`) - configure the property name each property is mapped to (`Map(target: 'prop')`) - change the value during transformation (`Map(transform: 'ucfirst')`) - control whether the value should be mapped or not (`Map(if: 'boolval')`) - reuse objects if possible (works better with doctrine UOW) Other implementation details: - if a property exists in B, it'll "automatically" be mapped (doesn't handle type errors, should we ?) - if a property doesn't exists in B it'll "automatically" **not** be mapped The rest is not "auto". ## Mapper Component The Mapper component allows you to map an object to another object, facilitating the mapping using attributes. ### Usage ```php use Symfony\Component\ObjectMapper\ObjectMapper; use Symfony\Component\ObjectMapper\Attributes\Map; // This maps class `A` to class `B`. #[Map(B::class)] class A { // This maps A::foo to B::bar. #[Map(target: 'bar')] public string $foo; // This calls ucfirst on A::transform #[Map(transform: 'ucfirst')] public string $name; // This doesn't map A::bar if it's value is falsy. #[Map(if: 'boolval')] public bool $bar = false; } $mapper = new ObjectMapper(); $mapper->map(new A); ``` The `Map` attribute has the following signature: ```php #[Attribute(Attribute::TARGET_CLASS | Attribute::TARGET_PROPERTY | Attribute::IS_REPEATABLE)] final class Map { /** * * `@param` null|string|class-string $source The property or the class to map to * `@param` null|string|class-string $target The property or the class to map from * `@param` string|callable(mixed $value, object $object): bool $if A Symfony service name or a callable that instructs whether to map * `@param` CallableType|CallableType[] $transform A Symfony service name or a callable that transform the value during mapping */ public function __construct( public readonly ?string $source = null, public readonly ?string $target = null, public readonly mixed $if = null, public readonly mixed $transform = null ){ } } ``` `if` and `transform` are callable or Symfony services, not that we need to introduce an interface for services to implement, this will follow if we want to introduce the component inside the Framework Bundle. The mapper also takes a `$source` argument if one needs to update an object instead of creating a new one: ```php $b = new B; $mapper = new ObjectMapper(); $mapper->map(new A, $b); ``` ## TODO - [x] AutoMapper or Automapper or something else? `Mapper` component with an `AutoMapper` implementation. - [x] max depth? Supports recursivity, `maxDepth` is for serializers. Commits ------- 3f99b03 [ObjectMapper] Object to Object mapper component
2 parents 4fb2615 + 3f99b03 commit 81039a8
Copy full SHA for 81039a8

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.
Dismiss banner

56 files changed

+1851
-0
lines changed

‎composer.json

Copy file name to clipboardExpand all lines: composer.json
+1
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,7 @@
9191
"symfony/mime": "self.version",
9292
"symfony/monolog-bridge": "self.version",
9393
"symfony/notifier": "self.version",
94+
"symfony/object-mapper": "self.version",
9495
"symfony/options-resolver": "self.version",
9596
"symfony/password-hasher": "self.version",
9697
"symfony/process": "self.version",
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
/Tests export-ignore
2+
/phpunit.xml.dist export-ignore
3+
/.git* export-ignore

‎src/Symfony/Component/ObjectMapper/.github/PULL_REQUEST_TEMPLATE.md

Copy file name to clipboardExpand all lines: src/Symfony/Component/ObjectMapper/.github/PULL_REQUEST_TEMPLATE.md
+8
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
name: Check subtree split
2+
3+
on:
4+
pull_request_target:
5+
6+
jobs:
7+
close-pull-request:
8+
runs-on: ubuntu-latest
9+
10+
steps:
11+
- name: Close pull request
12+
uses: actions/github-script@v6
13+
with:
14+
script: |
15+
if (context.repo.owner === "symfony") {
16+
github.rest.issues.createComment({
17+
owner: "symfony",
18+
repo: context.repo.repo,
19+
issue_number: context.issue.number,
20+
body: `
21+
Thanks for your Pull Request! We love contributions.
22+
23+
However, you should instead open your PR on the main repository:
24+
https://github.com/symfony/symfony
25+
26+
This repository is what we call a "subtree split": a read-only subset of that main repository.
27+
We're looking forward to your PR there!
28+
`
29+
});
30+
31+
github.rest.pulls.update({
32+
owner: "symfony",
33+
repo: context.repo.repo,
34+
pull_number: context.issue.number,
35+
state: "closed"
36+
});
37+
}

‎src/Symfony/Component/ObjectMapper/.github/workflows/close-pull-request.yml

Copy file name to clipboardExpand all lines: src/Symfony/Component/ObjectMapper/.github/workflows/close-pull-request.yml
+20
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
vendor/
2+
composer.lock
3+
phpunit.xml
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the Symfony package.
5+
*
6+
* (c) Fabien Potencier <fabien@symfony.com>
7+
*
8+
* For the full copyright and license information, please view the LICENSE
9+
* file that was distributed with this source code.
10+
*/
11+
12+
namespace Symfony\Component\ObjectMapper\Attribute;
13+
14+
/**
15+
* Configures a class or a property to map to.
16+
*
17+
* @experimental
18+
*
19+
* @author Antoine Bluchet <soyuka@gmail.com>
20+
*/
21+
#[\Attribute(\Attribute::TARGET_CLASS | \Attribute::TARGET_PROPERTY | \Attribute::IS_REPEATABLE)]
22+
readonly class Map
23+
{
24+
/**
25+
* @param string|class-string|null $source The property or the class to map from
26+
* @param string|class-string|null $target The property or the class to map to
27+
* @param string|bool|callable(mixed, object): bool|null $if A boolean, a service id or a callable that instructs whether to map
28+
* @param (string|callable(mixed, object): mixed)|(string|callable(mixed, object): mixed)[]|null $transform A service id or a callable that transforms the value during mapping
29+
*/
30+
public function __construct(
31+
public ?string $target = null,
32+
public ?string $source = null,
33+
public mixed $if = null,
34+
public mixed $transform = null,
35+
) {
36+
}
37+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
CHANGELOG
2+
=========
3+
4+
7.3
5+
---
6+
7+
* Add the component as experimental
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the Symfony package.
5+
*
6+
* (c) Fabien Potencier <fabien@symfony.com>
7+
*
8+
* For the full copyright and license information, please view the LICENSE
9+
* file that was distributed with this source code.
10+
*/
11+
12+
namespace Symfony\Component\ObjectMapper;
13+
14+
/**
15+
* Service used by "Map::if".
16+
*
17+
* @template T of object
18+
*
19+
* @experimental
20+
*
21+
* {@see Symfony\Component\ObjectMapper\Attribute\Map}
22+
*/
23+
interface ConditionCallableInterface
24+
{
25+
/**
26+
* @param mixed $value The value being mapped
27+
* @param T $object The object we're working on
28+
*/
29+
public function __invoke(mixed $value, object $object): bool;
30+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the Symfony package.
5+
*
6+
* (c) Fabien Potencier <fabien@symfony.com>
7+
*
8+
* For the full copyright and license information, please view the LICENSE
9+
* file that was distributed with this source code.
10+
*/
11+
12+
namespace Symfony\Component\ObjectMapper\Exception;
13+
14+
/**
15+
* @experimental
16+
*
17+
* @author Antoine Bluchet <soyuka@gmail.com>
18+
*/
19+
interface ExceptionInterface extends \Throwable
20+
{
21+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the Symfony package.
5+
*
6+
* (c) Fabien Potencier <fabien@symfony.com>
7+
*
8+
* For the full copyright and license information, please view the LICENSE
9+
* file that was distributed with this source code.
10+
*/
11+
12+
namespace Symfony\Component\ObjectMapper\Exception;
13+
14+
/**
15+
* @experimental
16+
*
17+
* @author Antoine Bluchet <soyuka@gmail.com>
18+
*/
19+
class MappingException extends RuntimeException
20+
{
21+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the Symfony package.
5+
*
6+
* (c) Fabien Potencier <fabien@symfony.com>
7+
*
8+
* For the full copyright and license information, please view the LICENSE
9+
* file that was distributed with this source code.
10+
*/
11+
12+
namespace Symfony\Component\ObjectMapper\Exception;
13+
14+
/**
15+
* @experimental
16+
*
17+
* @author Antoine Bluchet <soyuka@gmail.com>
18+
*/
19+
final class MappingTransformException extends RuntimeException
20+
{
21+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the Symfony package.
5+
*
6+
* (c) Fabien Potencier <fabien@symfony.com>
7+
*
8+
* For the full copyright and license information, please view the LICENSE
9+
* file that was distributed with this source code.
10+
*/
11+
12+
namespace Symfony\Component\ObjectMapper\Exception;
13+
14+
/**
15+
* @experimental
16+
*
17+
* @author Antoine Bluchet <soyuka@gmail.com>
18+
*/
19+
class RuntimeException extends \RuntimeException implements ExceptionInterface
20+
{
21+
}
+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
Copyright (c) 2025-present Fabien Potencier
2+
3+
Permission is hereby granted, free of charge, to any person obtaining a copy
4+
of this software and associated documentation files (the "Software"), to deal
5+
in the Software without restriction, including without limitation the rights
6+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7+
copies of the Software, and to permit persons to whom the Software is furnished
8+
to do so, subject to the following conditions:
9+
10+
The above copyright notice and this permission notice shall be included in all
11+
copies or substantial portions of the Software.
12+
13+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19+
THE SOFTWARE.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the Symfony package.
5+
*
6+
* (c) Fabien Potencier <fabien@symfony.com>
7+
*
8+
* For the full copyright and license information, please view the LICENSE
9+
* file that was distributed with this source code.
10+
*/
11+
12+
namespace Symfony\Component\ObjectMapper\Metadata;
13+
14+
/**
15+
* Configures a class or a property to map to.
16+
*
17+
* @internal
18+
*
19+
* @author Antoine Bluchet <soyuka@gmail.com>
20+
*/
21+
readonly class Mapping
22+
{
23+
/**
24+
* @param string|class-string|null $source The property or the class to map from
25+
* @param string|class-string|null $target The property or the class to map to
26+
* @param string|bool|callable(mixed, object): bool|null $if A boolean, Symfony service name or a callable that instructs whether to map
27+
* @param (string|callable(mixed, object): mixed)|(string|callable(mixed, object): mixed)[]|null $transform A service id or a callable that transform the value during mapping
28+
*/
29+
public function __construct(
30+
public ?string $target = null,
31+
public ?string $source = null,
32+
public mixed $if = null,
33+
public mixed $transform = null,
34+
) {
35+
}
36+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the Symfony package.
5+
*
6+
* (c) Fabien Potencier <fabien@symfony.com>
7+
*
8+
* For the full copyright and license information, please view the LICENSE
9+
* file that was distributed with this source code.
10+
*/
11+
12+
namespace Symfony\Component\ObjectMapper\Metadata;
13+
14+
/**
15+
* Factory to create Mapper metadata.
16+
*
17+
* @experimental
18+
*
19+
* @author Antoine Bluchet <soyuka@gmail.com>
20+
*/
21+
interface ObjectMapperMetadataFactoryInterface
22+
{
23+
/**
24+
* @param array<string, mixed> $context
25+
*
26+
* @return list<Mapping>
27+
*/
28+
public function create(object $object, ?string $property = null, array $context = []): array;
29+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the Symfony package.
5+
*
6+
* (c) Fabien Potencier <fabien@symfony.com>
7+
*
8+
* For the full copyright and license information, please view the LICENSE
9+
* file that was distributed with this source code.
10+
*/
11+
12+
namespace Symfony\Component\ObjectMapper\Metadata;
13+
14+
use Symfony\Component\ObjectMapper\Attribute\Map;
15+
use Symfony\Component\ObjectMapper\Exception\MappingException;
16+
17+
/**
18+
* @internal
19+
*
20+
* @author Antoine Bluchet <soyuka@gmail.com>
21+
*/
22+
final class ReflectionObjectMapperMetadataFactory implements ObjectMapperMetadataFactoryInterface
23+
{
24+
public function create(object $object, ?string $property = null, array $context = []): array
25+
{
26+
try {
27+
$refl = new \ReflectionClass($object);
28+
if ($property && !$refl->hasProperty($property)) {
29+
throw new MappingException(\sprintf('Property "%s" not found on "%s"', $property, get_debug_type($object)));
30+
}
31+
32+
$mapTo = [];
33+
foreach (($property ? $refl->getProperty($property) : $refl)->getAttributes(Map::class, \ReflectionAttribute::IS_INSTANCEOF) as $mapAttribute) {
34+
$map = $mapAttribute->newInstance();
35+
$mapTo[] = new Mapping($map->target, $map->source, $map->if, $map->transform);
36+
}
37+
38+
return $mapTo;
39+
} catch (\ReflectionException $e) {
40+
throw new MappingException($e->getMessage(), $e->getCode(), $e);
41+
}
42+
}
43+
}

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.