-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
f19bc16
commit 4205e3c
Showing
2 changed files
with
73 additions
and
0 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
<?php | ||
|
||
namespace App\Facades; | ||
|
||
use App\Services\GeoService; | ||
use Illuminate\Support\Facades\Facade; | ||
|
||
/** | ||
* @method static mixed fetch(array $query, string $format = 'json') | ||
* | ||
* @see \App\Services\GeoService | ||
*/ | ||
class Geo extends Facade | ||
{ | ||
/** | ||
* Create a new class instance. | ||
*/ | ||
public function __construct() | ||
{ | ||
// | ||
} | ||
|
||
public static function getFacadeAccessor(): string | ||
{ | ||
return GeoService::class; | ||
} | ||
} |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
<?php | ||
|
||
namespace App\Services; | ||
|
||
use Illuminate\Support\Facades\Http; | ||
use InvalidArgumentException; | ||
use Symfony\Component\HttpKernel\Exception\HttpException; | ||
use Throwable; | ||
|
||
class GeoService | ||
{ | ||
private string $uri = 'https://geoapi.heartrails.com/api'; | ||
|
||
private array $methods = ['getAreas', 'getPrefectures', 'getCities', 'getTowns', 'getStations', 'searchByPostal', 'searchByGeoLocation', 'suggest']; | ||
|
||
/** | ||
* Create a new class instance. | ||
*/ | ||
public function __construct() | ||
{ | ||
// | ||
} | ||
|
||
public function fetch($query, $format = 'json') | ||
{ | ||
$uri = $this->uri.'/'.$format; | ||
|
||
if (! in_array($query['method'], $this->methods)) { | ||
throw new InvalidArgumentException(trans('messages.failed.method_not_match', [ | ||
'method' => $query['method'], | ||
])); | ||
} | ||
|
||
if (! in_array(strtolower($format), ['json', 'xml'])) { | ||
throw new InvalidArgumentException(trans('messages.failed.response_format_not_match', compact('format'))); | ||
} | ||
|
||
try { | ||
$response = Http::get($uri, array_filter($query)); | ||
|
||
return $format === 'json' ? $response->json() : response($response->body())->header('Content-Type', 'text/xml'); | ||
} catch (Throwable $th) { | ||
throw new HttpException($th->getCode(), $th->getMessage()); | ||
} | ||
} | ||
} |