Completed
Push — master ( e3aa41...89474e )
by Nicolaas
04:08
created

ShopAccountForm   B

Complexity

Total Complexity 32

Size/Duplication

Total Lines 193
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 18

Importance

Changes 0
Metric Value
wmc 32
lcom 1
cbo 18
dl 0
loc 193
rs 7.04
c 0
b 0
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
C __construct() 0 80 16
A submit() 0 4 1
A proceed() 0 4 1
C creatememberandaddtoorder() 0 30 7
B processForm() 0 28 6
A saveDataToSession() 0 10 1
1
<?php
2
/**
3
 * @description: ShopAccountForm allows shop members to update their details.
4
 *
5
 *
6
 * @authors: Nicolaas [at] Sunny Side Up .co.nz
7
 * @package: ecommerce
8
 * @sub-package: forms
9
 * @inspiration: Silverstripe Ltd, Jeremy
10
 **/
11
class ShopAccountForm 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...
12
{
13
    /**
14
     * @param Controller $controller
15
     * @param string     $name,      Name of the form
0 ignored issues
show
Bug introduced by
There is no parameter named $name,. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
16
     */
17
    public function __construct($controller, $name, $mustCreateAccount = false)
18
    {
19
        $member = Member::currentUser();
20
        $requiredFields = null;
0 ignored issues
show
Unused Code introduced by
$requiredFields 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...
21
        if ($member && $member->exists()) {
22
            $fields = $member->getEcommerceFields(false);
23
            $clearCartAndLogoutLink = ShoppingCart_Controller::clear_cart_and_logout_link();
24
            $loginMessage =
25
                '<span class="customerName">'.trim(Convert::raw2xml($member->FirstName).' '.Convert::raw2xml($member->Surname)).'</span>, '
26
                .'<a href="'.$clearCartAndLogoutLink.'">'._t('Account.LOGOUT', 'Log out now?').
27
                '</a>';
28
            if ($loginMessage) {
29
                $loginField = new ReadonlyField(
30
                    'LoggedInAsNote',
31
                    _t('Account.LOGGEDIN', 'You are currently logged in as '),
32
                    $loginMessage
33
                );
34
                $loginField->dontEscape = true;
35
                $fields->push($loginField);
36
            }
37
            $actions = new FieldList();
38
            if ($order = ShoppingCart::current_order()) {
39
                if ($order->getTotalItems()) {
40
                    $actions->push(new FormAction('proceed', _t('Account.SAVE_AND_PROCEED', 'Save changes and proceed to checkout')));
41
                } else {
42
                    $actions->push(new FormAction('submit', _t('Account.SAVE', 'Save Changes')));
43
                }
44
            }
45
        } else {
46
            if (!$member) {
47
                $member = new Member();
48
            }
49
            $fields = new FieldList();
50
            $urlParams = $controller->getURLParams();
51
            $backURLLink = Director::baseURL();
52
            if ($urlParams) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $urlParams of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
53
                foreach ($urlParams as $urlParam) {
54
                    if ($urlParam) {
55
                        $backURLLink = Controller::join_links($backURLLink, $urlParam);
56
                    }
57
                }
58
            }
59
            $backURLLink = urlencode($backURLLink);
60
            $fields->push(new LiteralField('MemberInfo', '<p class="message good">'._t('OrderForm.MEMBERINFO', 'If you already have an account then please').' <a href="Security/login?BackURL='.$backURLLink.'">'._t('OrderForm.LOGIN', 'log in').'</a>.</p>'));
61
            $memberFields = $member->getEcommerceFields($mustCreateAccount);
62
            if ($memberFields) {
63
                foreach ($memberFields as $memberField) {
64
                    $fields->push($memberField);
65
                }
66
            }
67
            $passwordField = new PasswordField('PasswordCheck1', _t('Account.PASSWORD', 'Password'));
68
            $passwordFieldCheck = new PasswordField('PasswordCheck2', _t('Account.PASSWORDCHECK', 'Password (repeat)'));
69
            $fields->push($passwordField);
70
            $fields->push($passwordFieldCheck);
71
            $actions = new FieldList(
72
                new FormAction('creatememberandaddtoorder', _t('Account.SAVE', 'Create Account'))
73
            );
74
        }
75
76
        $requiredFields = ShopAccountForm_Validator::create($member->getEcommerceRequiredFields());
77
        parent::__construct($controller, $name, $fields, $actions, $requiredFields);
78
        $this->setAttribute('autocomplete', 'off');
79
        //extensions need to be set after __construct
80
        //extension point
81
        $this->extend('updateFields', $fields);
82
        $this->setFields($fields);
83
        $this->extend('updateActions', $actions);
84
        $this->setActions($actions);
85
        $this->extend('updateValidator', $requiredFields);
86
        $this->setValidator($requiredFields);
87
88
        if ($member) {
89
            $this->loadDataFrom($member);
90
        }
91
        $oldData = Session::get("FormInfo.{$this->FormName()}.data");
92
        if ($oldData && (is_array($oldData) || is_object($oldData))) {
93
            $this->loadDataFrom($oldData);
0 ignored issues
show
Bug introduced by
It seems like $oldData can also be of type object; however, Form::loadDataFrom() does only seem to accept array|object<DataObject>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
94
        }
95
        $this->extend('updateShopAccountForm', $this);
96
    }
