@param string $zone
@param string $city
@param string $address_2

@throws \PhpSigep\Services\Exception
@return Result<ListarAgenciasCliqueRetireResult[]>
487167
public function execute($zone, $city, $address_2)
    {
        $soapArgs = array(
            'uf'   => $zone,
            'municipio'   => $city,
            'bairro'   => $address_2
        );

        $result = new Result();

        try {
            $r = SoapClientFactory::getSoapAgenciaWS()->listarAgenciasCliqueERetirePorLocalidade($soapArgs);
            if (!$r || !is_object($r) || !isset($r->resultadoListaAgencia) || ($r instanceof \SoapFault)) {
                if ($r instanceof \SoapFault) {
                    throw $r;
                }

                throw new FailedResultException('Erro ao listar agencias Clique e Retire. Retorno: "' . $r . '"');
            }

            if ($r instanceof \stdClass) {
                $objectToarray = json_decode(json_encode($r), true);

                if ($objectToarray) {
                    $result->setResult(new ListarAgenciasCliqueRetireResult($objectToarray['resultadoListaAgencia']));
                } else {
                    throw new FailedConvertToArrayException('Erro ao converter Object para Array da Busca. Retorno: "' . print_r(json_last_error_msg(), true) . '"');
                }
            }
        } catch (\Exception $e) {
            if ($e instanceof \SoapFault) {
                $result->setIsSoapFault(true);
                $result->setErrorCode($e->getCode());
                $result->setErrorMsg("Resposta do Correios: " . SoapClientFactory::convertEncoding($e->getMessage()));
            } else {
                $result->setErrorCode($e->getCode());
                $result->setErrorMsg($e->getMessage());
            }
        }

        return $result;
    }
524070
private function cleanAddress($address, $updatableFields)
    {
        if (is_array($address)) {
            /** @var UpdatableFieldsConstructor $updatableFieldsConstructor */
            $updatableFieldsConstructor = oxNew(UpdatableFieldsConstructor::class);
            $cleaner = $updatableFieldsConstructor->getAllowedFieldsCleaner($updatableFields);
            return $cleaner->filterByUpdatableFields($address);
        }

        return $address;
    }
1097766
protected function getFromCache($address, $country)
    {
        $builder = $this->connection->createQueryBuilder();
        $builder
            ->select('*')
            ->from($this->connection->quoteIdentifier('tl_metamodel_perimetersearch'))
            ->where($builder->expr()->eq($this->connection->quoteIdentifier('search'), ':search'))
            ->andWhere($builder->expr()->eq($this->connection->quoteIdentifier('country'), ':country'))
            ->setParameter('search', $address)
            ->setParameter('country', $country);

        $statement = $builder->execute();

        // If we have no data just return null.
        if (!$statement->rowCount()) {
            return null;
        }

        $result = $statement->fetch(\PDO::FETCH_OBJ);

        // Build a new container.
        $container = new Container();
        $container->setLatitude($result->geo_lat);
        $container->setLongitude($result->geo_long);
        $container->setSearchParam(
            \strtr(
                $builder->getSQL(),
                [
                    ':search'  => $this->connection->quote($address),
                    ':country' => $this->connection->quote($country)
                ]
            )
        );

        return $container;
    }
108171
public function geocodeAddress($address)
	{
		$url = 'http://maps.googleapis.com/maps/api/geocode/json?sensor=false&address=' . urlencode($address);
		$response = $this->http->get($url);

		if ($response->code < 200 || $response->code >= 300)
		{
			throw new RuntimeException('Error code ' . $response->code . ' received geocoding address: ' . $response->body . '.');
		}

		$data = json_decode($response->body, true);

		if (!$data)
		{
			throw new RuntimeException('Invalid json received geocoding address: ' . $response->body . '.');
		}

		if ($data['status'] != 'OK')
		{
			return null;
		}

		return $data['results'][0];
	}
414614
private function _addressDigestPart(KlarnaAddr $address = null)
    {
        if ($address === null) {
            return array();
        }

        $keyOrder = array(
            'careof', 'street', 'zip', 'city', 'country', 'fname', 'lname'
        );

        $holder = $address->toArray();
        $digest = array();

        foreach ($keyOrder as $key) {
            if ($holder[$key] != "") {
                $digest[] = $holder[$key];
            }
        }

        return $digest;
    }
1322199
public static function formatAddress(array $address, $sep = ', ')
    {
        $address = array_merge(
            [
                'firstname' => '',
                'lastname' => '',
                'address1' => '',
                'address2' => '',
                'address3' => '',
                'postcode' => '',
                'city' => '',
                'country_code' => '',
            ],
            $address
        );

        $values = array_map('trim', [
                sprintf('%s %s', $address['firstname'], $address['lastname']),
                $address['address1'],
                $address['address2'],
                $address['address3'],
                $address['postcode'],
                $address['city'],
            ]);

        foreach ($values as $key => $val) {
            if (!$val) {
                unset($values[$key]);
            }
        }

        $fullAddress = implode($sep, $values);

        if ($countryCode = trim($address['country_code'])) {
            if ($fullAddress) {
                $fullAddress .= ' ';
            }

            $fullAddress .= sprintf('(%s)', $countryCode);
        }

        return $fullAddress;
    }
