RequestsHttpAdapter::__construct()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 3
nc 2
nop 1
1
<?php
2
3
namespace MusicBrainz\HttpAdapters;
4
5
use MusicBrainz\Exception;
6
use Requests;
7
8
/**
9
 * Requests HTTP Client Adapter
10
 */
11
class RequestsHttpAdapter extends AbstractHttpAdapter
12
{
13
14
    /**
15
     * Initializes the class.
16
     *
17
     * @param null $endpoint Override the default endpoint (useful for local development)
18
     */
19
    public function __construct($endpoint = NULL)
20
    {
21
        if (filter_var($endpoint, FILTER_VALIDATE_URL)) {
22
            $this->endpoint = $endpoint;
23
        }
24
    }
25
26
    /**
27
     * Perform an HTTP request on MusicBrainz
28
     *
29
     * @param  string  $path
30
     * @param  array   $params
31
     * @param  array   $options
32
     * @param  boolean $isAuthRequired
33
     * @param  boolean $returnArray force json_decode to return an array instead of an object
34
     *
35
     * @throws \MusicBrainz\Exception
36
     * @return array
37
     */
38
    public function call($path, array $params = array(), array $options = array(), $isAuthRequired = FALSE, $returnArray = FALSE)
39
    {
40
        if ($options['user-agent'] == '') {
41
            throw new Exception('You must set a valid User Agent before accessing the MusicBrainz API');
42
        }
43
44
        $url = $this->endpoint . '/' . $path;
45
        $i   = 0;
46
        foreach ($params as $name => $value) {
47
            $url .= ($i++ == 0) ? '?' : '&';
48
            $url .= urlencode($name) . '=' . urlencode($value);
49
        }
50
51
        $headers = array(
52
            'Accept'     => 'application/json',
53
            'User-Agent' => $options['user-agent']
54
        );
55
56
        $requestOptions = array();
57 View Code Duplication
        if ($isAuthRequired) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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.

Loading history...
58
            if ($options['user'] != NULL && $options['password'] != NULL) {
59
                $requestOptions['auth'] = array($options['user'], $options['password']);
60
            } else {
61
                throw new Exception('Authentication is required');
62
            }
63
        }
64
        $request = Requests::get($url, $headers, $requestOptions);
65
66
        // musicbrainz throttle
67
        sleep(1);
68
69
        return json_decode($request->body, $returnArray);
70
    }
71
}
72