<?php
class Core_Twig_Extensions_Extension_Form extends Twig_Extension
{
    /**
     * Returns a list of filters.
     *
     * @return array
     */
    public function getFilters()
    {
        return array(
            'attribs'     => new Twig_Filter_Function('core_form_attribs', array('pre_escape' => 'html', 'is_safe' => array('html'))),
            'export'      => new Twig_Filter_Function('core_form_export', array('pre_escape' => 'html', 'is_safe' => array('html'))),
            'assoc2array' => new Twig_Filter_Function('core_form_assoc2array', array('pre_escape' => 'html', 'is_safe' => array('html'))),
        );
    }

    /**
     * Name of this extension
     *
     * @return string
     */
    public function getName()
    {
        return 'Core_Twig_Form';
    }
}

function core_form_attribs($attribs)
{
    if ($attribs) {
        $rendered = array();
        foreach ($attribs as $name => $values) {
            if (null !== $values) {
                $rendered[] = $name .'="'. htmlspecialchars(implode(' ', (array) $values)) .'"';
            }
        }
        if ($rendered) {
            return ' '.implode(' ', $rendered);
        }
    }
}


function core_form_export(Array $options)
{
    $rendered = array();
    foreach ($options as $name => $values) {
        if (null !== $values) {
            $rendered[] = "'". $name ."': ". core_form_option_render($values);
        }
    }
    return "\t".implode(",\n\t", $rendered);
}

function core_form_option_render($option)
{
    if (is_int($option)) {
        return (int) $option;
    } else if (is_float($option)) {
        return (float) $option;
    } else if (is_string($option) && in_array($option, array('true', 'false'))) {
        return $option;
    } else if (is_bool($option)) {
        return $option ? 'true' : 'false';
    } else if (is_array($option)) {
        $options = array();
        foreach ($option as $index => $item) {
            $numeric = is_numeric($index);
            if ($numeric) {
                $options[] = core_form_option_render($item);
            } else {
                return '{'. core_form_export($option) .'}';
            }
        }
        return '['. implode(', ', $options) .']';
    } else {
        return "'". $option ."'";
    }
}

function core_form_assoc2array(array $assoc)
{
    $array = array();
    foreach ($assoc as $key => $value) {
        $array[] = compact('key', 'value');
    }
    return $array;
}