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

Connection::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 5
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 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