|
| 1 | +<?php declare(strict_types=1); |
| 2 | + |
| 3 | +namespace Neusta\Pimcore\ImportExportBundle\PimcoreConverter\Populator; |
| 4 | + |
| 5 | +use Neusta\ConverterBundle\Exception\PopulationException; |
| 6 | +use Neusta\ConverterBundle\Populator; |
| 7 | +use Symfony\Component\PropertyAccess\PropertyAccess; |
| 8 | +use Symfony\Component\PropertyAccess\PropertyAccessorInterface; |
| 9 | + |
| 10 | +/** |
| 11 | + * @template TSource of object |
| 12 | + * @template TTarget of object |
| 13 | + * @template TContext of object|null |
| 14 | + * |
| 15 | + * @implements Populator<TSource, TTarget, TContext> |
| 16 | + */ |
| 17 | +final class PropertyBasedMappingPopulator implements Populator |
| 18 | +{ |
| 19 | + /** @var \Closure(mixed, TContext=):mixed */ |
| 20 | + private \Closure $mapper; |
| 21 | + private PropertyAccessorInterface $accessor; |
| 22 | + |
| 23 | + /** |
| 24 | + * @param \Closure(mixed, TContext=):mixed|null $mapper |
| 25 | + */ |
| 26 | + public function __construct( |
| 27 | + private string $targetProperty, |
| 28 | + private string $propertyKey, |
| 29 | + private mixed $defaultValue = null, |
| 30 | + ?\Closure $mapper = null, |
| 31 | + ?PropertyAccessorInterface $accessor = null, |
| 32 | + private bool $skipNull = false, |
| 33 | + ) { |
| 34 | + $this->mapper = $mapper ?? static fn ($v) => $v; |
| 35 | + $this->accessor = $accessor ?? PropertyAccess::createPropertyAccessor(); |
| 36 | + } |
| 37 | + |
| 38 | + /** |
| 39 | + * @throws PopulationException |
| 40 | + */ |
| 41 | + public function populate(object $target, object $source, ?object $ctx = null): void |
| 42 | + { |
| 43 | + try { |
| 44 | + $value = $this->defaultValue; |
| 45 | + |
| 46 | + if (method_exists($source, 'getProperty') && $source->getProperty($this->propertyKey)) { |
| 47 | + $value = $source->getProperty($this->propertyKey); |
| 48 | + } |
| 49 | + |
| 50 | + if (!$this->skipNull || (null !== $value)) { |
| 51 | + $this->accessor->setValue($target, $this->targetProperty, ($this->mapper)($value, $ctx)); |
| 52 | + } |
| 53 | + } catch (\Throwable $exception) { |
| 54 | + throw new PopulationException('property["' . $this->propertyKey . '"]', $this->targetProperty, $exception); |
| 55 | + } |
| 56 | + } |
| 57 | +} |
0 commit comments