julien-c / iso3166

ISO 3166-1 alpha-2 mapping
65 stars 9 forks source link

Suggestion: Accept arbitrary attributes on countrySelector #7

Open manticorp opened 8 years ago

manticorp commented 8 years ago

An example call would be:

<?php
echo Iso3166\Codes::countrySelector('name', 'FR', array(
    'class' => 'classname',
    'id'    => 'idname',
    'role'  => 'select'
);`

or, in keeping with the previous classname implementation:

<?php
echo Iso3166\Codes::countrySelector('classname', 'name', 'FR', array(
    'id'    => 'idname',
    'role'  => 'select'
);`
manticorp commented 8 years ago

Example implementation:

public static function countrySelector($class = '', $name = 'country', $selected = null, $attributes = null)
{
    $attstring = '';
    if($attributes !== null && is_array($attributes)){
        foreach($attributes as $name => $value) {
            $attstring .= sprintf(' %s="%s"',htmlentities($name),htmlentities($value));
        }
    }
    return sprintf('<select class="%s" name="%s"%s>', $class, $name, $attstring)
        . implode(array_map(function($country, $code) use($selected) {
            return ($code == $selected)
                ? sprintf('<option value="%s" selected>%s</option>', $code, $country)
                : sprintf('<option value="%s">%s</option>', $code, $country);
        }, static::$countries, array_keys(static::$countries)))
        . '</select>';
}
manticorp commented 8 years ago

Or, even better:

public static function countrySelector($class = null, $name = 'country', $selected = null, $attributes = null)
{
    $attstring = '';
    if(!is_null($class) && is_string($class)) {
        if(is_array($attributes)){
            $attributes['class'] = $class;
        }
    }
    if($attributes !== null && is_array($attributes)){
        foreach($attributes as $name => $value) {
            $attstring .= sprintf(' %s="%s"',htmlentities($name),htmlentities($value));
        }
    }
    return sprintf('<select name="%s"%s>', $name, $attstring)
        . implode(array_map(function($country, $code) use($selected) {
            return ($code == $selected)
                ? sprintf('<option value="%s" selected>%s</option>', $code, $country)
                : sprintf('<option value="%s">%s</option>', $code, $country);
        }, static::$countries, array_keys(static::$countries)))
        . '</select>';
}