Passed
Push — 5.0.0 ( 51b79d...976529 )
by Fèvre
06:35
created

CustomDatabaseSessionHandler   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 29
dl 0
loc 48
rs 10
c 1
b 0
f 0
wmc 5

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A userId() 0 3 2
A write() 0 33 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Xetaravel\Extensions;
6
7
use Illuminate\Database\ConnectionInterface;
8
use Illuminate\Session\DatabaseSessionHandler;
9
use Illuminate\Support\Arr;
10
use Xetaravel\Services\DeviceDetectorService;
11
12
class CustomDatabaseSessionHandler extends DatabaseSessionHandler
13
{
14
    protected DeviceDetectorService $device;
15
16
    public function __construct(ConnectionInterface $connection, $table, $minutes, $app, DeviceDetectorService $device)
17
    {
18
        parent::__construct($connection, $table, $minutes, $app);
19
        $this->device = $device;
20
    }
21
22
    protected function userId()
23
    {
24
        return auth()->check() ? auth()->id() : null;
25
    }
26
27
    public function write($sessionId, $data): bool
28
    {
29
        $currentTime = now();
30
31
        $userAgent = request()->userAgent();
32
33
        $payload = [
34
            'payload' => base64_encode($data),
35
            'last_activity' => time(),
36
            'url' => request()->path(),
37
            'method' => request()->method(),
38
            'platform' => $this->device->getPlatform($userAgent),
39
            'platform_version' => $this->device->getPlatformVersion($userAgent),
40
            'browser' => $this->device->getBrowser($userAgent),
41
            'browser_version' => $this->device->getBrowserVersion($userAgent),
42
            'device_type' => $this->device->getDeviceType($userAgent),
43
            'updated_at' => $currentTime
44
        ];
45
46
        if ($this->exists) {
47
            $this->connection->table($this->table)->where('id', $sessionId)->update($payload);
48
        } else {
49
            $payload += [
50
                'id' => $sessionId,
51
                'user_id' => $this->userId(),
52
                'ip_address' => request()->ip(),
53
                'user_agent' => request()->userAgent(),
54
                'created_at' => $currentTime
55
            ];
56
            $this->connection->table($this->table)->insert(Arr::set($payload, 'id', $sessionId));
57
        }
58
59
        return $this->exists = true;
60
    }
61
}
62