<?php

namespace AppBundle\Form\Extension;

use Symfony\Component\Form\AbstractTypeExtension;
use Symfony\Component\Form\Extension\Core\Type\FormType;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Translation\TranslatorInterface;

class FormTypeExtension extends AbstractTypeExtension
{
    /**
     * @var
     */
    private $translationDomain;

    /**
     * @var TranslatorInterface
     */
    private $translator;

    /**
     * Constructor
     *
     * @param TranslatorInterface $translator
     */
    public function __construct(TranslatorInterface $translator)
    {
        $this->translator = $translator;
    }

    /**
     * Returns the name of the type being extended.
     *
     * @return string The name of the type being extended
     */
    public function getExtendedType()
    {
        return FormType::class;
    }

    /**
     * Add the help option
     *
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefined(['help', 'row_attr']);
    }

    /**
     * Pass the help text to the view
     *
     * @param FormView $view
     * @param FormInterface $form
     * @param array $options
     */
    public function buildView(FormView $view, FormInterface $form, array $options)
    {
        // Backup the form translation domain if one was set using the OptionsResolver
        if (!$form->getParent() && isset($options['translation_domain'])) {
            $this->translationDomain = $options['translation_domain'];
        }

        if (array_key_exists('help', $options)) {
            // Set the current translation domain:
            // 1. the one defined at the field level
            // 2. the one defined at the form level
            $translationDomain = $options['translation_domain'] ?? $this->translationDomain;

            // Translate the string if a translation domain is set, displays it otherwise.
            $view->vars['help'] = $translationDomain
                ? $this->translator->trans($options['help'], [], $translationDomain)
                : $options['help']
            ;
        }
        if (array_key_exists('row_attr', $options)) {
            $view->vars['row_attr'] = $options['row_attr'];
        }
    }
}
