Module::getDbComponent()   A
last analyzed

Complexity

Conditions 3
Paths 4

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 14
ccs 8
cts 8
cp 1
rs 9.4285
cc 3
eloc 7
nc 4
nop 1
crap 3
1
<?php
2
/**
3
 * Yii2 Dumpling.
4
 *
5
 * This file contains Dumpling module.
6
 *
7
 * @author  Alexei Korotin <[email protected]>
8
 */
9
10
namespace herroffizier\yii2dumpling;
11
12
use Yii;
13
use yii\base\BootstrapInterface;
14
use yii\base\InvalidParamException;
15
use yii\base\NotSupportedException;
16
use yii\db\Connection;
17
18
/**
19
 * Dumpling module.
20
 *
21
 * Acts like a facade for actual dumpers.
22
 */
23
class Module extends \yii\base\Module implements BootstrapInterface
24
{
25
    /**
26
     * Default database component.
27
     *
28
     * @var string
29
     */
30
    public $defaultDbComponent = 'db';
31
32
    /**
33
     * Default name for dump file.
34
     *
35
     * Aliases supported.
36
     *
37
     * @var string
38
     */
39
    public $defaultDumpFile = '@app/runtime/dump.sql';
40
41
    /**
42
     * Array of dumpers for different databases.
43
     *
44
     * Keys must be a valid DSN prefix.
45
     *
46
     * Values must be either a string which represents dumper class name
47
     * or an array with 'class' field.
48
     * Values are passed to Yii::createObject() method.
49
     *
50
     * @var mixed
51
     */
52
    public $dumpers = [
53
        'mysql' => [
54
            'class' => 'herroffizier\yii2dumpling\dumpers\MysqlDumper',
55
        ],
56
    ];
57
58
    /**
59
     * @param mixed $app
60
     * @codeCoverageIgnore
61
     */
62
    public function bootstrap($app)
63
    {
64
        $app->set($this->id, $this);
65
66
        if ($app instanceof \yii\console\Application) {
67
            $app->controllerMap[$this->id] = [
68
                'class' => 'herroffizier\yii2dumpling\commands\Controller',
69
                'module' => $this,
70
            ];
71
        }
72
    }
73
74
    /**
75
     * Parse DSN string into array.
76
     *
77
     * @param string $dsn
78
     *
79
     * @return string[]
80
     */
81 15
    protected function parseDsn($dsn)
82
    {
83 15
        list($driverName, $dsn) = explode(':', $dsn, 2);
84
85 15
        $values = ['driverName' => $driverName];
86 15
        $options = explode(';', $dsn);
87 15
        foreach ($options as $option) {
88
            // Some options in DSN may be a single string.
89 15
            if (mb_strpos($option, '=') !== false) {
90 12
                list($key, $value) = explode('=', $option, 2);
91 12
                $values[$key] = $value;
92 8
            } else {
93 7
                $values[] = $option;
94
            }
95 10
        }
96
97 15
        return $values;
98
    }
99
100 15
    protected function createDumper(Connection $dbComponent)
101
    {
102 15
        $dsn = $this->parseDsn($dbComponent->dsn);
103
104 15
        if (!isset($this->dumpers[$dsn['driverName']])) {
105 3
            throw new NotSupportedException('Cannot handle '.$dsn['driverName'].' db');
106
        }
107
108 12
        $dumper = Yii::createObject(
109 12
            $this->dumpers[$dsn['driverName']],
110
            [
111 12
                $dsn,
112 12
                $dbComponent->username,
113 12
                $dbComponent->password,
114
            ]
115 8
        );
116
117 12
        return $dumper;
118
    }
119
120 15
    protected function getDbComponent($db)
121
    {
122 15
        if (!$db) {
123 12
            $db = $this->defaultDbComponent;
124 8
        }
125
126 15
        $component = Yii::$app->{$db};
127
128 15
        if (!($component instanceof Connection)) {
129 3
            throw new InvalidParamException($db.' is not an '.Connection::className().' instance');
130
        }
131
132 15
        return $component;
133
    }
134
135 15
    protected function getDumpFilePath($file)
136
    {
137 15
        if (!$file) {
138 6
            $file = $this->defaultDumpFile;
139 4
        }
140
141 15
        return Yii::getAlias($file);
142
    }
143
144
    /**
145
     * Dump database to file.
146
     *
147
     * If file or db params are not specified, default values will be used.
148
     *
149
     * @param string $file
0 ignored issues
show
Documentation introduced by
Should the type for parameter $file not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
150
     * @param string $db
0 ignored issues
show
Documentation introduced by
Should the type for parameter $db not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
151
     */
152 9 View Code Duplication
    public function dump($file = null, $db = null)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
153
    {
154 9
        $dbComponent = $this->getDbComponent($db);
155 9
        $filePath = $this->getDumpFilePath($file);
156
157 9
        $dumper = $this->createDumper($dbComponent);
158
159 6
        $dumper->dump($filePath);
160 6
    }
161
162
    /**
163
     * Restore database from file.
164
     *
165
     * If file or db params are not specified, default values will be used.
166
     *
167
     * @param string $file
0 ignored issues
show
Documentation introduced by
Should the type for parameter $file not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
168
     * @param string $db
0 ignored issues
show
Documentation introduced by
Should the type for parameter $db not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
169
     */
170 6 View Code Duplication
    public function restore($file = null, $db = null)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
171
    {
172 6
        $dbComponent = $this->getDbComponent($db);
173 6
        $filePath = $this->getDumpFilePath($file);
174
175 6
        $dumper = $this->createDumper($dbComponent);
176
177 6
        $dumper->restore($filePath);
178 6
    }
179
}
180