MysqlDatabaseFactory::generate()   A
last analyzed

Complexity

Conditions 3
Paths 4

Size

Total Lines 17
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 11
dl 0
loc 17
c 0
b 0
f 0
rs 9.9
cc 3
nc 4
nop 0
1
<?php
2
3
namespace Starkerxp\DatabaseChecker\Factory;
4
5
use Starkerxp\DatabaseChecker\LoggerTrait;
6
use Starkerxp\DatabaseChecker\Repository\StructureInterface;
7
use Starkerxp\DatabaseChecker\Structure\MysqlDatabase;
8
9
10
/**
11
 * Transcris l'état de la base de données en version objet afin de pouvoir y appliquer les traitements.
12
 *
13
 * @package Starkerxp\DatabaseChecker\Factory
14
 */
15
class MysqlDatabaseFactory
16
{
17
18
    use LoggerTrait;
19
20
    protected $databaseName;
21
    protected $repositoryMysql;
22
    private $checkCollate = false;
23
24
    /**
25
     * MysqlDatabaseFactory constructor.
26
     *
27
     * @param StructureInterface $repositoryMysql
28
     * @param string             $databaseName
29
     */
30
    public function __construct(StructureInterface $repositoryMysql, $databaseName)
31
    {
32
        $this->repositoryMysql = $repositoryMysql;
33
        $this->databaseName = $databaseName;
34
    }
35
36
    public function enableCheckCollate(): void
37
    {
38
        $this->checkCollate = true;
39
    }
40
41
    /**
42
     * @return MysqlDatabase
43
     *
44
     * @throws \LogicException
45
     */
46
    public function generate(): MysqlDatabase
47
    {
48
        $export = [];
49
        $tables = $this->repositoryMysql->getTablesStructure($this->databaseName);
50
        foreach ($tables as $table) {
51
            $export['tables'][$table] = $this->getIndex($table);
52
            $export['tables'][$table]['columns'] = $this->getColumns($table);
53
        }
54
        $factoryJsonDatabase = new JsonDatabaseFactory(json_encode($export));
55
56
        try {
57
            $export = $factoryJsonDatabase->generate($this->databaseName);
58
        } catch (\Exception $e) {
59
            throw new \LogicException('Un expected error with json.' . $e->getMessage());
60
        }
61
62
        return $export;
63
    }
64
65
66
    protected function getIndex($table): array
67
    {
68
        if (!$results = $this->repositoryMysql->fetchIndexStructure($this->databaseName, $table)) {
69
            return [];
70
        }
71
        $export = [];
72
        foreach ($results as $row) {
73
            if ($row['INDEX_NAME'] === 'PRIMARY') {
74
                $export['primary'] = array_filter(explode(',', $row['COLUMN_NAME']));
75
                continue;
76
            }
77
            $key = 'indexes';
78
            if (!$row['NON_UNIQUE']) {
79
                $key = 'uniques';
80
            }
81
            if (!$row['NON_FULLTEXT']) {
82
                $key = 'fulltexts';
83
            }
84
            $export[$key][] = array_filter(['name' => $row['INDEX_NAME'], 'columns' => explode(',', $row['COLUMN_NAME'])]);
85
        }
86
87
        return $export;
88
    }
89
90
    protected function getColumns($table): array
91
    {
92
        $export = [];
93
        $results = $this->repositoryMysql->fetchColumnsStructure($this->databaseName, $table);
94
        foreach ($results as $row) {
95
            $type = $row['DATA_TYPE'];
96
            $length = str_replace([$type, '(', ')'], '', $row['COLUMN_TYPE']);
97
            if ($type === 'enum') {
98
                $type = $row['COLUMN_TYPE'];
99
                $length = null;
100
            }
101
            $export[$row['COLUMN_NAME']] = array_filter([
102
                'type' => $type,
103
                'length' => $length,
104
                'nullable' => $row['IS_NULLABLE'] !== 'NO',
105
                'defaultValue' => $row['IS_NULLABLE'] !== 'NO' && empty($row['COLUMN_DEFAULT']) ? 'NULL' : $row['COLUMN_DEFAULT'],
106
                'extra' => $row['EXTRA'],
107
                'collate' => $row['COLLATION_NAME'],
108
            ]);
109
            if (!$this->checkCollate) {
110
                unset($export[$row['COLUMN_NAME']]['collate']);
111
            }
112
        }
113
114
        return $export;
115
    }
116
117
	
118
	public function exportStructure(){
119
		$export = [];
120
        $tables = $this->repositoryMysql->getTablesStructure($this->databaseName);
121
        foreach ($tables as $table) {
122
            $export[$table] = $this->getIndex($table);
123
            $export[$table]['columns'] = $this->getColumns($table);
124
        }
125
		
126
		return json_encode($export);
127
	}
128
}
129