Implemented logic for not (yet) used EntityMerger service

This commit is contained in:
Jan Böhmer 2023-11-24 23:48:39 +01:00
parent 1da5e7ccd7
commit 07088c94e7
3 changed files with 52 additions and 1 deletions

View file

@ -23,7 +23,54 @@ declare(strict_types=1);
namespace App\Services\EntityMergers;
use App\Services\EntityMergers\Mergers\EntityMergerInterface;
use Symfony\Component\DependencyInjection\Attribute\TaggedIterator;
/**
* This service is used to merge two entities together.
* It automatically finds the correct merger (implementing EntityMergerInterface) for the two entities if one exists.
*/
class EntityMerger
{
public function __construct(#[TaggedIterator('app.entity_merger')] protected iterable $mergers)
{
}
/**
* This function finds the first merger that supports merging the other entity into the target entity.
* @param object $target
* @param object $other
* @param array $context
* @return EntityMergerInterface|null
*/
public function findMergerForObject(object $target, object $other, array $context = []): ?EntityMergerInterface
{
foreach ($this->mergers as $merger) {
if ($merger->supports($target, $other, $context)) {
return $merger;
}
}
return null;
}
/**
* This function merges the other entity into the target entity. If no merger is found an exception is thrown.
* The target entity will be modified and returned.
* @param object $target
* @param object $other
* @param array $context
* @template T of object
* @phpstan-param T $target
* @phpstan-param T $other
* @phpstan-return T
* @return object
*/
public function merge(object $target, object $other, array $context = []): object
{
$merger = $this->findMergerForObject($target, $other, $context);
if ($merger === null) {
throw new \RuntimeException('No merger found for merging '.get_class($other).' into '.get_class($target));
}
return $merger->merge($target, $other, $context);
}
}

View file

@ -24,9 +24,12 @@ declare(strict_types=1);
namespace App\Services\EntityMergers\Mergers;
use Symfony\Component\DependencyInjection\Attribute\AutoconfigureTag;
/**
* @template T of object
*/
#[AutoconfigureTag('app.entity_merger')]
interface EntityMergerInterface
{
/**

View file

@ -32,9 +32,10 @@ use App\Entity\PriceInformations\Orderdetail;
use Symfony\Component\DependencyInjection\Attribute\Autoconfigure;
/**
* This class merges two parts together.
*
* @implements EntityMergerInterface<Part>
*/
#[Autoconfigure(public: true)]
class PartMerger implements EntityMergerInterface
{