Completed
Pull Request — master (#42)
by Gino
03:48
created

AdminMenu::getInstance()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 9
rs 9.6667
cc 2
eloc 5
nc 2
nop 0
1
<?php
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 29 and the first side effect is on line 24.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
2
3
/*
4
 You may not change or alter any portion of this comment or credits
5
 of supporting developers from this source code or any supporting source code
6
 which is considered copyrighted (c) material of the original comment or credit authors.
7
8
 This program is distributed in the hope that it will be useful,
9
 but WITHOUT ANY WARRANTY; without even the implied warranty of
10
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
11
 */
12
/**
13
 * tdmcreate module.
14
 *
15
 * @copyright       The XOOPS Project http://sourceforge.net/projects/xoops/
16
 * @license         GNU GPL 2 (http://www.gnu.org/licenses/old-licenses/gpl-2.0.html)
17
 *
18
 * @since           2.5.0
19
 *
20
 * @author          Txmod Xoops http://www.txmodxoops.org
21
 *
22
 * @version         $Id: admin_menu.php 12258 2014-01-02 09:33:29Z timgno $
23
 */
24
defined('XOOPS_ROOT_PATH') or die('Restricted access');
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...
25
26
/**
27
 * Class AdminMenu.
28
 */
29
class AdminMenu extends TDMCreateFile
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
30
{
31
    /*
32
    *  @public function constructor
33
    *  @param null
34
    */
35
    /**
36
     *
37
     */
38
    public function __construct()
39
    {
40
        parent::__construct();
41
        $this->tdmcfile = TDMCreateFile::getInstance();
0 ignored issues
show
Documentation Bug introduced by
It seems like \TDMCreateFile::getInstance() of type object<TDMCreateFile> is incompatible with the declared type string of property $tdmcfile.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
42
        $this->xoopscode = TDMCreateXoopsCode::getInstance();
0 ignored issues
show
Bug introduced by
The property xoopscode 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...
43
    }
44
45
    /*
46
    *  @static function &getInstance
47
    *  @param null
48
    */
49
    /**
50
     * @return AdminMenu
51
     */
52
    public static function &getInstance()
53
    {
54
        static $instance = false;
55
        if (!$instance) {
56
            $instance = new self();
57
        }
58
59
        return $instance;
60
    }
61
62
    /*
63
    *  @public function write
64
    *  @param string $module
65
    *  @param object $table
66
    *  @param array $tables
67
    *  @param string $filename
68
    */
69
    /**
70
     * @param $module
71
     * @param $table
72
     * @param $tables
73
     * @param $filename
74
     */
75
    public function write($module, $tables, $filename)
76
    {
77
        $this->setModule($module);
78
        $this->setTables($tables);
79
        $this->setFileName($filename);
80
    }
81
82
    /*
83
     * @private function getAdminMenuArray
84
     * @param $param
85
     * @param $adminMenu
86
     * @param $ref
87
     *
88
     * @return string
89
     */
90
    private function getAdminMenuArray($param = array(), $adminMenu = false, $ref = false)
91
    {
92
        $ret = '';
93
        foreach ($param as $key => $value) {
94
            if ($adminMenu) {
95
                $ret .= $this->xoopscode->getXoopsCodeEqualsOperator("\$adminmenu[\$i]['{$key}']", "{$value}");
96
            } else {
97
                if ($ref) {
98
                    $ret .= $this->xoopscode->getXoopsCodeEqualsOperator("{$key}", "{$value}", true);
99
                } else {
100
                    $ret .= $this->xoopscode->getXoopsCodeEqualsOperator("{$key}", "{$value}");
101
                }
102
            }
103
        }
104
105
        return $ret;
106
    }
107
108
    /*
109
    *  @private function getAdminMenuHeader
110
    *  @param null
111
    */
112
    /**
113
     * @return string
114
     */
115
    private function getAdminMenuHeader()
116
    {
117
        $dirname = array('$dirname' => 'basename(dirname(__DIR__))');
118
        $ret = $this->getAdminMenuArray($dirname);
119
        $mod = array('$moduleHandler' => "xoops_gethandler('module')",
120
                    '$xoopsModule' => 'XoopsModule::getByDirname($dirname)',
121
                    '$moduleInfo' => "\$moduleHandler->get(\$xoopsModule->getVar('mid'))", );
122
        $ret .= $this->getAdminMenuArray($mod, false, true);
123
        $sys = array('$sysPathIcon32' => "\$moduleInfo->getInfo('sysicons32')");
124
        $ret .= $this->getAdminMenuArray($sys);
125
126
        return $ret;
127
    }
128
129
    /*
130
    *  @private function getAdminMenuDashboard
131
    *  @param string $language
132
    *  @param integer $menu
133
    */
134
    /**
135
     * @param $language
136
     * @param $menu
137
     *
138
     * @return string
139
     */
140
    private function getAdminMenuDashboard($language, $menu)
141
    {
142
        $param = array('title' => "{$language}{$menu}", 'link' => "'admin/index.php'", 'icon' => "\$sysPathIcon32.'/dashboard.png'");
143
        $ret = $this->xoopscode->getXoopsCodeEqualsOperator('$i', '1');
144
        $ret .= $this->getAdminMenuArray($param, true);
145
        $ret .= $this->getSimpleString('++$i;');
146
147
        return $ret;
148
    }
149
150
    /*
151
    *  @private function getAdminMenuImagesPath
152
    *  @param array $tables
153
    *  @param integer $t
154
    */
155
    /**
156
     * @param $tables
157
     * @param $t
158
     *
159
     * @return string
160
     */
161
    private function getAdminMenuImagesPath($tables, $t)
0 ignored issues
show
Unused Code introduced by
This method is not used, and could be removed.
Loading history...
162
    {
163
        $ret = '';
164
        $fields = $this->getTableFields($tables[$t]->getVar('table_id'));
0 ignored issues
show
Bug introduced by
The call to getTableFields() misses a required argument $tId.

This check looks for function calls that miss required arguments.

Loading history...
165
        foreach (array_keys($fields) as $f) {
166
            $fieldElement = $fields[$f]->getVar('field_element');
167
            switch ($fieldElement) {
168
                case 13:
169
                    $ret = $this->xoopscode->getXoopsCodeEqualsOperator("\$adminmenu[\$i]['icon']", "'assets/icons/32/{$tables[$t]->getVar('table_image')}'");
170
                    break;
171
                default:
172
                    $ret = $this->xoopscode->getXoopsCodeEqualsOperator("\$adminmenu[\$i]['icon']", "\$sysPathIcon32.'/{$tables[$t]->getVar('table_image')}'");
173
                    break;
174
            }
175
        }
176
177
        return $ret;
178
    }
179
180
    /*
181
     * @private function getAdminMenuList
182
     * @param string $module
183
     * @param string $language
184
     * @param string $langAbout
185
     * @param integer $menu    
186
     *
187
     * @return string
188
     */
189
    private function getAdminMenuList($module, $language, $langAbout, $menu)
190
    {
191
        $ret = '';
192
        $tables = $this->getTableTables($module->getVar('mod_id'), 'table_order');
0 ignored issues
show
Bug introduced by
The method getVar cannot be called on $module (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
193
        foreach (array_keys($tables) as $t) {
194
            $tablePermissions[] = $tables[$t]->getVar('table_permissions');
0 ignored issues
show
Coding Style Comprehensibility introduced by
$tablePermissions was never initialized. Although not strictly required by PHP, it is generally a good practice to add $tablePermissions = 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...
195
            if (1 == $tables[$t]->getVar('table_admin')) {
196
                ++$menu;
197
                $param1 = array('title' => "{$language}{$menu}", 'link' => "'admin/{$tables[$t]->getVar('table_name')}.php'", 'icon' => "'assets/icons/32/{$tables[$t]->getVar('table_image')}'");
198
                $ret .= $this->getAdminMenuArray($param1, true);
199
                $ret .= $this->getSimpleString('++$i;');
200
            }
201
        }
202
        if (in_array(1, $tablePermissions)) {
0 ignored issues
show
Bug introduced by
The variable $tablePermissions 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...
203
            ++$menu;
204
            $param2 = array('title' => "{$language}{$menu}", 'link' => "'admin/permissions.php'", 'icon' => "\$sysPathIcon32.'/permissions.png'");
205
            $ret .= $this->getAdminMenuArray($param2, true);
206
            $ret .= $this->getSimpleString('++$i;');
207
        }
208
        unset($menu);
209
        $param3 = array('title' => "{$langAbout}", 'link' => "'admin/about.php'", 'icon' => "\$sysPathIcon32.'/about.png'");
210
        $ret .= $this->getAdminMenuArray($param3, true);
211
        $ret .= $this->getSimpleString('unset($i);');
212
213
        return $ret;
214
    }
215
216
    /*
217
    *  @public function render
218
    *  @param null
219
    */
220
    /**
221
     * @return bool|string
222
     */
223 View Code Duplication
    public function render()
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...
224
    {
225
        $module = $this->getModule();
226
        $filename = $this->getFileName();
227
        $moduleDirname = $module->getVar('mod_dirname');
228
        $language = $this->getLanguage($moduleDirname, 'MI', 'ADMENU');
229
        $langAbout = $this->getLanguage($moduleDirname, 'MI', 'ABOUT');
230
        $menu = 1;
231
        $content = $this->getHeaderFilesComments($module, $filename);
232
        $content .= $this->getAdminMenuHeader();
233
        $content .= $this->getAdminMenuDashboard($language, $menu);
234
        $content .= $this->getAdminMenuList($module, $language, $langAbout, $menu);
235
236
        $this->tdmcfile->create($moduleDirname, 'admin', $filename, $content, _AM_TDMCREATE_FILE_CREATED, _AM_TDMCREATE_FILE_NOTCREATED);
0 ignored issues
show
Bug introduced by
The method create cannot be called on $this->tdmcfile (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
237
238
        return $this->tdmcfile->renderFile();
0 ignored issues
show
Bug introduced by
The method renderFile cannot be called on $this->tdmcfile (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
239
    }
240
}
241