<?php
/**
 * Date type handler
 *
 * @author Elze Kool <info@visualmedia.nl>
 */

namespace VisualM\FormBundle\Form\TypeHandler;

use DateTime;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Validator\Constraints as Assert;
use VisualM\FormBundle\Entity\FormFieldInterface;

/**
 * Date type handler
 *
 * @author Elze Kool <info@visualmedia.nl>
 */
class DateTypeHandler implements FormTypeHandlerInterface
{
    /**
     * {@inheritdoc}
     */
    public function getSymfonyType(FormFieldInterface $formField)
    {
        return DateType::class;
    }

    /**
     * {@inheritdoc}
     */
    public function getOptions(FormFieldInterface $formField)
    {
        $constraints = [];

        if ($formField->getVerplicht()) {
            $constraints[] = new Assert\NotBlank();
        }

        return [
            'widget' => 'single_text',
            'required' => $formField->getVerplicht(),
            'constraints' => $constraints
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function normalizeValue(FormFieldInterface $formField, $value)
    {
        return $value instanceof DateTime
            ? $value->format('d-m-Y')
            : $value;
    }

}

