GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.

Migration::last()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 16
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 16
rs 9.4285
cc 1
eloc 11
nc 1
nop 0
1
<?php
2
3
namespace ConsoleTools\Model;
4
5
use Zend\Db\Adapter\Adapter;
6
use Zend\Db\ResultSet\ResultSetInterface;
7
use Zend\Db\Sql\Expression;
8
use Zend\Db\Sql\Sql;
9
use Zend\Db\Sql\Ddl;
10
use Zend\Console\Prompt\Confirm;
11
use Zend\ServiceManager\ServiceLocatorAwareTrait;
12
use Zend\ServiceManager\ServiceLocatorInterface;
13
use Zend\Console\ColorInterface as Color;
14
15
/**
16
 * Generate class and methods for new migration
17
 *
18
 * @author     V.Leontiev <[email protected]>
19
 * @license    http://opensource.org/licenses/MIT MIT
20
 * @since      php 5.6 or higher
21
 * @see        https://github.com/newage/console-tools
22
 */
23
class Migration
24
{
25
    use ServiceLocatorAwareTrait;
26
27
    /**
28
     * Current db adapter
29
     *
30
     * @var Adapter
31
     */
32
    protected $adapter = null;
33
34
    /**
35
     * @var bool
36
     */
37
    protected $percona = false;
38
39
    /**
40
     * @var int
41
     */
42
    protected $port = false;
43
44
    /**
45
     * Migration table name of database
46
     *
47
     * @var string
48
     */
49
    const TABLE = 'migrations';
50
51
    /**
52
     * Constructor
53
     * Create migration table
54
     * Set current db adapter
55
     *
56
     * @param \Zend\Db\Adapter\Adapter $adapter
57
     */
58
    public function __construct($adapter = null, ServiceLocatorInterface $serviceLocator, $percona, $port)
0 ignored issues
show
Coding Style introduced by
Parameters which have default values should be placed at the end.

If you place a parameter with a default value before a parameter with a default value, the default value of the first parameter will never be used as it will always need to be passed anyway:

// $a must always be passed; it's default value is never used.
function someFunction($a = 5, $b) { }
Loading history...
59
    {
60
        $this->adapter = $adapter;
61
        $this->percona = $percona;
62
        $this->port = $port;
63
        $this->createTable();
64
        $this->setServiceLocator($serviceLocator);
65
    }
66
67
    /**
68
     * Create a migration table
69
     *
70
     * @return bool
71
     */
72
    public function createTable()
73
    {
74
        $sql = new Sql($this->adapter);
75
76
        try {
77
            $select = $sql->select(self::TABLE);
78
            $queryString = $sql->getSqlStringForSqlObject($select);
0 ignored issues
show
Deprecated Code introduced by
The method Zend\Db\Sql\Sql::getSqlStringForSqlObject() has been deprecated with message: Deprecated in 2.4. Use buildSqlString() instead

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
79
            $this->adapter->query($queryString, Adapter::QUERY_MODE_EXECUTE);
80
        } catch (\Exception $err) {
81
            $table = new Ddl\CreateTable(self::TABLE);
82
            $table->addColumn(new Ddl\Column\Integer('id'));
83
            $table->addColumn(new Ddl\Column\Char('migration', 255));
84
            $table->addColumn(new Ddl\Column\Text('up'));
85
            $table->addColumn(new Ddl\Column\Text('down'));
86
            $table->addColumn(new Ddl\Column\Integer('ignored', false, 0, array('length' => 1)));
87
88
            $table->addConstraint(new Ddl\Constraint\PrimaryKey('id'));
89
            $table->addConstraint(new Ddl\Constraint\UniqueKey(['migration'], 'unique_key'));
90
91
            $queryString = $sql->getSqlStringForSqlObject($table);
0 ignored issues
show
Deprecated Code introduced by
The method Zend\Db\Sql\Sql::getSqlStringForSqlObject() has been deprecated with message: Deprecated in 2.4. Use buildSqlString() instead

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
92
            $this->adapter->query($queryString, Adapter::QUERY_MODE_EXECUTE);
93
        }
94
    }
95
96
    /**
97
     * Get a last migration
98
     *
99
     * @return string
100
     */
101
    public function last()
102
    {
103
        $sql = new Sql($this->adapter);
104
        $select = $sql->select(self::TABLE);
105
        $select->columns(array(
106
            'last' => new Expression('MAX(id)'),
107
            'up',
108
            'down',
109
            'ignored'
110
        ));
111
112
        $selectString = $sql->getSqlStringForSqlObject($select);
0 ignored issues
show
Deprecated Code introduced by
The method Zend\Db\Sql\Sql::getSqlStringForSqlObject() has been deprecated with message: Deprecated in 2.4. Use buildSqlString() instead

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
113
        $results = $this->adapter->query($selectString, Adapter::QUERY_MODE_EXECUTE);
114
115
        return $results->current();
0 ignored issues
show
Bug introduced by
The method current does only exist in Zend\Db\Adapter\Driver\ResultInterface, but not in Zend\Db\Adapter\Driver\S...tSet\ResultSetInterface.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
116
    }
117
    /**
118
     * Get a last migration
119
     *
120
     * @param bool $isShow Show sql queries
0 ignored issues
show
Bug introduced by
There is no parameter named $isShow. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
121
     * @return string
122
     */
123
    public function get(array $where = [])
124
    {
125
        $sql = new Sql($this->adapter);
126
        $select = $sql->select(self::TABLE);
127
        $select->columns(array('*'));
128
        $select->where($where);
129
130
        $selectString = $sql->getSqlStringForSqlObject($select);
0 ignored issues
show
Deprecated Code introduced by
The method Zend\Db\Sql\Sql::getSqlStringForSqlObject() has been deprecated with message: Deprecated in 2.4. Use buildSqlString() instead

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
131
        $results = $this->adapter->query($selectString, Adapter::QUERY_MODE_EXECUTE);
132
133
        return $results->current();
0 ignored issues
show
Bug introduced by
The method current does only exist in Zend\Db\Adapter\Driver\ResultInterface, but not in Zend\Db\Adapter\Driver\S...tSet\ResultSetInterface.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
134
    }
135
136
    /**
137
     * Get applied a migrations name
138
     *
139
     * @return array
140
     */
141
    public function applied()
142
    {
143
        $migrationFiles = array();
144
        $sql = new Sql($this->adapter);
145
        $select = $sql->select();
146
        $select->from(self::TABLE);
147
148
        $selectString = $sql->getSqlStringForSqlObject($select);
0 ignored issues
show
Deprecated Code introduced by
The method Zend\Db\Sql\Sql::getSqlStringForSqlObject() has been deprecated with message: Deprecated in 2.4. Use buildSqlString() instead

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
149
        $results = $this->adapter->query($selectString, Adapter::QUERY_MODE_EXECUTE);
150
151
        if ($results->count() > 0) {
0 ignored issues
show
Bug introduced by
The method count does only exist in Zend\Db\Adapter\Driver\R...tSet\ResultSetInterface, but not in Zend\Db\Adapter\Driver\StatementInterface.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
152
            foreach ($results as $migration) {
0 ignored issues
show
Bug introduced by
The expression $results of type object<Zend\Db\Adapter\D...Driver\ResultInterface> is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
153
                $migrationFiles[] = $migration->migration;
154
            }
155
        }
156
157
        return $migrationFiles;
158
    }
159
160
    /**
161
     * Apply up on the migration
162
     * And insert migration name to base
163
     *
164
     * @param string $migrationName
165
     * @param array $migrationArray
166
     * @param bool $ignoreMigration
167
     * @param bool $doNotSaveAsExecuted
168
     * @throws \Exception
169
     * @internal param bool $ig
170
     */
171
    public function upgrade($migrationName, array $migrationArray, $ignoreMigration = false, $doNotSaveAsExecuted = false)
172
    {
173
        $connection = $this->adapter->getDriver()->getConnection();
174
        $connection->beginTransaction();
175
176
        try {
177
            if (!$ignoreMigration) {
178
                $this->executeQueriesOneByOne($migrationArray['up']);
179
            }
180
            if (!$doNotSaveAsExecuted) {
181
                $sql = new Sql($this->adapter);
182
                $insert = $sql->insert(self::TABLE);
183
                $insert->values(array(
184
                    'migration' => $migrationName,
185
                    'up' => $migrationArray['up'],
186
                    'down' => $migrationArray['down'],
187
                    'ignore' => (int)$ignoreMigration,
188
                ));
189
                $queryString = $sql->getSqlStringForSqlObject($insert);
0 ignored issues
show
Deprecated Code introduced by
The method Zend\Db\Sql\Sql::getSqlStringForSqlObject() has been deprecated with message: Deprecated in 2.4. Use buildSqlString() instead

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
190
                $this->adapter->query($queryString, Adapter::QUERY_MODE_EXECUTE);
191
            }
192
193
            $connection->commit();
194
        } catch (\Exception $exception) {
195
            $connection->rollback();
196
            throw new \Exception($exception->getMessage());
197
        }
198
    }
199
200
    /**
201
     * Apply down on the migration
202
     * And remove migration name from base
203
     *
204
     * @param string $migrationName
205
     * @param array $migrationArray
206
     * @param bool $ignore
207
     * @throws \Exception
208
     */
209
    public function downgrade($migrationName, array $migrationArray, $ignore = false)
210
    {
211
        $connection = $this->adapter->getDriver()->getConnection();
212
213
        try {
214
            $connection->beginTransaction();
215
216
            if (!$ignore) {
217
                $this->executeQueriesOneByOne($migrationArray['down']);
218
            }
219
220
            $sql = new Sql($this->adapter);
221
            $delete = $sql->delete(self::TABLE);
222
            $delete->where(array('migration' => $migrationName));
223
224
            $queryString = $sql->getSqlStringForSqlObject($delete);
0 ignored issues
show
Deprecated Code introduced by
The method Zend\Db\Sql\Sql::getSqlStringForSqlObject() has been deprecated with message: Deprecated in 2.4. Use buildSqlString() instead

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
225
            $this->adapter->query($queryString, Adapter::QUERY_MODE_EXECUTE);
226
227
            $connection->commit();
228
        } catch(\Exception $exception) {
0 ignored issues
show
Coding Style introduced by
Expected 1 space after CATCH keyword; 0 found
Loading history...
229
            $connection->rollback();
230
            throw new \Exception($exception->getMessage());
231
        }
232
    }
233
234
    /**
235
     * @param string $migration
236
     */
237
    protected function executeQueriesOneByOne($migration = '')
238
    {
239
        $console = $this->getServiceLocator()->get('console');
240
        $config = $this->getServiceLocator()->get('config');
241
        if (!isset($config['db'])) {
242
            throw new \RuntimeException('Does nto exist `db` config!');
243
        }
244
        $dbConfig = $config['db'];
245
246
        $queries = explode(';', $migration);
247
        foreach ($queries as $query) {
248
            $query = trim($query, " \t\n\r\0");
249
            if (!empty($query)) {
250
                if (Confirm::prompt($query . PHP_EOL . 'Run this query? [y/n]', 'y', 'n')) {
251
                    if ($this->executeInPerconaTool($query, $dbConfig) === false) {
252
                        $request = $this->adapter->query($query, Adapter::QUERY_MODE_EXECUTE);
253
254
                        if ($request instanceof ResultSetInterface) {
255
                            $console->writeLine('Affected rows: ' . $request->count(), Color::BLUE);
256
                        }
257
                    }
258
                } elseif (Confirm::prompt('Break execution and ROLLBACK? [y/n]', 'y', 'n')) {
259
                    $connection = $this->adapter->getDriver()->getConnection();
260
                    $connection->rollback();
261
                    exit;
262
                }
263
            }
264
        }
265
266
    }
267
268
    protected function executeInPerconaTool($query, $dbConfig): bool
269
    {
270
        if (stristr($query, 'ALTER TABLE') && $this->percona) {
271
            $cleanQuery = str_replace(['`', '\''], '', $query);
272
273
            preg_match('~ALTER TABLE\s([\w\d\_]+)\s(.*);?~smi', $cleanQuery, $matches);
274
            if (!isset($matches[1]) || !isset($matches[2])) {
275
                return false;
276
            }
277
            $console = $this->getServiceLocator()->get('console');
278
279
            $port = $dbConfig['port'];
280
            if (!empty($this->port)) {
281
                $port = $this->port;
282
            }
283
284
            $perconaString = sprintf(
285
                'pt-online-schema-change --execute --alter-foreign-keys-method=auto --password=%1$s --user=%2$s --alter "%6$s" D=%3$s,t=%5$s,h=%4$s,P=%7$s',
286
                $dbConfig['password'],
287
                $dbConfig['username'],
288
                $dbConfig['database'],
289
                $dbConfig['hostname'],
290
                $matches[1],
291
                $matches[2],
292
                $port
293
            );
294
            $result = shell_exec($perconaString);
295
            $console->writeLine('Percona response:', Color::BLUE);
296
            $console->writeLine($result, Color::WHITE);
297
            return true;
298
        }
299
        return false;
300
    }
301
}
302