client = $client; $this->latLngInterfaceFactory = $latLngInterfaceFactory; $this->json = $json; $this->getApiKey = $getApiKey; $this->addressToComponentsString = $addressToComponentsString; $this->addressToString = $addressToString; $this->addressToQueryString = $addressToQueryString; } /** * @inheritdoc * @throws LocalizedException */ public function execute(AddressInterface $address): LatLngInterface { $cacheKey = $addressString = $this->addressToString->execute($address); if (!isset($this->latLngCache[$cacheKey])) { $queryString = http_build_query([ 'key' => $this->getApiKey->execute(), 'components' => $this->addressToComponentsString->execute($address), 'address' => $this->addressToQueryString->execute($address), ]); $this->client->get(self::GOOGLE_ENDPOINT . '?' . $queryString); if ($this->client->getStatus() !== 200) { throw new LocalizedException(__('Unable to connect google API for geocoding')); } $res = $this->json->unserialize($this->client->getBody()); if ($res['status'] !== 'OK') { throw new LocalizedException(__('Unable to geocode address %1', $addressString)); } $location = $res['results'][0]['geometry']['location']; $this->latLngCache[$cacheKey] = $this->latLngInterfaceFactory->create([ 'lat' => (float)$location['lat'], 'lng' => (float)$location['lng'], ]); } return $this->latLngCache[$cacheKey]; } }