Passed
Push — master ( d9a4d3...d15b5c )
by CodexShaper
02:08
created

MysqlDumper::useSingleTransaction()   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 0
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
    public function getDumpOptions(string $credentialFile)
69
    {
70
        $options = [
71
            "{$this->dumpCommandPath}mysqldump",
72
            "--defaults-extra-file={$credentialFile}",
73
        ];
74
75
        if ($this->dbName) {
76
            $options['database'] = $this->dbName;
77
        }
78
        if ($this->socket) {
79
            $options['socket'] = "--socket={$this->socket}";
80
        }
81
        if ($this->skipComments) {
82
            $options['skipComments'] = '--skip-comments';
83
        }
84
        if (!$this->createTables) {
85
            $options['createTables'] = '--no-create-info';
86
        }
87
        if ($this->singleTransaction) {
88
            $options['singleTransaction'] = '--single-transaction';
89
        }
90
91
        if ($this->skipLockTables) {
92
            $options['skipLockTables'] = '--skip-lock-tables';
93
        }
94
95
        if ($this->quick) {
96
            $options['quick'] = '--quick';
97
        }
98
        if ($this->defaultCharacterSet) {
99
            $options['defaultCharacterSet'] = '--default-character-set=' . $this->defaultCharacterSet;
100
        }
101
        if (count($this->tables) > 0) {
102
            $options['tables'] = '--tables ' . implode(' ', $this->tables);
103
        }
104
        // Ignore Tables
105
        $ignoreTables = [];
106
        foreach ($this->ignoreTables as $tableName) {
107
            $ignoreTables[]          = "--ignore-table=" . $databaseArg . "." . $tableName;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $databaseArg seems to be never defined.
Loading history...
108
            $options['ignoreTables'] = implode(' ', $ignoreTables);
109
        }
110
        return $options;
111
    }
112
113
    protected function prepareDumpCommand(string $credentialFile, string $destinationPath): string
114
    {
115
        // Dump command
116
        $dumpCommand = implode(' ', $this->getDumpOptions($credentialFile));
117
        // Add compressor if compress is enable
118
        if ($this->isCompress) {
119
            return "{$dumpCommand} | {$this->compressBinaryPath}{$this->compressCommand} > {$destinationPath}{$this->compressExtension}";
120
        }
121
122
        return "{$dumpCommand} > {$destinationPath}";
123
    }
124
125
    protected function prepareRestoreCommand(string $credentialFile, string $filePath): string
126
    {
127
        // Database
128
        $database = $this->dbName;
129
        // Authentication File
130
        $authenticate = "--defaults-extra-file=" . $credentialFile;
131
        // Restore command
132
        $restoreCommand = sprintf("%smysql %s %s",
133
            $this->dumpCommandPath,
134
            $authenticate,
135
            $database
136
        );
137
        // Add compressor if compress is enable
138
        if ($this->isCompress) {
139
            return "{$this->compressBinaryPath}{$this->compressCommand} < {$filePath} | {$restoreCommand}";
140
        }
141
142
        return "{$restoreCommand} < {$filePath}";
143
    }
144
145
    protected function runCommand($filePath, $action)
146
    {
147
        try {
148
            // Get Credentials
149
            $credentials = $this->getCredentials();
150
            // Create a temporary file
151
            $this->tempFile = tempnam(sys_get_temp_dir(), 'mysqlpass');
152
            // Create file handler
153
            $handler = fopen($this->tempFile, 'r+');
154
            // Write credentials into temporary file
155
            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

155
            fwrite(/** @scrutinizer ignore-type */ $handler, $credentials);
Loading history...
156
157
            if ($action == 'dump') {
158
                $this->command = preg_replace('/\s+/', ' ', $this->prepareDumpCommand($this->tempFile, $filePath));
159
            } else if ($action == 'restore') {
160
                $this->command = preg_replace('/\s+/', ' ', $this->prepareRestoreCommand($this->tempFile, $filePath));
161
            }
162
            // Get Symfony process with prepared command
163
            $process = $this->prepareProcessCommand();
164
165
            if ($this->debug) {
166
                $process->mustRun();
167
            } else {
168
                $process->run();
169
            }
170
            // close handler
171
            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

171
            fclose(/** @scrutinizer ignore-type */ $handler);
Loading history...
172
            // Remove temporary
173
            unlink($this->tempFile);
174
175
        } catch (ProcessFailedException $e) {
176
            throw new \Exception($e->getMessage());
177
178
        }
179
    }
180
181
    protected function getCredentials()
182
    {
183
        $contents = [
184
            '[client]',
185
            "user = '{$this->username}'",
186
            "password = '{$this->password}'",
187
            "host = '{$this->host}'",
188
            "port = '{$this->port}'",
189
        ];
190
        return implode(PHP_EOL, $contents);
191
    }
192
}
193