Skip to content

Instantly share code, notes, and snippets.

@ahsio
Last active November 17, 2022 09:03
Show Gist options
  • Save ahsio/d202708e88d9c7458a8ed074293a8774 to your computer and use it in GitHub Desktop.
Save ahsio/d202708e88d9c7458a8ed074293a8774 to your computer and use it in GitHub Desktop.
Lodel - Base mapping implementation
<?php
namespace App\Mapper;
class Mapper implements MapperInterface
{
/** @var array */
private $mapperConfigurations = [];
/**
* @param MapperConfigurationInterface $mapperConfiguration
*/
public function addMapperConfiguration(MapperConfigurationInterface $mapperConfiguration)
{
$this->mapperConfigurations[] = $mapperConfiguration;
}
public function map($source, $target)
{
$sourceType = is_array($source) ? 'array' : get_class($source);
foreach ($this->mapperConfigurations as $mapperConfiguration) {
if ($sourceType == $mapperConfiguration->getSource() && $target == $mapperConfiguration->getTarget()) {
return $mapperConfiguration->process($source, $target);
}
}
}
}
<?php
namespace App\DependencyInjection\CompilerPass;
use App\Mapper\Mapper;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\Reference;
class MapperCompilerPass implements CompilerPassInterface
{
public function process(ContainerBuilder $container)
{
// Fetch the Mapper
$mapperDefinition = $container->findDefinition(Mapper::class);
// Fetch all mapper configurations by tag 'app.mapper'
$mappers = $container->findTaggedServiceIds('app.mapper');
// Call `Mapper::addMapperConfiguration`
foreach ($mappers as $mapper => $id) {
$mapperDefinition->addMethodCall('addMapperConfiguration', [new Reference($mapper)]);
}
}
}
<?php
namespace App\Mapper;
interface MapperConfigurationInterface
{
public function getSource(): string;
public function getTarget(): string;
public function process($source, $target);
}
<?php
namespace App\Mapper;
use App\Mapper\MapperConfigurationInterface;
interface MapperInterface
{
public function addMapperConfiguration(MapperConfigurationInterface $mapperConfiguration);
public function map($source, $target);
}
<?php
namespace App\Mapper\DTO;
use App\Mapper\MapperConfigurationInterface;
use App\DTO\MyCustomDTO;
use App\Entity\MyCustomEntity;
class MyCustomMapperConfiguration extends ConfigurationMapper implements MapperConfigurationInterface
{
public function getSource(): string
{
return MyCustomEntity::class';
}
public function getTarget(): string
{
return MyCustomDTO::class;
}
public function process($source, $target)
{
$myDTO = new MyCustomDTO();
// mapping logic
return $myDTO;
}
}
services:
// ...
App\Mapper\DTO\MyCustomMapperConfiguration:
tags:
- 'app.mapper'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment