<?php

namespace Plainwork\Ui\Renderer;

use Plainwork\Http\Request;
use Plainwork\Ui\Component\Html;
use Plainwork\Ui\Ui;

final class HtmlRenderer
{
    public $ui = Ui::class;

    public function __invoke(Html $el, Request $request)
    {
        $ret = $el->getHtml();
        $vars = $el->getVars();

        $pos = 0;
        $i = 0;
        while (false !== ($pos = strpos($ret, '{', $pos))) {
            $pos2 = strpos($ret, '}', $pos + 1);
            $placeholder = substr($ret, $pos + 1, $pos2 - $pos - 1);

            $to = $vars[$i];
            if ('esc' === $placeholder) {
                $to = esc_html($to);
            } elseif ('attr' === $placeholder) {
                $to = esc_attr($to);
            } else {
                $to = 'unknown placeholder ' . $placeholder;
            }

            $ret = substr($ret, 0, $pos) . $to . substr($ret, $pos2 + 1);
 
            ++$i;
        }

        return $ret;
    }
}
