Skip to content

Instantly share code, notes, and snippets.

@bastien70
Last active May 29, 2021 13:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bastien70/aabe1d26569cae96a5c254eb75e9bb5c to your computer and use it in GitHub Desktop.
Save bastien70/aabe1d26569cae96a5c254eb75e9bb5c to your computer and use it in GitHub Desktop.
<?php
namespace App\DataTransformer;
use ApiPlatform\Core\DataTransformer\DataTransformerInitializerInterface;
use ApiPlatform\Core\DataTransformer\DataTransformerInterface;
use ApiPlatform\Core\Serializer\AbstractItemNormalizer;
use App\Dto\CheeseListingInput;
use App\Entity\CheeseListing;
class CheeseListingInputDataTransformer implements DataTransformerInitializerInterface
{
public function initialize(string $inputClass, array $context = [])
{
$dto = new CheeseListingInput();
if(isset($context[AbstractItemNormalizer::OBJECT_TO_POPULATE])) {
/** @var CheeseListing $cheeseListing */
$cheeseListing = $context[AbstractItemNormalizer::OBJECT_TO_POPULATE];
$dto->title = $cheeseListing->getTitle();
$dto->description = $cheeseListing->getDescription();
$dto->price = $cheeseListing->getPrice();
$dto->isPublished = $cheeseListing->getIsPublished();
$dto->owner = $cheeseListing->getOwner();
}
return $dto;
}
/**
* @param CheeseListingInput $input
*/
public function transform($input, string $to, array $context = [])
{
if(isset($context[AbstractItemNormalizer::OBJECT_TO_POPULATE])) {
$cheeseListing = $context[AbstractItemNormalizer::OBJECT_TO_POPULATE];
} else {
$cheeseListing = new CheeseListing($input->title);
}
return $cheeseListing->setDescription($input->description)
->setPrice($input->price)
->setOwner($input->owner)
->setIsPublished($input->isPublished);
}
public function supportsTransformation($data, string $to, array $context = []): bool
{
if($data instanceof CheeseListing) {
// already transformed
return false;
}
return $to === CheeseListing::class && ($context['input']['class'] ?? null) === CheeseListingInput::class;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment