<?php

namespace Plainwork\Ui\Renderer\Form;

use Plainwork\Http\Request;
use Plainwork\Ui\Component\Form\SelectInput;
use Plainwork\Ui\Component\HtmlElement;

final class SelectInputRenderer
{
    public function __invoke(SelectInput $el, Request $request, callable $next)
    {
        $el = $el
            ->withTag('select')
            ;

        $value = $el->getValue();

        $options = $el->getOptions();
        foreach ($options as $k => $v) {
            $option = (new HtmlElement('option', $v))
                ->withAttr('value', $k)
                ;
            if ($value == $k) {
                $option->withAttr('selected', true);
            }

            $el->append($option);
        }

        return $next($el, $request);
    }
}
