Rest   A
last analyzed

Complexity

Total Complexity 13

Size/Duplication

Total Lines 139
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 7

Test Coverage

Coverage 66%

Importance

Changes 0
Metric Value
wmc 13
lcom 1
cbo 7
dl 0
loc 139
ccs 33
cts 50
cp 0.66
rs 10
c 0
b 0
f 0

9 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 7 1
A getHttp() 0 4 1
A setHttp() 0 4 1
A getAccessToken() 0 4 1
A setAccessToken() 0 4 1
A __call() 0 11 2
B parseResponse() 0 27 3
A registerHttpMiddleware() 0 5 1
A accessTokenMiddleware() 0 15 2
1
<?php
2
3
/*
4
 * This file is part of the light/easemob.
5
 *
6
 * (c) lichunqiang <[email protected]>
7
 *
8
 * This source file is subject to the MIT license that is bundled
9
 * with this source code in the file LICENSE.
10
 */
11
12
namespace light\Easemob\Rest;
13
14
use light\Easemob\Core\AccessToken;
15
use light\Easemob\Core\Http;
16
use light\Easemob\Exception\EasemobException;
17
use light\Easemob\Exception\MethodNotFoundException;
18
use light\Easemob\Support\Log;
19
use Psr\Http\Message\RequestInterface;
20
use Psr\Http\Message\ResponseInterface;
21
22
/**
23
 * Class Rest.
24
 *
25
 * @method post($uri, $options = [])
26
 * @method get($uri, $options = [])
27
 * @method put($uri, $options = [])
28
 * @method delete($uri, $options = [])
29
 * @method upload($uri, $options = [])
30
 */
31
abstract class Rest
32
{
33
    /**
34
     * @var Http
35
     */
36
    protected $http;
37
    /**
38
     * @var \light\Easemob\Core\AccessToken
39
     */
40
    protected $accessToken;
41
42 3
    public function __construct(AccessToken $accessToken, Http $http)
43
    {
44 3
        $this->accessToken = $accessToken;
45 3
        $this->http = $http;
46
47 3
        $this->registerHttpMiddleware();
48 3
    }
49
50
    /**
51
     * @return Http
52
     */
53
    public function getHttp()
54
    {
55
        return $this->http;
56
    }
57
58
    /**
59
     * @param Http $http
60
     */
61
    public function setHttp($http)
62
    {
63
        $this->http = $http;
64
    }
65
66
    /**
67
     * @return AccessToken
68
     */
69
    public function getAccessToken()
70
    {
71
        return $this->accessToken;
72
    }
73
74
    /**
75
     * @param AccessToken $accessToken
76
     */
77
    public function setAccessToken($accessToken)
78
    {
79
        $this->accessToken = $accessToken;
80
    }
81
82
    /**
83
     * @param $name
84
     * @param $arguments
85
     *
86
     * @throws MethodNotFoundException
87
     *
88
     * @return mixed
89
     */
90 3
    public function __call($name, $arguments)
91
    {
92 3
        $httpMethods = ['GET', 'POST', 'DELETE', 'PUT', 'UPLOAD'];
93
94 3
        if (in_array(strtoupper($name), $httpMethods)) {
95 3
            return $this->parseResponse(
96 3
                call_user_func_array([$this->http, $name], $arguments)
97 3
            );
98
        }
99
        throw new MethodNotFoundException('Call undefined method.');
100
    }
101
102
    /**
103
     * Parse response.
104
     *
105
     * @param ResponseInterface $response
106
     *
107
     * @throws EasemobException
108
     * @throws \light\Easemob\Exception\HttpException
109
     *
110
     * @return mixed
111
     */
112 3
    protected function parseResponse(ResponseInterface $response)
113
    {
114 3
        $statusCode = $response->getStatusCode();
115 3
        if (200 !== $statusCode) {
116
            //通用false代表此次请求失败,并没有成功
117 3
            Log::error('Got an error reponse:', [
118 3
                '__class__' => get_called_class(),
119 3
                'code' => $statusCode,
120 3
                'responseBody' => (string) $response->getBody(),
121 3
            ]);
122
123 3
            return false;
124
        }
125 2
        $result = $this->http->parseJSON($response);
126
127 2
        Log::debug('Parse response body result:', ['response' => $result]);
128
129 2
        if (isset($result['error'])) {
130
            Log::error('Got an error from server:', [
131
                '__class__' => get_called_class(),
132
                'error' => $result,
133
            ]);
134
            throw new EasemobException($result['error_description']);
135
        }
136
137 2
        return $result;
138
    }
139
140
    /**
141
     * Set request access_token query.
142
     */
143 3
    protected function registerHttpMiddleware()
144
    {
145
        // access token
146 3
        $this->http->addMiddleware($this->accessTokenMiddleware());
147 3
    }
148
149
    /**
150
     * Attache access token to request query.
151
     *
152
     * @return \Closure
153
     */
154
    public function accessTokenMiddleware()
155
    {
156
        return function (callable $handler) {
157 3
            return function (RequestInterface $request, array $options) use ($handler) {
158
159 3
                if (!$this->accessToken->getToken()) {
160
                    return $handler($request, $options);
161
                }
162
163 3
                $request = $request->withHeader('Authorization', 'Bearer ' . $this->accessToken->getToken());
164
165 3
                return $handler($request, $options);
166 3
            };
167 3
        };
168
    }
169
}
170