1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace MusicBrainz\HttpAdapters; |
4
|
|
|
|
5
|
|
|
use Guzzle\Http\ClientInterface; |
6
|
|
|
use MusicBrainz\Exception; |
7
|
|
|
|
8
|
|
|
/** |
9
|
|
|
* Guzzle Http Adapter |
10
|
|
|
*/ |
11
|
|
|
class GuzzleHttpAdapter extends AbstractHttpAdapter |
12
|
|
|
{ |
13
|
|
|
/** |
14
|
|
|
* The Guzzle client used to make cURL requests |
15
|
|
|
* |
16
|
|
|
* @var \Guzzle\Http\ClientInterface |
17
|
|
|
*/ |
18
|
|
|
private $client; |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* Initializes the class. |
22
|
|
|
* |
23
|
|
|
* @param \Guzzle\Http\ClientInterface $client The Guzzle client used to make requests |
24
|
|
|
* @param null $endpoint Override the default endpoint (useful for local development) |
25
|
|
|
*/ |
26
|
|
View Code Duplication |
public function __construct(ClientInterface $client, $endpoint = NULL) |
|
|
|
|
27
|
|
|
{ |
28
|
|
|
$this->client = $client; |
29
|
|
|
|
30
|
|
|
if (filter_var($endpoint, FILTER_VALIDATE_URL)) { |
31
|
|
|
$this->endpoint = $endpoint; |
32
|
|
|
} |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
/** |
36
|
|
|
* Perform an HTTP request on MusicBrainz |
37
|
|
|
* |
38
|
|
|
* @param string $path |
39
|
|
|
* @param array $params |
40
|
|
|
* @param array $options |
41
|
|
|
* @param boolean $isAuthRequired |
42
|
|
|
* @param boolean $returnArray disregarded |
43
|
|
|
* |
44
|
|
|
* @throws \MusicBrainz\Exception |
45
|
|
|
* @return array |
46
|
|
|
*/ |
47
|
|
|
public function call($path, array $params = array(), array $options = array(), $isAuthRequired = FALSE, $returnArray = FALSE) |
48
|
|
|
{ |
49
|
|
|
if ($options['user-agent'] == '') { |
50
|
|
|
throw new Exception('You must set a valid User Agent before accessing the MusicBrainz API'); |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
$this->client->setBaseUrl($this->endpoint); |
54
|
|
|
$this->client->setConfig( |
55
|
|
|
array( |
56
|
|
|
'data' => $params |
57
|
|
|
) |
58
|
|
|
); |
59
|
|
|
|
60
|
|
|
$request = $this->client->get($path . '{?data*}'); |
61
|
|
|
$request->setHeader('Accept', 'application/json'); |
62
|
|
|
$request->setHeader('User-Agent', $options['user-agent']); |
63
|
|
|
|
64
|
|
|
if ($isAuthRequired) { |
65
|
|
|
if ($options['user'] != NULL && $options['password'] != NULL) { |
66
|
|
|
$request->setAuth($options['user'], $options['password'], CURLAUTH_DIGEST); |
67
|
|
|
} else { |
68
|
|
|
throw new Exception('Authentication is required'); |
69
|
|
|
} |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
$request->getQuery()->useUrlEncoding(FALSE); |
73
|
|
|
|
74
|
|
|
// musicbrainz throttle |
75
|
|
|
sleep(1); |
76
|
|
|
|
77
|
|
|
return $request->send()->json(); |
78
|
|
|
} |
79
|
|
|
} |
80
|
|
|
|
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.