CampaignMonitorMemberDOD::addCampaignMonitorList()   C
last analyzed

Complexity

Conditions 12
Paths 80

Size

Total Lines 44
Code Lines 31

Duplication

Lines 9
Ratio 20.45 %

Importance

Changes 0
Metric Value
dl 9
loc 44
rs 5.1612
c 0
b 0
f 0
cc 12
eloc 31
nc 80
nop 2

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
3
/**
4
 * @author nicolaas [at] sunnysideup.co.nz
5
 * TO DO: only apply the on afterwrite to people in the subscriber group.
6
 *
7
 **/
8
9
class CampaignMonitorMemberDOD extends DataExtension
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...
10
{
11
12
    /**
13
     * name of the field to use for sign-ups
14
     * @var String
15
     */
16
    private static $campaign_monitor_signup_fieldname = "CampaignMonitorSubscriptions";
0 ignored issues
show
Unused Code introduced by
The property $campaign_monitor_signup_fieldname is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
17
18
    /**
19
     * array of fields where the member value is set as the default for the
20
     * custom field ...
21
     * The should be like this
22
     *
23
     *     CustomFieldCode => MemberFieldOrMethod
24
     * @var array
25
     */
26
    private static $custom_fields_member_field_or_method_map = array();
0 ignored issues
show
Unused Code introduced by
The property $custom_fields_member_field_or_method_map is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
27
28
    /**
29
     *
30
     *
31
     * @var null | CampaignMonitorAPIConnector
32
     *
33
     */
34
    private static $_api = null;
35
36
    /**
37
     *
38
     * @return CampaignMonitorAPIConnector
39
     */
40
    private function getCMAPI()
41
    {
42
        if (!self::$_api) {
43
            self::$_api = CampaignMonitorAPIConnector::create();
0 ignored issues
show
Documentation Bug introduced by
It seems like \CampaignMonitorAPIConnector::create() of type object<CampaignMonitorAPIConnector> is incompatible with the declared type null of property $_api.

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...
44
            self::$_api->init();
45
        }
46
        return self::$_api;
47
    }
48
49
    /**
50
     * returns a form field for signing up to all available lists
51
     * or if a list is provided, for that particular list.
52
     *
53
     * @param CampaignMonitorSignupPage | string | Null $listPage
54
     * @param string $fieldName
55
     * @param string $fieldTitle
56
     *
57
     * @return FormField
58
     */
59
    public function getCampaignMonitorSignupField($listPage = null, $fieldName = "", $fieldTitle = "")
60
    {
61
        if (!is_object($listPage)) {
62
            $listPage = CampaignMonitorSignupPage::get()->filter(array("ListID" => $listPage))->first();
63
        }
64
        $field = null;
65
        if (!$fieldName) {
66
            $fieldName = Config::inst()->get("CampaignMonitorMemberDOD", "campaign_monitor_signup_fieldname");
67
        }
68
        $api = $this->getCMAPI();
69
        $currentValues = null;
70
        if ($listPage) {
71
            if ($listPage->ReadyToReceiveSubscribtions()) {
72
                $currentSelection = "Subscribe";
73
                $optionArray = array();
74
                $optionArray["Subscribe"] = _t("CampaignMonitorSignupPage.SUBSCRIBE_TO", "subscribe to")." ".$listPage->getListTitle();
75
                $optionArray["Unsubscribe"] = _t("CampaignMonitorSignupPage.UNSUBSCRIBE_FROM", "unsubscribe from ")." ".$listPage->getListTitle();
76
                if ($this->owner->exists()) {
77
                    if ($api->getSubscriberCanReceiveEmailsForThisList($listPage->ListID, $this->owner)) {
78
                        $currentValues = $api->getSubscriber($listPage->ListID, $this->owner);
79
                        //$currentSelection = "Unsubscribe";
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% 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...
80
                    }
81
                }
82
                if (!$fieldTitle) {
83
                    $fieldTitle = _t("CampaignMonitorSignupPage.SIGNUP_FOR", "Sign up for ")." ".$listPage->getListTitle();
84
                }
85
                $subscribeField = OptionsetField::create($fieldName, $fieldTitle, $optionArray, $currentSelection);
86
                $field = CompositeField::create($subscribeField);
87
                $field->addExtraClass("CMFieldsCustomFieldsHolder");
88
                //add custom fields
89
                $linkedMemberFields = Config::inst()->get("CampaignMonitorMemberDOD", "custom_fields_member_field_or_method_map");
90
                $customFields = $listPage->CampaignMonitorCustomFields()->filter(array("Visible" => 1));
91
                foreach ($customFields as $customField) {
92
                    $valueSet = false;
93
                    $customFormField = $customField->getFormField("CMCustomField");
94
                    if ($currentValues && isset($currentValues->CustomFields)) {
95
                        foreach ($currentValues->CustomFields as $customFieldObject) {
0 ignored issues
show
Bug introduced by
The property CustomFields does not seem to exist in CS_REST_Wrapper_Result.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
96
                            if ($customFieldObject->Key == $customField->Title) {
97
                                if ($value = $customFieldObject->Value) {
98
                                    $valueSet = true;
99
                                }
100
                                $customFormField->setValue($value);
101
                            }
102
                        }
103
                    }
104
                    if (isset($linkedMemberFields[$customFormField->Code]) && !$valueSet) {
105
                        $fieldOrMethod = $linkedMemberFields[$custom->Code];
0 ignored issues
show
Bug introduced by
The variable $custom does not exist. Did you mean $customFields?

This check looks for variables that are accessed but have not been defined. It raises an issue if it finds another variable that has a similar name.

The variable may have been renamed without also renaming all references.

Loading history...
106
                        if ($this->owner->hasMethod($fieldOrMethod)) {
107
                            $value = $this->owner->$fieldOrMethod();
108
                        } else {
109
                            $value = $this->owner->$fieldOrMethod;
110
                        }
111
                        if ($value) {
112
                            $customFormField->setValue($value);
113
                        }
114
                    }
115
                    $field->push($customFormField);
116
                }
117
            }
118
        } else {
119
            if (!$fieldTitle) {
120
                $fieldTitle = _t("CampaignMonitorMemberDOD.NEWSLETTERSIGNUP", "Newsletter sign-up");
121
            }
122
            $lists = CampaignMonitorSignupPage::get_ready_ones();
123
            $array = array();
124
            foreach ($lists as $list) {
125
                $array[$list->ListID] = $list->getListTitle();
126
            }
127
            if (count($array)) {
128
                $field = new CheckboxSetField(
129
                    $fieldName,
130
                    $fieldTitle,
131
                    $array
132
                );
133
                $field->setDefaultItems($this->owner->CampaignMonitorSignupPageIDs());
134
            }
135
        }
136
        if (!$field) {
137
            $field = ReadonlyField::create(
138
                $fieldName,
139
                $fieldTitle,
140
                _t("CampaignMonitorMemberDOD.NO_LISTS_AVAILABLE", "No lists available right now.  Please come back soon.")
141
            );
142
        }
143
        return $field;
144
    }
145
146
147
    /**
148
     * action subscription form
149
     * @param CampaignMonitorSignUpPage $page
0 ignored issues
show
Bug introduced by
There is no parameter named $page. 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...
150
     * @param Array $array
0 ignored issues
show
Bug introduced by
There is no parameter named $array. 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...
151
     * @param Form $form
152
     *
153
     * return string: can be subscribe / unsubscribe / error
154
     */
155
    public function processCampaignMonitorSignupField($listPage, $data, $form)
0 ignored issues
show
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...
156
    {
157
        $typeOfAction = "unsubscribe";
158
        //many choices
159
        if (isset($data["SubscribeManyChoices"])) {
160
            $listPages = CampaignMonitorSignupPage::get_ready_ones();
161
            foreach ($listPages as $listPage) {
162
                if (isset($data["SubscribeManyChoices"][$listPage->ListID]) && $data["SubscribeManyChoices"][$listPage->ListID]) {
163
                    $this->owner->addCampaignMonitorList($listPage->ListID);
164
                    $typeOfAction = "subscribe";
165
                } else {
166
                    $this->owner->removeCampaignMonitorList($listPage->ListID);
167
                }
168
            }
169
        }
170
        //one choice
171
        elseif (isset($data["SubscribeChoice"])) {
172
            if ($data["SubscribeChoice"] == "Subscribe") {
173
                $customFields = $listPage->CampaignMonitorCustomFields()->filter(array("Visible" => 1));
174
                $customFieldsArray = array();
175
                foreach ($customFields as $customField) {
176
                    if (isset($data["CMCustomField".$customField->Code])) {
177
                        $customFieldsArray[$customField->Code] = $data["CMCustomField".$customField->Code];
178
                    }
179
                }
180
                $this->owner->addCampaignMonitorList($listPage->ListID, $customFieldsArray);
181
                $typeOfAction = "subscribe";
182
            } else {
183
                $this->owner->removeCampaignMonitorList($listPage->ListID);
184
            }
185
        } else {
186
            user_error("Subscriber field missing", E_USER_WARNING);
187
        }
188
        return $typeOfAction;
189
    }
190
191
    /**
192
     * immediately unsubscribe if you are logged in.
193
     * @param HTTPRequest
194
     */
195 View Code Duplication
    public function unsubscribe($request)
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...
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...
196
    {
197
        $member = Member::currentUser();
198
        if ($member) {
199
            $member->removeCampaignMonitorList($this->ListID);
0 ignored issues
show
Bug introduced by
The property ListID 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...
200
            $this->Content = $member->Email." has been removed from this list: ".$this->getListTitle();
0 ignored issues
show
Bug introduced by
The property Content 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...
Bug introduced by
The method getListTitle() does not seem to exist on object<CampaignMonitorMemberDOD>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
201
        } else {
202
            Security::permissionFailure($this, _t("CAMPAIGNMONITORSIGNUPPAGE.LOGINFIRST", "Please login first."));
0 ignored issues
show
Documentation introduced by
$this is of type this<CampaignMonitorMemberDOD>, but the function expects a object<Controller>|null.

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...
203
        }
204
        return array();
205
    }
206
207
    /**
208
     * is this user currently signed up to one or more newsletters
209
     *
210
     * @return Boolean
0 ignored issues
show
Documentation introduced by
Should the return type not be boolean|null?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
211
     */
212
    public function IsCampaignMonitorSubscriber()
213
    {
214
        CampaignMonitorSignupPage::get_ready_ones()
215
            ->where("MemberID = ".$this->owner->ID)
0 ignored issues
show
Bug introduced by
The property ID does not seem to exist in SS_Object.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
216
            ->innerJoin("Group_Members", "CampaignMonitorSignupPage ON CampaignMonitorSignupPage.GroupID = Group_Members.GroupID")
217
            ->count() ? true : false;
218
    }
219
220
    /**
221
     * add to Group
222
     * add to CM database...
223
     * @param CampaignMonitorSignupPage | Int $listPage
224
     * @param array $customFields
225
     * @return Boolean - returns true on success
226
     */
227
    public function addCampaignMonitorList($listPage, $customFields = array())
228
    {
229
        $api = $this->getCMAPI();
230
        $outcome = 0;
231
        if (is_string($listPage)) {
232
            $listPage = CampaignMonitorSignupPage::get()->filter(array("ListID" => $listPage))->first();
233
        }
234
        //internal database
235 View Code Duplication
        if ($listPage && $listPage->GroupID) {
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...
236
            if ($gp = Group::get()->byID($listPage->GroupID)) {
237
                $groups = $this->owner->Groups();
238
                if ($groups) {
239
                    $this->owner->Groups()->add($gp);
240
                    $outcome++;
241
                }
242
            }
243
        }
244
        if ($listPage && $listPage->ListID) {
245
            if ($api->getSubscriber($listPage->ListID, $this->owner)) {
246
                if ($api->updateSubscriber(
247
                    $listPage->ListID,
248
                    $oldEmailAddress = "",
249
                    $this->owner,
0 ignored issues
show
Compatibility introduced by
$this->owner of type object<SS_Object> is not a sub-type of object<Member>. It seems like you assume a child class of the class SS_Object to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
250
                    $customFields,
251
                    $resubscribe = true,
252
                    $restartSubscriptionBasedAutoResponders = false
253
                )) {
254
                    $outcome++;
255
                }
256
            } elseif (!$api->addSubscriber(
257
                $listPage->ListID,
258
                $this->owner,
0 ignored issues
show
Compatibility introduced by
$this->owner of type object<SS_Object> is not a sub-type of object<Member>. It seems like you assume a child class of the class SS_Object to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
259
                $customFields,
260
                true,
261
                false
262
            )) {
263
                $outcome++;
264
            }
265
        }
266
        if ($outcome > 1) {
0 ignored issues
show
Unused Code introduced by
This if statement, and the following return statement can be replaced with return $outcome > 1;.
Loading history...
267
            return true;
268
        }
269
        return false;
270
    }
271
272
    /**
273
     *
274
     * remove from Group
275
     * remove from CM database...
276
     * @param CampaignMonitorSignupPage | Int $listPage
277
     * @return boolean returns true if successful.
278
     */
279
    public function removeCampaignMonitorList($listPage)
280
    {
281
        $api = $this->getCMAPI();
282
        $outcome = 0;
283
        if (is_string($listPage)) {
284
            $listPage = CampaignMonitorSignupPage::get()->filter(array("ListID" => $listPage))->first();
285
        }
286 View Code Duplication
        if ($listPage->GroupID) {
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...
287
            if ($gp = Group::get()->byID($listPage->GroupID)) {
288
                $groups = $this->owner->Groups();
289
                if ($groups) {
290
                    $this->owner->Groups()->remove($gp);
291
                    $outcome++;
292
                }
293
            }
294
        }
295
        if ($listPage->ListID) {
296
            if (!$api->unsubscribeSubscriber($listPage->ListID, $this->owner)) {
297
                $outcome++;
298
            }
299
        }
300
        if ($outcome > 1) {
0 ignored issues
show
Unused Code introduced by
This if statement, and the following return statement can be replaced with return $outcome > 1;.
Loading history...
301
            return true;
302
        }
303
        return false;
304
    }
305
306
    /**
307
     * returns a list of list IDs
308
     * that the user is currently subscribed to.
309
     *
310
     * @return Array
311
     */
312
    public function CampaignMonitorSignupPageIDs()
313
    {
314
        $api = $this->getCMAPI();
315
        $lists = $api->getListsForEmail($this->owner);
316
        $array = array();
317
        if ($lists && count($lists)) {
318
            foreach ($lists as $listArray) {
0 ignored issues
show
Bug introduced by
The expression $lists of type object<CS_REST_Wrapper_Result> is not traversable.
Loading history...
319
                if (in_array($listArray["SubscriberState"], array("Active", "Bounced"))) {
320
                    $array[$listArray["ListID"]] = $listArray["ListID"];
321
                }
322
            }
323
        }
324
        return $array;
325
    }
326
}
327