Intraface_Install   B
last analyzed

Complexity

Total Complexity 46

Size/Duplication

Total Lines 253
Duplicated Lines 25.3 %

Coupling/Cohesion

Components 1
Dependencies 10

Importance

Changes 0
Metric Value
dl 64
loc 253
rs 8.3999
c 0
b 0
f 0
wmc 46
lcom 1
cbo 10

12 Methods

Rating   Name   Duplication   Size   Complexity  
B __construct() 0 14 6
A dropDatabase() 15 15 4
C createDatabaseSchema() 14 25 7
A emptyDatabase() 15 15 4
A createStartingValues() 7 14 4
B resetServer() 0 28 4
B deleteUploadDirectory() 13 13 5
B grantModuleAccess() 0 30 4
A loginUser() 0 11 1
B runHelperFunction() 0 29 3
A registerModules() 0 6 1
A splitSql() 0 16 3

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like Intraface_Install often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Intraface_Install, and based on these observations, apply Extract Interface, too.

1
<?php
2
class Intraface_Install
3
{
4
    /**
5
     * @var object database connection
6
     */
7
    private $db;
8
9
    /**
10
     * constructor. Checks if the script can be run. Connects to database.
11
     */
12
    function __construct()
0 ignored issues
show
Coding Style introduced by
__construct uses the super-global variable $_SERVER which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
13
    {
14
        if (!defined('SERVER_STATUS') OR SERVER_STATUS == 'PRODUCTION') {
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
Coding Style introduced by
As per coding-style, PHP keywords should be in lowercase; expected or, but found OR.
Loading history...
15
            die('Can not be performed on PRODUCTION SERVER');
0 ignored issues
show
Coding Style Compatibility introduced by
The method __construct() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
16
        } elseif (!empty($_SERVER['HTTP_HOST']) AND $_SERVER['HTTP_HOST'] == 'www.intraface.dk') {
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as and instead of && is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
Coding Style introduced by
As per coding-style, PHP keywords should be in lowercase; expected and, but found AND.
Loading history...
17
            die('Can not be performed on www.intraface.dk');
0 ignored issues
show
Coding Style Compatibility introduced by
The method __construct() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
18
        }
19
20
        $this->db = MDB2::singleton(DB_DSN);
21
22
        if (PEAR::isError($this->db)) {
23
            throw new Exception($this->db->getUserInfo());
24
        }
25
    }
26
27 View Code Duplication
    function dropDatabase()
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...
28
    {
29
        $result = $this->db->query("SHOW TABLES FROM " . DB_NAME);
30
        if (PEAR::isError($result)) {
31
            throw new Exception($result->getUserInfo());
32
        }
33
34
        while ($line = $result->fetchRow(MDB2_FETCHMODE_ASSOC)) {
35
            $drop = $this->db->exec('DROP TABLE ' . $line['tables_in_' . DB_NAME]);
36
            if (PEAR::IsError($drop)) {
37
                throw new Exception($drop->getUserInfo());
38
            }
39
        }
40
        return true;
41
    }
42
43
    function createDatabaseSchema()
44
    {
45
        $sql_structure = file_get_contents(dirname(__FILE__) . '/database-structure.sql');
46
        $sql_arr = Intraface_Install::splitSql($sql_structure);
47
48 View Code Duplication
        foreach ($sql_arr as $sql) {
49
            if (empty($sql)) { continue; }
50
            $result = $this->db->exec($sql);
51
            if (PEAR::isError($result)) {
52
                throw new Exception($result->getUserInfo());
53
            }
54
        }
55
56
        $sql_structure = file_get_contents(dirname(__FILE__) . '/database-update.sql');
57
        $sql_arr = Intraface_Install::splitSql($sql_structure);
58
59 View Code Duplication
        foreach ($sql_arr as $sql) {
60
            if (empty($sql)) { continue; }
61
            $result = $this->db->exec($sql);
62
            if (PEAR::isError($result)) {
63
                throw new Exception($result->getUserInfo());
64
            }
65
        }
66
        return true;
67
    }
68
69 View Code Duplication
    function emptyDatabase()
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...
70
    {
71
        $result = $this->db->query("SHOW TABLES FROM " . DB_NAME);
72
        if (PEAR::isError($result)) {
73
            throw new Exception($result->getUserInfo());
74
        }
75
        while ($line = $result->fetchRow(MDB2_FETCHMODE_ASSOC)) {
76
            $truncate = $this->db->exec('TRUNCATE TABLE ' . $line['Tables_in_'.DB_NAME]);
77
            if (PEAR::IsError($truncate)) {
78
                throw new Exception($truncate->getUserInfo());
79
            }
80
        }
81
        return true;
82
83
    }
84
85
    function createStartingValues()
86
    {
87
        $sql_values = file_get_contents(dirname(__FILE__) . '/database-values.sql');
88
        $sql_arr = Intraface_Install::splitSql($sql_values);
89
90 View Code Duplication
        foreach ($sql_arr as $sql) {
91
            if (empty($sql)) { continue; }
92
            $result = $this->db->exec($sql);
93
            if (PEAR::isError($result)) {
94
                throw new Exception($result->getUserInfo());
95
            }
96
        }
97
        return true;
98
    }
99
100
    function resetServer()
101
    {
102
        /*
0 ignored issues
show
Unused Code Comprehensibility introduced by
64% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
103
        if (!$this->dropDatabase()) {
104
            throw new Exception('could not drop database');
105
        }
106
        if (!$this->createDatabaseSchema()) {
107
            throw new Exception('could not create schema');
108
        }
109
        */
110
111
        if (!$this->emptyDatabase()) {
112
            throw new Exception('could not empty database');
113
        }
114
115
        if (!$this->createStartingValues()) {
116
            throw new Exception('could not create values');
117
        }
118
119
        $this->deleteUploadDirectory(PATH_UPLOAD);
120
121
        if (!file_exists(PATH_UPLOAD)) {
122
            mkdir(PATH_UPLOAD);
123
        }
124
125
        return true;
126
127
    }
128
129 View Code Duplication
    function deleteUploadDirectory($f)
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...
130
    {
131
        if ( is_dir( $f ) ){
132
            foreach ( scandir( $f ) as $item ){
0 ignored issues
show
Coding Style introduced by
Space found after opening bracket of FOREACH loop
Loading history...
Coding Style introduced by
Space found before closing bracket of FOREACH loop
Loading history...
133
                if ( !strcmp( $item, '.' ) || !strcmp( $item, '..' ) )
0 ignored issues
show
Coding Style Best Practice introduced by
It is generally a best practice to always use braces with control structures.

Adding braces to control structures avoids accidental mistakes as your code changes:

// Without braces (not recommended)
if (true)
    doSomething();

// Recommended
if (true) {
    doSomething();
}
Loading history...
134
                    continue;
135
                $this->deleteUploadDirectory( $f . "/" . $item );
136
            }
137
            rmdir( $f );
138
        } else{
139
            @unlink( $f );
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
140
        }
141
    }
142
143
    /**
144
     * grants access to given modules
145
     */
146
    public function grantModuleAccess($modules)
147
    {
148
        $this->registerModules();
149
        $modules = explode(',', $modules);
150
151
        require_once 'Intraface/modules/intranetmaintenance/IntranetMaintenance.php';
152
        // The moduleaccess only goes for intranet_id 1
153
        $intranet = new IntranetMaintenance(1);
154
        require_once 'Intraface/modules/intranetmaintenance/UserMaintenance.php';
155
        $user = new UserMaintenance(1);
156
        $user->setIntranetAccess(1);
157
158
        require_once 'Intraface/modules/intranetmaintenance/ModuleMaintenance.php';
159
        foreach ($modules as $module_name) {
160
            $module = ModuleMaintenance::factory($module_name);
161
162
            if ($module->get('id') == 0) {
163
                throw new Exception('Invalid module '.$module_name);
164
            }
165
            $intranet->setModuleAccess($module->get('id'));
166
            $user->setModuleAccess($module->get('id'), 1);
167
            $sub_accesss = $module->get('sub_access');
168
            foreach ($sub_accesss as $sub_access) {
169
                $user->setSubAccess($module->get('id'), $sub_access['id'], 1);
170
            }
171
        }
172
173
        return true;
174
175
    }
176
177
    /**
178
     * login the user
179
     */
180
    function loginUser()
181
    {
182
        /* session_start(); */ // session_start is in reset_staging_server. Should only be one place.
183
184
        $adapter = new Intraface_Auth_User($this->db, session_id(), '[email protected]', 'startup');
185
        $auth = new Intraface_Auth(session_id());
186
        $user = $auth->authenticate($adapter);
187
188
        return $user;
189
190
    }
191
192
    /**
193
     * run helper functions
194
     */
195
    public function runHelperFunction($functions)
196
    {
197
        $functions = explode(',', $functions);
198
199
        // We create kernel so it can be used in the helper functions
200
        if (session_id() != '') {
201
            $kernel = new Intraface_Kernel(session_id());
202
        } else {
203
            $kernel = new Intraface_Kernel;
204
        }
205
        $kernel->user = new Intraface_User(1);
206
        $kernel->user->setIntranetId(1);
207
        $kernel->intranet = new Intraface_Intranet(1);
208
        $kernel->setting = new Intraface_Setting(1, 1);
209
210
        // adds the intranet_id to Doctrine!
211
        Intraface_Doctrine_Intranet::singleton(1);
212
213
        foreach ($functions AS $function) {
0 ignored issues
show
Coding Style introduced by
AS keyword must be lowercase; expected "as" but found "AS"
Loading history...
Coding Style introduced by
As per coding-style, PHP keywords should be in lowercase; expected as, but found AS.
Loading history...
214
            $object_method = explode(':', trim($function));
215
            $object_method[0] = str_replace('/', '', $object_method[0]);
216
            $object_method[0] = str_replace('\\', '', $object_method[0]);
217
218
            require_once dirname(__FILE__) . '/Helper/'.$object_method[0].'.php';
219
            $object_name = 'Install_Helper_'.$object_method[0];
220
            $object = new $object_name($kernel, $this->db);
221
            $object->$object_method[1]();
222
        }
223
    }
224
225
    /**
226
     * register modules
227
     */
228
    private function registerModules()
229
    {
230
        require_once 'Intraface/modules/intranetmaintenance/ModuleMaintenance.php';
231
        $modulemaintenance = new ModuleMaintenance;
232
        $modulemaintenance->register();
233
    }
234
235
    /**
236
     * splits a mysql export into separate
237
     */
238
    static function splitSql($sql)
239
    {
240
        if (strpos($sql, "\r\n")) {
241
            $str_sep = "\r\n";
242
        } else {
243
            $str_sep = "\n";
244
        }
245
        if (substr($sql, 0, 2) == '--') {
246
            $sql = substr($sql, strpos($sql, $str_sep));
247
        }
248
        $sql = preg_replace($str_sep."/--[a-zA-Z0-9\/\:\`,. _-]*/", '', $sql);
249
        $parts = preg_split("/;( )*".$str_sep.'/', $sql);
250
        $parts = array_map('trim', $parts);
251
        return $parts;
252
253
    }
254
}
255