1271302
public function geocode($address)
    {
        $query = $this->buildQuery('address', $address);

        $response = $this->validateResponse(
            $this->getResponse($query)
        );

        return $this->buildResults($response['results']);
    }
1302466
public function delZoneRecord($zone, $recordid)
    {
        if (!$recordid) {
            throw new \Exception('missing record id');
        }
        // Make sure we know what zone to target
        if (!isset($this->zones[$zone])) {
            throw new \Exception("unknown zone {$zone} did you call getZones()?");
        }
        $zoneid = $this->zones[$zone]['id'];
        if (!$zoneid) {
            throw new \Exception("could not determine zone id for {$zone}");
        }
        $uri = $this->baseuri.'/zones/'.$zoneid.'/dns_records/'.$recordid;
        $result = $this->httpDelete($uri);

        return $result;
    }
653826
public function transform(Address $address)
    {
        return [
            'address' => $address->address,
            'addressableId' => $address->addressable_id,
            'addressableType' => $address->addressable_type,
            'country' => $address->country,
            'id' => $address->id,
            'label' => $address->label,
            'municipality' => $address->municipality,
            'postcode' => $address->postcode,
            'stateProvince' => $address->state_province,
        ];
    }
200485
protected function setAddress($address)
    {
        if (is_array($address)) {
            $new_address = [];

            foreach (['address', 'city', 'state', 'zip'] as $field) {
                if (array_key_exists($field, $address)) {
                    $new_address[] = $address[$field];
                }
            }

            $address = implode(' ', $new_address);
        }

        return $address;
    }
62143
public function getEntry(Address $address)
    {
        $events = array_filter($this->events, function (Entry $entry) use ($address) {
            return $entry->getAddress()->isMatch($address);
        });
        $last_matching_entry = null;
        foreach ($events as $entry) {
            if ($entry->getAddress()->isEntireCache() || $entry->getAddress()->isEntireBin()) {
                $last_matching_entry = null;
            } elseif (!is_null($entry->expiration) && $entry->expiration < $_SERVER['REQUEST_TIME']) {
                $last_matching_entry = null;
            } else {
                $last_matching_entry = clone $entry;
            }
        }
        // Last event was a deletion, so miss.
        if (is_null($last_matching_entry) || is_null($last_matching_entry->value)) {
            $this->misses++;
            return null;
        }

        $unserialized_value = @unserialize($last_matching_entry->value);

        // If unserialization failed, miss.
        if (false === $unserialized_value && serialize(false) !== $last_matching_entry->value) {
            throw new UnserializationException($address, $last_matching_entry->value);
        }

        $last_matching_entry->value = $unserialized_value;

        $this->hits++;
        return $last_matching_entry;
    }
780509
public void setAddress(String street_1, String street_2, String city, String postal_code, String state, String country)
    {
        this.address.put("street_1", street_1);
        this.address.put("street_2", street_2);
        this.address.put("city", city);
        this.address.put("postal_code", postal_code);
        this.address.put("state", state);
        this.address.put("country", country);
    }
276995
public function addZoneRecord($zone, $type, $name, $content, $ttl = 120)
    {
        // List of supported record types to add
        $types = ['A', 'AAAA', 'TXT', 'CNAME'];
        if (!in_array($type, $types)) {
            throw new \Exception("record type {$type} not in list of supported types: ".implode(',', $types));
        }
        // Make sure we know what zone to target
        if (!isset($this->zones[$zone])) {
            throw new \Exception("unknown zone {$zone} did you call getZones()?");
        }
        /*
            <urn2:createResourceRecords>
                <urn2:domainName>test.com</urn2:domainName>
                <urn2:resourceRecord allowanyIP="false">
                    <urn2:resourceRecordId>?</urn2:resourceRecordId>
                    <urn2:owner>_acme-challenge.three.test.com.</urn2:owner>
                    <urn2:type>TXT</urn2:type>
                    <urn2:ttl>120</urn2:ttl>
                    <urn2:rData>i9x9C8DlEZmUuqaa90dchYN4C23zso</urn2:rData>
                </urn2:resourceRecord>
                <urn2:comments>LetsEncrypt AutoEnrollment</urn2:comments>
            </urn2:createResourceRecords>
        */
        $owner = $name.'.';
        $params = [
                    'domainName'     => $zone,
                    'resourceRecord' => [
                                            'owner' => $owner,
                                            'type'  => $type,
                                            'ttl'   => $ttl,
                                            'rData' => $content,
                                        ],
                    ];
        $response = $this->soapCall('createResourceRecords', $params);
        if (!$response['callSuccess']) {
            throw new \Exception('SOAP callSuccess false');
        }
        // Update our cache of zone resource records after adding one
        $this->zonerecords[$zone] = $this->fetchRecords($zone);
        /* Sample resource record added to a zone
            [resourceRecordId] => 21042133
            [owner] => 044-smtp-in-5.test.com.
            [type] => MX
            [ttl] => 14400
            [rData] => 10 044-smtp-in-1e.test.com.
        */
        foreach ($this->zonerecords[$zone] as $record) {
            if ($record['owner'] == $owner
            &&    $record['type'] == $type
            &&    $record['ttl'] == $ttl
            &&    $record['rData'] = $content) {
                return $record;
            }
        }
        throw new \Exception('Added record but could not identify new resource record');
    }
