<?php

declare(strict_types=1);

namespace Gls\GlsPoland\Form\DataTransformer;

use Gls\GlsPoland\AdePlus\Printout\LabelsPrintMode;
use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception\TransformationFailedException;

final class LabelsPrintModeDataTransformer implements DataTransformerInterface
{
    public function transform($value): ?string
    {
        if (null === $value) {
            return null;
        }

        if (!$value instanceof LabelsPrintMode) {
            throw new TransformationFailedException(sprintf('Expected a %s.', LabelsPrintMode::class));
        }

        return (string) $value;
    }

    public function reverseTransform($value)
    {
        if (null === $value) {
            return null;
        }

        if (!is_string($value)) {
            throw new TransformationFailedException('Expected a string.');
        }

        try {
            return LabelsPrintMode::from($value);
        } catch (\Exception $e) {
            throw new TransformationFailedException($e->getMessage(), $e->getCode(), $e);
        }
    }
}
