Completed
Push — master ( d208aa...25518b )
by Lars
12:37
created

UserPreferences::postForm()   C

Complexity

Conditions 8
Paths 32

Size

Total Lines 52
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 72

Importance

Changes 0
Metric Value
cc 8
eloc 13
nc 32
nop 0
dl 0
loc 52
ccs 0
cts 20
cp 0
crap 72
rs 6.8493
c 0
b 0
f 0

How to fix   Long Method   

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_modules_controlpanel_Controller_UserPreferences extends k_Component
3
{
4
    protected $error;
5
    protected $template;
6
7
    function __construct(k_TemplateFactory $template)
8
    {
9
        $this->template = $template;
10
    }
11
12
    protected function map($name)
13
    {
14
        if ($name == 'intranet') {
15
            return 'Intraface_modules_intranetmaintenance_Controller_Intranet_Index';
16
        } elseif ($name == 'user') {
17
            return 'Intraface_modules_intranetmaintenance_Controller_User_Index';
18
        } elseif ($name == 'preferences') {
19
            return 'Intraface_modules_controlpanel_Controller_UserPreferences';
20
        }
21
    }
22
23
    function getValues()
24
    {
25
        /*
0 ignored issues
show
Unused Code Comprehensibility introduced by
67% 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...
26
        $value['rows_pr_page'] = $this->getKernel()->setting->get('user', 'rows_pr_page');
27
        $value['theme'] = $this->getKernel()->setting->get('user', 'theme');
28
        $value['ptextsize'] = $this->getKernel()->setting->get('user', 'ptextsize');
29
        */
30
        $value['label'] = $this->getKernel()->setting->get('user', 'label');
0 ignored issues
show
Coding Style Comprehensibility introduced by
$value was never initialized. Although not strictly required by PHP, it is generally a good practice to add $value = 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...
31
        $value['language'] = $this->getKernel()->setting->get('user', 'language');
32
        //$value['htmleditor'] = $this->getKernel()->setting->get('user', 'htmleditor');
0 ignored issues
show
Unused Code Comprehensibility introduced by
70% 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...
33
        return $value;
34
    }
35
36
    function renderHtml()
37
    {
38
        $smarty = $this->template->create(dirname(__FILE__) . '/templates/userpreferences');
39
        return $smarty->render($this);
40
    }
41
42
    function postForm()
0 ignored issues
show
Coding Style introduced by
postForm uses the super-global variable $_POST 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...
43
    {
44
        /*
0 ignored issues
show
Unused Code Comprehensibility introduced by
68% 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...
45
        if (!$this->getKernel()->setting->set('user', 'rows_pr_page', $_POST['rows_pr_page'])) {
46
            $error[] = 'rows_pr_page';
47
        }
48
        if (!$this->getKernel()->setting->set('user', 'theme', $_POST['theme'])) {
49
            $error[] = 'theme';
50
        }
51
        if (!$this->getKernel()->setting->set('user', 'ptextsize', $_POST['ptextsize'])) {
52
            $error[] = 'theme';
53
        }
54
        */
55
56
57
        if (isset($_POST['label']) and !isset($labels_standard[$_POST['label']])) {
0 ignored issues
show
Bug introduced by
The variable $labels_standard seems to never exist, and therefore isset should always return false. Did you maybe rename this variable?

This check looks for calls to isset(...) or empty() on variables that are yet undefined. These calls will always produce the same result and can be removed.

This is most likely caused by the renaming of a variable or the removal of a function/method parameter.

Loading history...
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...
58
            $this->getError()->set('error in label - not allowed');
59
        }
60
61
        if (!$this->getKernel()->setting->set('user', 'label', $_POST['label'])) {
62
            $this->getError()->set('error in label');
63
        }
64
65
        if (!empty($_POST['language']) and !array_key_exists($_POST['language'], $this->getKernel()->getTranslation()->getLangs())) {
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...
66
            $this->getError()->set('error in language - not allowed');
67
        }
68
69
        if (!$this->getKernel()->setting->set('user', 'language', $_POST['language'])) {
70
            $this->getError()->set('error in language');
71
        }
72
73
        /*
0 ignored issues
show
Unused Code Comprehensibility introduced by
69% 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...
74
        if ($this->getKernel()->user->hasModuleAccess('cms')) {
75
            $validator = new Intraface_Validator($error);
76
            $validator->isString($_POST['htmleditor'], 'error in htmleditor not a string', '');
77
78
            if (!array_key_exists($_POST['htmleditor'], $editors)) {
79
                $error->set('error in htmleditor not allowed');
80
            }
81
            if (!$this->getKernel()->setting->set('user', 'htmleditor', $_POST['htmleditor'])) {
82
                $error->set('error in htmleditor not saved');
83
            }
84
        }
85
        */
86
87
        if (!$this->getError()->isError()) {
88
            return new k_SeeOther($this->url('../'));
89
        }
90
        $value = $_POST;
0 ignored issues
show
Unused Code introduced by
$value 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...
91
92
        return $this->render();
93
    }
94
95
    function getLabelStandards()
96
    {
97
        return $labels_standard = array(
0 ignored issues
show
Unused Code introduced by
$labels_standard 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...
98
            0 => '3x7',
99
            1 => '2x8'
100
        );
101
    }
102
103
    function getError()
104
    {
105
        if (is_object($this->error)) {
106
            return $this->error;
107
        }
108
        return ($this->error = new Intraface_Error());
109
    }
110
111
    function getKernel()
112
    {
113
        return $this->context->getKernel();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface k_Context as the method getKernel() does only exist in the following implementations of said interface: Intraface_Controller_Index, Intraface_Controller_ModuleGatekeeper, Intraface_Controller_ModulePackage_Process, Intraface_Controller_Restricted, Intraface_Controller_SwitchIntranet, Intraface_Filehandler_Controller_Batchedit, Intraface_Filehandler_Controller_CKEditor, Intraface_Filehandler_Controller_Crop, Intraface_Filehandler_Controller_Index, Intraface_Filehandler_Controller_SelectFile, Intraface_Filehandler_Controller_Show, Intraface_Filehandler_Controller_Size, Intraface_Filehandler_Controller_Sizes, Intraface_Filehandler_Controller_Upload, Intraface_Filehandler_Controller_UploadMultiple, Intraface_Filehandler_Controller_UploadScript, Intraface_Fileimport_Controller_Index, Intraface_Keyword_Controller_Connect, Intraface_Keyword_Controller_Index, Intraface_Keyword_Controller_Show, Intraface_modules_accoun...ontroller_Account_Index, Intraface_modules_accoun...ontroller_Account_Popup, Intraface_modules_accoun...Controller_Account_Show, Intraface_modules_accounting_Controller_Daybook, Intraface_modules_accounting_Controller_Index, Intraface_modules_accounting_Controller_Post_Index, Intraface_modules_accounting_Controller_Post_Show, Intraface_modules_accounting_Controller_Search, Intraface_modules_accounting_Controller_Settings, Intraface_modules_accounting_Controller_State, Intraface_modules_accoun...roller_State_Creditnote, Intraface_modules_accoun...ller_State_Depreciation, Intraface_modules_accoun...ontroller_State_Invoice, Intraface_modules_accoun...ontroller_State_Payment, Intraface_modules_accoun...oller_State_Procurement, Intraface_modules_accoun...ntroller_State_Reminder, Intraface_modules_accoun...roller_State_SelectYear, Intraface_modules_accounting_Controller_Vat_Index, Intraface_modules_accounting_Controller_Vat_Show, Intraface_modules_accoun...ontroller_Voucher_Index, Intraface_modules_accoun...Controller_Voucher_Show, Intraface_modules_accounting_Controller_Year_Edit, Intraface_modules_accounting_Controller_Year_End, Intraface_modules_accounting_Controller_Year_Index, Intraface_modules_accoun...troller_Year_Primosaldo, Intraface_modules_accounting_Controller_Year_Show, Intraface_modules_administration_Controller_Index, Intraface_modules_admini...ion_Controller_Intranet, Intraface_modules_cms_Controller_Element, Intraface_modules_cms_Controller_Elements, Intraface_modules_cms_Controller_Index, Intraface_modules_cms_Controller_Navigation, Intraface_modules_cms_Controller_Page, Intraface_modules_cms_Controller_Pages, Intraface_modules_cms_Controller_Section, Intraface_modules_cms_Controller_Sections, Intraface_modules_cms_Controller_Site, Intraface_modules_cms_Controller_Stylesheet, Intraface_modules_cms_Controller_Template, Intraface_modules_cms_Co...ler_TemplateSectionEdit, Intraface_modules_cms_Controller_TemplateSections, Intraface_modules_cms_Controller_Templates, Intraface_modules_contac...troller_BatchNewsletter, Intraface_modules_contact_Controller_Choosecontact, Intraface_modules_contac...ntroller_Contactpersons, Intraface_modules_contact_Controller_Import, Intraface_modules_contact_Controller_Index, Intraface_modules_contact_Controller_Memos, Intraface_modules_contact_Controller_Merge, Intraface_modules_contact_Controller_Sendemail, Intraface_modules_contact_Controller_Show, Intraface_modules_contro...ntroller_ChangePassword, Intraface_modules_controlpanel_Controller_Index, Intraface_modules_controlpanel_Controller_User, Intraface_modules_contro...troller_UserPreferences, Intraface_modules_curren...ller_ExchangeRate_Index, Intraface_modules_curren...changeRate_ProductPrice, Intraface_modules_currency_Controller_Index, Intraface_modules_currency_Controller_Show, Intraface_modules_debtor_Controller_Collection, Intraface_modules_debtor_Controller_Create, Intraface_modules_debtor_Controller_Depreciation, Intraface_modules_debtor_Controller_Depreciations, Intraface_modules_debtor_Controller_Index, Intraface_modules_debtor_Controller_Item, Intraface_modules_debtor_Controller_Items, Intraface_modules_debtor_Controller_Payment, Intraface_modules_debtor_Controller_Payments, Intraface_modules_debtor_Controller_Reminder, Intraface_modules_debtor_Controller_Reminders, Intraface_modules_debtor_Controller_Settings, Intraface_modules_debtor_Controller_Show, Intraface_modules_debtor_Controller_Typenegotiator, Intraface_modules_email_Controller_Email, Intraface_modules_email_Controller_Index, Intraface_modules_fileimport_Controller_Index, Intraface_modules_filemanager_Controller_Index, Intraface_modules_intran...enance_Controller_Index, Intraface_modules_intran...ntroller_Intranet_Index, Intraface_modules_intran...Controller_Intranet_Key, Intraface_modules_intran...ler_Intranet_Permission, Intraface_modules_intran...ontroller_Intranet_Show, Intraface_modules_intran...ance_Controller_Modules, Intraface_modules_intran...e_Controller_User_Index, Intraface_modules_intran...troller_User_Permission, Intraface_modules_intran...ce_Controller_User_Show, Intraface_modules_module...e_Controller_AddPackage, Intraface_modules_modulepackage_Controller_Index, Intraface_modules_modulepackage_Controller_Package, Intraface_modules_modulepackage_Controller_Payment, Intraface_modules_module...age_Controller_PostForm, Intraface_modules_modulepackage_Controller_Process, Intraface_modules_newsletter_Controller_Index, Intraface_modules_newsletter_Controller_Letter, Intraface_modules_newsletter_Controller_Letters, Intraface_modules_newsletter_Controller_List, Intraface_modules_newsletter_Controller_Lists, Intraface_modules_newsletter_Controller_Log, Intraface_modules_newsletter_Controller_Send, Intraface_modules_newsle..._Controller_Subscribers, Intraface_modules_onlinepayment_Controller_Index, Intraface_modules_online...ent_Controller_Settings, Intraface_modules_payment_Controller_Index, Intraface_modules_payment_Controller_Show, Intraface_modules_procurement_Controller_Index, Intraface_modules_procurement_Controller_Item, Intraface_modules_procurement_Controller_Items, Intraface_modules_procur...ontroller_PurchasePrice, Intraface_modules_procurement_Controller_Show, Intraface_modules_produc...troller_AttributeGroups, Intraface_modules_produc...tributeGroups_Attribute, Intraface_modules_produc...er_AttributeGroups_Show, Intraface_modules_product_Controller_BatchEdit, Intraface_modules_produc...oller_BatchPriceChanger, Intraface_modules_product_Controller_Index, Intraface_modules_produc...r_Productattributegroup, Intraface_modules_product_Controller_Related, Intraface_modules_product_Controller_Selectproduct, Intraface_modules_produc..._Selectproductvariation, Intraface_modules_product_Controller_Show, Intraface_modules_produc...ntroller_Show_PlainText, Intraface_modules_produc...troller_Show_Variations, Intraface_modules_produc...s_SelectAttributeGroups, Intraface_modules_product_Controller_Variation, Intraface_modules_shop_C...r_BasketEvaluation_Edit, Intraface_modules_shop_C..._BasketEvaluation_Index, Intraface_modules_shop_C...r_BasketEvaluation_Show, Intraface_modules_shop_Controller_Categories, Intraface_modules_shop_C...oller_Categories_Create, Intraface_modules_shop_Controller_Categories_Show, Intraface_modules_shop_C...oller_DiscountCampaigns, Intraface_modules_shop_Controller_FeaturedProducts, Intraface_modules_shop_Controller_Index, Intraface_modules_shop_Controller_Show, Intraface_modules_stock_Controller_Index, Intraface_modules_stock_Controller_Product, Intraface_modules_stock_Controller_Variations, Intraface_modules_todo_Controller_Edit, Intraface_modules_todo_Controller_Index, Intraface_modules_todo_Controller_Todo.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
114
    }
115
116
    function getModules()
117
    {
118
        return $this->getKernel()->getModules();
119
    }
120
}
121