Passed
Push — main ( 2bf89b...450136 )
by mikhail
03:21
created

SQLiteBaselineStorage::init()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 5
dl 0
loc 8
ccs 0
cts 7
cp 0
rs 10
c 1
b 0
f 0
cc 1
nc 1
nop 1
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace SavinMikhail\CommentsDensity\Baseline\Storage;
6
7
use Doctrine\DBAL\DriverManager;
8
use Doctrine\DBAL\Connection;
9
10
final class SQLiteBaselineStorage implements BaselineStorageInterface
11
{
12
    private Connection $connection;
13
14
    public function init(string $path): void
15
    {
16
        $connectionParams = [
17
            'driver' => 'pdo_sqlite',
18
            'path' => $path,
19
        ];
20
        $this->connection = DriverManager::getConnection($connectionParams);
21
        $this->initializeDatabase();
22
    }
23
24
    private function initializeDatabase(): void
25
    {
26
        $schema = $this->connection->createSchemaManager();
27
        $tables = $schema->listTables();
28
29
        if (!in_array('comments', array_map(fn($table) => $table->getName(), $tables))) {
30
            $this->connection->executeStatement('
31
                CREATE TABLE comments (
32
                    file_path TEXT NOT NULL,
33
                    line_number INTEGER NOT NULL,
34
                    comment TEXT NOT NULL,
35
                    type TEXT NOT NULL,
36
                    PRIMARY KEY (file_path, line_number)
37
                )
38
            ');
39
        }
40
    }
41
42
    public function setComments(array $comments): void
43
    {
44
        foreach ($comments as $comment) {
45
            $this->connection->insert('comments', [
46
                'file_path' => $comment->file,
47
                'line_number' => $comment->line,
48
                'comment' => $comment->content,
49
                'type' => $comment->commentType,
50
            ]);
51
        }
52
    }
53
54
    public function filterComments(array $comments): array
55
    {
56
        $filteredComments = [];
57
        foreach ($comments as $comment) {
58
            $query = $this->connection->createQueryBuilder()
59
                ->select('*')
60
                ->from('comments')
61
                ->where('file_path = :file_path')
62
                ->andWhere('line_number = :line_number')
63
                ->setParameter('file_path', $comment->file)
64
                ->setParameter('line_number', $comment->line)
65
                ->executeQuery();
66
67
            if (!$query->fetchAssociative()) {
68
                $filteredComments[] = $comment;
69
            }
70
        }
71
        return $filteredComments;
72
    }
73
}
74