Passed
Push — master ( bc79f7...517d2b )
by Samuel
02:55
created

UserActivityData::toArrayForDatabase()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 9
c 0
b 0
f 0
dl 0
loc 12
ccs 10
cts 10
cp 1
rs 9.9666
cc 2
nc 2
nop 0
crap 2
1
<?php
2
3
namespace App\Domain\User\Data;
4
5
use App\Domain\User\Enum\UserActivity;
6
7
class UserActivityData
8
{
9
    public ?int $id;
10
    public ?int $userId; // Has to be nullable when user id is unknown
11
    public UserActivity $action = UserActivity::UPDATED; // Default to updated
12
    public ?string $table;
13
    public ?int $rowId;
14
    public ?array $data;
15
    public ?\DateTimeImmutable $datetime;
16
    public ?string $ipAddress;
17
    public ?string $userAgent;
18
19
    // When returning the report to the client add the page url
20
    public ?string $pageUrl = null;
21
    public ?string $timeAndActionName = null; // Time in the correct format and action name with upper case
22
23 49
    public function __construct(array $userActivityValues = [])
24
    {
25 49
        $this->id = $userActivityValues['id'] ?? null;
26 49
        $this->userId = $userActivityValues['user_id'] ?? null;
27 49
        $this->action = UserActivity::tryFrom($userActivityValues['action'] ?? '') ?? UserActivity::UPDATED;
28 49
        $this->table = $userActivityValues['table'] ?? null;
29 49
        $this->rowId = $userActivityValues['row_id'] ?? null;
30 49
        $this->data = $userActivityValues['data'] ?? null ?
31 49
            json_decode($userActivityValues['data'], true, 512, JSON_THROW_ON_ERROR) : null;
32 49
        $this->datetime = $userActivityValues['datetime'] ?? null ?
33 49
            new \DateTimeImmutable($userActivityValues['datetime']) : null;
34 49
        $this->ipAddress = $userActivityValues['ip_address'] ?? null;
35 49
        $this->userAgent = $userActivityValues['user_agent'] ?? null;
36
    }
37
38 48
    public function toArrayForDatabase(): array
39
    {
40 48
        return [
41 48
            'id' => $this->id,
42 48
            'user_id' => $this->userId,
43 48
            'action' => $this->action->value,
44 48
            'table' => $this->table,
45 48
            'row_id' => $this->rowId,
46 48
            'data' => $this->data ? json_encode($this->data, JSON_PARTIAL_OUTPUT_ON_ERROR) : null,
47
            // Datetime never needed for insert as it's done by the database
48 48
            'ip_address' => $this->ipAddress,
49 48
            'user_agent' => $this->userAgent,
50 48
        ];
51
    }
52
}
53