Passed
Branch ops-updates (277b44)
by Björn
05:09
created

SetupController   A

Complexity

Total Complexity 18

Size/Duplication

Total Lines 114
Duplicated Lines 0 %

Test Coverage

Coverage 14.75%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 61
c 1
b 0
f 0
dl 0
loc 114
ccs 9
cts 61
cp 0.1475
rs 10
wmc 18

5 Methods

Rating   Name   Duplication   Size   Complexity  
F updatedbAction() 0 84 14
A onDispatch() 0 11 1
A indexAction() 0 3 1
A installAction() 0 3 1
A updateAction() 0 3 1
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
    public function onDispatch(\Zend\Mvc\MvcEvent $e)
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
The assignment to $result is dead and can be removed.
Loading history...
68
69
        $only_testing = $request->getParam('test', false);
0 ignored issues
show
Bug introduced by
false of type false is incompatible with the type string expected by parameter $default of Zend\Console\Request::getParam(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

69
        $only_testing = $request->getParam('test', /** @scrutinizer ignore-type */ false);
Loading history...
70
        $be_verbose = $request->getParam('verbose', false);
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
            if ($be_verbose) { echo 'EXCEPTION: ' . PHP_EOL . print_r($ex, true) . PHP_EOL; 
0 ignored issues
show
Bug introduced by
Are you sure print_r($ex, true) of type string|true can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

101
            if ($be_verbose) { echo 'EXCEPTION: ' . PHP_EOL . /** @scrutinizer ignore-type */ print_r($ex, true) . PHP_EOL; 
Loading history...
102
            }
103
        }
104
        if (!is_array($compareResult) || (count($compareResult) < 1) ) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $compareResult does not seem to be defined for all execution paths leading up to this point.
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
The assignment to $updateResult is dead and can be removed.
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
                if ($be_verbose) { echo 'EXCEPTION: ' . PHP_EOL . print_r($ex, true) . PHP_EOL; 
132
                }
133
            }
134
        }
135
        
136
        return 0;
137
    }
138
}
139