Função de busca de Endereço pelo CEP
-	Desenvolvido Felipe Olivaes para ajaxbox.com.br
-	Utilizando WebService de CEP da republicavirtual.com.br
@param  string $cep
@return array  $retorno
558444
public static function getEndereco($cep)
    {
        $cep = urlencode($cep);
        $resultado = @file_get_contents("http://republicavirtual.com.br/web_cep.php?cep=$cep&formato=json");
        if (!$resultado) {
            $resultado = '{"resultado":"0","resultado_txt":"erro ao buscar cep"}';
        }
        $ret = json_decode($resultado, true);

        return $ret;
    }
840303
private function normalizeEndpoint(Endpoint $endpoint)
    {
        $normalizedEndpoint = [
            'serviceName' => $endpoint->getServiceName(),
        ];

        if (null !== ($ipv4 = $endpoint->getIpv4())) {
            $normalizedEndpoint['ipv4'] = $ipv4;
        }

        if (null !== ($ipv6 = $endpoint->getIpv6())) {
            $normalizedEndpoint['ipv6'] = $ipv6;
        }

        if (null !== ($port = $endpoint->getPort())) {
            $normalizedEndpoint['port'] = $port;
        }

        return $normalizedEndpoint;
    }
1171767
public function load($key)
    {
        //bufor nieaktywny
        if (!$this->isActive()) {
            return;
        }
        //pobranie z rejestru aplikacji jeśli istnieje
        if ($this->getRegistry()->issetOption($key)) {
            return $this->getRegistry()->getOption($key);
        }
        //zwrot zwalidowanych danych
        return $this->validateAndPrepareBackendData($key, $this->_handler->load($key));
    }
689877
public function parseP(\DOMElement $p) {
		$classTitle = $this->parseValueClassTitle($p, ' ');

		if ($classTitle !== null) {
			return $classTitle;
		}

		$this->resolveChildUrls($p);

		if ($p->tagName == 'img' and $p->hasAttribute('alt')) {
			$pValue = $p->getAttribute('alt');
		} elseif ($p->tagName == 'area' and $p->hasAttribute('alt')) {
			$pValue = $p->getAttribute('alt');
		} elseif (($p->tagName == 'abbr' or $p->tagName == 'link') and $p->hasAttribute('title')) {
			$pValue = $p->getAttribute('title');
		} elseif (in_array($p->tagName, array('data', 'input')) and $p->hasAttribute('value')) {
			$pValue = $p->getAttribute('value');
		} else {
			$pValue = $this->textContent($p);
		}

		return $pValue;
	}
989114
protected function validaCEP($cep)
    {
        $formated_cep = preg_replace("/[^0-9]/", "", $cep);
        if (!preg_match('/^[0-9]{8}?$/', $formated_cep)) {
            throw new \Exception("CEP inválido");
        }
        $this->cep = $formated_cep;
    }
36786
public function processResponse($resp = '')
    {
        preg_match_all("/<EPAYMENT>(.*?)<\/EPAYMENT>/", $resp, $matches);
        $data = explode("|", $matches[1][0]);
        if (is_array($data)) {
            if (count($data) > 0) {
                $counter = 1;
                foreach ($data as $dataValue) {
                    $this->debugMessage[] = 'EPAYMENT_ELEMENT_' . $counter .': ' . $dataValue;
                    $counter++;
                }
            }
        }
        return $this->nameData($data);
    }
337157
public function generate($payload, $container = 'data')
    {
        $function      = null;
        $function_list = [
            'bson_encode',
            'MongoDB\BSON\fromPHP',
        ];

        foreach ($function_list as $bson_function) {
            if (function_exists($bson_function)) {
                $function = $bson_function;
            }
        }

        if (is_null($function)) {
            throw new ResponderException('Failed To Generate BSON - Supporting Library Not Available');  // @codeCoverageIgnore
        }

        if ($payload) {
            $prevHandler = set_error_handler(function ($errno, $errstr, $errfile, $errline, $errcontext) {
                throw new \Exception;  // @codeCoverageIgnore
            });

            try {
                $bson = $function([$container => $payload]);
                if ( ! $bson) {
                    throw new \Exception;  // @codeCoverageIgnore
                }
            } catch (\Exception $e) {
                set_error_handler($prevHandler);
                throw new ResponderException('Failed To Generate BSON');
            }

            set_error_handler($prevHandler);

            return $bson;
        }

        return '';
    }
751777
public function execute(\Drouter\Container $container)
    {
        $rota = $this->getMatchedRoute();

        $callable = $rota->getCallable();
        $params = $rota->getParams();

        $middlewares = $this->getMiddlewares();
        $routeName = $rota->getName();
        $groupPrefix = $rota->getGroupPrefix();

        //Middlewares de group
        if (!is_null($groupPrefix) && isset($this->groupMiddlewares[$groupPrefix])) {
            $middlewares1 = $this->groupMiddlewares[$groupPrefix];
            $routeMiddlewares = $rota->getMiddlewares();
            $rota->addMiddlewares($this->joinMiddlewares($middlewares1, $routeMiddlewares));
        }

        //Middlewares de routeNames armazenadas em memoria para adição posterior
        if (isset($middlewares[$routeName])) {
            $middlewares1 = $middlewares[$routeName];
            $routeMiddlewares = $rota->getMiddlewares();
            $rota->addMiddlewares($this->joinMiddlewares($middlewares1, $routeMiddlewares));
            unset($this->middlewares[$routeName]);
        }

        //rotas globais acima das indicadas com name
        if (isset($middlewares['*'])) {
            $middlewares1 = $middlewares['*'];
            $routeMiddlewares = $rota->getMiddlewares();
            $rota->addMiddlewares($this->joinMiddlewares($middlewares1, $routeMiddlewares));
        }

        if (count($rota->getMiddlewares())) {
            Middleware::executeMiddlewares($rota->getMiddlewares(), $container);
        }

        if (is_string($callable) && preg_match('/^[a-zA-Z\d\\\\]+[\:][\w\d]+$/', $callable)) {
            $exp = explode(':', $callable);

            $obj = filter_var($exp[0], FILTER_SANITIZE_STRING);
            $obj = new $obj($container);
            $method = filter_var($exp[1], FILTER_SANITIZE_STRING);

            $callable = [$obj, $method];
        }
            

        if (!empty($params)) {
            $params = array_values($params);
        }

        $container->options = $rota->getOptions();

        if (is_object($callable) || (is_string($callable) && is_callable($callable))) {
            $params[] = $container;
        }

        call_user_func_array($callable, $params);
    }
690988
public function execute(\PhpSigep\Model\PreListaDePostagem $params)
    {
        $xmlDaPreLista = $this->getPlpXml($params);

        $listaEtiquetas = array();
        foreach ($params->getEncomendas() as $objetoPostal) {
            $listaEtiquetas[] = $objetoPostal->getEtiqueta()->getEtiquetaSemDv();
        }

        $xml = utf8_encode($xmlDaPreLista->flush());
//		$xml = utf8_encode($xml);
//		$xml = iconv('UTF-8', 'ISO-8859-1', $xml);

        $soapArgs = array(
            'xml'            => $xml,
            'idPlpCliente'   => '',
            'cartaoPostagem' => $params->getAccessData()->getCartaoPostagem(),
            'listaEtiquetas' => $listaEtiquetas,
            'usuario'        => $params->getAccessData()->getUsuario(),
            'senha'          => $params->getAccessData()->getSenha(),
        );
        
        $result = new Result();
        try {
            $r = SoapClientFactory::getSoapClient()->fechaPlpVariosServicos($soapArgs);
            if (class_exists('\StaLib_Logger',false)) {
                \StaLib_Logger::log('Retorno SIGEP fecha PLP: ' . print_r($r, true));
            }
            if ($r instanceof \SoapFault) {
                throw $r;
            }
            if ($r && $r->return) {
                $result->setResult(new FechaPlpVariosServicosRetorno(array('idPlp' => $r->return)));
            } else {
                $result->setErrorCode(0);
                $result->setErrorMsg('A resposta do Correios não está no formato esperado. Resposta recebida: "' . 
                    $r . '"');
            }
        } catch (\Exception $e) {
            if ($e instanceof \SoapFault) {
                $result->setIsSoapFault(true);
                $result->setErrorCode($e->getCode());
                $result->setErrorMsg(SoapClientFactory::convertEncoding($e->getMessage()));
            } else {
                $result->setErrorCode($e->getCode());
                $result->setErrorMsg($e->getMessage());
            }
        }
        
        return $result;
    }