97
98
    /**
99
     * Save the changes to the form, and go back to the account page.
100
     *
101
     * @return bool + redirection
102
     */
103
    public function submit($data, $form, $request)
104
    {
105
        return $this->processForm($data, $form, $request, '');
106
    }
107
108
    /**
109
     * Save the changes to the form, and redirect to the checkout page.
110
     *
111
     * @return bool + redirection
112
     */
113
    public function proceed($data, $form, $request)
114
    {
115
        return $this->processForm($data, $form, $request, CheckoutPage::find_link());
116
    }
117
118
    /**
119
     * create a member and add it to the order
120
     * then redirect back...
121
     *
122
     * @param array $data
123
     * @param Form  $form
124
     */
125
    public function creatememberandaddtoorder($data, $form)
126
    {
127
        $member = new Member();
128
        $order = ShoppingCart::current_order();
129
        if ($order && $order->exists()) {
130
            $form->saveInto($member);
131
            $password = ShopAccountForm_PasswordValidator::clean_password($data);
132
            if ($password) {
133
                $member->changePassword($password);
0 ignored issues
show
Bug introduced by
It seems like $password defined by \ShopAccountForm_Passwor...::clean_password($data) on line 131 can also be of type array; however, Member::changePassword() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
134
                if ($member->validate()->valid()) {
135
                    $member->write();
136
                    if ($member->exists()) {
137
                        if (!$order->MemberID) {
0 ignored issues
show
Documentation introduced by
The property MemberID does not exist on object<Order>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
138
                            $order->MemberID = $member->ID;
0 ignored issues
show
Documentation introduced by
The property MemberID does not exist on object<Order>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
139
                            $order->write();
140
                        }
141
                        $member->login();
142
                        $this->sessionMessage(_t('ShopAccountForm.SAVEDDETAILS', 'Your details has been saved.'), 'good');
143
                    } else {
144
                        $this->sessionMessage(_t('ShopAccountForm.COULD_NOT_CREATE_RECORD', 'Could not save create a record for your details.'), 'bad');
145
                    }
146
                } else {
147
                    $this->sessionMessage(_t('ShopAccountForm.COULD_NOT_VALIDATE_MEMBER', 'Could not save your details.'), 'bad');
148
                }
149
            }
150
        } else {
151
            $this->sessionMessage(_t('ShopAccountForm.COULDNOTFINDORDER', 'Could not find order.'), 'bad');
152
        }
153
        $this->controller->redirectBack();
154
    }
155
156
    /**
157
     *@return bool + redirection
158
     **/
159
    protected function processForm($data, $form, $request, $link = '')
0 ignored issues
show
Unused Code introduced by
The parameter $request 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...
160
    {
161
        $member = Member::currentUser();
162
        if (!$member) {
163
            $form->sessionMessage(_t('Account.DETAILSNOTSAVED', 'Your details could not be saved.'), 'bad');
164
            $this->controller->redirectBack();
165
        }
166
        $form->saveInto($member);
167
        $password = ShopAccountForm_PasswordValidator::clean_password($data);
168
        if ($password) {
169
            $member->changePassword($password);
170
        } elseif ($data['PasswordCheck1']) {
171
            $form->sessionMessage(_t('Account.NO_VALID_PASSWORD', 'You need to enter a valid password.'), 'bad');
172
            $this->controller->redirectBack();
173
        }
174
        if ($member->validate()->valid()) {
175
            $member->write();
176
            if ($link) {
177
                return $this->controller->redirect($link);
178
            } else {
179
                $form->sessionMessage(_t('Account.DETAILSSAVED', 'Your details have been saved.'), 'good');
180
                $this->controller->redirectBack();
181
            }
182
        } else {
183
            $form->sessionMessage(_t('Account.NO_VALID_DATA', 'Your details can not be updated.'), 'bad');
184
            $this->controller->redirectBack();
185
        }
186
    }
187
188
    /**
189
     * saves the form into session.
190
     *
191
     * @param array $data - data from form.
0 ignored issues
show
Bug introduced by
There is no parameter named $data. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
192
     */
193
    public function saveDataToSession()
194
    {
195
        $data = $this->getData();
196
        unset($data['AccountInfo']);
197
        unset($data['LoginDetails']);
198
        unset($data['LoggedInAsNote']);
199
        unset($data['PasswordCheck1']);
200
        unset($data['PasswordCheck2']);
201
        Session::set("FormInfo.{$this->FormName()}.data", $data);
0 ignored issues
show
Documentation introduced by
$data is of type array, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
202
    }
203
}
204