Created
January 19, 2019 15:49
-
-
Save bhardwajRahul/8634f8b7ec7b21fa4d61d76072fa3568 to your computer and use it in GitHub Desktop.
API wrapper
This file contains hidden or 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
<?php | |
namespace App\DistanceApi\Api; | |
/* | |
|-------------------------------------------------------------------------- | |
| Request Class | |
|-------------------------------------------------------------------------- | |
| | |
| This class is used when querying your API. | |
| | |
| * Class is called via the Facade 'Api' | |
| * E.g. Api::getDistance('api'); | |
| | |
*/ | |
class Request { | |
/** | |
* @var string The domain location of the API | |
*/ | |
private static $curl; | |
private static $requestParameters = array(); | |
private static $domain = 'https://maps.googleapis.com'; | |
/** | |
* @var string Path to Google Distance Matrix API | |
*/ | |
private static $path = 'maps/api/distancematrix/json'; | |
private static $measuringUnit = 'metric'; | |
/** | |
* @var array Any additional parameters to be sent with each request | |
*/ | |
private static function getParameters() { | |
return [ | |
'units'=> self::$measuringUnit, | |
'key' => env('YOUR_API_KEY'), | |
]; | |
} | |
private static $coordinateParameters = [ | |
'origins','destinations' | |
]; | |
/** | |
* @var bool Set whether the cURL request will be over HTTP or HTTPS | |
* false = HTTP | |
* true = HTTPS | |
*/ | |
private static $secure = true; | |
private static function getDistance($params =[]) { | |
self::$curl = curl_init(); | |
curl_setopt_array( self::$curl, [ | |
CURLOPT_SSL_VERIFYPEER => self::$secure, | |
CURLOPT_RETURNTRANSFER => 1, | |
CURLOPT_URL => self::urlBuilder($params), | |
] | |
); | |
return curl_exec( self::$curl); | |
} | |
/** | |
* Function to build URL | |
*/ | |
private static function urlBuilder($params = []){ | |
return self::$domain . '/' . self::$path . '?' . http_build_query($params); | |
} | |
/** | |
* Distance calculation | |
*/ | |
public static function calculateDistance($data){ | |
$data = array_map(function($v){return implode(',',(array)$v);},$data); | |
$data = array_combine(self::$coordinateParameters,$data); | |
self::$requestParameters = self::getParameters(); | |
self::$requestParameters = array_merge($data,self::$requestParameters); | |
$response = json_decode(self::getDistance(self::$requestParameters), true); | |
if (isset($response['rows'][0]['elements'][0]['distance']['value'])) { | |
$response = $response['rows'][0]['elements'][0]['distance']['value']; | |
}else{ | |
$response = $response['error_message']; | |
} | |
return $response; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment