Completed
Pull Request — master (#3)
by Tristan
08:51 queued 04:13
created

RestClient::get()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 4
1
<?PHP
2
3
/**
4
 * MyPoseo API Bundle
5
 *
6
 * @author Tristan Bessoussa <[email protected]>
7
 */
8
9
namespace Tristanbes\MyPoseoBundle\Connection;
10
11
use Http\Client\HttpClient;
12
use Http\Client\Common\PluginClient;
13
use Http\Client\Common\Plugin\AuthenticationPlugin;
14
use Http\Discovery\HttpClientDiscovery;
15
use Http\Discovery\MessageFactoryDiscovery;
16
use Http\Message\Authentication\QueryParam;
17
use Psr\Http\Message\ResponseInterface;
18
19
use Tristanbes\MyPoseoBundle\Exception\NotEnoughCreditsException;
20
use Tristanbes\MyPoseoBundle\Exception\ThrottleLimitException;
21
22
/**
23
 * This class is a wrapper for the HTTP client.
24
 */
25
class RestClient
26
{
27
    /**
28
     * Your API key.
29
     *
30
     * @var string
31
     */
32
    private $apiKey;
33
34
    /**
35
     * @var HttpClient
36
     */
37
    protected $httpClient;
38
39
    /**
40
     * @var string
41
     */
42
    protected $apiHost;
43
44
    /**
45
     * @var null
46
     */
47
    protected $cache;
48
49
    /**
50
     * @param string     $apiKey
51
     * @param string     $apiHost
52
     * @param HttpClient $httpClient
53
     */
54
    public function __construct($apiKey, $apiHost, HttpClient $httpClient = null, $cache = null)
55
    {
56
        $this->apiKey     = $apiKey;
57
        $this->apiHost    = $apiHost;
58
        $this->httpClient = $httpClient;
59
        $this->cache      = $cache;
60
    }
61
62
     /**
63
     * @return HttpClient
64
     */
65
    protected function getHttpClient()
66
    {
67
        if ($this->httpClient === null) {
68
            $this->httpClient = HttpClientDiscovery::find();
69
        }
70
71
        $authentication = new QueryParam(['key' => $this->apiKey]);
72
73
        $authenticationPlugin = new AuthenticationPlugin($authentication);
74
75
        $client = new PluginClient($this->httpClient, [$authenticationPlugin]);
76
77
        return $client;
78
    }
79
80
    /**
81
     * Sends the API request if cache not hit
82
     *
83
     * @param string  $method
84
     * @param string  $uri
85
     * @param null    $body
86
     * @param array   $headers
87
     * @param string  $cacheKey
88
     * @param integer $ttl
89
     *
90
     * @return Response
91
     */
92
    public function send($method, $uri, $body = null, array $headers = [], $cacheKey = null, $ttl = null)
93
    {
94
        $saveToCache = false;
95
96
        if ($cacheKey && $ttl && $this->cache) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $cacheKey of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
Bug Best Practice introduced by
The expression $ttl of type integer|null is loosely compared to true; this is ambiguous if the integer can be zero. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
97
            if ($this->cache->contains($cacheKey)) {
98
                return $this->cache->fetch($cacheKey);
99
            } else {
100
                $saveToCache = true;
101
            }
102
        }
103
104
        if (is_array($body)) {
105
            $body = http_build_query($body);
106
            $headers['Content-Type'] = 'application/x-www-form-urlencoded';
107
        }
108
109
        $request = MessageFactoryDiscovery::find()->createRequest($method, $this->getApiUrl($uri), $headers, $body);
110
        $rawResponse = $this->getHttpClient()->sendRequest($request);
111
112
        $response = $this->processResponse($rawResponse);
113
114
        if (true === $saveToCache) {
115
            $this->cache->save($cacheKey, $response, $ttl);
0 ignored issues
show
Bug introduced by
The method save cannot be called on $this->cache (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
116
        }
117
118
        return $response;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $response; (array) is incompatible with the return type documented by Tristanbes\MyPoseoBundle...ection\RestClient::send of type Tristanbes\MyPoseoBundle\Connection\Response.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
119
    }
120
121
    /**
122
     * Process the API response, provides error handling
123
     *
124
     * @param ResponseInterface $response
125
     *
126
     * @throws \Exception
127
     *
128
     * @return array
129
     */
130
    public function processResponse(ResponseInterface $response)
131
    {
132
        $httpResponseCode = (int) $response->getStatusCode();
133
134
        $data = (string) $response->getBody();
135
        $jsonResponseData = json_decode($data, false);
136
137
        $result = new \stdClass();
138
        // return response data as json if possible, raw if not
139
        $result->http_response_body = $data && $jsonResponseData === null ? $data : $jsonResponseData;
140
        $result->http_response_code = $httpResponseCode;
141
142
        if (isset($jsonResponseData['status']) && $jsonResponseData['status'] != "success") {
143
            throw new \Exception('MyPoseo API: '.$data['message']);
144
        }
145
146
        if ($jsonResponseData['myposeo']['code'] == '-1' && $jsonResponseData['myposeo']['message'] == 'No enough credits') {
147
            throw new NotEnoughCreditsException();
148
        }
149
150
        if ($jsonResponseData['myposeo']['code'] == '-1') {
151
            throw new ThrottleLimitException();
152
        }
153
154
        return $jsonResponseData;
155
    }
156
157
    /**
158
     * @param string $endpointUrl
159
     * @param array  $queryString
160
     * @param null   $cacheKey
161
     * @param null   $ttl
162
     *
163
     * @return ResponseInterface
164
     */
165
    public function get($endpointUrl, $queryString = [], $cacheKey = null, $ttl = null)
166
    {
167
        return $this->send('GET', $endpointUrl.'?'.http_build_query($queryString), null, [], $cacheKey, $ttl);
168
    }
169
170
    /**
171
     * @param string $endpointUrl
172
     * @param array  $postData
173
     *
174
     * @return \stdClass
175
     */
176
    public function post($endpointUrl, array $postData = [])
177
    {
178
        $postDataMultipart = [];
179
        foreach ($postData as $key => $value) {
180
            if (is_array($value)) {
181
                $index = 0;
182
                foreach ($value as $subValue) {
183
                    $postDataMultipart[] = [
184
                        'name'     => sprintf('%s[%d]', $key, $index++),
185
                        'contents' => $subValue,
186
                    ];
187
                }
188
            } else {
189
                $postDataMultipart[] = [
190
                    'name'     => $key,
191
                    'contents' => $value,
192
                ];
193
            }
194
        }
195
196
        return $this->send('POST', $endpointUrl, $postDataMultipart);
197
    }
198
199
    /**
200
     * @param $uri
201
     *
202
     * @return string
203
     */
204
    private function getApiUrl($uri)
205
    {
206
        return $this->generateEndpoint($this->apiHost).$uri;
207
    }
208
209
    /**
210
     * @param string $apiEndpoint
211
     *
212
     * @return string
213
     */
214
    private function generateEndpoint($apiEndpoint)
215
    {
216
        return sprintf('%s/', $apiEndpoint);
217
    }
218
}
219