<?php
|
|
namespace App\DataTransformer;
|
|
use ApiPlatform\Core\DataTransformer\DataTransformerInterface;
|
use ApiPlatform\Core\Validator\ValidatorInterface;
|
use App\Dto\CreateSecretDTO;
|
use App\Entity\Secret;
|
|
class CreateSecretTransformer implements DataTransformerInterface
|
{
|
/**
|
* @var ValidatorInterface
|
*/
|
private $validator;
|
|
public function __construct(ValidatorInterface $validator)
|
{
|
$this->validator = $validator;
|
}
|
|
/**
|
* @inheritDoc
|
*/
|
public function transform($object, string $to, array $context = [])
|
{
|
$this->validator->validate($object);
|
|
$expireInMinutes = $object->expireAfter > 0 ? $object->expireAfter : 0;
|
|
$expireTime = null;
|
|
if ($expireInMinutes)
|
{
|
$expireTime = (new \DateTimeImmutable())
|
->add(new \DateInterval('PT' . $expireInMinutes . 'M'));
|
}
|
|
return (new Secret())
|
->setSecretText($object->secret)
|
->setExpiresAt($expireTime)
|
->setRemainingViews($object->expireAfterViews);
|
}
|
|
/**
|
* @inheritDoc
|
*/
|
public function supportsTransformation($data, string $to, array $context = []): bool
|
{
|
if ($to !== Secret::class)
|
{
|
return false;
|
}
|
|
if ($data instanceof CreateSecretDTO)
|
{
|
return true;
|
}
|
|
if (isset($data['secret']) && isset($data["expireAfterViews"]))
|
{
|
return true;
|
}
|
|
return false;
|
}
|
}
|