<?php
/**
 * @copyright NetMonsters <team@netmonsters.ru>
 * @link http://netmonsters.ru
 * @package Majestic
 * @subpackage View
 * @since 2010-03-09
 * @version SVN: $Id$
 * @filesource $URL$
 */

class GetViewHelper extends ViewHelper
{
    
    protected $get;
    
    public function get($replace)
    {
        $get = $this->getSanitizedRequest();
        if (!is_array($replace)) {
            $replace = array($replace);
        }
        foreach ($replace as $key => $value) {
            if (is_int($key)) {
                unset($get[$value]);
            } else {
                $get[$key] = $this->impl($key, $value);
            }
        }
        return '?' . $this->view->escape(implode('&', $get));
    }
    
    protected function getSanitizedRequest()
    {
        if ($this->get === null) {
            $get = Env::Get();
            foreach ($get as $key => $value) {
                $this->get[$key] = $this->impl($key, $value);
            }
        }
        return $this->get;
    }
    
    protected function impl($name, $value)
    {
        if (is_array($value)){
            $result = array();
            foreach ($value as $key => $val) {
                $result[] = $name . '[' . $key . ']=' . $val;
            }
            $result = implode('&', $result);
        } else {
            $result = $name . '=' . $value;
        }
        return $result;
    }
}