<?php

class request{

    public function get($name, $filter = ""){
        return $this->getHelper($_REQUEST, $name, $filter);
    }
    
    public function getPost($name, $filter = ""){
        return $this->getHelper($_POST, $name, $filter);
    }
    
    public function getQuery($name){
        return $this->getHelper($_GET, $name, "");
    }
    
    public function getServer($name){
        if (isset($_SERVER[$name])){
            return $_SERVER[$name];
        }
        return 0;
    }
    
    public function has($name){
        return isset($_REQUEST[$name]);
    }
    
    public function hasPost($name){
        return isset($_POST[$name]);
    }
    
    public function hasQuery($name){
        return isset($_GET[$name]);
    }
    
    public function isAjax(){
        return isset($_SERVER["HTTP_X_REQUESTED_WITH"]) && $_SERVER["HTTP_X_REQUESTED_WITH"] === "XMLHttpRequest";
    }
    
    public function isPost(){
        return $_SERVER["REQUEST_METHOD"] === 'POST';
    }
    
    public function isGet(){
        return $_SERVER["REQUEST_METHOD"] === 'GET';
    }
    
    protected final function getHelper($source, $name, $filter){
        if (empty($source) || !isset($source[$name])){
            return $source;
        }
        
        $value = $source[$name];
        if ($filter){
            $value = $this->sanitize($value, $filter);
        }
        
        return $value;
    }
    
    public function sanitize($value, $filter){
        switch ($filter){
            case 'email':
                return filter_var($value, FILTER_SANITIZE_EMAIL);
            case 'int':
                return filter_var($value, FILTER_SANITIZE_NUMBER_INT);
            case 'int!':
                return intval($value);
            case 'absint':
                return abs(intval($value));
            case 'string':
                return filter_var($value, FILTER_SANITIZE_STRING);
            case 'float':
                return filter_var($value, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
            case 'float!':
                return doubleval($value);
            case 'alphanum':
                return preg_replace("/[^A-Za-z0-9]/", "", $value);
            case 'trim':
                return trim($value);
            case 'striptags':
                return strip_tags($value);
            case 'lower':
                return function_exists('mb_strtolower') ? mb_strtolower($value) : strtolower($value);
            case 'upper':
                return function_exists('mb_strtoupper') ? mb_strtoupper($value) : strtoupper($value);
        }
    }
}