Completed
Pull Request — master (#187)
by Sergey
02:14
created

User::getUserName()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 6
rs 9.4285
cc 2
eloc 3
nc 2
nop 0
1
<?php
2
3
namespace seregazhuk\PinterestBot\Api\Providers;
4
5
use LogicException;
6
use seregazhuk\PinterestBot\Api\Response;
7
use seregazhuk\PinterestBot\Api\Traits\UploadsImages;
8
use seregazhuk\PinterestBot\Helpers\UrlBuilder;
9
10
class User extends Provider
11
{
12
    use UploadsImages;
13
14
    /**
15
     * @var array
16
     */
17
    protected $loginRequiredFor = [
18
        'profile',
19
        'convertToBusiness',
20
        'changePassword',
21
        'isBanned',
22
        'deactivate',
23
        'getUserName',
24
        'invite'
25
    ];
26
27
    const REGISTRATION_COMPLETE_EXPERIENCE_ID = '11:10105';
28
    const ACCOUNT_TYPE_OTHER = 'other';
29
30
    /**
31
     * Updates or returns user profile info. Gets associative array as a param. Available keys of array are:
32
     * 'last_name', 'first_name', 'username', 'about', 'location' and 'website_url'.
33
     * You can also change user avatar by passing 'profile_image'.
34
     *
35
     * @param array $userInfo If empty returns current user profile.
36
     *
37
     * @return bool|array
38
     */
39
    public function profile($userInfo = [])
40
    {
41
        if(empty($userInfo)) {
42
            return $this->execGetRequest([], UrlBuilder::RESOURCE_GET_USER_SETTINGS);
43
        }
44
45
        if (isset($userInfo['profile_image'])) {
46
            $userInfo['profile_image_url'] = $this->upload($userInfo['profile_image']);
47
        }
48
49
        return $this->execPostRequest($userInfo, UrlBuilder::RESOURCE_UPDATE_USER_SETTINGS);
50
    }
51
52
    /**
53
     * Register a new user.
54
     *
55
     * @param string $email
56
     * @param string $password
57
     * @param string $name
58
     * @param string $country
59
     * @param int $age
60
     *
61
     * @return bool
62
     */
63
    public function register($email, $password, $name, $country = 'GB', $age = 18)
64
    {
65
        $data = [
66
            "age"        => $age,
67
            "email"      => $email,
68
            "password"   => $password,
69
            "country"    => $country,
70
            "first_name" => $name,
71
            "container"  => "home_page"
72
        ];
73
74
        return $this->makeRegisterCall($data);
75
    }
76
77
    /**
78
     * Register a new business account.
79
     *
80
     * @param string $email
81
     * @param string $password
82
     * @param string $businessName
83
     * @param string $website
84
     * @return bool|mixed
85
     */
86
    public function registerBusiness($email, $password, $businessName, $website = '')
87
    {
88
        $data = [
89
            "email"         => $email,
90
            "password"      => $password,
91
            "website_url"   => $website,
92
            "business_name" => $businessName,
93
            "account_type"  => self::ACCOUNT_TYPE_OTHER,
94
        ];
95
96
        return $this->makeRegisterCall($data);
97
    }
98
99
    /**
100
     * Convert your account to a business one.
101
     *
102
     * @param string $businessName
103
     * @param string $websiteUrl
104
     *
105
     * @return bool
106
     */
107
    public function convertToBusiness($businessName, $websiteUrl = '')
108
    {
109
        $data = [
110
            'business_name' => $businessName,
111
            'website_url'   => $websiteUrl,
112
            'account_type'  => self::ACCOUNT_TYPE_OTHER,
113
        ];
114
115
        return $this->execPostRequest($data, UrlBuilder::RESOURCE_CONVERT_TO_BUSINESS);
116
    }
117
118
    /**
119
     * Login as pinner.
120
     *
121
     * @param string $username
122
     * @param string $password
123
     *
124
     * @param bool $autoLogin
125
     * @return bool
126
     */
127
    public function login($username, $password, $autoLogin = true)
128
    {
129
        if ($this->request->isLoggedIn()) return true;
130
131
        $this->checkCredentials($username, $password);
132
133
        // Trying to load previously saved cookies from last login
134
        // session for this username.
135
        if($autoLogin && $this->request->autoLogin($username)) {
136
            return true;
137
        }
138
139
        return $this->processLogin($username, $password);
140
    }
141
142
    public function logout()
143
    {
144
        $this->request->logout();
145
    }
146
147
    /**
148
     * @return bool
149
     */
150
    public function isLoggedIn()
151
    {
152
        return $this->request->isLoggedIn();
153
    }
154
155
    /**
156
     * Checks if current user is banned
157
     *
158
     * @return bool
159
     */
160
    public function isBanned()
161
    {
162
        $profile = $this->profile();
163
164
       return isset($profile['is_write_banned']) ?
165
           (bool)$profile['is_write_banned'] :
166
           false;
167
    }
168
169
    /**
170
     * Returns current user username
171
     *
172
     * @return string
173
     */
174
    public function getUserName()
175
    {
176
        $profile = $this->profile();
177
178
        return isset($profile['username']) ? $profile['username'] : '';
179
    }
180
181
    /**
182
     * @param string $oldPassword
183
     * @param string $newPassword
184
     * @return bool
185
     */
186
    public function changePassword($oldPassword, $newPassword)
187
    {
188
        $request = [
189
            'old_password'         => $oldPassword,
190
            'new_password'         => $newPassword,
191
            'new_password_confirm' => $newPassword,
192
        ];
193
194
        return $this->execPostRequest($request, UrlBuilder::RESOURCE_CHANGE_PASSWORD);
195
    }
196
197
    /**
198
     * Deactivates your account.
199
     *
200
     * @param string $reason
201
     * @param string $explanation
202
     * @return bool
203
     */
204
    public function deactivate($reason = 'other', $explanation = '')
205
    {
206
        $profile = $this->profile();
207
208
        if(!isset($profile['id'])) return false;
209
210
        $request = [
211
            'user_id'     => $profile['id'],
212
            'reason'      => $reason,
213
            'explanation' => $explanation,
214
        ];
215
216
        return $this->execPostRequest($request, UrlBuilder::RESOURCE_DEACTIVATE_ACCOUNT);
217
    }
218
219
    /**
220
     * Validates password and login.
221
     *
222
     * @param string $username
223
     * @param string $password
224
     */
225
    protected function checkCredentials($username, $password)
226
    {
227
        if (!$username || !$password) {
228
            throw new LogicException('You must set username and password to login.');
229
        }
230
    }
231
232
    /**
233
     * @return bool
234
     */
235
    protected function completeRegistration()
236
    {
237
        $this->request->setTokenFromCookies();
238
239
        return $this->execPostRequest(
240
                ['placed_experience_id' => self::REGISTRATION_COMPLETE_EXPERIENCE_ID],
241
                UrlBuilder::RESOURCE_REGISTRATION_COMPLETE
242
            );
243
    }
244
245
    /**
246
     * @param array $data
247
     * @return bool|mixed
248
     */
249
    protected function makeRegisterCall($data)
250
    {
251
        $this->visitMainPage();
252
        $this->request->setTokenFromCookies();
253
254
        if (!$this->execPostRequest($data, UrlBuilder::RESOURCE_CREATE_REGISTER)) {
255
            return false;
256
        }
257
258
        return $this->completeRegistration();
259
    }
260
261
    /**
262
     * @param string $username
263
     * @param string $password
264
     * @return bool
265
     */
266
    protected function processLogin($username, $password)
267
    {
268
        $this->request->clearToken();
269
270
        $credentials = [
271
            'username_or_email' => $username,
272
            'password'          => $password,
273
        ];
274
275
        $response = $this->execPostRequest($credentials, UrlBuilder::RESOURCE_LOGIN, true);
276
        if ($response->hasErrors()) {
277
            return false;
278
        }
279
280
        $this->request->login();
281
282
        return true;
283
    }
284
285
    /**
286
     * Send invite to email
287
     * @param string $email
288
     * @return bool|Response
289
     */
290
    public function invite($email)
291
    {
292
        $data = [
293
            'email' => $email,
294
            'type'  => 'email',
295
        ];
296
297
        return $this->execPostRequest($data, UrlBuilder::RESOURCE_INVITE);
298
    }
299
    
300
    /**
301
     * Ask for password reset link in email
302
     *
303
     * @param string $user Username or user mail
304
     * @return bool
305
     */
306
    public function sendPasswordResetLink($user)
307
    {
308
        $request = ['username_or_email' => $user];
309
310
        return $this->execPostRequest($request, UrlBuilder::RESOURCE_RESET_PASSWORD_SEND_LINK);
311
    }
312
313
    /**
314
     * Set a new password by link from reset password email
315
     *
316
     * @param $link
317
     * @param string $newPassword
318
     * @return bool|Response
319
     */
320
    public function resetPassword($link, $newPassword)
321
    {
322
        // Visit link to get current reset token, username and token expiration
323
        $this->execGetRequest([], $link);
324
        $this->request->clearToken();
325
326
        $passwordResetUrl = $this->request->getHttpClient()->getCurrentUrl();
327
328
        $urlData = parse_url($passwordResetUrl);
329
        $username = trim(str_replace('/pw/', '', $urlData['path']), '/');
330
331
        $query = [];
332
        parse_str($urlData['query'], $query);
333
334
335
        return $this->execPostRequest([
336
                'username'             => $username,
337
                'new_password'         => $newPassword,
338
                'new_password_confirm' => $newPassword,
339
                'token'                => $query['t'],
340
                'expiration'           => $query['e'],
341
            ], UrlBuilder::RESOURCE_RESET_PASSWORD_UPDATE, true);
342
    }
343
344
345
    public function visitMainPage()
346
    {
347
        $this->execGetRequest([], '');
348
    }
349
}
350