928883
private function respaldarDocumentosEmitidos()
    {
        // obtener DTE emitidos en el Portal MIPYME del SII
        $this->log('Descargando documentos emitidos');
        $emitidos = $this->LibreDTE->post('/utilidades/sii/mipyme_dte_emitidos/'.$this->args['contribuyente'], [
            'auth'=>[
                'rut' => $this->args['usuario'],
                'clave' => $this->args['clave'],
            ],
        ]);
        if ($emitidos['status']['code']!=200) {
            $this->log(' [error] Al obtener DTE emitidos en Portal MIPYME del SII: '.$emitidos['body']);
            return;
        }
        file_put_contents($this->args['salida'].'/emitidos_'.$this->args['contribuyente'].'.json', json_encode($emitidos['body'], JSON_PRETTY_PRINT));
        // descargar PDF y XML de los documentos
        $n_docs = count($emitidos['body']);
        $i = 0;
        foreach ($emitidos['body'] as $doc) {
            $i++;
            $this->log('Descargando PDF y XML '.$this->num($i).'/'.$this->num($n_docs).' '.$doc['dte'].' #'.$doc['folio']);
            // descargar PDF
            $pdf = $this->LibreDTE->post('/utilidades/sii/mipyme_dte_emitido_pdf/'.$this->args['contribuyente'].'/'.$doc['codigo'], [
                'auth'=>[
                    'rut' => $this->args['usuario'],
                    'clave' => $this->args['clave'],
                ],
            ]);
            if ($pdf['status']['code']!=200) {
                $this->log(' [error] Al obtener el PDF '.$doc['codigo'].': '.$pdf['body']);
            } else {
                file_put_contents($this->args['salida'].'/emitidos/dte_'.$this->args['contribuyente'].'_T'.$this->getCodigoDTE($doc['dte']).'F'.$doc['folio'].'.pdf', $pdf['body']);
            }
            // descargar XML
            $xml = $this->LibreDTE->post('/utilidades/sii/mipyme_dte_emitido_xml/'.$this->args['contribuyente'].'/'.$this->getCodigoDTE($doc['dte']).'/'.$doc['folio'], [
                'auth'=>[
                    'rut' => $this->args['usuario'],
                    'clave' => $this->args['clave'],
                ],
            ]);
            if ($xml['status']['code']!=200) {
                $this->log(' [error] Al obtener el XML '.$doc['codigo'].': '.$xml['body']);
            } else {
                file_put_contents($this->args['salida'].'/emitidos/dte_'.$this->args['contribuyente'].'_T'.$this->getCodigoDTE($doc['dte']).'F'.$doc['folio'].'.xml', $xml['body']);
            }
        }
    }
1354644
protected function getOrigin($endPoint)
    {
        $url = parse_url($endPoint);
        $origin = $url['scheme'].'://'.$url['host'];
        if (isset($url['port'])) {
            $origin = $origin.':'.$url['port'];
        }

        return $origin;
    }
