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

namespace VisualM\FormBundle\Form\TypeHandler;

use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use VisualM\FormBundle\Entity\FormFieldInterface;

/**
 * Abstract Choice type handler
 *
 * @author Elze Kool <info@visualmedia.nl>
 * M.u.v ::completeOptionChoices, die is copyright (c) MetaClass Groningen, 2017
 */
abstract class AbstractChoiceTypeHandler implements FormTypeHandlerInterface
{
    /**
     * {@inheritdoc}
     */
    public function getSymfonyType(FormFieldInterface $formField)
    {
        return ChoiceType::class;
    }

    /**
     * Create Choices from Waarden
     *
     * @param mixed $waarden Waarden string|array of string
     *
     * @return array<string> Choices
     */
    protected function createChoices($waarden)
    {
        $choices = [];
        if (null === $waarden || is_string($waarden)) {
            $waarden = explode("\n", $waarden);
        }
        foreach ($waarden as $waarde) {
            $choices[trim($waarde)] = trim($waarde);
        }
        return $choices;
    }

    /**
     * @param array $handlerOptions
     * @param mixed $data null|string|array of string
     */
    public function completeOptionChoices(&$options, $data)
    {
        if ($data === null) {
            return;
        }
        if (is_array($data)) {
            foreach ($data as $value) {
                if (!isset($options['choices'][$value])) {
                    $options['choices'][$value] = $value;
                }
            }
        } else {
            if (!isset($options['choices'][$data])) {
                $options['choices'][$data] = $data;
            }
        }
    }
}

