Passed
Pull Request — master (#75)
by Korotkov
12:47
created

DatabaseLogger   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 56
Duplicated Lines 0 %

Importance

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

5 Methods

Rating   Name   Duplication   Size   Complexity  
A up() 0 13 1
A isTable() 0 7 1
A checkLog() 0 12 1
A __construct() 0 3 1
A writeLog() 0 8 1
1
<?php
2
3
namespace App\Ship\Utils;
4
5
use Rudra\Container\Facades\Rudra;
6
7
class DatabaseLogger
8
{
9
    protected \PDO $dsn;
10
    protected string $table;
11
12
    public function __construct()
13
    {
14
        $this->dsn = Rudra::get("DSN");
15
    }
16
17
    protected function up(): void
18
    {
19
        $query = $this->dsn->prepare("
20
            CREATE TABLE {$this->table} (
21
            `id` INT NOT NULL AUTO_INCREMENT ,
22
            `name` VARCHAR(255) NOT NULL , 
23
            `created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ,
24
            `updated_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
25
                PRIMARY KEY (`id`)
26
            ) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci
27
        ");
28
29
        $query->execute();
30
    }
31
32
    protected function isTable()
33
    {
34
        $query = $this->dsn->query("
35
            SHOW TABLES LIKE '{$this->table}';
36
        ");
37
38
        return $query->fetchColumn();
39
    }
40
41
    protected function writeLog(string $name): void
42
    {
43
        $query = $this->dsn->prepare("
44
            INSERT INTO {$this->table} (`name`)
45
            VALUES (:name)"
46
        );
47
48
        $query->execute([':name' => $name]);
49
    }
50
51
    protected function checkLog(string $name)
52
    {
53
        $stmt = $this->dsn->prepare("
54
            SELECT * FROM {$this->table}
55
            WHERE name = :name
56
        ");
57
58
        $stmt->execute([
59
            ':name' => $name,
60
        ]);
61
62
        return $stmt->fetch(\PDO::FETCH_ASSOC);
63
    }
64
}