emersonbroga
12/13/2012 - 6:03 PM

Cep Class for use with the republica virtual db.

Cep Class for use with the republica virtual db.

$cep = new \Cep($cep, $formato);
header( $cep->header );
print( $cep->resultado );
class Cep
{
    private $url = 'http://www.republicavirtual.com.br/web_cep.php?';
    private $cep, $formato, $consulta;
    public $uf, $cidade, $bairro, $tipo_logradouro, $logradouro, $header;
    public $resultado;

    public function __construct($cep, $formato='query_string')
    {
        $this->cep = preg_replace('([^0-9])', '', $cep);
        $this->formato = trim(strtolower($formato));

        $result = $this->fetch();
      
        if(!$result){
          $this->header    = 'HTTP/1.0 404 Not Found';
        	$this->resultado = 'Not found';
        	return;
        }
        	
        	
		$result = array();
        $result['uf'] 				= $this->uf;
        $result['cidade'] 			= $this->cidade;
        $result['bairro'] 			= $this->bairro;
        $result['tipo_logradouro']  = $this->tipo_logradouro;
        $result['logradouro'] 		= $this->logradouro;
        $result['formato']			= $this->formato;
    	
        //replace null to empty
    	foreach($result as $key => $value){
    		if( is_null($value) || mb_strlen($value) == 0 || empty($value))
    			$result[$key] = '';
    	}
    	
        switch( $this->formato )
        {
        	case 'querystring':
        	case 'query_string':	
        		$this->header = 'Content-Type: text/plain';
        		foreach($result as $key => $value)
        			$result[$key] = utf8_decode($value);
        		
        		$this->resultado = http_build_query($result);
        		break;
        		
        	case 'json':
        		$this->header = 'Content-Type: application/json';	 
        		$this->resultado = json_encode($result);
        		break;
        	
        	case 'jsonp':
        		$this->header = 'Content-Type: text/plain';
        		$this->resultado = sprintf('cepCallback(%s)', json_encode($result));
        		break;
        	
        	case 'xml':
        		$xml = new SimpleXMLElement('<xml/>');
        		$xmlCep = $xml->addChild('cep');
        		
        		foreach($result as $key => $value){
        			$xmlCep->addChild($key, $value );
        		}
        		
        		$this->header = 'Content-type: text/xml';
        		$this->resultado = $xml->asXML();
        		break;	
        	
        	default:
        		$this->header = 'Content-Type: application/json';
        		$result['formato'] = '"'.$this->formato.'" not implemented.';
        		foreach($result as $key => $value)
        			$result[$key] = utf8_decode($value);
        		
        		$this->resultado = json_encode($result);
        		break;
        }	
    }

    public function getStatus()
    {
        $return = array('status' => $this->resultado);
        switch($this->resultado) {
            case 0: $return['msg'] = 'cep não encontrado'; break;
            case 1: $return['msg'] = 'encontrado endereço completo'; break;
            case 2: $return['msg'] = 'encontrado cidade/uf'; break;
        }
        echo json_encode($return);
    }

    public function __toString()
    {
        return $this->consulta;
    }
    
	public function curl($url, $method = 'get', $data = array())
    {
    	$curl = curl_init();
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($curl, CURLOPT_COOKIEJAR, md5($url).'.jar.txt');
		curl_setopt($curl, CURLOPT_COOKIEFILE, md5($url).'.txt');
		curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.3) Gecko/20070309 Firefox/2.0.0.3");
        
        if($method == 'get') {
        	curl_setopt($curl, CURLOPT_URL, $url . (strpos($url, '?') === FALSE ? '?' . http_build_query($data) : ''));
		}
        elseif($method == 'post') {
        	curl_setopt($curl, CURLOPT_URL, $url);
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
		}
        
        $content = curl_exec($curl);
        $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        curl_close($curl);
        
        return (object) array(
                'status' => $status,
                'content' => $content
        );
	}
	
	
	public function fetch()
	{
		try {
			
			//Cep XXXXX-XXX
			$cep  = substr($this->cep,0,-3) . '-' . substr($this->cep,5);
			//Cep XXXXX
			$cep5 = substr($this->cep,0,-3);
			
			$host = x;
			$user = x;
			$pass = x;
			$db   = x;
			
			$pdo = new PDO('mysql:host='.$host.';dbname='.$db, $user, $pass, array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));
		
			$query = sprintf('SELECT * FROM cep_log_index WHERE cep5 = "%s"', $cep5);
			
			$stmt   = $pdo->query($query);
	 		$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
	 		$result = ($result) ? (object) current($result) : null;
	 		
	 		if($result){
	 			
	 			$this->uf = strtoupper($result->uf);
	 			
	 			$query = sprintf('SELECT * FROM %s WHERE cep = "%s"', strtolower($this->uf), $cep);
				$stmt   = $pdo->query($query);
	 			$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
	 			$result = ($result) ? (object) current($result) : null;
	 			
	 			
	 			$this->resultado 		= isset($result->resultado) 		? $result->resultado 		: null;
            	$this->cidade 			= isset($result->cidade) 			? $result->cidade 			: null;
            	$this->bairro 			= isset($result->bairro) 			? $result->bairro 			: null;
            	$this->tipo_logradouro 	= isset($result->tp_logradouro) 	? $result->tp_logradouro 	: null;
            	$this->logradouro 		= isset($result->logradouro) 		? $result->logradouro 		: null;
	 			
            	return ($result) ? true : false;
            	
	 		}else{

	 			$query = sprintf('SELECT * FROM cep_unico WHERE cep = "%s"', $cep);
				$stmt   = $pdo->query($query);
	 			$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
	 			$result = ($result) ? (object) current($result) : null;
	 			
	 			$this->cidade 			= isset($result->Nome)	? $result->Nome	: null;
            	$this->uf 				= isset($result->UF) 	? strtoupper($result->UF) 	: null;
            	
            		 			
            	return ($result) ? true : false;
            	
	 		}
		
		} catch(PDOException $ex) {
			//handle me.
			return false;
		}
		
		
	}
    
}