<?php

/*
  Clase SuperGetter
  Clase encargada de recoger los métodos get y post
  @version 1.0
 */

class SuperGetter {
	
    //Constructor y destructor
    public function __construct() {
    }

    public function __destruct() {
        
    }
	
	//Función encargada de recibir una variable recibida vía http (get o post):
	public static function get($variableName = '', $defaultValue = NULL, $method = ''){
		$retorno = $defaultValue;
		//Si nos mandan una variable, la recogemos sólo a ella:
		if ($variableName != ''){
			//Hay que ver si la variable ha llegado por get o por post (siempre y cuandno hayan especificado el método:
			if ($method == ''){
				//Hay que comprobar si la variable está seteada en GET o en POST:
				if (static::isInGet($variableName)){
					$retorno = $_GET[$variableName];
				}else if (static::isInPost($variableName)){
					$retorno = $_POST[$variableName];
				}
			}else{
				$method = strtoupper($method);
				if ( ($method == 'GET') && (static::isInGet($variableName)) ){
					$retorno = $_GET[$variableName];
				}else if ( ($method == 'POST') && (static::isInPost($variableName)) ){
					$retorno = $_POST[$variableName];
				}
			}
		}else{
			$variableList = file_get_contents('php://input');
			$retorno = $variableList;
		}
		return($retorno);
	}
	
	public static function getJson(){
		return(file_get_contents('php://input'));
	}
	
	public static function isInGet($variableName){
		$retorno = false;
		if (isset($_GET[$variableName])){
			$retorno = true;
		}
		return($retorno);
	}
	public static function isInPost($variableName){
		$retorno = false;
		if (isset($_POST[$variableName])){
			$retorno = true;
		}
		return($retorno);
	}
	
	//Funciones que uso para concatenar dos strings sin repetir la parte que se solape
	private static function findOverlap($str1, $str2){
		$return = array();
		$sl1 = strlen($str1);
		$sl2 = strlen($str2);
		$max = $sl1>$sl2?$sl2:$sl1;
		$i=1;
		while($i<=$max){
			$s1 = substr($str1, -$i);
			$s2 = substr($str2, 0, $i);
			if($s1 == $s2){
				$return[] = $s1;
			}
			$i++;
		}
		if(empty($return)){
			$return = false;
		}
		return($return);
	}

	public static function replaceOverlap($str1, $str2, $length = "long"){
		if($overlap = static::findOverlap($str1, $str2)){
			switch($length){
				case "short":
					$overlap = $overlap[0];
				break;
				case "long":
				default:
					$overlap = $overlap[count($overlap)-1];
				break;
			}     
			$str1 = substr($str1, 0, -strlen($overlap));
			$str2 = substr($str2, strlen($overlap));
			return $str1.$overlap.$str2;
		}
		return false;
	}
}
