44
55use GuzzleHttp \Client ;
66use GuzzleHttp \Exception \ConnectException ;
7+ use GuzzleHttp \Promise \PromiseInterface ;
78
89class Geocoder
910{
@@ -70,6 +71,43 @@ public function setHost(string $host): void
7071 * @return array{status: array{code: int, message: string}, results: list<mixed>, total_results: int, ...}
7172 */
7273 public function geocode (string $ query , array $ optParams = []): array
74+ {
75+ $ url = $ this ->buildUrl ($ query , $ optParams );
76+
77+ $ ret = json_decode ($ this ->getJSON ($ url ), true );
78+ if (!is_array ($ ret )) {
79+ throw new \Exception ('Failed to decode API response ' );
80+ }
81+ /** @var array{status: array{code: int, message: string}, results: list<mixed>, total_results: int, ...} */
82+ return $ ret ;
83+ }
84+
85+ /** @param array<string, string> $optParams */
86+ public function geocodeAsync (string $ query , array $ optParams = []): PromiseInterface
87+ {
88+ $ url = $ this ->buildUrl ($ query , $ optParams );
89+
90+ if ($ this ->client === null ) {
91+ $ this ->client = $ this ->buildClient ();
92+ }
93+
94+ return $ this ->client ->getAsync ($ url , ['http_errors ' => false ])
95+ ->then (function (\Psr \Http \Message \ResponseInterface $ response ) {
96+ $ ret = json_decode ((string ) $ response ->getBody (), true );
97+ if (!is_array ($ ret )) {
98+ throw new \Exception ('Failed to decode API response ' );
99+ }
100+ return $ ret ;
101+ }, function (\Throwable $ e ) {
102+ if ($ e instanceof ConnectException) {
103+ return json_decode ($ this ->generateErrorJSON (498 , 'network issue ' . $ e ->getMessage ()), true );
104+ }
105+ throw $ e ;
106+ });
107+ }
108+
109+ /** @param array<string, string> $optParams */
110+ protected function buildUrl (string $ query , array $ optParams = []): string
73111 {
74112 $ url = $ this ->url . 'q= ' . urlencode ($ query );
75113
@@ -84,12 +122,7 @@ public function geocode(string $query, array $optParams = []): array
84122 }
85123 $ url .= '&key= ' . urlencode ($ this ->key );
86124
87- $ ret = json_decode ($ this ->getJSON ($ url ), true );
88- if (!is_array ($ ret )) {
89- throw new \Exception ('Failed to decode API response ' );
90- }
91- /** @var array{status: array{code: int, message: string}, results: list<mixed>, total_results: int, ...} */
92- return $ ret ;
125+ return $ url ;
93126 }
94127
95128 protected function isValidHost (string $ host ): bool
0 commit comments