Completed
Push — master ( d71336...b5cc88 )
by Razon
02:32
created

SessionFactory::create()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 16
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 14
nc 1
nop 4
dl 0
loc 16
rs 9.7998
c 0
b 0
f 0
1
<?php
2
namespace App\Factory;
3
4
use App\Model\Session;
5
use Ramsey\Uuid\Uuid;
6
use Yii;
7
use yii\web\Request;
8
9
class SessionFactory
10
{
11
    /**
12
     * Creates a session from request.
13
     *
14
     * @param int     $userId          user ID.
15
     * @param int     $duration        session duration
16
     * @param int     $refreshDuration session fresh duration
17
     * @param Request $request
18
     *
19
     * @return Session
20
     */
21
    public static function create(int $userId, int $duration, int $refeshDuration, Request $request): Session
22
    {
23
        $ip = $request->getUserIP();
24
        $userAgent = mb_substr($request->getUserAgent(), 0, 255);
25
        $token = static::generateToken($userId);
26
        $refeshToken = static::generateRefreshToken($userId);
27
        $now = time();
28
        return new Session([
29
            'id' => Uuid::uuid4()->toString(),
30
            'token' => $token,
31
            'refresh_token' => $refeshToken,
32
            'user_id' => $userId,
33
            'expire_time' => $now + $duration,
34
            'refresh_token_expire_time' => $now + $refeshDuration,
35
            'ip_address' => $ip,
36
            'user_agent' => $userAgent,
37
        ]);
38
    }
39
40
    /**
41
     * Generates access token.
42
     *
43
     * @param int $userId user ID.
44
     *
45
     * @return string
46
     */
47
    public static function generateToken(int $userId): string
48
    {
49
        return ($userId % 10) . Yii::$app->getSecurity()->generateRandomString(31);
50
    }
51
52
    /**
53
     * Generates refresh token.
54
     *
55
     * @param int $userId user ID.
56
     *
57
     * @return string
58
     */
59
    public static function generateRefreshToken(int $userId): string
60
    {
61
        return ($userId % 10) . Yii::$app->getSecurity()->generateRandomString(63);
62
    }
63
}
64