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.
Completed
Push — master ( f9f70e...107e1c )
by Vadim
10:28
created

MigrationController::isApplySchema()   A

Complexity

Conditions 4
Paths 8

Size

Total Lines 16
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 16
rs 9.2
c 0
b 0
f 0
cc 4
eloc 10
nc 8
nop 2
1
<?php
2
3
namespace ConsoleTools\Controller;
4
5
use Zend\Db\Adapter\Adapter;
6
use Zend\Mvc\Controller\AbstractActionController;
7
use Zend\Console\ColorInterface as Color;
8
use Zend\Console\Adapter\AdapterInterface as Console;
9
use Zend\Console\Exception\RuntimeException;
10
use ConsoleTools\Model\Migration;
11
use Zend\Console\Prompt\Char;
12
13
/**
14
 * Controller for console operations as create, upgrate and current migrations
15
 * 
16
 * @author     V.Leontiev <[email protected]>
17
 * @license    http://opensource.org/licenses/MIT MIT
18
 * @since      php 5.3 or higher
19
 * @see        https://github.com/newage/console-tools
20
 */
21
class MigrationController extends AbstractActionController
22
{
23
    const UPGRADE_KEY = 'up';
24
    const DOWNGRADE_KEY = 'down';
25
26
    /**
27
     * Destination to folder with migration files
28
     * 
29
     * @var string
30
     */
31
    protected $migrationFolder = null;
32
33
    /**
34
     * Execute one migration
35
     * 
36
     */
37
    public function executeAction()
38
    {
39
        /* @var $console Console */
40
        $console   = $this->getServiceLocator()->get('console');
41
        $request   = $this->getRequest();
42
        $migration = $request->getParam('number');
43
        
44
        $migrationPath = $this->getMigrationFolder();
45
        $filePath = $migrationPath . $migration . '.php';
46
47
        if (!file_exists($filePath)) {
48
            $console->writeLine('Migration does not exists: ' . $filePath, Color::RED);
49
        } else {
50
            if (!$this->isApplySchema($console)) {
51
                false;
52
            }
53
54
            $migrationArray = $this->includeMigration($filePath);
55
56
            if ($request->getParam(self::UPGRADE_KEY)) {
57
                $this->applyMigration(self::UPGRADE_KEY, $migration, $migrationArray);
58
            } elseif ($request->getParam(self::DOWNGRADE_KEY)) {
59
                $this->applyMigration(self::DOWNGRADE_KEY, $migration, $migrationArray);
60
            }
61
        }
62
    }
63
64
    /**
65
     * Show confirm for migration
66
     *
67
     * @param string $action
68
     * @param string $migration
69
     * @param array $migrationArray
70
     * @return bool
71
     */
72
    protected function applyMigration($action, $migration, $migrationArray)
73
    {
74
        /* @var $adapter \Zend\Db\Adapter\Adapter */
75
        /* @var $console Console */
76
        $adapter    = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
77
        $console    = $this->getServiceLocator()->get('console');
78
        $model      = new Migration($adapter);
0 ignored issues
show
Documentation introduced by
$adapter is of type object|array, but the function expects a object<Zend\Db\Adapter\Adapter>|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
79
        $methodName = $action == self::UPGRADE_KEY ? 'upgrade' : 'downgrade';
80
81
        $console->writeLine();
82
        $console->write('Current migration: ');
83
        $console->writeLine($this->getMigrationFolder() . $migration . '.php', Color::YELLOW);
84
        $console->writeLine($migrationArray[$action], Color::BLUE);
85
        $exist = $model->get(array('migration' => $migration));
86
        $doNotSaveAsExecuted = false;
87
        if (!empty($exist) && empty($exist['ignored'])) {
88
            $console->writeLine('This migration was already executed', Color::YELLOW);
89
            $doNotSaveAsExecuted = true;
90
        } elseif (!empty($exist) && !empty($exist['ignored'])) {
91
            $console->writeLine('This migration was already pseudo-executed (ignored)', Color::LIGHT_CYAN);
92
        }
93
        $answer = Char::prompt('Apply this migration (Yes / no / ignore forever)? [y/n/i]', 'yni');
94
        switch ($answer) {
95
            case 'y':
96
                if ($action == self::UPGRADE_KEY) {
97
                    $model->$methodName($migration, $migrationArray, $ignore = false, $doNotSaveAsExecuted);
98
                    $console->writeLine('This migration successful upgraded', Color::GREEN);
99
                } else {
100
                    $model->$methodName($migration, $migrationArray, $ignore = false);
101
                    $console->writeLine('This migration successful downgraded', Color::GREEN);
102
                }
103
            break;
104
            case 'i':
105
                $model->$methodName($migration, $migrationArray, $ignore = true);
106
                if ($action == self::UPGRADE_KEY) {
107
                    $console->writeLine('This migration pseudo-upgraded', Color::LIGHT_CYAN);
108
                } else {
109
                    $console->writeLine('This migration pseudo-downgraded', Color::LIGHT_CYAN);
110
                }
111
            break;
112
            case 'n':
113
            default:
114
                $console->writeLine('This migration discarded', Color::RED);
115
                return false;
116
            break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
117
        }
118
119
        return true;
120
    }
121
122
    /**
123
     * Create new migration file
124
     * 
125
     * @throws RuntimeException
126
     */
127
    public function createAction()
128
    {
129
        $console = $this->getServiceLocator()->get('console');
130
131
        if (!$console instanceof Console) {
132
            throw new RuntimeException('Cannot obtain console adapter. Are we running in a console?');
133
        }
134
        $request = $this->getRequest();
135
        $short_name = $request->getParam('short_name', '');
136
137
        $config = $this->getServiceLocator()->get('Config');
138
        if (isset($config['console-tools']['migration_template'])) {
139
            $dateTemplate = $config['console-tools']['migration_template'];
140
        } else {
141
            $dateTemplate = 'YmdHis';
142
        }
143
144
        $migrationPath = $this->getMigrationFolder();
145
        if (!is_dir($migrationPath)) {
146
            mkdir($migrationPath, 0777);
147
        }
148
149
        $date = new \DateTime();
150
        if ($short_name) {
151
            $short_name = '_' . $short_name;
152
        }
153
        
154
        $migrationName = $date->format($dateTemplate) . $short_name . '.php';
155
        
156
        $migrationContent = <<<EOD
157
<?php
158
        
159
return [
160
    'up' => "",
161
    'down' => ""
162
];
163
164
EOD;
165
        
166
        file_put_contents($migrationPath . $migrationName, $migrationContent);
167
        
168
        $console->writeLine('Created migration file: ' . $migrationPath . $migrationName, Color::GREEN);
169
    }
170
    
171
    /**
172
     * Upgrade/downgrade to migration
173
     * 
174
     * @throws RuntimeException
175
     */
176
    public function upgradeAction()
177
    {
178
        $console = $this->getServiceLocator()->get('console');
179
        if (!$console instanceof Console) {
180
            throw new RuntimeException('Cannot obtain console adapter. Are we running in a console?');
181
        }
182
        
183
        $adapter             = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
184
        $model               = new Migration($adapter);
0 ignored issues
show
Documentation introduced by
$adapter is of type object|array, but the function expects a object<Zend\Db\Adapter\Adapter>|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
185
        $request             = $this->getRequest();
186
        $toMigration         = $request->getParam('number', 'all');
187
        $migrationsFromBase  = $model->applied();
188
        $migrationFolderPath = $this->getMigrationFolder();
189
        $files               = array();
190
191
        if (!$this->isApplySchema($console, $adapter)) {
0 ignored issues
show
Documentation introduced by
$adapter is of type object|array, but the function expects a null|object<Zend\Db\Adapter\Adapter>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
192
            false;
193
        }
194
195
        if ($toMigration == 'all') {
196
            $filesDirty = scandir($migrationFolderPath);
197
            for ($i=0; $i<count($filesDirty); $i++) {
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
198
                if (substr($filesDirty[$i], 0, 1) != '.') {
199
                    array_push($files, substr($filesDirty[$i], 0, -4));
200
                }
201
            }
202
            $filesFromDrive = array_diff($files, $migrationsFromBase);
203
            asort($files, SORT_NATURAL);
204
            $files = array_diff($filesFromDrive, $migrationsFromBase);
205
            asort($files, SORT_NATURAL);
206
            $upgradeAction = self::UPGRADE_KEY;
207
        } elseif (in_array($toMigration, $migrationsFromBase)) {
208
            $key = array_search($toMigration, $migrationsFromBase);
209
            $files = array_slice($migrationsFromBase, $key);
210
            rsort($files, SORT_NATURAL);
211
            $upgradeAction = self::DOWNGRADE_KEY;
212
        } else {
213
            $console->writeLine('Did not apply the migration: ' . $toMigration, Color::RED);
214
            return false;
215
        }
216
        
217
        if (!count($files)) {
218
            $console->writeLine('You have last version of database', Color::GREEN);
219
            return false;
220
        }
221
        
222
        foreach ($files as $migration) {
223
            $migrationPath = $migrationFolderPath .
224
                DIRECTORY_SEPARATOR . $migration . '.php';
225
226
            $migrationArray = $this->includeMigration($migrationPath);
227
228
            try {
229
                switch ($upgradeAction) {
230
                    case self::DOWNGRADE_KEY:
231
                        //downgrade action
232
                        $this->applyMigration(self::DOWNGRADE_KEY, $migration, $migrationArray);
233
                        break;
234
                    case self::UPGRADE_KEY:
235
                        //upgrade action
236
                        $this->applyMigration(self::UPGRADE_KEY, $migration, $migrationArray);
237
                        break;
238
                    default:
239
                        throw new \Exception('Not set action');
240
                        break;
0 ignored issues
show
Unused Code introduced by
break; does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
241
                }
242
                continue;
243
            } catch (\Exception $err) {
244
                $console->writeLine('Current migration failed commit', Color::RED);
245
                $console->writeLine($err->getMessage(), Color::RED);
246
                return false;
247
            }
248
        }
249
    }
250
251
    /**
252
     * Show last applied migration number
253
     * 
254
     */
255
    public function lastAction()
256
    {
257
        $console = $this->getServiceLocator()->get('console');
258
        if (!$console instanceof Console) {
259
            throw new RuntimeException('Cannot obtain console adapter. Are we running in a console?');
260
        }
261
262
        $request = $this->getRequest();
263
        $adapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
264
        $model = new Migration($adapter);
0 ignored issues
show
Documentation introduced by
$adapter is of type object|array, but the function expects a object<Zend\Db\Adapter\Adapter>|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
265
        $lastMigration = $model->last();
266
267
        $migrationName = $this->getMigrationFolder() . $lastMigration->last . '.php';
268
        if ($request->getParam('show')) {
269
            $console->writeLine('Last applied the migration: ' . $migrationName, Color::GREEN);
270
            $console->writeLine('=== Up SQL ===', Color::YELLOW);
271
            $console->writeLine($lastMigration->up, Color::GREEN);
272
            $console->writeLine('=== Down SQL ===', Color::YELLOW);
273
            $console->writeLine($lastMigration->down, Color::GREEN);
274
        } else {
275
            $console->writeLine('Last applied the migration: ' . $migrationName, Color::GREEN);
276
        }
277
    }
278
279
    /**
280
     * @param Console|null $console
281
     * @param Adapter|null $adapter
282
     * @return bool
283
     */
284
    protected function isApplySchema(Console $console = null, Adapter $adapter = null)
285
    {
286
        if ($console === null) {
287
            $console = $this->getServiceLocator()->get('console');
288
        }
289
        if ($adapter === null) {
290
            $adapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
291
        }
292
293
        $console->writeLine('Current schema: '.$adapter->getCurrentSchema(), Color::GREEN);
294
        $answer = Char::prompt('The schema is correct (Yes/No)? [y/n]', 'yn');
295
        if ($answer == 'n') {
296
            return false;
297
        }
298
        return true;
299
    }
300
301
    /**
302
     * Get migration folder from config file
303
     *
304
     * @return string
305
     */
306
    protected function getMigrationFolder()
307
    {
308
        if ($this->migrationFolder === null) {
309
            $config = $this->getServiceLocator()->get('config');
310
            $this->migrationFolder = getcwd() . '/' . $config['console-tools']['migration_folder'] . '/';
311
        }
312
313
        return $this->migrationFolder;
314
    }
315
316
    /**
317
     * @param $migrationPath
318
     * @return mixed
319
     */
320
    protected function includeMigration($migrationPath)
321
    {
322
        $migrationArray = include $migrationPath;
323
324
        return $migrationArray;
325
    }
326
}
327