OAuth2UserIdentity   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 53
Duplicated Lines 16.98 %

Coupling/Cohesion

Components 0
Dependencies 2

Importance

Changes 0
Metric Value
wmc 5
lcom 0
cbo 2
dl 9
loc 53
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A rules() 9 9 1
A findIdentity() 0 4 1
A findIdentityByAccessToken() 0 4 1
A getUserInfo() 0 18 2

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
namespace hiapi\Core\Auth;
4
5
use hiqdev\yii\compat\yii;
6
use yii\helpers\Json;
7
8
/**
9
 * User identity model working with HIAM
10
 *
11
 */
12
class OAuth2UserIdentity extends UserIdentity
13
{
14
    public $id;
15
    public $username;
16
    public $state;
17
    public $roles = [];
18
19
    /**
20
     * {@inheritdoc}
21
     */
22 View Code Duplication
    public function rules()
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...
23
    {
24
        return [
25
            ['id',          'integer'],
26
            ['username',    'string'],
27
            ['state',       'string'],
28
            ['roles',       'trim'],
29
        ];
30
    }
31
32
    /** {@inheritdoc} */
33
    public static function findIdentity($id)
34
    {
35
        throw new \yii\base\InvalidCallException('no `findIdentity` and not expected');
36
    }
37
38
    /**
39
     * {@inheritdoc}
40
     */
41
    public static function findIdentityByAccessToken($token, $type = null)
42
    {
43
        return self::fromArray(self::getUserInfo($token));
44
    }
45
46
    public static function getUserInfo($token): array
47
    {
48
        $url = yii::getApp()->params['oauth2.userinfoUrl'] ?? null;
49
        if (empty($url)) {
50
            return [];
51
        }
52
53
        $ch = curl_init();
54
        curl_setopt($ch, CURLOPT_URL, $url);
55
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
56
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
57
            'Authorization: Bearer ' . $token,
58
        ]);
59
        $res = curl_exec($ch);
60
        curl_close($ch);
61
62
        return Json::decode((string)$res);
63
    }
64
}
65