This repository has been archived by the owner on Jul 27, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 79
/
ClientAbstract.php
104 lines (93 loc) · 2.56 KB
/
ClientAbstract.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
<?php
/*
*
* @copyright Copyright (c) 2013-2019 2amigos
* @link http://2amigos.us
* @license http://www.opensource.org/licenses/bsd-license.php New BSD License
*
*/
namespace dosamigos\google\maps;
use Exception;
use GuzzleHttp\Client as HttpClient;
use GuzzleHttp\Exception\RequestException;
use Yii;
use yii\base\BaseObject;
/**
* ClientAbstract
*
* Base class for those objects that make requests to the Google Web Services API
*
* @author Antonio Ramirez <[email protected]>
*
* @link http://www.2amigos.us/
* @package dosamigos\google\maps
*/
abstract class ClientAbstract extends BaseObject
{
/**
* @var string response format. Can be json or xml.
*/
public $format = 'json';
/**
* @var array the request parameters
*/
public $params = [];
/**
* @var \Guzzle\Http\Client a client to make requests to the Google API
*/
private $_guzzle;
/**
* Returns the api url
* @return string
*/
abstract public function getUrl();
/**
* @inheritdoc
*/
public function init()
{
/** @var MapAsset|null $mapBundle */
$mapBundle = @Yii::$app->getAssetManager()->getBundle(MapAsset::className());
if ($mapBundle) {
$this->params = array_merge($this->params, $mapBundle->options);
}
/** BACKWARD COMPATIBILITY */
if (!isset($this->params['key']) || !$this->params['key']) {
$this->params['key'] = @Yii::$app->params['googleMapsApiKey'] ? : null;
}
if (!$this->params['key']) {
throw new Exception("Invalid configuration - missing Google API key! Configure MapAsset bundle in assetManager");
}
}
/**
* Makes the request to the Google API
*
* @param array $options for the guzzle request
*
* @return mixed|null
*/
protected function request($options = [])
{
try {
$params = array_filter($this->params);
$response = $this->getClient()
->get($this->getUrl(), ['query' => $params], $options);
return trim($this->format) === 'json'
? json_decode($response->getBody(), true)
: simplexml_load_string($response->getBody());
} catch (RequestException $e) {
return null;
}
}
/**
* Returns the guzzle client
* @return \Guzzle\Http\Client|HttpClient
*/
protected function getClient()
{
if ($this->_guzzle === null) {
$this->_guzzle = new HttpClient();
}
return $this->_guzzle;
}
}