1
|
|
|
<?php |
2
|
|
|
namespace MusicBrainz\HttpAdapters; |
3
|
|
|
|
4
|
|
|
use GuzzleHttp\ClientInterface; |
5
|
|
|
use MusicBrainz\Exception; |
6
|
|
|
|
7
|
|
|
class GuzzleFiveAdapter extends AbstractHttpAdapter |
8
|
|
|
{ |
9
|
|
|
/** |
10
|
|
|
* @var ClientInterface |
11
|
|
|
*/ |
12
|
|
|
private $client; |
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* Initialize class |
16
|
|
|
* |
17
|
|
|
* @param ClientInterface $client |
18
|
|
|
* @param null $endpoint |
19
|
|
|
*/ |
20
|
|
View Code Duplication |
public function __construct(ClientInterface $client, $endpoint = null) |
|
|
|
|
21
|
|
|
{ |
22
|
|
|
$this->client = $client; |
23
|
|
|
|
24
|
|
|
if(filter_var($endpoint, FILTER_VALIDATE_URL)) { |
25
|
|
|
$this->endpoint = $endpoint; |
26
|
|
|
} |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* Perform an HTTP request on MusicBrainz |
31
|
|
|
* |
32
|
|
|
* @param string $path |
33
|
|
|
* @param array $params |
34
|
|
|
* @param array $options |
35
|
|
|
* @param boolean $isAuthRequired |
36
|
|
|
* @param boolean $returnArray |
37
|
|
|
* |
38
|
|
|
* @throws Exception |
39
|
|
|
* @return array |
40
|
|
|
*/ |
41
|
|
|
public function call($path, array $params = array(), array $options = array(), $isAuthRequired = false, $returnArray = false) |
42
|
|
|
{ |
43
|
|
|
if($options['user-agent'] == '') { |
44
|
|
|
throw new Exception('You must set a valid User Agent before accessing the MusicBrainz API'); |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
$requestOptions = [ |
48
|
|
|
'headers' => [ |
49
|
|
|
'Accept' => 'application/json', |
50
|
|
|
'User-Agent' => $options['user-agent'] |
51
|
|
|
], |
52
|
|
|
'query' => $params |
53
|
|
|
]; |
54
|
|
|
|
55
|
|
View Code Duplication |
if ($isAuthRequired) { |
|
|
|
|
56
|
|
|
if ($options['user'] != null && $options['password'] != null) { |
57
|
|
|
$requestOptions['auth'] = [ |
58
|
|
|
'username' => $options['user'], |
59
|
|
|
'password' => $options['password'], |
60
|
|
|
CURLAUTH_DIGEST |
61
|
|
|
]; |
62
|
|
|
} else { |
63
|
|
|
throw new Exception('Authentication is required'); |
64
|
|
|
} |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
$request = $this->client->createRequest('GET', $this->endpoint . '/' . $path, $requestOptions); |
68
|
|
|
|
69
|
|
|
// musicbrainz throttle |
70
|
|
|
sleep(1); |
71
|
|
|
|
72
|
|
|
return $this->client->send($request)->json(); |
73
|
|
|
} |
74
|
|
|
} |
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.