Completed
Push — master ( 5e98ad...5c516d )
by Alexey
04:03
created

Vk   B

Complexity

Total Complexity 49

Size/Duplication

Total Lines 170
Duplicated Lines 40.59 %

Coupling/Cohesion

Components 1
Dependencies 7

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 69
loc 170
rs 8.5454
c 1
b 0
f 0
wmc 49
lcom 1
cbo 7

2 Methods

Rating   Name   Duplication   Size   Complexity  
F auth() 69 123 44
B checkAppAccess() 0 42 5

How to fix   Duplicated Code    Complexity   

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:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like Vk often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Vk, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
/**
4
 * Social helper vk
5
 *
6
 * @author Alexey Krupskiy <[email protected]>
7
 * @link http://inji.ru/
8
 * @copyright 2015 Alexey Krupskiy
9
 * @license https://github.com/injitools/cms-Inji/blob/master/LICENSE
10
 */
11
12
namespace Users\SocialHelper;
13
14
class Vk extends \Users\SocialHelper
15
{
16
    public static function auth()
3 ignored issues
show
Coding Style introduced by
auth uses the super-global variable $_GET which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
Coding Style introduced by
auth uses the super-global variable $_POST which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
Coding Style introduced by
auth uses the super-global variable $_COOKIE which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
17
    {
18
        $config = static::getConfig();
19 View Code Duplication
        if (empty($_GET['code']) && empty($_GET['error'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
20
            $query = [
21
                'client_id' => $config['appId'],
22
                'scope' => 'email',
23
                'response_type' => 'code',
24
                'display' => 'page',
25
                'redirect_uri' => 'http://' . INJI_DOMAIN_NAME . '/users/social/auth/vk'
26
            ];
27
            \Tools::redirect("https://oauth.vk.com/authorize?" . http_build_query($query));
28
        }
29 View Code Duplication
        if (empty($_GET['code']) && !empty($_GET['error'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
30
            \Tools::redirect('/', 'Произошла ошибка во время авторизации через соц. сеть: ' . $_GET['error_description']);
31
        }
32
        $query = [
33
            'client_id' => $config['appId'],
34
            'client_secret' => $config['secret'],
35
            'code' => $_GET['code'],
36
            'redirect_uri' => 'http://' . INJI_DOMAIN_NAME . '/users/social/auth/vk'
37
        ];
38
        $result = @file_get_contents("https://oauth.vk.com/access_token?" . http_build_query($query));
39
        if ($result === false) {
40
            \Tools::redirect('/', 'Во время авторизации произошли ошибки', 'danger');
41
        }
42
        $result = json_decode($result, true);
43
        if (empty($result['user_id'])) {
44
            \Tools::redirect('/', 'Во время авторизации произошли ошибки', 'danger');
45
        }
46
        $userQuery = [
47
            'user_id' => $result['user_id'],
48
            'fields' => 'sex, bdate, photo_max_orig, home_town',
49
            'access_token' => $result['access_token']
50
        ];
51
        $userResult = @file_get_contents("https://api.vk.com/method/users.get?" . http_build_query($userQuery));
52
        if (!$userResult) {
53
            \Tools::redirect('/', 'Во время авторизации произошли ошибки', 'danger');
54
        }
55
        $userDetail = json_decode($userResult, true);
56
        if (empty($userDetail['response'][0])) {
57
            \Tools::redirect('/', 'Во время авторизации произошли ошибки', 'danger');
58
        }
59
        $social = static::getObject();
60
        $userSocial = \Users\User\Social::get([['uid', $result['user_id']], ['social_id', $social->id]]);
61
        if ($userSocial && $userSocial->user) {
62
            \App::$cur->users->newSession($userSocial->user);
63 View Code Duplication
            if (!empty(\App::$cur->users->config['loginUrl'][\App::$cur->type])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
64
                \Tools::redirect(\App::$cur->users->config['loginUrl'][\App::$cur->type]);
65
            }
66
        } else {
67
            if ($userSocial && !$userSocial->user) {
68
                $userSocial->delete();
69
            }
70 View Code Duplication
            if (!\Users\User::$cur->id) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
71
                $user = false;
72
                if (!empty($result['email'])) {
73
                    $user = \Users\User::get($result['email'], 'mail');
74
                }
75
                if (!$user) {
76
                    $user = new \Users\User();
77
                    $user->group_id = 2;
78
                    $user->role_id = 2;
79
                    if (!empty($result['email'])) {
80
                        $user->login = $user->mail = $result['email'];
81
                    }
82
                    $invite_code = (!empty($_POST['invite_code']) ? $_POST['invite_code'] : ((!empty($_COOKIE['invite_code']) ? $_COOKIE['invite_code'] : ((!empty($_GET['invite_code']) ? $_GET['invite_code'] : '')))));
83
                    if (!empty($invite_code)) {
84
                        $invite = \Users\User\Invite::get($invite_code, 'code');
85
                        $inveiteError = false;
86
                        if (!$invite) {
87
                            Msg::add('Такой код пришлашения не найден', 'danger');
88
                            $inveiteError = true;
89
                        }
90
                        if ($invite->limit && !($invite->limit - $invite->count)) {
91
                            Msg::add('Лимит приглашений для данного кода исчерпан', 'danger');
92
                            $inveiteError = true;
93
                        }
94
                        if (!$inveiteError) {
95
                            $user->parent_id = $invite->user_id;
96
                            $invite->count++;
97
                            $invite->save();
98
                        }
99
                    }
100
                    if (!$user->parent_id && !empty(\App::$cur->Users->config['defaultPartner'])) {
101
                        $user->parent_id = \App::$cur->Users->config['defaultPartner'];
102
                    }
103
                    $user->save();
104
                    $userInfo = new \Users\User\Info();
105
                    $userInfo->user_id = $user->id;
106
                    $userInfo->save();
107
                }
108
            } else {
109
                $user = \Users\User::$cur;
110
            }
111 View Code Duplication
            if (!$user->info->photo_file_id && !empty($userDetail['response'][0]['photo_max_orig'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
112
                $user->info->photo_file_id = \App::$cur->files->uploadFromUrl($userDetail['response'][0]['photo_max_orig']);
113
            }
114 View Code Duplication
            if (!$user->info->first_name && !empty($userDetail['response'][0]['first_name'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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
                $user->info->first_name = $userDetail['response'][0]['first_name'];
116
            }
117 View Code Duplication
            if (!$user->info->last_name && !empty($userDetail['response'][0]['last_name'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
118
                $user->info->last_name = $userDetail['response'][0]['last_name'];
119
            }
120 View Code Duplication
            if (!$user->info->city && !empty($userDetail['response'][0]['home_town'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
121
                $user->info->city = $userDetail['response'][0]['home_town'];
122
            }
123
            if (!$user->info->sex && !empty($userDetail['response'][0]['sex'])) {
124
                $user->info->sex = $userDetail['response'][0]['sex'] == 2 ? 1 : ($userDetail['response'][0]['sex'] == 1 ? 2 : 0);
125
            }
126
            if ($user->info->bday == '0000-00-00' && !empty($userDetail['response'][0]['bdate'])) {
127
                $user->info->bday = substr_count($userDetail['response'][0]['bdate'], '.') == 2 ? \DateTime::createFromFormat('d.m.Y', $userDetail['response'][0]['bdate'])->format('Y-m-d') : (substr_count($userDetail['response'][0]['bdate'], '.') == 1 ? \DateTime::createFromFormat('d.m', $userDetail['response'][0]['bdate'])->format('Y-m-1') : '0000-00-00');
128
            }
129
            $user->info->save();
130
            $userSocial = new \Users\User\Social();
131
            $userSocial->uid = $result['user_id'];
132
            $userSocial->social_id = $social->id;
133
            $userSocial->user_id = $user->id;
134
            $userSocial->save();
135
            \App::$cur->users->newSession($user);
136
            \Tools::redirect(\App::$cur->users->config['loginUrl'][\App::$cur->type], 'Вы успешно зарегистрировались через ВКонтакте', 'success');
137
        }
138
    }
139
140
    public static function checkAppAccess()
141
    {
142
        $viewer_id = filter_input(INPUT_GET, 'viewer_id', FILTER_SANITIZE_NUMBER_INT);
143
        $get_auth_key = filter_input(INPUT_GET, 'auth_key', FILTER_SANITIZE_STRING);
144
145
        $config = static::getConfig();
146
147
        $auth_key = md5($config['appId'] . '_' . $viewer_id . '_' . $config['secret']);
148
149
        if ($auth_key !== $get_auth_key) {
150
            return FALSE;
151
        }
152
        $userQuery = [
153
            'user_id' => $viewer_id,
154
            'fields' => 'photo_medium,nickname, domain, sex, bdate, city, country, timezone, photo_50, photo_100, photo_200_orig, has_mobile, contacts, education, online, relation, last_seen, status, can_write_private_message, can_see_all_posts, can_post, universities',
155
            'access_token' => filter_input(INPUT_GET, 'access_token', FILTER_SANITIZE_STRING)
156
        ];
157
        $userResult = json_decode(@file_get_contents("https://api.vk.com/method/users.get?" . http_build_query($userQuery)), true);
158
        $object = static::getObject();
159
160
        $socUser = \Users\User\Social::get([['social_id', $object->pk()], ['uid', $viewer_id]]);
161
        if (!$socUser) {
162
            $user = new \Users\User();
163
            $user->login = $userResult['response'][0]['domain'];
164
            $user->save();
165
            $info = new \Users\User\Info();
166
            $info->user_id = $user->id;
167
            $info->sex = $userResult['response'][0]['sex'] == 2 ? 1 : ($userResult['response'][0]['sex'] == 1 ? 2 : 0);
168
            $info->first_name = $userResult['response'][0]['first_name'];
169
            $info->last_name = $userResult['response'][0]['last_name'];
170
            $info->photo_file_id = \App::$cur->files->uploadFromUrl($userResult['response'][0]['photo_200_orig'], ['accept_group' => 'image']);
171
            $info->save();
172
            $social = new \Users\User\Social();
173
            $social->user_id = $user->id;
174
            $social->social_id = 1;
175
            $social->uid = $userResult['response'][0]['uid'];
176
            $social->save();
177
        } else {
178
            $user = $socUser->user;
179
        }
180
        return $user;
181
    }
182
183
}
184