Last active
December 16, 2015 15:40
-
-
Save rederlo/1efe5df80806b60504cf to your computer and use it in GitHub Desktop.
Exemplo de CakePhp Behavior Buscar Cep
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
App::uses('ModelBehavior', 'Model'); | |
/** | |
* Created by PhpStorm. | |
* User: Ederlo Rodrigo de Oliveira | |
* Date: 16/12/15 | |
* Time: 09:23 | |
*/ | |
class CepUtilBehavior extends ModelBehavior | |
{ | |
/** | |
* @var string | |
*/ | |
public $url = 'http://cep.correiocontrol.com.br'; | |
/** | |
* @var string | |
*/ | |
public $url2 = 'https://viacep.com.br/ws'; | |
/** | |
* @var string | |
*/ | |
public $type = 'json'; | |
/** | |
* Setup this behavior with the specified configuration settings. | |
* | |
* @param Model $model Model using this behavior | |
* @param array $config Configuration settings for $model | |
* @return void | |
*/ | |
public function setup(Model $model, $config = array()) | |
{ | |
parent::setup($model, $config); // TODO: Change the autogenerated stub | |
} | |
/** | |
* @param int $cep | |
* @return mixed | |
* @throws Exception | |
*/ | |
public function cep(Model $model, $cep = 0) | |
{ | |
try{ | |
$cep = filter_var($cep, FILTER_SANITIZE_NUMBER_INT); | |
$json = file_get_contents("{$this->url2}/{$cep}/{$this->type}"); | |
return json_decode($json, true); | |
} catch (Exception $e){ | |
try{ | |
$cep = filter_var($cep, FILTER_SANITIZE_NUMBER_INT); | |
$json = file_get_contents("{$this->url}/{$cep}.{$this->type}"); | |
return json_decode($json, true); | |
} catch (Exception $e) { | |
throw new Exception($e); | |
} | |
} catch (Exception $e){ | |
return json_decode(['json' => '']); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment