<?php
/**
 * @author      Aurélien BERNARD - TRYDEA - 2020
 */

declare(strict_types=1);

namespace Shared\Authentication\ApiTransformer;

use ApiPlatform\Core\DataTransformer\DataTransformerInterface;
use Exception;
use Shared\Authentication\Dto\UserPostInput;
use Shared\Authentication\Entity\User;

/**
 * Class UserPostInputDataTransformer.
 */
class UserPostInputDataTransformer implements DataTransformerInterface
{

    /**
     * @var bool
     */
    private bool $isLdapOn;

    /**
     * UserPostInputDataTransformer constructor.
     * @param bool $isLdapOn
     */
    public function __construct(bool $isLdapOn)
    {
        $this->isLdapOn = $isLdapOn;
    }

    /**
     * @inheritDoc
     */
    public function supportsTransformation($data, string $to, array $context = []): bool
    {
        return User::class === $to && null !== ($context['input']['class'] ?? null) && $context['input']['class'] === UserPostInput::class;
    }

    /**
     * @param UserPostInput $object
     * @param string $to
     * @param array $context
     * @return User
     * @throws Exception
     * @see DataTransformerInterface
     */
    public function transform($object, string $to, array $context = []): User
    {
        if ($this->isLdapOn) {
            throw new Exception('');
        }
        return (new User())
            ->setActive(true)
            ->setSurname($object->getSurname())
            ->setName($object->getName())
            ->setUsername($object->getUsername())
            ->setEmail($object->getEmail())
            ->setRoles(['ROLE_USER']);
    }
}
