TrainingSignupForm   A
last analyzed

Complexity

Total Complexity 19

Size/Duplication

Total Lines 114
Duplicated Lines 11.4 %

Coupling/Cohesion

Components 1
Dependencies 12

Importance

Changes 0
Metric Value
wmc 19
lcom 1
cbo 12
dl 13
loc 114
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
D __construct() 0 43 9
D doSave() 13 36 10

How to fix   Duplicated Code   

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:

1
<?php
2
3
class TrainingSignupForm extends Form
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...
4
{
5
    public function __construct($controller, $name, $title = "Training")
6
    {
7
        if ($member = Member::currentUser()) {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
8
        } else {
9
            $member = new Member();
10
        }
11
        $fields = new FieldList(
12
            new HeaderField($title)
13
        );
14
        $extraFields = $member->getTrainingFields();
15
        foreach ($extraFields as $field) {
16
            if ("Password" == $field->title() && $member->ID) {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
17
            } elseif ("Password" == $field->title()) {
18
                $fields->push(new ConfirmedPasswordField("Password"));
19
            } else {
20
                $fields->push($field);
21
            }
22
        }
23
        $actions = new FieldList(
24
                new FormAction("doSave", "Sign Up Now")
25
        );
26
        $requiredFields = new RequiredFields(
27
            "FirstName",
28
            "Surname",
29
            "Email",
30
            "Password"
31
        );
32
        if ($controller->Options) {
33
            $array = array();
34
            $explodedOptions = explode(",", $controller->Options);
35
            foreach ($explodedOptions as $option) {
36
                $option = trim(Convert::raw2att($option));
37
                $array[$option] = $option;
38
            }
39
            if (count($array)) {
40
                $fields->push(new DropdownField("SelectedOption", "Select Option", $array));
41
            }
42
        }
43
        $fields->push(new TextField("BookingCode", "Booking Code (if any)"));
44
        parent::__construct($controller, $name, $fields, $actions, $requiredFields);
45
        $this->loadNonBlankDataFrom($member);
0 ignored issues
show
Documentation Bug introduced by
The method loadNonBlankDataFrom does not exist on object<TrainingSignupForm>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
46
        return $this;
0 ignored issues
show
Bug introduced by
Constructors do not have meaningful return values, anything that is returned from here is discarded. Are you sure this is correct?
Loading history...
47
    }
48
49
    public function doSave($data, $form)
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
Unused Code introduced by
The parameter $form is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
50
    {
51 View Code Duplication
        if (isset($data['Password']) && is_array($data['Password'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
52
            $data['Password'] = $data['Password']['_Password'];
53
        }
54
55
        // We need to ensure that the unique field is never overwritten
56
        $uniqueField = Member::get_unique_identifier_field();
0 ignored issues
show
Deprecated Code introduced by
The method Member::get_unique_identifier_field() has been deprecated with message: 4.0 Use the "Member.unique_identifier_field" config setting instead

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
57 View Code Duplication
        if (isset($data[$uniqueField])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
58
            $SQL_unique = Convert::raw2sql($data[$uniqueField]);
59
            $existingUniqueMember = Member::get()->filter(array($uniqueField => $SQL_unique))->first();
60
            if ($existingUniqueMember && $existingUniqueMember->exists()) {
61
                if (Member::currentUserID() != $existingUniqueMember->ID) {
62
                    die("current member does not match enrolled member.");
0 ignored issues
show
Coding Style Compatibility introduced by
The method doSave() 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...
63
                    return false;
0 ignored issues
show
Unused Code introduced by
return false; 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...
64
                }
65
            }
66
        }
67
        $member = Member::currentUser();
68
        if (!$member) {
69
            $member = new Member();
70
        }
71
72
        $member->update($data);
73
        $member->write();
74
        $arrayExtraFields = array();
75
        if (isset($data["SelectedOption"])) {
76
            $arrayExtraFields["SelectedOption"] = $data["SelectedOption"];
77
        }
78
        if (isset($data["BookingCode"])) {
79
            $arrayExtraFields["BookingCode"] = $data["BookingCode"];
80
        }
81
        $this->controller->addAttendee($member, $arrayExtraFields);
82
        $this->redirect($this->getController()->Link("thankyou"));
0 ignored issues
show
Unused Code introduced by
The call to Controller::Link() has too many arguments starting with 'thankyou'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
Bug introduced by
The method redirect() does not exist on TrainingSignupForm. Did you maybe mean getRedirectToFormOnValidationError()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
83
        return;
84
    }
85
86
/*
87
88
I don't think saveInto can deal with saving many_many relations
89
currently, unless your Post class has a customised method called
90
saveCategories($data) in which you simply add the code like this:
91
92
$this->Categories->add($item, $extraFields),
93
where $item should be the category's ID (you can get it from $data),
94
depending on how your Form is stuctured, your $extraFields should be
95
either from $data, or assigned from backend by you before you call
96
saveInto in doPostForm or before you call $this->Categories->add
97
saveCetegories.
98
99
The name of saving many_many relation (here refer to saveCategories)
100
must bond with your field name, ie, if your field is called:
101
new DropdownField('GoneWithWind',"Category", $catOptions), the save
102
method must name as saveGoneWithWind().
103
104
if PrimeCategory need to be also submitted from from, your your can
105
get CategoryID and PrimeCategory in an array from $data, try this:
106
new DropdownField('Categories[CetegoryID]',"Category", $catOptions),
107
new CheckboxField('Categories[PrimeCategory]', "Prime Category?"),
108
The $data[Categories] submitted from from is a array.
109
110
In addition, dropdown field is not supposed to simulate many_many
111
relation, CheckboxSetField is aim to submit multiple IDs from a form
112
(maybe you have you special consideration here?). If this is the case,
113
$this->Categories->add need to change to $this->Categories-
114
115
*/
116
}
117