Skip to content

Instantly share code, notes, and snippets.

@BoShurik
Last active November 20, 2018 20:10
Show Gist options
  • Save BoShurik/7aafc932e9dcf74be2196a09d6da15bd to your computer and use it in GitHub Desktop.
Save BoShurik/7aafc932e9dcf74be2196a09d6da15bd to your computer and use it in GitHub Desktop.
automapper-issue
<?php
$config = new AutoMapperConfig();
$config
->registerMapping(OrderDTO::class, Order::class)
->forMember('value', Operation::mapFrom(function (OrderDTO $dto) {
return new Value($dto->currency, $dto->value);
}))
->forMember('items', Operation::mapFromWithMapper(function (OrderDTO $dto, AutoMapper $mapper) {
$items = [];
foreach ($dto->items as $item) {
$items[] = $mapper->map($item, Item::class);
}
return $items;
}))
;
$config
->registerMapping(ItemDTO::class, Item::class)
->forMember('value', Operation::mapFrom(function (ItemDTO $dto) {
return new Value(/*OrderDTO::$currency*/, $dto->value);
}))
;
$mapper = new AutoMapper($config);
$orderDTO = new OrderDTO();
$orderDTO->currency = 'EUR';
$orderDTO->value = 1;
$itemDTO = new ItemDTO();
$itemDTO->value = 1;
$orderDTO->items[] = $itemDTO;
$order = $mapper->map($orderDTO, Order::class);
<?php
class Item
{
/**
* @var Value
*/
public $value;
public function __construct(Value $value)
{
$this->value = $value;
}
}
<?php
class ItemDTO
{
/**
* @var float
*/
public $value;
}
<?php
class Order
{
/**
* @var Value
*/
public $value;
/**
* @var Item[]
*/
public $items;
}
<?php
class OrderDTO
{
/**
* @var string
*/
public $currency;
/**
* @var float
*/
public $value;
/**
* @var ItemDTO[]
*/
public $items;
}
<?php
$config = new AutoMapperConfig();
$config
->registerMapping(OrderDTO::class, Order::class)
->forMember('value', Operation::mapFrom(function (OrderDTO $dto) {
return new Value($dto->currency, $dto->value);
}))
->forMember('items', Operation::mapFromWithMapper(function (OrderDTO $dto, AutoMapper $mapper) {
$items = [];
foreach ($dto->items as $item) {
$items[] = $mapper->map($item, Item::class, [
'currency' => $dto->currency,
]);
}
return $items;
}))
;
$config
->registerMapping(ItemDTO::class, Item::class)
->forMember('value', Operation::mapFromWithContext(function (ItemDTO $dto, array $context) {
return new Value($context['currency'] ?? 'EUR', $dto->value);
}))
;
<?php
class Value
{
/**
* @var string
*/
public $currency;
/**
* @var float
*/
public $value;
public function __construct(string $currency, float $value)
{
$this->currency = $currency;
$this->value = $value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment