Passed
Push — master ( 280670...1a4dd3 )
by Jacques
02:08
created

Client::setPassword()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 1
1
<?php declare(strict_types=1);
2
/**
3
 * SmartCall Restful API (v3) HTTP Client.
4
 *
5
 * PLEASE NOTE: The interface is very fluid while the intial integration
6
 * is taking place.  It will be refactored in the near future.
7
 *
8
 * @author    Jacques Marneweck <[email protected]>
9
 * @copyright 2017-2019 Jacques Marneweck.  All rights strictly reserved.
10
 * @license   MIT
11
 */
12
13
namespace Jacques\Smartcall\HttpClient;
14
15
use Jacques\Smartcall\HttpClient\Traits\SmartLoad;
16
use Jacques\Smartcall\HttpClient\Traits\SmartRica;
17
use Jacques\Smartcall\HttpClient\Traits\Utilities;
18
19
class Client extends \GuzzleHttp\Client
20
{
21
    use SmartLoad;
22
    use SmartRica;
23
    use Utilities;
24
25
    /**
26
     * @const string Version number
27
     */
28
    const VERSION = '0.0.1';
29
30
    /**
31
     * Defaults to expecting that Apache Tomcat runs on port 8080 on localhost
32
     * (127.0.0.1).
33
     *
34
     * @var array
35
     */
36
    protected $options = [
37
        'scheme'   => 'https',
38
        'hostname' => 'localhost',
39
        'port'     => '8080',
40
        'token'    => null,
41
        'username' => null,
42
        'password' => null,
43
    ];
44
45
    /**
46
     * @param array $options
47
     */
48 61
    public function __construct($options = [])
49
    {
50
        /*
51
         * Allow on instantiation to overwrite the defaults
52
         */
53 61
        $this->options = array_merge(
54 61
            $this->options,
55 61
            $options
56
        );
57
        $config = [
58 61
            'base_uri' => sprintf(
59 61
                '%s://%s:%s/',
60 61
                $this->options['scheme'],
61 61
                $this->options['hostname'],
62 61
                $this->options['port']
63
            ),
64
            'verify'  => false,
65
            'headers' => [
66 61
                'User-Agent' => 'SmartcallRestfulAPIClient-PHP/'.self::VERSION.' '.\GuzzleHttp\default_user_agent(),
67
            ],
68
        ];
69 61
        parent::__construct($config);
70 61
    }
71
72
    /**
73
     * Set the bearer token.
74
     *
75
     * @param string $token Bearer Token from Auth request
76
     *
77
     * @return void
78
     */
79 45
    public function setBearerToken($token): void
80
    {
81 45
        $this->options['token'] = $token;
82 45
    }
83
84
    /**
85
     * Set the password for basic authentication.
86
     *
87
     * @param string $password Password for use with basic authentication
88
     *
89
     * @return void
90
     */
91 5
    public function setPassword($password): void
92
    {
93 5
        $this->options['password'] = $password;
94 5
    }
95
96
    /**
97
     * Set the username for basic authentication.
98
     *
99
     * @param string $username Username for use with basic authentication
100
     *
101
     * @return void
102
     */
103 5
    public function setUsername($username): void
104
    {
105 5
        $this->options['username'] = $username;
106 5
    }
107
108
    /**
109
     * Authenticate and get Bearer token from SmartCall.
110
     *
111
     * @throws Exception
112
     *
113
     * @return array
114
     */
115 4 View Code Duplication
    public function auth()
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...
116
    {
117
        try {
118 4
            $response = $this->post(
119 4
                '/webservice/auth',
120
                [
121
                    'headers' => [
122 4
                        'Authorization' => $this->bearerOrBasic(),
123
                    ],
124
                ]
125
            );
126
127
            return [
128 1
                'status'    => 'ok',
129 1
                'http_code' => $response->getStatusCode(),
130 1
                'body'      => (string) $response->getBody(),
131
            ];
132 3
        } catch (\GuzzleHttp\Exception\ClientException $e) {
0 ignored issues
show
Bug introduced by
The class GuzzleHttp\Exception\ClientException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
133 3
            return $this->clientError($e);
134
        } catch (\GuzzleHttp\Exception\ServerException $e) {
0 ignored issues
show
Bug introduced by
The class GuzzleHttp\Exception\ServerException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
135
            return $this->parseError($e);
136
        }
137
    }
138
139
    /**
140
     * Authenticate and invalidates all the user allocated tokens.
141
     *
142
     * @throws Exception
143
     *
144
     * @return array
145
     */
146 2 View Code Duplication
    public function authDelete()
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...
147
    {
148
        try {
149 2
            $response = $this->delete(
150 2
                '/webservice/auth',
151
                [
152
                    'headers' => [
153 2
                        'Authorization' => $this->bearerOrBasic(),
154
                    ],
155
                ]
156
            );
157
158
            return [
159 1
                'status'    => 'ok',
160 1
                'http_code' => $response->getStatusCode(),
161 1
                'body'      => (string) $response->getBody(),
162
            ];
163 1
        } catch (\GuzzleHttp\Exception\ClientException $e) {
0 ignored issues
show
Bug introduced by
The class GuzzleHttp\Exception\ClientException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
164 1
            return $this->clientError($e);
165
        } catch (\GuzzleHttp\Exception\ServerException $e) {
0 ignored issues
show
Bug introduced by
The class GuzzleHttp\Exception\ServerException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
166
            return $this->parseError($e);
167
        }
168
    }
169
170
    /**
171
     * Authenticate and invalidates all the user allocated tokens.
172
     *
173
     * @throws Exception
174
     *
175
     * @return array
176
     */
177 3 View Code Duplication
    public function authFlush()
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...
178
    {
179
        try {
180 3
            $response = $this->delete(
181 3
                '/webservice/auth/token',
182
                [
183
                    'headers' => [
184 3
                        'Authorization' => $this->bearerOrBasic(),
185
                    ],
186
                ]
187
            );
188
189
            return [
190 2
                'status'    => 'ok',
191 2
                'http_code' => $response->getStatusCode(),
192 2
                'body'      => (string) $response->getBody(),
193
            ];
194 1
        } catch (\GuzzleHttp\Exception\ClientException $e) {
0 ignored issues
show
Bug introduced by
The class GuzzleHttp\Exception\ClientException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
195 1
            return $this->clientError($e);
196
        } catch (\GuzzleHttp\Exception\ServerException $e) {
0 ignored issues
show
Bug introduced by
The class GuzzleHttp\Exception\ServerException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
197
            return $this->parseError($e);
198
        }
199
    }
200
201
    /**
202
     * Authenticate and gets the number of available session tokens.
203
     *
204
     * @throws Exception
205
     *
206
     * @return array
207
     */
208 3 View Code Duplication
    public function authToken()
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...
209
    {
210
        try {
211 3
            $response = $this->get(
212 3
                '/webservice/auth/token',
213
                [
214
                    'headers' => [
215 3
                        'Authorization' => $this->bearerOrBasic(),
216
                    ],
217
                ]
218
            );
219
220
            return [
221 1
                'status'    => 'ok',
222 1
                'http_code' => $response->getStatusCode(),
223 1
                'body'      => (string) $response->getBody(),
224
            ];
225 2
        } catch (\GuzzleHttp\Exception\ClientException $e) {
0 ignored issues
show
Bug introduced by
The class GuzzleHttp\Exception\ClientException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
226 2
            return $this->clientError($e);
227
        } catch (\GuzzleHttp\Exception\ServerException $e) {
0 ignored issues
show
Bug introduced by
The class GuzzleHttp\Exception\ServerException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
228
            return $this->parseError($e);
229
        }
230
    }
231
232
    /**
233
     * Test SmartCall is responding.
234
     *
235
     * @throws Exception
236
     *
237
     * @return array
238
     */
239 1
    public function ping()
240
    {
241
        try {
242 1
            $response = $this->get(
243 1
                '/webservice/test/ping'
244
            );
245
246
            return [
247 1
                'status'    => 'ok',
248 1
                'http_code' => $response->getStatusCode(),
249 1
                'body'      => (string) $response->getBody(),
250
            ];
251
        } catch (\GuzzleHttp\Exception\ClientException $e) {
0 ignored issues
show
Bug introduced by
The class GuzzleHttp\Exception\ClientException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
252
            return $this->clientError($e);
253
        } catch (\GuzzleHttp\Exception\ServerException $e) {
0 ignored issues
show
Bug introduced by
The class GuzzleHttp\Exception\ServerException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
254
            return $this->parseError($e);
255
        }
256
    }
257
258
    /**
259
     * Parse the java exception that we receive from Smartcall's Tomcat's.
260
     *
261
     * @param \GuzzleHttp\Exception\ClientException $exception
262
     *
263
     * @return array
264
     */
265 29 View Code Duplication
    private function clientError(\GuzzleHttp\Exception\ClientException $exception): 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...
266
    {
267 29
        $body = (string) $exception->getResponse()->getBody();
268
269
        return [
270 29
            'status'    => 'error',
271 29
            'http_code' => $exception->getResponse()->getStatusCode(),
272 29
            'body'      => json_decode($body),
273
        ];
274
    }
275
276
    /**
277
     * Parse the java exception that we receive from Smartcall's Tomcat's.
278
     *
279
     * @param \GuzzleHttp\Exception\ServerException $exception
280
     *
281
     * @return array
282
     */
283 View Code Duplication
    private function parseError(\GuzzleHttp\Exception\ServerException $exception): 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...
284
    {
285
        $body = (string) $exception->getResponse()->getBody();
286
        preg_match('/<p><b>(JBWEB\d{6}): type<\/b> (JBWEB\d{6}): Exception report<\/p><p><b>(JBWEB\d{6}): message<\/b> <u>(.*[^<\/u>])<\/u><\/p><p><b>(JBWEB\d{6}): description<\/b> <u>(.+[^<\/u>])<\/u><\/p>/ims', $body, $matches);
287
288
        return [
289
            'status'    => 'error',
290
            'http_code' => $exception->getResponse()->getStatusCode(),
291
            'body'      => $matches['6'],
292
        ];
293
    }
294
295
    /**
296
     * Use basic authentication header content if bearer token  is not set.
297
     *
298
     * @return string
299
     */
300 56
    private function bearerOrBasic(): string
301
    {
302
        /**
303
         * Get the function calling this method.
304
         */
305 56
        $caller = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 2)[1]['function'];
306
307 56
        if (!($caller == 'auth')
308
        ) {
309 52
            return sprintf(
310 52
                'Bearer %s',
311 52
                $this->options['token']
312
            );
313
        }
314
315 4
        return sprintf(
316 4
            'Basic %s',
317 4
            base64_encode(
318 4
                sprintf(
319 4
                    '%s:%s',
320 4
                    $this->options['username'],
321 4
                    $this->options['password']
322
                )
323
            )
324
        );
325
    }
326
}
327