410710
private function executeQuery(string $url, string $locale = null): AddressCollection
    {
        if (null !== $locale) {
            $url = sprintf('%s&language=%s', $url, $locale);
        }

        $content = $this->getUrlContents($url);
        $json = json_decode($content, true);

        // https://geocoder.opencagedata.com/api#codes
        if (isset($json['status'])) {
            switch ($json['status']['code']) {
                case 400:
                    throw new InvalidArgument('Invalid request (a required parameter is missing).');
                case 402:
                    throw new QuotaExceeded('Valid request but quota exceeded.');
                case 403:
                    throw new InvalidCredentials('Invalid or missing api key.');
            }
        }

        if (!isset($json['total_results']) || 0 == $json['total_results']) {
            return new AddressCollection([]);
        }

        $locations = $json['results'];

        if (empty($locations)) {
            return new AddressCollection([]);
        }

        $results = [];
        foreach ($locations as $location) {
            $builder = new AddressBuilder($this->getName());
            $this->parseCoordinates($builder, $location);

            $components = $location['components'];
            $annotations = $location['annotations'];

            $this->parseAdminsLevels($builder, $components);
            $this->parseCountry($builder, $components);
            $builder->setLocality($this->guessLocality($components));
            $builder->setSubLocality($this->guessSubLocality($components));
            $builder->setStreetNumber(isset($components['house_number']) ? $components['house_number'] : null);
            $builder->setStreetName($this->guessStreetName($components));
            $builder->setPostalCode(isset($components['postcode']) ? $components['postcode'] : null);
            $builder->setTimezone(isset($annotations['timezone']['name']) ? $annotations['timezone']['name'] : null);

            /** @var OpenCageAddress $address */
            $address = $builder->build(OpenCageAddress::class);
            $address = $address->withMGRS(isset($annotations['MGRS']) ? $annotations['MGRS'] : null);
            $address = $address->withMaidenhead(isset($annotations['Maidenhead']) ? $annotations['Maidenhead'] : null);
            $address = $address->withGeohash(isset($annotations['geohash']) ? $annotations['geohash'] : null);
            $address = $address->withWhat3words(isset($annotations['what3words'], $annotations['what3words']['words']) ? $annotations['what3words']['words'] : null);
            $address = $address->withFormattedAddress($location['formatted']);

            $results[] = $address;
        }

        return new AddressCollection($results);
    }
1183187
public function getCoordinatesByString(string $address) : CoordinatesInterface
    {
        $url = $this->addressQuery($address);
        $json = $this->fetchUrl($url);

        // convert google data to coordinates
        $coordinates = CoordinatesBuild::create($json->results[0]);

        return $coordinates;
    }
918155
private function _generatorAddressCode($address)
    {
        $addressCode = array_search($address, $this->_addressCodeList);
        $classification = $this->_addressCodeClassification($addressCode);
        switch ($classification) {
            case 'country':
                $pattern = '/\d{4}(?!00)[0-9]{2}$/';
                $addressCode = $this->_getRandAddressCode($pattern);
                break;
            case 'province':
                $provinceCode = substr($addressCode, 0, 2);
                $pattern = '/^'.$provinceCode.'\d{2}(?!00)[0-9]{2}$/';
                $addressCode = $this->_getRandAddressCode($pattern);
                break;
            case 'city':
                $cityCode = substr($addressCode, 0, 4);
                $pattern = '/^'.$cityCode.'(?!00)[0-9]{2}$/';
                $addressCode = $this->_getRandAddressCode($pattern);
                break;
        }

        return $addressCode;
    }
936690
public static function findUniqueByZone( $name, $countryId, $provinceId, $zone ) {

		return self::find()->where( 'name=:name AND countryId=:cid AND provinceId=:pid AND zone=:zone', [ ':name' => $name, ':cid' => $countryId, ':pid' => $provinceId, ':zone' => $zone ] )->one();
	}