289578
private function getResults($endpoint)
    {
        $results = [];
        $this->errorMessage = null;

        // Send the request
        $client = new Client(); //GuzzleHttp\Client

        do {
            try {
                $response = $client->request('GET', $endpoint, [
                    'headers' => $this->headers,
                    'query' => ['$select' => $this->select,
                        '$filter' => $this->filter,
                        '$orderby' => $this->orderby,
                        '$groupby' => $this->groupby,
                        '$having' => $this->having,
                        '$top' => $this->top,
                        '$skip' => $this->skip,
                        '$distinct' => $this->distinct
                    ],
                    'curl' => $this->setGetCurlopts(),
                ]);

            } catch (\GuzzleException $e) {
                $this->errorMessage = $e->getResponse()->getBody()->getContents();
                return false;
            } catch (\GuzzleHttp\Exception\ClientException $e) {
                $this->errorMessage = $e->getResponse()->getBody()->getContents();
                return false;
            } catch (\GuzzleHttp\Exception\RequestException $e) {
                $this->errorMessage = $e->getResponse()->getBody()->getContents();
                return false;
            } catch (\GuzzleHttp\Exception\ServerException $e) {
                $this->errorMessage = $e->getResponse()->getBody()->getContents();
                return false;
            }

            $r = json_decode($response->getBody(), true);

            // Get the number of rows returned
            $num = count($r);

            // Add this result set to the previous results
            $results = array_merge($results, $r);

            // Skip the rows we just got back if there were 1000 of them and query again
            ($num == 1000) ? $this->skip += 1000 : $this->skip = 0;

        } while ($this->skip > 0);

        $this->reset();
        return $results;
    }
384839
public function GetProtoHeader(
        \Peg\Lib\Definitions\Element\FunctionElement $function
    )
    {
        $proto = "/* {{{ ";

        foreach($function->overloads as $overload)
        {
            $proto .= "proto ";

            $proto .= $this->symbols->GetPHPStandardType($overload->return_type);

            $proto .= " " . $overload->function->name . "(";

            foreach($overload->parameters as $parameter)
            {
                $proto .= $this->symbols->GetPHPStandardType($parameter);

                if(!$parameter->is_const && ($parameter->is_pointer || $parameter->is_reference))
                {
                    $proto .= " &" . $parameter->name;
                }
                else
                {
                    $proto .= " " . $parameter->name;
                }

                if($parameter->default_value)
                {
                    $proto .= " = " . $parameter->default_value;
                }

                $proto .= ", ";
            }

            $proto = rtrim($proto, ", ");

            $proto .= ")";

            if($overload->description)
                $proto .= "\n       " . $overload->description;

            $proto .= "\n       ";
        }

        $proto = rtrim($proto, " \n");

        $proto .= " */\n";

        return $proto;
    }
992171
private function validarCep($cep) {
	    // retira espacos em branco
	    $cep = str_replace("-", "", trim($cep));

	    // expressao regular para avaliar o cep
	    $checkCep = preg_match("/^[0-9]{8}$/", $cep);
	    
	    // verifica o resultado
	    if(!$checkCep) {            
	        return false;
	    }
	    
	    return true;
	}
214490
public static function toResponse($request, $response)
    {
        if ($response instanceof View) {
            $response = $response->render();
        }

        if ($response instanceof Responsable) {
            $response = $response->toResponse();
        }

        if (! $response instanceof SymfonyResponse) {
            $response = response($response);
        }

        if ($response->getStatusCode() === Response::HTTP_NOT_MODIFIED) {
            $response->setNotModified();
        }

        // Tratamento finais do response
        $response = $response->prepare($request->getBaseRequest());

        // Fix Content-Type to application/json
        $charset = $response->getCharset() ?: 'UTF-8';
        if (0 === stripos($response->headers->get('Content-Type'), 'application/json') && false === stripos($response->headers->get('Content-Type'), 'charset')) {
            $response->headers->set('Content-Type', $response->headers->get('Content-Type').'; charset=' . $charset);
        }

        return $response;
    }
1284823
def configurar_interface_de_rede(self, configuracao):
        
        resp = self._http_post('configurarinterfacederede',
                configuracao=configuracao.documento())
        conteudo = resp.json()
        return RespostaSAT.configurar_interface_de_rede(conteudo.get('retorno'))
246453
def configurar_interface_de_rede(self, configuracao):
        
        retorno = super(ClienteSATLocal, self).\
                configurar_interface_de_rede(configuracao)
        return RespostaSAT.configurar_interface_de_rede(retorno)