Completed
Push — master ( cc8038...edef00 )
by Bartko
01:27
created

Connection   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 56
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
wmc 7
lcom 1
cbo 1
dl 0
loc 56
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A insertInitData() 0 21 3
A createDataSourceFromCurrentDatabaseState() 0 18 2
A quoteIdentifier() 0 4 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace StefanoTreeTest\DbTester;
6
7
use PDO;
8
9
class Connection
10
{
11
    private $pdo;
12
13
    public function __construct(PDO $pdo)
14
    {
15
        $this->pdo = $pdo;
16
        $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
17
    }
18
19
    public function insertInitData(ArrayDataSource $dataSource)
20
    {
21
        $connection = $this->pdo;
22
        foreach ($dataSource->getTableNames() as $tableName) {
23
            foreach ($dataSource->getTableData($tableName) as $rowData) {
24
                $sql = sprintf(
25
                    'INSERT INTO %s (%s) VALUES (%s)',
26
                    $this->quoteIdentifier($tableName),
27
                    implode(', ', array_map(function ($key) {
28
                        return $this->quoteIdentifier($key);
29
                    }, array_keys($rowData))),
30
                    implode(', ', array_map(function ($valueKey) {
31
                        return ':'.$valueKey;
32
                    }, array_keys($rowData)))
33
                );
34
35
                $connection->prepare($sql)
36
                    ->execute($rowData);
37
            }
38
        }
39
    }
40
41
    public function createDataSourceFromCurrentDatabaseState(array $tables): ArrayDataSource
42
    {
43
        $connection = $this->pdo;
44
45
        $data = array();
46
        foreach ($tables as $tableName) {
47
            $sql = sprintf(
48
                'SELECT * FROM %s',
49
                $this->quoteIdentifier($tableName)
50
            );
51
52
            $rows = $connection->query($sql)
53
                ->fetchAll(PDO::FETCH_ASSOC);
54
            $data[$tableName] = $rows;
55
        }
56
57
        return new ArrayDataSource($data);
58
    }
59
60
    private function quoteIdentifier(string $identifier): string
61
    {
62
        return $identifier; // todo Quote identifier. Possible SQL injection
63
    }
64
}
65