VkontakteClient::getTokenByCode()   B
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 25
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 25
ccs 0
cts 15
cp 0
rs 8.8571
c 0
b 0
f 0
cc 1
eloc 17
nc 1
nop 2
crap 2
1
<?php
2
3
namespace AppBundle\Service\Vkontakte;
4
5
use GuzzleHttp\Client;
6
7
/**
8
 * Vkontakte API facade
9
 * @link https://vk.com/dev/methods
10
 * @author Vehsamrak
11
 */
12
class VkontakteClient
13
{
14
15
    const API_URL = 'https://api.vk.com/method/';
16
    const VK_REQUEST_TOKEN_URL = 'https://oauth.vk.com/access_token';
17
18
    /** @var float */
19
    private $version;
20
21
    /** @var string */
22
    private $vkClientId;
23
24
    /** @var string */
25
    private $vkSecret;
26
27
    public function __construct(float $version, string $vkClientId, string $vkSecret)
28
    {
29
        $this->version = $version;
30
        $this->vkClientId = $vkClientId;
31
        $this->vkSecret = $vkSecret;
32
    }
33
34
    public function getTokenByCode(string $vkAuthorizationCode, string $callbackUrl): AccessToken
35
    {
36
        $parameters = [
37
            'client_id'     => $this->vkClientId,
38
            'client_secret' => $this->vkSecret,
39
            'redirect_uri'  => $callbackUrl,
40
            'code'          => $vkAuthorizationCode,
41
        ];
42
43
        $vkontakteRequestTokenUrl = sprintf(
44
            '%s?%s',
45
            self::VK_REQUEST_TOKEN_URL,
46
            http_build_query($parameters)
47
        );
48
49
        $client = new Client();
50
        $httpResponse = $client->request('GET', $vkontakteRequestTokenUrl);
51
        $result = json_decode($httpResponse->getBody(), true);
52
53
        $userVkId = $result['user_id'];
54
        $vkToken = $result['access_token'];
55
        $userEmail = $result['email'] ?? '';
56
57
        return new AccessToken($userVkId, $vkToken, $userEmail);
58
    }
59
60
    public function getUserName(string $token)
61
    {
62
        $parameters = [
63
            'fields' => join(',', ['nickname', 'screen_name']),
64
        ];
65
66
        $result = $this->getMethod('users.get', $token, $parameters);
67
68
        $nickname = $result['nickname'];
69
        $firstName = $result['first_name'];
70
        $lastName = $result['last_name'];
71
72
        $username = $nickname;
73
74
        if (!$username) {
75
            $username = trim(sprintf('%s %s', $firstName, $lastName));
76
        }
77
78
        if (!$username) {
79
            $username = $result['screen_name'];
80
        }
81
82
        return $username;
83
    }
84
85
    private function getMethod(string $method, string $token, array $parameters = []): array
86
    {
87
        $parameters = array_merge(
88
            $parameters,
89
            [
90
                'access_token' => $token,
91
                'v'            => $this->version,
92
            ]
93
        );
94
95
        $client = new Client();
96
        $httpResponse = $client->request(
97
            'GET',
98
            sprintf('%s%s?%s', self::API_URL, $method, http_build_query($parameters))
99
        );
100
101
        $decodedResponse = json_decode($httpResponse->getBody(), true)['response'];
102
103
        return reset($decodedResponse);
104
    }
105
}
106