<?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\FormField;

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

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

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

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

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

}

