Last active
May 29, 2021 13:49
-
-
Save bastien70/aabe1d26569cae96a5c254eb75e9bb5c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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