Skip to content

Commit

Permalink
feat(facades): Geo API Service
Browse files Browse the repository at this point in the history
  • Loading branch information
zhaiyuxin103 committed Aug 26, 2024
1 parent f19bc16 commit 4205e3c
Show file tree
Hide file tree
Showing 2 changed files with 73 additions and 0 deletions.
27 changes: 27 additions & 0 deletions app/Facades/Geo.php
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;
}
}
46 changes: 46 additions & 0 deletions app/Services/GeoService.php
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());
}
}
}

0 comments on commit 4205e3c

Please sign in to comment.