Completed
Push — master ( 3888fe...7b95f2 )
by Carlos
02:54
created

Douban::getUserByToken()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 10
rs 9.9332
c 0
b 0
f 0
cc 1
nc 1
nop 2
1
<?php
2
3
namespace Overtrue\Socialite\Providers;
4
5
use Overtrue\Socialite\User;
6
7
/**
8
 * @see http://developers.douban.com/wiki/?title=oauth2 [使用 OAuth 2.0 访问豆瓣 API]
9
 */
10
class Douban extends Base
11
{
12
    public const NAME = 'douban';
13
14
    protected function getAuthUrl(): string
15
    {
16
        return $this->buildAuthUrlFromBase('https://www.douban.com/service/auth2/auth');
17
    }
18
19
    protected function getTokenUrl(): string
20
    {
21
        return 'https://www.douban.com/service/auth2/token';
22
    }
23
24
    /**
25
     * @param string     $token
26
     * @param array|null $query
27
     *
28
     * @return array
29
     */
30
    protected function getUserByToken(string $token, ?array $query = []): array
31
    {
32
        $response = $this->getHttpClient()->get('https://api.douban.com/v2/user/~me', [
33
            'headers' => [
34
                'Authorization' => 'Bearer '.$token,
35
            ],
36
        ]);
37
38
        return json_decode($response->getBody()->getContents(), true) ?? [];
39
    }
40
41
    /**
42
     * @param array $user
43
     *
44
     * @return \Overtrue\Socialite\User
45
     */
46
    protected function mapUserToObject(array $user): User
47
    {
48
        return new User([
49
            'id' => $user['id'] ?? null,
50
            'nickname' => $user['name'] ?? null,
51
            'name' => $user['name'] ?? null,
52
            'avatar' => $user['avatar'] ?? null,
53
            'email' => null,
54
        ]);
55
    }
56
57
    /**
58
     * @param string $code
59
     *
60
     * @return array|string[]
61
     */
62
    protected function getTokenFields(string $code): array
63
    {
64
        return parent::getTokenFields($code) + ['grant_type' => 'authorization_code'];
65
    }
66
67
    /**
68
     * @param string $code
69
     *
70
     * @return array
71
     * @throws \Overtrue\Socialite\Exceptions\AuthorizeFailedException
72
     */
73
    public function tokenFromCode(string $code): array
74
    {
75
        $response = $this->getHttpClient()->post($this->getTokenUrl(), [
76
            'form_params' => $this->getTokenFields($code),
77
        ]);
78
79
        return $this->normalizeAccessTokenResponse($response->getBody()->getContents());
80
    }
81
}
82