Skip to content
This repository has been archived by the owner on May 16, 2024. It is now read-only.

Custom model transformer not being applied #15

Open
twisted1919 opened this issue Apr 12, 2024 · 0 comments
Open

Custom model transformer not being applied #15

twisted1919 opened this issue Apr 12, 2024 · 0 comments

Comments

@twisted1919
Copy link

I have created this model transformer:

<?php

namespace App\AutoMapper;

use App\ApiResource\JobApi;
use App\Entity\Job;
use AutoMapper\Transformer\CustomTransformer\CustomModelTransformerInterface;
use Symfony\Component\PropertyInfo\Type;

final readonly class JobToJobApiCustomTransformer implements CustomModelTransformerInterface
{
    public function supports(array $sourceTypes, array $targetTypes): bool
    {
        return $this->hasType($sourceTypes, Job::class) && $this->hasType($targetTypes, JobApi::class);
    }

    /**
     * @param object|array<int, mixed> $source
     * @return JobApi
     * @throws \Exception
     */
    public function transform(object|array $source): JobApi
    {
        if (!($source instanceof Job)) {
            throw new \Exception(sprintf('Expected instance of %s, %s given', Job::class, gettype($source)));
        }

        $target = new JobApi();

        $target->setId($source->getId());
        $target->setUser($source->getUser());
       
        // more...

        return $target;
    }

    /**
     * @param Type[] $types
     * @param class-string $class
     */
    private function hasType(array $types, string $class): bool
    {
        foreach ($types as $type) {
            if ($type->getClassName() === $class) {
                return true;
            }
        }

        return false;
    }
}

And using it as:

/** @var ArrayCollection<int, JobApi> $jobs */
$jobs = new ArrayCollection();

/** @var Job $item */
foreach ($pagination->getItems() as $item) {
    /** @var JobApi $job */
    $job = $this->autoMapper->map($item, JobApi::class);
    $jobs->add($job);
}

it just doesn't find the custom transformer at all. It does find custom property transformers as I use them but this custom model transformer is nowhere to be applied...

I tested this for a few hours, no matter how I put it, I can't trigger the custom transformer at all.

@Korbeil - can you please check this?

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant