<commit_before><?php
/**
 * Koowa Framework - http://developer.joomlatools.com/koowa
 *
 * @copyright	Copyright (C) 2007 - 2013 <NAME> and Timble CVBA. (http://www.timble.net)
 * @license		GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
 * @link		http://github.com/joomlatools/koowa for the canonical source repository
 */


/**
 * Listbox Template Helper
 *
 * @author  <NAME> <https://github.com/johanjanssens>
 * @package Koowa\Component\Koowa
 */
class KTemplateHelperListbox extends KTemplateHelperSelect
{
    /**
     * Adds the option to enhance the select box using Select2
     *
     * @param array|KObjectConfig $config
     * @return string
     */
    public function optionlist($config = array())
    {
        $config = new KObjectConfigJson($config);
        $config->append(array(
            'prompt'    => '- '.$this->translate('Select').' -',
            'options' 	=> array(),
            'select2'   => false,
            'attribs'	=> array(),
        ))->append(array(
            'select2_options' => array(
                'element' => $config->attribs->id ? '#'.$config->attribs->id : 'select[name='.$config->name.']',
                'options' => array()
            )
        ));

        $html = '';

        if ($config->select2)
        {
            if ($config->deselect)
            {
                // select2 needs the first option empty for placeholders to work on single select boxes
                if (!$config->attribs->multiple) {
                    $config->options = array_merge(array($this->option(array('label' => ''))), $config->options->toArray());
                }

                // special configuration for select2 placeholder
                $config->select2_options->append(array(
                    'options' => array(
                        'placeholder' => $this->translate($config->prompt),
                        'allowClear'  => true
                    )
                ));
            }

            $html .= $this->getTemplate()->getHelper('behavior')->select2($config->select2_options);
        }

        $html .= parent::optionlist($config);

        return $html;
    }

    /**
     * Generates an HTML enabled listbox
     *
     * @param   array   $config An optional array with configuration options
     * @return  string  Html
     */
    public function enabled( $config = array())
    {
        $config = new KObjectConfigJson($config);
        $config->append(array(
            'name'      => 'enabled',
            'attribs'   => array(),
            'deselect'  => true,
        ))->append(array(
            'selected'  => $config->{$config->name}
        ));

        $options = array();

        if($config->deselect) {
            $options[] = $this->option(array('label' => $config->prompt, 'value' => ''));
        }

        $options[] = $this->option(array('label' => $this->translate( 'Enabled' ) , 'value' => 1 ));
        $options[] = $this->option(array('label' => $this->translate( 'Disabled' ), 'value' => 0 ));

        //Add the options to the config object
        $config->options = $options;

        return $this->optionlist($config);
    }

    /**
     * Generates an HTML published listbox
     *
     * @param   array   $config An optional array with configuration options
     * @return  string  Html
     */
    public function published($config = array())
    {
        $config = new KObjectConfigJson($config);
        $config->append(array(
            'name'      => 'enabled',
            'attribs'   => array(),
            'deselect'  => true,
        ))->append(array(
            'selected'  => $config->{$config->name}
        ));
    
        $options = array();
    
        if ($config->deselect) {
            $options[] = $this->option(array('label' => $config->prompt, 'value' => ''));
        }
    
        $options[] = $this->option(array('label' => $this->translate('Published'), 'value' => 1 ));
        $options[] = $this->option(array('label' => $this->translate('Unpublished') , 'value' => 0 ));
    
        //Add the options to the config object
        $config->options = $options;
    
        return $this->optionlist($config);
    }

    /**
     * Generates an HTML optionlist based on the distinct data from a model column.
     *
     * The column used will be defined by the name -> value => column options in cascading order.
     *
     * If no 'model' name is specified the model identifier will be created using the helper identifier. The model name
     * will be the pluralised package name.
     *
     * If no 'value' option is specified the 'name' option will be used instead. If no 'text'  option is specified the
     * 'value' option will be used instead.
     *
     * @param 	array 	$config An optional array with configuration options
     * @return	string	Html
     * @see __call()
     */
    protected function _render($config = array())
    {
        $config = new KObjectConfig($config);
        $config->append(array(
            'autocomplete' => false
        ));

        if($config->autocomplete) {
            $result = $this->_autocomplete($config);
        } else {
            $result = $this->_listbox($config);
        }

        return $result;
    }

    /**
     * Generates an HTML optionlist based on the distinct data from a model column.
     *
     * The column used will be defined by the name -> value => column options in
     * cascading order.
     *
     * If no 'model' name is specified the model identifier will be created using
     * the helper identifier. The model name will be the pluralised package name.
     *
     * If no 'value' option is specified the 'name' option will be used instead.
     * If no 'label' option is specified the 'value' option will be used instead.
     *
     * @param 	array|KObjectConfig 	$config An optional array with configuration options
     * @return	string	Html
     * @see __call()
     */
    protected function _listbox($config = array())
    {
        $config = new KObjectConfigJson($config);
        $config->append(array(
            'name'		  => '',
            'attribs'	  => array(),
            'model'		  => KStringInflector::pluralize($this->getIdentifier()->package),
            'deselect'    => true,
            'unique'	  => true
        ))->append(array(
            'value'		      => $config->name,
            'selected'        => $config->{$config->name},
            'identifier'      => 'com://'.$this->getIdentifier()->domain.'/'.$this->getIdentifier()->package.'.model.'.$config->model
        ))->append(array(
            'label'		      => $config->value,
        ))->append(array(
            'filter' 	      => array('sort' => $config->label),
        ));

        $list = $this->getObject($config->identifier)->setState(KObjectConfig::unbox($config->filter))->fetch();

        //Get the list of items
        $items = array();
        foreach($list as $key => $item) {
            $items[$key] = $item->getProperty($config->value);
        }

        if ($config->unique) {
            $items = array_unique($items);
        }

        //Compose the options array
        $options = array();
        if($config->deselect) {
            $options[] = $this->option(array('label' => $this->translate($config->prompt)));
        }

        foreach ($items as $key => $value)
        {
            $item      = $list->find($key);
            $options[] = $this->option(array('label' => $item->{$config->label}, 'value' => $item->{$config->value}));
        }

        //Compose the selected array
        if($config->selected instanceof KModelEntityInterface)
        {
            $selected = array();
            foreach($config->selected as $entity) {
                $selected[] = $entity->{$config->value};
            }

            $config->selected = $selected;
        }

        //Add the options to the config object
        $config->options = $options;

        return $this->optionlist($config);
    }

    /**
     * Renders a listbox with autocomplete behavior
     *
     * @see    ComKoowaTemplateHelperBehavior::_listbox
     *
     * @param  array|KObjectConfig    $config
     * @return string	The html output
     */
    protected function _autocomplete($config = array())
    {
        $config = new KObjectConfigJson($config);
        $config->append(array(
            'name'	   => '',
            'attribs'  => array(),
            'model'	   => KStringInflector::pluralize($this->getIdentifier()->package),
            'validate' => true,
            'filter'   => array(),
        ))->append(array(
            'element'    => $config->attribs->id ? '#'.$config->attribs->id : 'input[name='.$config->name.']',
            'options'    => array('multiple' => (bool) $config->attribs->multiple),
            'deselect'   => true,
            'prompt'     => '- '.$this->translate('Select').' -',
            'unique'     => true,
            'select2'    => false,
            'value'	     => $config->name,
            'selected'   => $config->{$config->name},
            'identifier' => 'com://'.$this->getIdentifier()->domain.'/'.$this->getIdentifier()->package.'.model.'.$config->model
        ))->append(array(
            'label'	     => $config->value,
        ))->append(array(
            'text'       => $config->label,
            'filter' 	 => array('sort' => $config->label),
        ));

        if (!$config->url)
        {
            $identifier = $this->getIdentifier($config->identifier);
            $parts      = array(
                'option' => 'com_'.$identifier->package,
                'view'   => $identifier->name,
                'format' => 'json'
            );

            if ($config->filter) {
                $parts = array_merge($parts, KObjectConfig::unbox($config->filter));
            }

            $config->url = $this->getTemplate()->getView()->getRoute($parts, false, false);
        }

        $html = '';

        // TODO: Remove when select2 properly support AJAX multiple listboxes by sending choices
        // as an array (presumably for v4).
        if ($config->attribs->multiple)
        {
            $html .= '<script>
            kQuery(function($) {
                var el = $("' . $config->element . '");
                var form = el.closest("form");

                var explode = function(e) {
                   if (el.val()) {
                        if (el.attr("name").substr(-2) !== "[]") {
                            // Make the input an array.
                            el.attr("name", el.attr("name") + "[]");
                        }

                        var values = el.val().split(",");
                        $.each(values, function(idx, value) {
                            form.append(el.clone().val(value));
                        });
                        el.remove();
                    } else {
                        // If there is no value, then we remove the element anyways to mimic a real select box.
                        el.remove();
                    }
                };

                if (form.hasClass("-koowa-form") || form.hasClass("-koowa-grid")) {
                    form.submit(explode);
                } else {
                    var element = form.get(0);

                    if (element.addEvent) {
                        element.addEvent("submit", explode);
                    } else if (element.addEventListener) {
                        element.addEventListener("submit", explode, false);
                    } else if (element.attachEvent) {
                        element.attachEvent("onsubmit", explode);
                    }
                }
            });</script>';
        }

        $html .= $this->getTemplate()->getHelper('behavior')->autocomplete($config);

        $config->attribs->name = $config->name;

        if ($config->selected) {
            $config->attribs->value = json_encode(KObjectConfig::unbox($config->selected));
        }<commit_msg>re #91 : If the 'selected' config option is an entity transform it to an array.<commit_after><?php
/**
 * Koowa Framework - http://developer.joomlatools.com/koowa
 *
 * @copyright	Copyright (C) 2007 - 2013 <NAME> and Timble CVBA. (http://www.timble.net)
 * @license		GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
 * @link		http://github.com/joomlatools/koowa for the canonical source repository
 */


/**
 * Listbox Template Helper
 *
 * @author  <NAME> <https://github.com/johanjanssens>
 * @package Koowa\Component\Koowa
 */
class KTemplateHelperListbox extends KTemplateHelperSelect
{
    /**
     * Adds the option to enhance the select box using Select2
     *
     * @param array|KObjectConfig $config
     * @return string
     */
    public function optionlist($config = array())
    {
        $config = new KObjectConfigJson($config);
        $config->append(array(
            'prompt'    => '- '.$this->translate('Select').' -',
            'options' 	=> array(),
            'select2'   => false,
            'attribs'	=> array(),
        ))->append(array(
            'select2_options' => array(
                'element' => $config->attribs->id ? '#'.$config->attribs->id : 'select[name='.$config->name.']',
                'options' => array()
            )
        ));

        $html = '';

        if ($config->select2)
        {
            if ($config->deselect)
            {
                // select2 needs the first option empty for placeholders to work on single select boxes
                if (!$config->attribs->multiple) {
                    $config->options = array_merge(array($this->option(array('label' => ''))), $config->options->toArray());
                }

                // special configuration for select2 placeholder
                $config->select2_options->append(array(
                    'options' => array(
                        'placeholder' => $this->translate($config->prompt),
                        'allowClear'  => true
                    )
                ));
            }

            $html .= $this->getTemplate()->getHelper('behavior')->select2($config->select2_options);
        }

        $html .= parent::optionlist($config);

        return $html;
    }

    /**
     * Generates an HTML enabled listbox
     *
     * @param   array   $config An optional array with configuration options
     * @return  string  Html
     */
    public function enabled( $config = array())
    {
        $config = new KObjectConfigJson($config);
        $config->append(array(
            'name'      => 'enabled',
            'attribs'   => array(),
            'deselect'  => true,
        ))->append(array(
            'selected'  => $config->{$config->name}
        ));

        $options = array();

        if($config->deselect) {
            $options[] = $this->option(array('label' => $config->prompt, 'value' => ''));
        }

        $options[] = $this->option(array('label' => $this->translate( 'Enabled' ) , 'value' => 1 ));
        $options[] = $this->option(array('label' => $this->translate( 'Disabled' ), 'value' => 0 ));

        //Add the options to the config object
        $config->options = $options;

        return $this->optionlist($config);
    }

    /**
     * Generates an HTML published listbox
     *
     * @param   array   $config An optional array with configuration options
     * @return  string  Html
     */
    public function published($config = array())
    {
        $config = new KObjectConfigJson($config);
        $config->append(array(
            'name'      => 'enabled',
            'attribs'   => array(),
            'deselect'  => true,
        ))->append(array(
            'selected'  => $config->{$config->name}
        ));
    
        $options = array();
    
        if ($config->deselect) {
            $options[] = $this->option(array('label' => $config->prompt, 'value' => ''));
        }
    
        $options[] = $this->option(array('label' => $this->translate('Published'), 'value' => 1 ));
        $options[] = $this->option(array('label' => $this->translate('Unpublished') , 'value' => 0 ));
    
        //Add the options to the config object
        $config->options = $options;
    
        return $this->optionlist($config);
    }

    /**
     * Generates an HTML optionlist based on the distinct data from a model column.
     *
     * The column used will be defined by the name -> value => column options in cascading order.
     *
     * If no 'model' name is specified the model identifier will be created using the helper identifier. The model name
     * will be the pluralised package name.
     *
     * If no 'value' option is specified the 'name' option will be used instead. If no 'text'  option is specified the
     * 'value' option will be used instead.
     *
     * @param 	array 	$config An optional array with configuration options
     * @return	string	Html
     * @see __call()
     */
    protected function _render($config = array())
    {
        $config = new KObjectConfig($config);
        $config->append(array(
            'autocomplete' => false
        ));

        if($config->autocomplete) {
            $result = $this->_autocomplete($config);
        } else {
            $result = $this->_listbox($config);
        }

        return $result;
    }

    /**
     * Generates an HTML optionlist based on the distinct data from a model column.
     *
     * The column used will be defined by the name -> value => column options in
     * cascading order.
     *
     * If no 'model' name is specified the model identifier will be created using
     * the helper identifier. The model name will be the pluralised package name.
     *
     * If no 'value' option is specified the 'name' option will be used instead.
     * If no 'label' option is specified the 'value' option will be used instead.
     *
     * @param 	array|KObjectConfig 	$config An optional array with configuration options
     * @return	string	Html
     * @see __call()
     */
    protected function _listbox($config = array())
    {
        $config = new KObjectConfigJson($config);
        $config->append(array(
            'name'		  => '',
            'attribs'	  => array(),
            'model'		  => KStringInflector::pluralize($this->getIdentifier()->package),
            'deselect'    => true,
            'unique'	  => true
        ))->append(array(
            'value'		      => $config->name,
            'selected'        => $config->{$config->name},
            'identifier'      => 'com://'.$this->getIdentifier()->domain.'/'.$this->getIdentifier()->package.'.model.'.$config->model
        ))->append(array(
            'label'		      => $config->value,
        ))->append(array(
            'filter' 	      => array('sort' => $config->label),
        ));

        $list = $this->getObject($config->identifier)->setState(KObjectConfig::unbox($config->filter))->fetch();

        //Get the list of items
        $items = array();
        foreach($list as $key => $item) {
            $items[$key] = $item->getProperty($config->value);
        }

        if ($config->unique) {
            $items = array_unique($items);
        }

        //Compose the options array
        $options = array();
        if($config->deselect) {
            $options[] = $this->option(array('label' => $this->translate($config->prompt)));
        }

        foreach ($items as $key => $value)
        {
            $item      = $list->find($key);
            $options[] = $this->option(array('label' => $item->{$config->label}, 'value' => $item->{$config->value}));
        }

        //Compose the selected array
        if($config->selected instanceof KModelEntityInterface)
        {
            $selected = array();
            foreach($config->selected as $entity) {
                $selected[] = $entity->{$config->value};
            }

            $config->selected = $selected;
        }

        //Add the options to the config object
        $config->options = $options;

        return $this->optionlist($config);
    }

    /**
     * Renders a listbox with autocomplete behavior
     *
     * @see    ComKoowaTemplateHelperBehavior::_listbox
     *
     * @param  array|KObjectConfig    $config
     * @return string	The html output
     */
    protected function _autocomplete($config = array())
    {
        $config = new KObjectConfigJson($config);
        $config->append(array(
            'name'	   => '',
            'attribs'  => array(),
            'model'	   => KStringInflector::pluralize($this->getIdentifier()->package),
            'validate' => true,
            'filter'   => array(),
        ))->append(array(
            'element'    => $config->attribs->id ? '#'.$config->attribs->id : 'input[name='.$config->name.']',
            'options'    => array('multiple' => (bool) $config->attribs->multiple),
            'deselect'   => true,
            'prompt'     => '- '.$this->translate('Select').' -',
            'unique'     => true,
            'select2'    => false,
            'value'	     => $config->name,
            'selected'   => $config->{$config->name},
            'identifier' => 'com://'.$this->getIdentifier()->domain.'/'.$this->getIdentifier()->package.'.model.'.$config->model
        ))->append(array(
            'label'	     => $config->value,
        ))->append(array(
            'text'       => $config->label,
            'filter' 	 => array('sort' => $config->label),
        ));

        if (!$config->url)
        {
            $identifier = $this->getIdentifier($config->identifier);
            $parts      = array(
                'option' => 'com_'.$identifier->package,
                'view'   => $identifier->name,
                'format' => 'json'
            );

            if ($config->filter) {
                $parts = array_merge($parts, KObjectConfig::unbox($config->filter));
            }

            $config->url = $this->getTemplate()->getView()->getRoute($parts, false, false);
        }

        $html = '';

        // TODO: Remove when select2 properly support AJAX multiple listboxes by sending choices
        // as an array (presumably for v4).
        if ($config->attribs->multiple)
        {
            $html .= '<script>
            kQuery(function($) {
                var el = $("' . $config->element . '");
                var form = el.closest("form");

                var explode = function(e) {
                   if (el.val()) {
                        if (el.attr("name").substr(-2) !== "[]") {
                            // Make the input an array.
                            el.attr("name", el.attr("name") + "[]");
                        }

                        var values = el.val().split(",");
                        $.each(values, function(idx, value) {
                            form.append(el.clone().val(value));
                        });
                        el.remove();
                    } else {
                        // If there is no value, then we remove the element anyways to mimic a real select box.
                        el.remove();
                    }
                };

                if (form.hasClass("-koowa-form") || form.hasClass("-koowa-grid")) {
                    form.submit(explode);
                } else {
                    var element = form.get(0);

                    if (element.addEvent) {
                        element.addEvent("submit", explode);
                    } else if (element.addEventListener) {
                        element.addEventListener("submit", explode, false);
                    } else if (element.attachEvent) {
                        element.attachEvent("onsubmit", explode);
                    }
                }
            });</script>';
        }

        $html .= $this->getTemplate()->getHelper('behavior')->autocomplete($config);

        $config->attribs->name = $config->name;

        if ($config->selected)
        {
            //Compose the selected array
            if($config->selected instanceof KModelEntityInterface)
            {
                $selected = array();
                foreach($config->selected as $entity) {
                    $selected[] = $entity->{$config->value};
                }

                $config->selected = $selected;
            }

            $config->attribs->value = json_encode(KObjectConfig::unbox($config->selected));
        }
{'fraction_non_alphanumeric': 0.15434399705075164, 'fraction_numerical': 0.0022938598287797485, 'mean_word_length': 1.7063518456933822, 'pattern_counts': {'":': 0, '<': 17, '<?xml version=': 0, '>': 456, 'https://': 2, 'lorem ipsum': 0, 'www.': 4, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6269408', 'n_tokens_mistral': 6688, 'n_tokens_neox': 6452, 'n_words': 1508}