Intraface_Controller_Restricted::getSubmenu()   D
last analyzed

Complexity

Conditions 10
Paths 4

Size

Total Lines 43
Code Lines 30

Duplication

Lines 26
Ratio 60.47 %

Code Coverage

Tests 0
CRAP Score 110

Importance

Changes 0
Metric Value
cc 10
eloc 30
nc 4
nop 0
dl 26
loc 43
rs 4.8196
c 0
b 0
f 0
ccs 0
cts 40
cp 0
crap 110

How to fix   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
class Intraface_Controller_Restricted extends k_Component
3
{
4
    protected $mdb2;
5
    protected $db_sql;
6
    protected $kernel;
7
    protected $user_gateway;
8
    protected $kernel_gateway;
9
    protected $template;
10
    protected $cache;
11
12
    function __construct(Cache_Lite $cache, DB_Sql $db_sql, MDB2_Driver_Common $mdb2, Intraface_UserGateway $gateway, Intraface_KernelGateway $kernel_gateway, k_TemplateFactory $template)
13
    {
14
        $this->mdb2 = $mdb2; // this is here to make sure set names utf8 is run as the first thing in the app
15
        $this->db_sql = $db_sql;
16
        $this->user_gateway = $gateway;
17
        $this->kernel_gateway = $kernel_gateway;
18
        $this->template = $template;
19
        $this->cache = $cache;
20
    }
21
22
    function document()
23
    {
24
        return $this->document;
25
    }
26
27
    protected function map($name)
28
    {
29
        if ($name == 'switchintranet') {
30
            return 'Intraface_Controller_SwitchIntranet';
31
        } elseif ($name == 'module') {
32
            return 'Intraface_Controller_ModuleGatekeeper';
33
        }
34
    }
35
36
    function dispatch()
37
    {
38
        if ($this->identity()->anonymous()) {
39
            throw new k_NotAuthorized();
40
        }
41
42
        return parent::dispatch();
43
    }
44
45
    function renderHtml()
46
    {
47
        $this->document->setTitle('Dashboard');
48
49
        $_advice[] = array();
0 ignored issues
show
Coding Style Comprehensibility introduced by
$_advice was never initialized. Although not strictly required by PHP, it is generally a good practice to add $_advice = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
50
        $_attention_needed[] = array();
0 ignored issues
show
Coding Style Comprehensibility introduced by
$_attention_needed was never initialized. Although not strictly required by PHP, it is generally a good practice to add $_attention_needed = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
51
        if (in_array($this->query('message'), array('hide'))) {
52
            $this->getKernel()->setting->set('user', 'homepage.message', 'hide');
53
        }
54
55
        $kernel = $this->getKernel();
56
57
        // getting stuff to show on the dashboard
58
        $modules = $this->getKernel()->getModules();
59
60
        foreach ($modules as $module) {
61
            if (!$this->getKernel()->intranet->hasModuleAccess(intval($module['id']))) {
62
                continue;
63
            }
64
            if (!$this->getKernel()->user->hasModuleAccess(intval($module['id']))) {
65
                continue;
66
            }
67
68
            $module = $this->getKernel()->useModule($module['name']);
69
            $frontpage_files = $module->getFrontpageFiles();
70
71
            if (!is_array($frontpage_files) or count($frontpage_files) == 0) {
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...
72
                continue;
73
            }
74
75
            foreach ($frontpage_files as $file) {
76
                $file = PATH_INCLUDE_MODULE . $module->getName() . '/' .$file;
77
                if (file_exists($file)) {
78
                    include($file);
79
                }
80
            }
81
        }
82
        // Adds link for id user details is filled in. They are going to be in the top.
83
        if ($this->getKernel()->user->hasModuleAccess('controlpanel')) {
84
            if (!$this->getKernel()->user->isFilledIn()) {
85
                $_advice[] = array(
86
                    'msg' => 'all information about you has not been filled in',
87
                    'link' => $this->url('core/restricted/module/controlpanel/user', array('edit')),
88
                    'module' => 'dashboard'
89
                );
90
            }
91
        }
92
93
        $data = array(
94
            '_attention_needed' => $_attention_needed,
95
            '_advice' => $_advice
96
        );
97
98
        $smarty = $this->template->create(dirname(__FILE__) . '/templates/restricted');
99
        return $smarty->render($this, $data);
100
    }
101
102
    function wrapHtml($content)
103
    {
104
        if ($this->document()->title() == 'No Title') {
105
            $this->document->setTitle('Intraface.dk');
106
        }
107
108
        $tpl = $this->template->create(dirname(__FILE__) . '/templates/main');
109
        $content = $tpl->render($this, array('content' => $content));
110
        return new k_HttpResponse(200, $content);
111
    }
112
113
    function execute()
114
    {
115
        return $this->wrap(parent::execute());
116
    }
117
118
    /**
119
     * @todo Maybe move to a user object implementing getIntranet()
120
     * In $intranet we can have the transient gateways.
121
     *
122
     * class component_ShowProduct {
123
     *   protected $user_gateway;
124
     *   function __construct(UserGateway $user_gateway) {
125
     *     $this->user_gateway = $user_gateway;
126
     *   }
127
     *   function GET() {
128
     *     $user = $user_gateway->getByUsername($this->identity()->getUsername());
129
     *     return $this->render('product.tpl.php', array('product' => $user->getIntranet()->getProduct()));
130
     *   }
131
     * }
132
     *
133
     * http://pastie.org/683209
134
     *
135
     * @return object
136
     */
137
    function getKernel()
138
    {
139
        if (is_object($this->kernel)) {
140
            return $this->kernel;
141
        }
142
        try {
143
            return $this->kernel = $this->kernel_gateway->findByUserobject($this->user_gateway->findByUsername($this->identity()->user()));
144
        } catch (Exception $e) {
145
            return new k_SeeOther($this->url('/logout'));
146
        }
147
    }
148
149
    function getLastView()
150
    {
151
        $last_view = $this->getKernel()->setting->get('user', 'homepage.last_view');
152
        $this->getKernel()->setting->set('user', 'homepage.last_view', date('Y-m-d H:i:s'));
153
        return $last_view;
154
    }
155
156
    function getUserMenu()
157
    {
158
        $this->usermenu = array();
0 ignored issues
show
Bug introduced by
The property usermenu does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
159
        $this->usermenu[0]['name'] = $this->t('Logout');
160
        $this->usermenu[0]['url'] = $this->url('/logout');
161 View Code Duplication
        if (count($this->getKernel()->user->getIntranetList()) > 1) {
162
            $this->usermenu[1]['name'] = $this->t('Switch intranet');
163
            $this->usermenu[1]['url'] = $this->url('/restricted/switchintranet');
164
        }
165
        $this->usermenu[2]['name'] = $this->t('Modules');
166
        $this->usermenu[2]['url'] = $this->url('/restricted/module');
167
        $this->usermenu[3]['name'] = $this->t('Control panel');
168
        $this->usermenu[3]['url'] = $this->url('/restricted/module/controlpanel');
169
170
        return $this->usermenu;
171
    }
172
173
    function getMenu()
174
    {
175
        $this->menu = array();
0 ignored issues
show
Bug introduced by
The property menu does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
176
        $i = 0;
177
        $this->menu[$i]['name'] = $this->t('dashboard');
178
        $this->menu[$i]['url'] = $this->url('/restricted/');
179
        $i++;
180
        $this->db = new DB_Sql;
0 ignored issues
show
Bug introduced by
The property db does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
181
        $this->db->query("SELECT name, menu_label, name FROM module WHERE active = 1 AND show_menu = 1 ORDER BY menu_index");
182
        while ($this->db->nextRecord()) {
183
            if ($this->getKernel()->user->hasModuleAccess($this->db->f('name'))) {
184
                $this->menu[$i]['name'] = $this->t($this->db->f('name'));
185
                $this->menu[$i]['url'] = $this->url('/restricted/module/' . $this->db->f("name"));
186
                $i++;
187
            }
188
        }
189
        return $this->menu;
190
    }
191
192
    function getSubmenu()
193
    {
194
        $this->primary_module = $this->kernel->getPrimaryModule();
0 ignored issues
show
Bug introduced by
The property primary_module does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
195
        $this->submenu = array();
0 ignored issues
show
Bug introduced by
The property submenu does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
196
        if (is_object($this->primary_module)) {
197
            $all_submenu = $this->primary_module->getSubmenu();
198
            if (count($all_submenu) > 0) { // added to avoid error messages
199
                $j = 0;
200
                for ($i = 0, $max = count($all_submenu); $i < $max; $i++) {
201
                    $access = false;
202 View Code Duplication
                    if ($all_submenu[$i]['sub_access'] != '') {
203
                        $sub = explode(":", $all_submenu[$i]['sub_access']);
204
205
                        switch ($sub[0]) {
206
                            case 'sub_access':
207
                                if ($this->getKernel()->user->hasSubAccess($this->primary_module->module_name, $sub[1])) {
208
                                    $access = true;
209
                                }
210
                                break;
211
                            case 'module':
212
                                if ($this->getKernel()->user->hasModuleAccess($sub[1])) {
213
                                    $access = true;
214
                                }
215
                                break;
216
                            default:
217
                                throw new Exception('Der er ikke angivet om submenu skal tjekke efter sub_access eller module adgang, for undermenupunktet i Page->start();');
218
                                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...
219
                        }
220
                    } else {
221
                        $access = true;
222
                    }
223
224 View Code Duplication
                    if ($access) {
225
                        $this->submenu[$j]['name'] = $this->t($all_submenu[$i]['label']);
226
                        $this->submenu[$j]['url'] = $this->primary_module->getPath(). $all_submenu[$i]['url'];
227
                        $j++;
228
                    }
229
                }
230
            }
231
        }
232
233
        return $this->submenu;
234
    }
235
236
    function getIntranetName()
237
    {
238
        return $this->getKernel()->intranet->get('name');
239
        ;
240
    }
241
    
242
    function getThemeKey()
243
    {
244
        return $this->getKernel()->setting->get('user', 'theme');
245
    }
246
247
    function getFontSize()
248
    {
249
         return $this->getKernel()->setting->get('user', 'ptextsize');
250
    }
251
}
252