Completed
Push — master ( 06dbdb...3b3e36 )
by do
05:48
created

Token::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
ccs 0
cts 3
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * Date: 2018/4/11
4
 * Time: 10:51
5
 */
6
namespace JinWeChat\Kernel;
7
use JinWeChat\Kernel\Contracts\TokenInterface;
8
use Pimple\Container;
9
use Psr\Http\Message\RequestInterface;
10
use JinWechat\Kernel\Traits\HasHttpRequests;
11
use JinWechat\Kernel\Traits\InteractsWithCache;
12
use JinWechat\Kernel\Exceptions\HttpException;
13
class Token implements TokenInterface{
14
    use HasHttpRequests, InteractsWithCache;
0 ignored issues
show
Bug introduced by
The trait JinWechat\Kernel\Traits\HasHttpRequests requires the property $baseUri which is not provided by JinWeChat\Kernel\Token.
Loading history...
15
16
    protected $app;
17
    protected $requestMethod = 'GET';
18
    protected $token;
19
    protected $queryName;
20
    protected $safeSeconds = 500;
21
    /**
22
     * @var string
23
     */
24
    protected $tokenKey = 'token';
25
26
    /**
27
     * @var string
28
     */
29
    protected $cachePrefix = 'jinwechat.kernel.token.';
30
    public function __construct(Container $app)
31
    {
32
        $this->app = $app;
33
    }
34
35
    public function getToken(): array
36
    {
37
        $cacheKey = $this->getCacheKey();
38
        $cache = $this->getCache();
39
        if ($cache->has($cacheKey)) {
40
            return $cache->get($cacheKey);
41
        }
42
43
        $token = $this->requestToken($this->getCredentials(), true);
0 ignored issues
show
Bug introduced by
The method getCredentials() does not exist on JinWeChat\Kernel\Token. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

43
        $token = $this->requestToken($this->/** @scrutinizer ignore-call */ getCredentials(), true);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
44
45
        $this->setToken($token[$this->tokenKey], $token['expires_in'] ?? 57600);
0 ignored issues
show
Bug introduced by
The method setToken() does not exist on JinWeChat\Kernel\Token. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

45
        $this->/** @scrutinizer ignore-call */ 
46
               setToken($token[$this->tokenKey], $token['expires_in'] ?? 57600);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
46
47
        return $token;
48
    }
49
    public function applyToRequest(RequestInterface $request, array $requestOptions = []): RequestInterface
50
    {
51
        parse_str($request->getUri()->getQuery(), $query);
52
53
        $query = http_build_query(array_merge($this->getQuery(), $query));
54
55
        return $request->withUri($request->getUri()->withQuery($query));
56
    }
57
    protected function getQuery(): array
58
    {
59
        return [$this->queryName ?? $this->token => $this->getToken()[$this->token]];
60
    }
61
    /**
62
     * @return string
63
     */
64
    protected function getCacheKey()
65
    {
66
        return $this->cachePrefix.$this->app['config']['username'];
67
    }
68
    public function requestToken(array $credentials, $toArray = false)
69
    {
70
        $response = $this->sendRequest($credentials);
0 ignored issues
show
Bug introduced by
The method sendRequest() does not exist on JinWeChat\Kernel\Token. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

70
        /** @scrutinizer ignore-call */ 
71
        $response = $this->sendRequest($credentials);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
71
        $result = json_decode($response->getBody()->getContents(), true);
72
        $formatted = $this->castResponseToType($response, $this->app['config']->get('response_type'));
73
        if (preg_match('/token=([\d]+)/i', $result['redirect_url'], $match)) {
74
            $this->token = $match[1];
75
        }
76
        $this->baseRefer = $result['redirect_url'];
0 ignored issues
show
Bug Best Practice introduced by
The property baseRefer does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
77
78
        if (empty($result['redirect_url'])) {
79
            throw new HttpException('Request token fail: '.json_encode($result, JSON_UNESCAPED_UNICODE), $response, $formatted);
80
        }
81
82
        return $toArray ? $result : $formatted;
83
    }
84
}