Passed
Push — master ( 66f0ce...79be23 )
by CodexShaper
02:15
created

MysqlDumper::setDefaultCharacterSet()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 4
rs 10
1
<?php
2
3
namespace CodexShaper\Dumper\Drivers;
4
5
use CodexShaper\Dumper\Dumper;
6
use Symfony\Component\Process\Exception\ProcessFailedException;
7
8
class MysqlDumper extends Dumper
9
{
10
    /*@var bool*/
11
    protected $singleTransaction = false;
12
    /*@var bool*/
13
    protected $skipLockTables = false;
14
    /*@var bool*/
15
    protected $quick = false;
16
    /*@var bool*/
17
    protected $skipComments = true;
18
    /*@var string*/
19
    protected $defaultCharacterSet = '';
20
    /*@var bool*/
21
    protected $createTables = true;
22
23
    public function useSingleTransaction()
24
    {
25
        $this->singleTransaction = true;
26
        return $this;
27
    }
28
    public function useSkipLockTables()
29
    {
30
        $this->skipLockTables = true;
31
        return $this;
32
    }
33
    public function useQuick()
34
    {
35
        $this->quick = true;
36
        return $this;
37
    }
38
    public function doNotUseSkipComments()
39
    {
40
        $this->skipComments = false;
41
        return $this;
42
    }
43
    public function doNotUseCreateTables()
44
    {
45
        $this->createTables = false;
46
        return $this;
47
    }
48
    public function setDefaultCharacterSet(string $charecterSet)
49
    {
50
        $this->defaultCharacterSet = $charecterSet;
51
        return $this;
52
    }
53
54
    public function dump(string $destinationPath = "")
55
    {
56
        $destinationPath = !empty($destinationPath) ? $destinationPath : $this->destinationPath;
57
        $this->runCommand($destinationPath, "dump");
58
        return $this;
59
    }
60
61
    public function restore(string $restorePath = "")
62
    {
63
        $restorePath = !empty($restorePath) ? $restorePath : $this->restorePath;
64
        $this->runCommand($restorePath, 'restore');
65
        return $this;
66
    }
67
68
    protected function prepareDumpCommand(string $credentialFile, string $destinationPath): string
69
    {
70
        $dumpCommand = sprintf(
71
            '%smysqldump %s %s %s %s %s %s %s %s %s %s %s',
72
            $this->dumpCommandPath,
73
            $this->prepareAuthentication($credentialFile),
74
            $this->prepareDatabase(),
75
            $this->prepareSocket(),
76
            $this->prepareSkipComments(),
77
            $this->prepareCreateTables(),
78
            $this->prepareSingleTransaction(),
79
            $this->prepareSkipLockTables(),
80
            $this->prepareQuick(),
81
            $this->prepareDefaultCharSet(),
82
            $this->prepareIncludeTables(),
83
            $this->prepareIgnoreTables()
84
        );
85
86
        if ($this->isCompress) {
87
88
            return "{$dumpCommand} | {$this->compressBinaryPath}{$this->compressCommand} > {$destinationPath}{$this->compressExtension}";
89
        }
90
91
        return "{$dumpCommand} > {$destinationPath}";
92
    }
93
94
    protected function prepareRestoreCommand(string $credentialFile, string $filePath): string
95
    {
96
        $restoreCommand = sprintf("%smysql %s %s",
97
            $this->dumpCommandPath,
98
            $this->prepareAuthentication($credentialFile),
99
            $this->prepareDatabase()
100
        );
101
102
        if ($this->isCompress) {
103
104
            return "{$this->compressBinaryPath}{$this->compressCommand} < {$filePath} | {$restoreCommand}";
105
        }
106
107
        return "{$restoreCommand} < {$filePath}";
108
    }
109
110
    protected function runCommand($filePath, $action)
111
    {
112
        try {
113
114
            $credentials    = $this->getCredentials();
115
            $this->tempFile = tempnam(sys_get_temp_dir(), 'mysqlpass');
116
            $handler        = fopen($this->tempFile, 'r+');
117
            fwrite($handler, $credentials);
0 ignored issues
show
Bug introduced by
It seems like $handler can also be of type false; however, parameter $handle of fwrite() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

117
            fwrite(/** @scrutinizer ignore-type */ $handler, $credentials);
Loading history...
118
119
            if ($action == 'dump') {
120
                $this->command = preg_replace('/\s+/', ' ', $this->prepareDumpCommand($this->tempFile, $filePath));
121
            }
122
123
            if ($action == 'restore') {
124
                $this->command = preg_replace('/\s+/', ' ', $this->prepareRestoreCommand($this->tempFile, $filePath));
125
            }
126
127
            $process = $this->prepareProcessCommand();
128
129
            if ($this->debug) {
130
                $process->mustRun();
131
            } else {
132
                $process->run();
133
            }
134
135
            fclose($handler);
0 ignored issues
show
Bug introduced by
It seems like $handler can also be of type false; however, parameter $handle of fclose() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

135
            fclose(/** @scrutinizer ignore-type */ $handler);
Loading history...
136
            unlink($this->tempFile);
137
138
        } catch (ProcessFailedException $e) {
139
            throw new \Exception($e->getMessage());
140
141
        }
142
    }
143
144
    protected function getCredentials()
145
    {
146
        $contents = [
147
            '[client]',
148
            "user = '{$this->username}'",
149
            "password = '{$this->password}'",
150
            "host = '{$this->host}'",
151
            "port = '{$this->port}'",
152
        ];
153
        return implode(PHP_EOL, $contents);
154
    }
155
156
    public function prepareDatabase()
157
    {
158
        return $this->dbName;
159
    }
160
161
    public function prepareIncludeTables()
162
    {
163
        $includeTables    = (count($this->tables) > 0) ? implode(' ', $this->tables) : "";
164
        $includeTablesArg = !empty($includeTables) ? '--tables ' . $includeTables : '';
165
        return $includeTablesArg;
166
    }
167
168
    public function prepareIgnoreTables()
169
    {
170
        $ignoreTablesArgs = [];
171
        foreach ($this->ignoreTables as $tableName) {
172
            $ignoreTablesArgs[] = "--ignore-table={$databaseArg}.{$tableName}";
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $databaseArg seems to be never defined.
Loading history...
173
        }
174
        $ignoreTablesArg = (count($ignoreTablesArgs) > 0) ? implode(' ', $ignoreTablesArgs) : '';
175
        return $ignoreTablesArg;
176
    }
177
178
    public function prepareSingleTransaction()
179
    {
180
        return $this->singleTransaction ? "--single-transaction" : "";
181
    }
182
183
    public function prepareSkipLockTables()
184
    {
185
        return $this->skipLockTables ? "--skip-lock-tables" : "";
186
    }
187
188
    public function prepareQuick()
189
    {
190
        return $this->quick ? "--quick" : "";
191
    }
192
193
    public function prepareCreateTables()
194
    {
195
        return !$this->createTables ? '--no-create-info' : '';
196
    }
197
198
    public function prepareSkipComments()
199
    {
200
        return $this->skipComments ? '--skip-comments' : '';
201
    }
202
203
    public function prepareSocket()
204
    {
205
        return ($this->socket !== '') ? "--socket={$this->socket}" : '';
206
    }
207
208
    public function prepareDefaultCharSet()
209
    {
210
        return ($this->defaultCharacterSet !== '') ? "--default-character-set={$this->defaultCharacterSet}" : '';
211
    }
212
213
    public function prepareAuthentication(string $credentialFile)
214
    {
215
        return "--defaults-extra-file={$credentialFile}";
216
    }
217
}
218