Passed
Push — master ( 700b0f...aafb0a )
by Björn
18:25 queued 10s
created

SetupController::updatedbAction()   F

Complexity

Conditions 14
Paths 341

Size

Total Lines 85

Duplication

Lines 4
Ratio 4.71 %

Code Coverage

Tests 0
CRAP Score 210

Importance

Changes 0
Metric Value
dl 4
loc 85
ccs 0
cts 48
cp 0
rs 3.2639
c 0
b 0
f 0
cc 14
nc 341
nop 0
crap 210

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * BB's Zend Framework 2 Components
4
 * 
5
 * BaseApp
6
 *
7
 * @package   [MyApplication]
8
 * @package   BB's Zend Framework 2 Components
9
 * @package   BaseApp
10
 * @author    Björn Bartels <[email protected]>
11
 * @link      https://gitlab.bjoernbartels.earth/groups/zf2
12
 * @license   http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0
13
 * @copyright copyright (c) 2016 Björn Bartels <[email protected]>
14
 */
15
16
namespace Application\Controller;
17
18
use Zend\Console\Request as ConsoleRequest;
19
use Zend\View\Model\ViewModel;
20
use Application\Controller\BaseActionController;
21
use Application\Model\DbStructUpdater;
22
23
class SetupController extends BaseActionController
24
{
25
    
26 1 View Code Duplication
    public function onDispatch(\Zend\Mvc\MvcEvent $e)
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...
27
    {
28 1
        $this->setActionTitles(
29
            array(
30 1
            'index' => $this->translate("setup"),
31 1
            'install' => $this->translate("install"),
32 1
            'update' => $this->translate("update"),
33 1
            'updatedb' => $this->translate("update database structure"),
34
            )
35
        );
36 1
        return parent::onDispatch($e);
37
    }
38 1
    public function indexAction()
39
    {
40 1
        return new ViewModel();
41
    }
42
    
43
    public function installAction()
44
    {
45
        return new ViewModel();
46
    }
47
    
48
    public function updateAction()
49
    {
50
        return new ViewModel();
51
    }
52
    
53
    public function updatedbAction()
54
    {
55
56
        echo 'update database structure...' . PHP_EOL;
57
        
58
        $request = $this->getRequest();
59
        $db = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
60
        $config = $this->getServiceLocator()->get('Config');
61
        
62
        // Make sure that we are running in a console and the user has not tricked our
63
        // application into running this action from a public web server.
64
        if (!$request instanceof ConsoleRequest) {
65
            throw new \RuntimeException('You can only use this action from a console!');
66
        }
67
        $result = '';
0 ignored issues
show
Unused Code introduced by
$result is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
68
69
        $only_testing = $request->getParam('test', false);
0 ignored issues
show
Documentation introduced by
false is of type boolean, but the function expects a string|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...
70
        $be_verbose = $request->getParam('verbose', false);
0 ignored issues
show
Documentation introduced by
false is of type boolean, but the function expects a string|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...
71
72
        if ($be_verbose) { echo 'current path: ' . getcwd() . PHP_EOL; 
73
        }
74
        
75
        // get tables
76
        $sql = $db->query("SHOW TABLES;");
77
        $tables = $sql->execute();
78
        $tableQueries = array();
79
        foreach ($tables as $table) { //while ($table = $tables->current()) {
80
            $tableName = $table["Tables_in_".$config["db"]["database"]];
81
             // describe tables
82
            $tableSql = $db->query("SHOW CREATE TABLE `" . $tableName . "`;");
83
            $tableCreate = $tableSql->execute();
84
            $tableSpec = $tableCreate->current();
85
            $tableQueries[] = $tableSpec["Create Table"].";";
86
        }
87
        $currentStructure = implode("\n", $tableQueries);
88
        
89
        // read INSTALL.SQL
90
        $filename = getcwd() ."". "/sql/install.sql";
91
        $installSQL = file_get_contents($filename);
92
        //file_put_contents(getcwd() ."". "/sql/current.sql", $currentStructure);
93
        
94
        // compare SQLs
95
        try {
96
            $structureUpdater = new DbStructUpdater();
97
            $compareResult = $structureUpdater->getUpdates($currentStructure, $installSQL);
98
            //$compareResult = $structureUpdater->getUpdates($installSQL, $currentStructure);
99
        } catch (\Exception $ex) {
100
            echo 'ERROR COMPARING DATABASE STRUCTURE! ' . PHP_EOL;
101 View Code Duplication
            if ($be_verbose) { echo 'EXCEPTION: ' . PHP_EOL . print_r($ex, true) . PHP_EOL; 
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
102
            }
103
        }
104
        if (!is_array($compareResult) || (count($compareResult) < 1) ) {
0 ignored issues
show
Bug introduced by
The variable $compareResult does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
105
            echo '...database is up-to-date, no actions needed.' . PHP_EOL;
106
            return 0;
107
        }
108
            
109
        // transaction(!): update db
110
        
111
        if ($only_testing) {
112
            echo 'testing mode...' . PHP_EOL;
113
            echo 'detected sql update statements:' . PHP_EOL;
114
            echo  implode(";\n", $compareResult).";" . PHP_EOL;
115
        } else {
116
            try {
117
                $dbConnection = $db->getDriver()->getConnection();
118
                $dbConnection->beginTransaction();
119
                foreach ($compareResult as $updateSql) {
120
                    if ($be_verbose) { echo 'executing sql: ' . $updateSql . PHP_EOL; 
121
                    }
122
                    $dbupdate = $db->query($updateSql);
123
                    $updateResult = $dbupdate->execute();
0 ignored issues
show
Unused Code introduced by
$updateResult is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
124
                    if ($be_verbose) { echo '...done' . PHP_EOL; 
125
                    }
126
                }
127
                $dbConnection->commit();
128
            } catch (\Exception $ex) {
129
                $dbConnection->rollback();
130
                echo 'ERROR COMPARING DATABASE STRUCTURE! ' . PHP_EOL;
131 View Code Duplication
                if ($be_verbose) { echo 'EXCEPTION: ' . PHP_EOL . print_r($ex, true) . PHP_EOL; 
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
132
                }
133
            }
134
        }
135
        
136
        return 0;
137
    }
138
}
139