Skip to content

Commit

Permalink
Merge pull request #41 from Toilal/constructor-destination-context
Browse files Browse the repository at this point in the history
Set destination class context to support custom constructor implementation
  • Loading branch information
mark-gerarts authored Aug 5, 2019
2 parents e0a411b + ae64905 commit 0ca74fd
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 1 deletion.
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -837,6 +837,9 @@ object by default. It is accessible using `$context['AutoMapper::DESTINATION_CON
This is useful in scenarios where you need data from the destination object
to populate the object you're mapping.

When implementing a custom constructor, the context will contain the destination
class by default. It is accessible using `$context['AutoMapper::DESTINATION_CLASS_CONTEXT']`.

### Misc

- Passing `NULL` as an argument for the source object to `map` returns `NULL`.
Expand Down
6 changes: 5 additions & 1 deletion src/AutoMapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@
class AutoMapper implements AutoMapperInterface
{
public const DESTINATION_CONTEXT = '__destination';

public const DESTINATION_CLASS_CONTEXT = '__destination_class';

/**
* @var AutoMapperConfigInterface
Expand Down Expand Up @@ -72,7 +74,9 @@ public function map($source, string $destinationClass, array $context = [])
}

if ($mapping->hasCustomConstructor()) {
$destinationObject = $mapping->getCustomConstructor()($source, $this, $context);
$destinationObject = $mapping->getCustomConstructor()($source, $this, array_merge([
self::DESTINATION_CLASS_CONTEXT => $destinationClass
]));
}
elseif (interface_exists($destinationClass)) {
// If we're mapping to an interface a valid custom constructor has
Expand Down

0 comments on commit 0ca74fd

Please sign in to comment.