<?php

namespace AppBundle\Form\Extension;

use Symfony\Component\Form\AbstractTypeExtension;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\OptionsResolver\OptionsResolver;

class CollectionTypeExtension extends AbstractTypeExtension
{
    /**
     * @var array List of additional options defined by this extension
     */
    private $options = [
        'label_add',
        'label_delete',
    ];

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

    /**
     * Add the options
     *
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefined($this->options);
    }

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

        foreach ($this->options as $o) {
            if (array_key_exists($o, $options)) {
                $translationDomain = $options['translation_domain'] ?? $translationDomain;

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