Passed
Branch real-time-api (b64dfc)
by James
03:20
created

Request::setClient()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
ccs 2
cts 2
cp 1
cc 1
nc 1
nop 1
crap 1
1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: james
5
 * Date: 12/07/2018
6
 * Time: 13:35
7
 */
8
9
namespace CwsOps\LivePerson\Rest;
10
11
use CwsOps\LivePerson\Account\Config;
12
use CwsOps\LivePerson\Traits\HasLoggerTrait;
13
use GuzzleHttp\Client;
14
use GuzzleHttp\Exception\GuzzleException;
15
use Psr\Log\LoggerInterface;
16
17
/**
18
 *
19
 * Class Request
20
 *
21
 * @package CwsOps\LivePerson
22
 */
23
class Request
24
{
25
    use HasLoggerTrait;
26
27
    const METHOD_GET = 'GET';
28
    const METHOD_POST = 'POST';
29
30
    /**
31
     * An AccountConfig obj
32
     *
33
     * @var Config $config
34
     */
35
    private $config;
36
37
    /**
38
     * The total retry limit.
39
     *
40
     * @var int $retryLimit
41
     */
42
    private $retryLimit;
43
44
    /**
45
     * @var LoggerInterface $logger
46
     */
47
    private $logger;
48
49
    /**
50
     * The number of times tried.
51
     *
52
     * @var int retry_counter
53
     */
54
    private $retryCounter;
55
    /** @var string $bearer */
56
    private $bearer;
57
    /** @var UrlBuilder */
58
    private $urlBuilder;
59
    private $client;
60
61
62
    /**
63
     * Request constructor.
64
     *
65
     * @param Config $accountConfig
66
     * @param int $retryLimit the number of times to retry on failure. Recommended is 3.
67
     * @param LoggerInterface|null $logger
68
     */
69 1
    public function __construct(Config $accountConfig, int $retryLimit = 3, LoggerInterface $logger = null)
70
    {
71 1
        $this->config = $accountConfig;
72 1
        $this->retryLimit = $retryLimit;
73 1
        $this->logger = $this->hasLogger($logger);
74
75
        // Set the retry counter to zero.
76 1
        $this->retryCounter = 0;
77 1
        $this->urlBuilder = new UrlBuilder();
78 1
    }
79
80
    /**
81
     * @codeCoverageIgnore
82
     *
83
     * Gets the domain for a specified service
84
     *
85
     * @param string $service
86
     *
87
     * @return string
88
     */
89
    public function getDomain(string $service)
90
    {
91
        $response = $this->v1("https://api.liveperson.net/api/account/{$this->config->getAccountId()}/service/{$service}/baseURI.json?version=1", Request::METHOD_GET);
92
93
        return $response->baseUri;
94
    }
95
96
    /**
97
     * @codeCoverageIgnore
98
     *
99
     * Creates a URLBuilder instance with the domain allready set.
100
     *
101
     * @param $service
102
     *
103
     * @return UrlBuilder|null
104
     */
105
    public function buildUrl($service)
106
    {
107
        try {
108
            return $this->urlBuilder->create(true)
109
                ->setService($this->getDomain($service));
110
        } catch (BuilderLockedException $e) {
111
            $this->logger->critical($e->getMessage());
112
        }
113
        return $this->urlBuilder;
114
    }
115
116
    /**
117
     * @codeCoverageIgnore
118
     * Performs the actual request on the livePerson api.
119
     *
120
     * @param string $url the URL to make the request to.
121
     * @param string $method The method to request the data
122
     * @param array|null $payload an array of parameters to place into the body of the request.
123
     *
124
     * @return array|\stdClass an array that contains the result or an empty array on error.
125
     */
126
    public function v1($url, $method = Request::METHOD_GET, $payload = null)
127
    {
128
129
130
        $args = [
131
            'auth' => 'oauth',
132
            'headers' => [
133
                'content-type' => 'application/json',
134
            ],
135
            'form_params' => $payload ?: []
136
        ];
137
138
        try {
139
            $response = $this->getClient()->request($method, $url, $args);
140
            $responseBody = json_decode($response->getBody());
141
142
            return $responseBody;
143
144
        } catch (GuzzleException $e) {
145
            if ($this->retryCounter < $this->retryLimit || $this->retryLimit === -1) {
146
147
                $this->logger->info(sprintf('attempt $d failed trying in %d seconds', $this->retryCounter + 1, 15000));
148
149
                usleep(15000);
150
                $this->retryCounter++;
151
                $responseBody = $this->v1($url, $method, $payload);
152
153
                return $responseBody;
154
            } else {
155
                $this->logger->critical(sprintf('client error: %s', $e->getMessage()));
156
                return [];
157
            }
158
        }
159
160
    }
161
162
    /**
163
     * @codeCoverageIgnore
164
     *
165
     * Performs the actual request on the livePerson api.
166
     *
167
     * @param string $url the URL to make the request to.
168
     * @param string $method The method to request the data
169
     * @param array|null $payload an array of parameters to place into the body of the request.
170
     * @param array $headers
171
     *
172
     * @return \stdClass an array that contains the result or an empty array on error.
173
     */
174
    public function v2(string $url, $method, $payload = [], $headers = [])
175
    {
176
        $this->login();
177
        $args = [
178
            'headers' => array_merge([
179
                'content-type' => 'application/json',
180
                'Authorization' => 'Bearer ' . $this->bearer
181
            ], $headers ?: []),
182
            'form_params' => $payload ?: []
183
        ];
184
185
186
        try {
187
            $response = $this->getClient()->request($method, $url, $args);
188
189
            return json_decode($response->getBody());
190
        } catch (GuzzleException $e) {
191
            $this->logger->critical(sprintf('client error: %s', $e->getMessage()));
192
            return new \stdClass();
193
        }
194
    }
195
196
    /**
197
     * Gets the the Guzzle Client.
198
     *
199
     * @return Client
200
     */
201 1
    public function getClient()
202
    {
203 1
        if (null === $this->client) {
204 1
            $this->client = new Client();
205
        }
206
207 1
        return $this->client;
208
    }
209
210
    /**
211
     * Sets the Guzzle Client.
212
     *
213
     * @param Client $client
214
     */
215 1
    public function setClient(Client $client)
216
    {
217 1
        $this->client = $client;
218 1
    }
219
220
221
    /**
222
     * @codeCoverageIgnore
223
     * Logs into the API.
224
     */
225
    private function login()
226
    {
227
        $auth = [
228
            'username' => $this->config->getUsername(),
229
            'appKey' => $this->config->getConsumerKey(),
230
            'secret' => $this->config->getConsumerSecret(),
231
            'accessToken' => $this->config->getToken(),
232
            'accsessTokenSecret' => $this->config->getTokenSecret()
233
        ];
234
235
        $url = "https://api/account/{$this->config->getAccountId()}/login?v-1.3";
236
237
        $response = $this->v1($url, Request::METHOD_POST, $auth);
238
239
        $this->bearer = $response->bearer;
240
    }
241
}
242