<?php
/**
 * Created by JetBrains PhpStorm.
 * User: jrotering
 * Date: 7/5/13
 * Time: 6:57 PM
 * To change this template use File | Settings | File Templates.
 */

$optionEl = '<option ' . '__id__ __class__ __value__ __selected__ __disabled__>__text__' . '</option>';

function keysToPlaceholders(&$value, $key) {
    $value = '__field.' . $value . '__';
}
function tplResults(array $rows, $tplChunk, array $map, $selected = null, $chosen = 'selected') {

    switch($chosen) {
        case 'selected':
            $chosenAttr = ' selected="selected"';
            break;
        case 'checked':
            $chosenAttr = ' checked="checked"';
            break;
        default:
            $chosenAttr = ' selected="selected"';
            break;
    }

    $return = '';
    $idfield = (isset($map['idfield'])) ? $map['idfield'] : 'id';

    $keyrow = $rows[0]; // get the first row to find the keys
    $keys = array_keys($keyrow);
    array_walk($keys, 'keysToPlaceholders');

    foreach ($rows as $row) {
        $tpl = $tplChunk;
        foreach ($map['fields'] as $rule) {
            if (isset($row[$rule['field']])) { // if the record has a value for specified field
                $display = str_replace('__field__', $row[$rule['field']], $rule['display']);
                $tpl = str_replace('__' . $rule['attr'] . '__', $display, $tpl);
            }
        }
        $tpl =  str_replace($keys, $row, $tpl);
        if ($selected && $row[$idfield] == $selected) {
            $tpl = str_replace('__' . $chosen . '__', $chosenAttr, $tpl);
        }
        /* remove all remaining placeholders */
        $return .= preg_replace("/__[a-zA-Z0-9\.]+__/", '', $tpl) . "\n";
    }
    return $return;
}