Test Failed
Push — master ( e3c39f...fe570d )
by Mihail
07:20
created

Apps/Model/Front/User/FormSocialAuth.php (3 issues)

Labels
1
<?php
2
3
namespace Apps\Model\Front\User;
4
5
use Apps\ActiveRecord\UserProvider;
6
use Apps\Model\Front\Profile\FormAvatarUpload;
7
use Ffcms\Core\App;
8
use Ffcms\Core\Exception\ForbiddenException;
9
use Ffcms\Core\Helper\FileSystem\File;
10
use Ffcms\Core\Helper\Type\Arr;
11
use Ffcms\Core\Helper\Type\Str;
12
use Ffcms\Core\Interfaces\iUser;
13
use Symfony\Component\HttpFoundation\File\File as FileObject;
14
15
/**
16
 * Class FormSocialAuth. Model of social authorization and registering on top layer of register model.
17
 * @package Apps\Model\Front\User
18
 */
19
class FormSocialAuth extends FormRegister
20
{
21
    /** @var string */
22
    public $profileLink;
23
24
    /** @var string */
25
    private $_provider_name;
26
    private $_provider_id;
27
    /** @var \Hybrid_User_Profile */
28
    private $_identity;
29
    /** @var UserProvider */
30
    private $_record;
31
32
    /**
33
     * FormSocialAuth constructor. Pass provider name as string and identity as object of hybrid auth
34
     * @param bool $provider
35
     * @param $identity
36
     */
37
    public function __construct($provider, $identity)
38
    {
39
        $this->_provider_name = (string)$provider;
40
        $this->_identity = $identity;
41
        parent::__construct(false);
42
    }
43
44
    /**
45
     * Parse user identifier to attributes
46
     */
47
    public function before()
48
    {
49
        // set unique user id from provider response
50
        $this->_provider_id = $this->_identity->identifier;
51
52
        // grab some data from identity provider
53
        if ($this->email === null) {
54
            $this->email = $this->_identity->email;
55
        }
56
        $this->profileLink = $this->_identity->profileURL;
57
58
        // get record info from db for this identifier if exists
59
        $this->_record = UserProvider::where('provider_name', '=', $this->_provider_name)
60
            ->where('provider_id', '=', $this->_provider_id)
61
            ->first();
62
    }
63
64
    /**
65
     * Check if this identity always exists
66
     * @return bool
67
     */
68
    public function identityExists()
69
    {
70
        return ($this->_record !== null && $this->_record->count() === 1);
71
    }
72
73
    /**
74
     * Make user authorization from social identity to website session
75
     * @return bool
76
     * @throws \Ffcms\Core\Exception\ForbiddenException
77
     */
78
    public function makeAuth()
79
    {
80
        if ($this->_record === null) {
81
            return false;
82
        }
83
        // get user from belongsTo relation
84
        $user = $this->_record->user;
85
        // maybe user was deleted without data provider record?
86
        if (!$user instanceof iUser) {
87
            throw new ForbiddenException(__('User related to this social account was deleted'));
88
        }
89
        // initialize login model
90
        $loginModel = new FormLogin();
91
        // open session & return status
92
        return $loginModel->openSession($user);
93
    }
94
95
    /**
96
     * Override default registration function with social auth data compatability
97
     * @param bool $activation
98
     * @return bool
99
     */
100
    public function tryRegister($activation = false)
101
    {
102
        // try to complete register process
103
        $success = parent::tryRegister($activation);
104
        if ($success && $this->_userObject !== null) {
105
            // save remote auth data to relation table
106
            $provider = new UserProvider();
107
            $provider->provider_name = $this->_provider_name;
108
            $provider->provider_id = $this->_provider_id;
109
            $provider->user_id = $this->_userObject->id;
110
            $provider->save();
111
112
            // get profile object from attr
113
            $profile = $this->_profileObject;
114
            // set nickname from remote service
115
            if (!Str::likeEmpty($this->_identity->displayName)) {
116
                $profile->nick = $this->_identity->displayName;
117
            }
118
            // set profile as user website
119
            $profile->url = $this->_identity->profileURL;
120
            // try to get gender (sex)
121
            if ($this->_identity->gender !== null) {
122
                $profile->sex = $this->_identity->gender === 'female' ? 2 : 1;
123
            }
124
            // set birthday if available
125
            if ($this->_identity->birthDay !== null && $this->_identity->birthMonth !== null && $this->_identity->birthYear !== null) {
126
                $profile->birthday = $this->_identity->birthYear . '-' . $this->_identity->birthMonth . '-' . $this->_identity->birthDay;
127
            }
128
129
            // try to parse avatar from remote service
130
            if ($this->_identity->photoURL !== null) {
131
                $this->parseAvatar($this->_identity->photoURL, $this->_userObject->id);
132
            }
133
134
            // save profile data
135
            $profile->save();
0 ignored issues
show
The method save() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

135
            $profile->/** @scrutinizer ignore-call */ 
136
                      save();

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
136
        }
137
138
        return $success;
139
    }
140
141
    /**
142
     * Try to download and parse remote avatar
143
     * @param string $url
144
     * @param int $userId
145
     */
146
    protected function parseAvatar($url, $userId)
147
    {
148
        // check if user is defined
149
        if ((int)$userId < 1) {
150
            return;
151
        }
152
153
        // check remote image extension
154
        $imageExtension = Str::lastIn($url, '.', true);
155
        if (!Arr::in($imageExtension, ['png', 'gif', 'jpg', 'jpeg'])) {
156
            return;
157
        }
158
159
        // try to get image binary data
160
        $imageContent = File::getFromUrl($url);
161
        if ($imageContent === null || Str::likeEmpty($imageContent)) {
0 ignored issues
show
It seems like $imageContent can also be of type false; however, parameter $string of Ffcms\Core\Helper\Type\Str::likeEmpty() does only seem to accept null|string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

161
        if ($imageContent === null || Str::likeEmpty(/** @scrutinizer ignore-type */ $imageContent)) {
Loading history...
162
            return;
163
        }
164
165
        // write image to filesystem
166
        $imagePath = '/upload/user/avatar/original/' . $userId . '.' . $imageExtension;
167
        $write = File::write($imagePath, $imageContent);
0 ignored issues
show
It seems like $imageContent can also be of type false; however, parameter $content of Ffcms\Core\Helper\FileSystem\File::write() does only seem to accept null|string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

167
        $write = File::write($imagePath, /** @scrutinizer ignore-type */ $imageContent);
Loading history...
168
        if ($write === false) {
169
            return;
170
        }
171
172
        // try to write and resize file
173
        try {
174
            $fileObject = new FileObject(root . $imagePath);
175
            $avatarUpload = new FormAvatarUpload();
176
            $avatarUpload->resizeAndSave($fileObject, $userId, 'small');
177
            $avatarUpload->resizeAndSave($fileObject, $userId, 'medium');
178
            $avatarUpload->resizeAndSave($fileObject, $userId, 'big');
179
        } catch (\Exception $e) {
180
            if (App::$Debug) {
181
                App::$Debug->addException($e);
182
            }
183
        }
184
    }
185
}
186