<?php
/**
 * Choice Type Fix for Boolean values
 *
 * @author Elze Kool <info@visualmedia.nl>
 */

namespace VisualM\ManagementBundle\Form\Type;

use Symfony\Component\Form\Extension\Core\Type\ChoiceType as OrgChoiceType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;

/**
 * Choice Type Fix for Boolean values
 *
 * @author Elze Kool <info@visualmedia.nl>
 */
class ChoiceType extends OrgChoiceType
{
    /**
     * Check if choices are boolean
     *
     * @param array $choices
     *
     * @return bool
     */
    private function isBooleanList($choices)
    {
        $keys = array_keys($choices);
        return (count($choices) == 2 AND in_array(0, $keys, true) AND in_array(1, $keys, true));
    }

    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        if (
            $options['expanded'] === true AND
            is_array($options['choices']) AND
            $this->isBooleanList($options['choices']) AND
            isset($options['choices_as_values']) AND
            $options['choices_as_values'] !== true
        ) {
            // Add event listener that checks for bool data and convert it to 0 or 1
            $builder->addEventListener(FormEvents::PRE_SET_DATA, function(FormEvent $event) {
                $data = $event->getData();
                if (is_bool($data)) {
                    $event->setData($data ? 1 : 0);
                }
            });
        }
        parent::buildForm($builder, $options);
    }

}
