HttpClient::createRequest()   A
last analyzed

Complexity

Conditions 4
Paths 3

Size

Total Lines 17
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 4

Importance

Changes 0
Metric Value
dl 0
loc 17
ccs 12
cts 12
cp 1
rs 9.2
c 0
b 0
f 0
cc 4
eloc 11
nc 3
nop 5
crap 4
1
<?php
2
3
namespace Trello\HttpClient;
4
5
use Guzzle\Http\Client as GuzzleClient;
6
use Guzzle\Http\ClientInterface;
7
use Guzzle\Http\Message\Request;
8
use Guzzle\Http\Message\Response;
9
use Trello\Exception\ErrorException;
10
use Trello\Exception\RuntimeException;
11
use Trello\HttpClient\Listener\AuthListener;
12
use Trello\HttpClient\Listener\ErrorListener;
13
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
14
15
class HttpClient implements HttpClientInterface
16
{
17
    protected $options = array(
18
        'base_url'    => 'https://api.trello.com/',
19
        'user_agent'  => 'php-trello-api (http://github.com/cdaguerre/php-trello-api)',
20
        'timeout'     => 10,
21
        'api_version' => 1,
22
    );
23
24
    /**
25
     * @var ClientInterface
26
     */
27
    protected $client;
28
29
    protected $headers = array();
30
31
    private $lastResponse;
32
    private $lastRequest;
33
34
    /**
35
     * @param array           $options
36
     * @param ClientInterface $client
37
     */
38 307
    public function __construct(array $options = array(), ClientInterface $client = null)
39
    {
40 307
        $this->options = array_merge($this->options, $options);
41 307
        $client = $client ?: new GuzzleClient($this->options['base_url'], $this->options);
42 307
        $this->client  = $client;
43
44 307
        $this->addListener('request.error', array(new ErrorListener($this->options), 'onRequestError'));
0 ignored issues
show
Unused Code introduced by
The call to ErrorListener::__construct() has too many arguments starting with $this->options.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
45 307
        $this->clearHeaders();
46 307
    }
47
48
    /**
49
     * {@inheritDoc}
50
     */
51 1
    public function setOption($name, $value)
52
    {
53 1
        $this->options[$name] = $value;
54 1
    }
55
56
    /**
57
     * {@inheritDoc}
58
     */
59
    public function setHeaders(array $headers)
60
    {
61
        $this->headers = array_merge($this->headers, $headers);
62
    }
63
64
    /**
65
     * Clears used headers
66
     */
67 13
    public function clearHeaders()
68
    {
69 13
        $this->headers = array(
70 13
            'Accept' => sprintf('application/vnd.orcid.%s+json', $this->options['api_version']),
71 13
            'User-Agent' => sprintf('%s', $this->options['user_agent']),
72
        );
73 13
    }
74
75
    /**
76
     * @param string $eventName
77
     */
78 13
    public function addListener($eventName, $listener)
79
    {
80 13
        $this->client->getEventDispatcher()->addListener($eventName, $listener);
81 13
    }
82
83
    public function addSubscriber(EventSubscriberInterface $subscriber)
84
    {
85
        $this->client->addSubscriber($subscriber);
86
    }
87
88
    /**
89
     * {@inheritDoc}
90
     */
91 2
    public function get($path, array $parameters = array(), array $headers = array())
92
    {
93 2
        return $this->request($path, $parameters, 'GET', $headers);
94
    }
95
96
    /**
97
     * {@inheritDoc}
98
     */
99 View Code Duplication
    public function post($path, $body = null, array $headers = array())
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
100
    {
101
        if (!isset($headers['Content-Type'])) {
102
            $headers['Content-Type'] = 'application/x-www-form-urlencoded';
103
        }
104
105
        return $this->request($path, $body, 'POST', $headers);
106
    }
107
108
    /**
109
     * {@inheritDoc}
110
     */
111 1 View Code Duplication
    public function patch($path, $body = null, array $headers = array())
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
112
    {
113 1
        if (!isset($headers['Content-Type'])) {
114 1
            $headers['Content-Type'] = 'application/x-www-form-urlencoded';
115 1
        }
116
117 1
        return $this->request($path, $body, 'PATCH', $headers);
118
    }
119
120
    /**
121
     * {@inheritDoc}
122
     */
123 1
    public function delete($path, $body = null, array $headers = array())
124
    {
125 1
        return $this->request($path, $body, 'DELETE', $headers);
126
    }
127
128
    /**
129
     * {@inheritDoc}
130
     */
131 1 View Code Duplication
    public function put($path, $body, array $headers = array())
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
132
    {
133 1
        if (!isset($headers['Content-Type'])) {
134 1
            $headers['Content-Type'] = 'application/x-www-form-urlencoded';
135 1
        }
136
137 1
        return $this->request($path, $body, 'PUT', $headers);
138
    }
139
140
    /**
141
     * {@inheritDoc}
142
     */
143 5
    public function request($path, $body = null, $httpMethod = 'GET', array $headers = array(), array $options = array())
144
    {
145 5
        $request = $this->createRequest($httpMethod, $path, $body, $headers, $options);
146
147
        try {
148 5
            $response = $this->client->send($request);
149 5
        } catch (\LogicException $e) {
150
            throw new ErrorException($e->getMessage(), $e->getCode(), $e);
151
        } catch (\RuntimeException $e) {
152
            throw new RuntimeException($e->getMessage(), $e->getCode(), $e);
153
        }
154
155 5
        $this->lastRequest  = $request;
156 5
        $this->lastResponse = $response;
157
158 5
        return $response;
159
    }
160
161
    /**
162
     * {@inheritDoc}
163
     */
164 4
    public function authenticate($tokenOrLogin, $password = null, $method)
165
    {
166 4
        $this->addListener('request.before_send', array(
167 4
            new AuthListener($tokenOrLogin, $password, $method), 'onRequestBeforeSend',
168 4
        ));
169 4
    }
170
171
    /**
172
     * @return Request
173
     */
174
    public function getLastRequest()
175
    {
176
        return $this->lastRequest;
177
    }
178
179
    /**
180
     * @return Response
181
     */
182
    public function getLastResponse()
183
    {
184
        return $this->lastResponse;
185
    }
186
187
    /**
188
     * @param string $httpMethod
189
     * @param string $path
190
     */
191 5
    protected function createRequest($httpMethod, $path, $body = null, array $headers = array(), array $options = array())
192
    {
193 5
        $path = $this->options['api_version'].'/'.$path;
194
195 5
        if ($httpMethod === 'GET' && $body) {
196 1
            $path .= (false === strpos($path, '?') ? '?' : '&');
197 1
            $path .= utf8_encode(http_build_query($body, '', '&'));
198 1
        }
199
200 5
        return $this->client->createRequest(
201 5
            $httpMethod,
202 5
            $path,
203 5
            array_merge($this->headers, $headers),
204 5
            $body,
205
            $options
206 5
        );
207
    }
208
}
209