Completed
Pull Request — master (#138)
by Roma
01:33
created

LinkedinProvider::getBasicProfile()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 13
rs 9.8333
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
3
/*
4
 * This file is part of the overtrue/socialite.
5
 *
6
 * (c) overtrue <[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 Overtrue\Socialite\Providers;
13
14
use Overtrue\Socialite\AccessTokenInterface;
15
use Overtrue\Socialite\ProviderInterface;
16
use Overtrue\Socialite\User;
17
18
/**
19
 * Class LinkedinProvider.
20
 *
21
 * @see https://developer.linkedin.com/docs/oauth2 [Authenticating with OAuth 2.0]
22
 */
23
class LinkedinProvider extends AbstractProvider implements ProviderInterface
24
{
25
    /**
26
     * The scopes being requested.
27
     *
28
     * @var array
29
     */
30
    protected $scopes = ['r_liteprofile', 'r_emailaddress'];
31
32
    /**
33
     * {@inheritdoc}
34
     */
35
    protected function getAuthUrl($state)
36
    {
37
        return $this->buildAuthUrlFromBase('https://www.linkedin.com/oauth/v2/authorization', $state);
38
    }
39
40
    /**
41
     * Get the access token for the given code.
42
     *
43
     * @param string $code
44
     *
45
     * @return \Overtrue\Socialite\AccessToken
46
     */
47 View Code Duplication
    public function getAccessToken($code)
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...
48
    {
49
        $response = $this->getHttpClient()
50
            ->post($this->getTokenUrl(), ['form_params' => $this->getTokenFields($code)]);
51
52
        return $this->parseAccessToken($response->getBody());
53
    }
54
55
    /**
56
     * {@inheritdoc}
57
     */
58
    protected function getTokenUrl()
59
    {
60
        return 'https://www.linkedin.com/oauth/v2/accessToken';
61
    }
62
63
    /**
64
     * Get the POST fields for the token request.
65
     *
66
     * @param string $code
67
     *
68
     * @return array
69
     */
70
    protected function getTokenFields($code)
71
    {
72
        return parent::getTokenFields($code) + ['grant_type' => 'authorization_code'];
73
    }
74
75
    /**
76
     * {@inheritdoc}
77
     */
78
    protected function getUserByToken(AccessTokenInterface $token)
79
    {
80
        $basicProfile = $this->getBasicProfile($token);
0 ignored issues
show
Documentation introduced by
$token is of type object<Overtrue\Socialite\AccessTokenInterface>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
81
        $emailAddress = $this->getEmailAddress($token);
0 ignored issues
show
Documentation introduced by
$token is of type object<Overtrue\Socialite\AccessTokenInterface>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
82
83
        return array_merge($basicProfile, $emailAddress);
84
    }
85
86
    /**
87
     * Get the basic profile fields for the user.
88
     *
89
     * @param string $token
90
     *
91
     * @return array
92
     */
93
    protected function getBasicProfile($token)
94
    {
95
        $url = 'https://api.linkedin.com/v2/me?projection=(id,firstName,lastName,profilePicture(displayImage~:playableStreams))';
96
97
        $response = $this->getHttpClient()->get($url, [
98
            'headers' => [
99
                'Authorization' => 'Bearer '.$token,
100
                'X-RestLi-Protocol-Version' => '2.0.0',
101
            ],
102
        ]);
103
104
        return (array) json_decode($response->getBody(), true);
105
    }
106
107
    /**
108
     * Get the email address for the user.
109
     *
110
     * @param string $token
111
     *
112
     * @return array
113
     */
114 View Code Duplication
    protected function getEmailAddress($token)
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...
115
    {
116
        $url = 'https://api.linkedin.com/v2/emailAddress?q=members&projection=(elements*(handle~))';
117
118
        $response = $this->getHttpClient()->get($url, [
119
            'headers' => [
120
                'Authorization' => 'Bearer '.$token,
121
                'X-RestLi-Protocol-Version' => '2.0.0',
122
            ],
123
        ]);
124
125
        return (array) $this->arrayItem(json_decode($response->getBody(), true), 'elements.0.handle~');
126
    }
127
128
    /**
129
     * {@inheritdoc}
130
     */
131
    protected function mapUserToObject(array $user)
132
    {
133
        $preferredLocale = $this->arrayItem($user, 'firstName.preferredLocale.language').'_'.$this->arrayItem($user, 'firstName.preferredLocale.country');
134
        $firstName = $this->arrayItem($user, 'firstName.localized.'.$preferredLocale);
135
        $lastName = $this->arrayItem($user, 'lastName.localized.'.$preferredLocale);
136
        $name = $firstName.' '.$lastName;
137
138
        $images = (array) $this->arrayItem($user, 'profilePicture.displayImage~.elements', []);
139
        $avatars = array_filter($images, function ($image) {
140
            return $image['data']['com.linkedin.digitalmedia.mediaartifact.StillImage']['storageSize']['width'] === 100;
141
        });
142
        $avatar = array_shift($avatars);
143
        $originalAvatars = array_filter($images, function ($image) {
144
            return $image['data']['com.linkedin.digitalmedia.mediaartifact.StillImage']['storageSize']['width'] === 800;
145
        });
146
        $originalAvatar = array_shift($originalAvatars);
147
148
        return new User([
149
            'id' => $this->arrayItem($user, 'id'),
150
            'nickname' => $name,
151
            'name' => $name,
152
            'email' => $this->arrayItem($user, 'emailAddress'),
153
            'avatar' => $avatar ? $this->arrayItem($avatar, 'identifiers.0.identifier') : null,
154
            'avatar_original' => $originalAvatar ? $this->arrayItem($originalAvatar, 'identifiers.0.identifier') : null,
155
        ]);
156
    }
157
158
    /**
159
     * Set the user fields to request from LinkedIn.
160
     *
161
     * @param array $fields
162
     *
163
     * @return $this
164
     */
165
    public function fields(array $fields)
166
    {
167
        $this->fields = $fields;
0 ignored issues
show
Bug introduced by
The property fields does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
168
169
        return $this;
170
    }
171
172
    /**
173
     * Determine if the provider is operating as stateless.
174
     *
175
     * @return bool
176
     */
177
    protected function isStateless()
178
    {
179
        return true;
180
    }
181
}
182