CampaignMonitorAPIConnector::saveToCache()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 7

Duplication

Lines 10
Ratio 100 %

Importance

Changes 0
Metric Value
dl 10
loc 10
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 7
nc 2
nop 2
1
<?php
2
3
/**
4
 * Main Holder page for Recipes
5
 *@author nicolaas [at] sunnysideup.co.nz
6
 */
7
class CampaignMonitorAPIConnector extends Object
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...
8
{
9
10
    /**
11
     * REQUIRED!
12
     * this is the CM url for logging in.
13
     * which can be used by the client.
14
     * @var String
15
     */
16
    private static $campaign_monitor_url = "";
0 ignored issues
show
Unused Code introduced by
The property $campaign_monitor_url 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
     * REQUIRED!
20
     * @var String
21
     */
22
    private static $client_id = "";
0 ignored issues
show
Unused Code introduced by
The property $client_id 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...
23
24
25
    /**
26
     * OPTION 1: API KEY!
27
     * @var String
28
     */
29
    private static $api_key = "";
0 ignored issues
show
Unused Code introduced by
The property $api_key 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...
30
31
32
    /**
33
     * OPTION 2: OAUTH OPTION
34
     * @var String
35
     */
36
    private static $client_secret = "";
0 ignored issues
show
Unused Code introduced by
The property $client_secret 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...
37
38
    /**
39
     * OPTION 2: OAUTH OPTION
40
     * @var String
41
     */
42
    private static $redirect_uri = "";
0 ignored issues
show
Unused Code introduced by
The property $redirect_uri 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...
43
44
    /**
45
     * OPTION 2: OAUTH OPTION
46
     * @var String
47
     */
48
    private static $code = "";
0 ignored issues
show
Unused Code introduced by
The property $code 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...
49
50
    /**
51
     *
52
     * @var Boolean
53
     */
54
    protected $debug = false;
55
56
    /**
57
     *
58
     * @var Boolean
59
     */
60
    protected $allowCaching = false;
61
62
    /**
63
     *
64
     * @var Int
65
     */
66
    protected $httpStatusCode = 0;
67
68
69
    /**
70
     *
71
     * must be called to use this API.
72
     */
73
    public function init()
74
    {
75
        //require_once Director::baseFolder().'/'.SS_CAMPAIGNMONITOR_DIR.'/third_party/vendor/autoload.php';
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...
76
        //require_once Director::baseFolder().'/'.SS_CAMPAIGNMONITOR_DIR.'/third_party/vendor/campaignmonitor/createsend-php/csrest_lists.php';
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...
77
    }
78
79
    /**
80
     * turn debug on or off
81
     *
82
     * @param Boolean
83
     */
84
    public function setDebug($b)
85
    {
86
        $this->debug = $b;
87
    }
88
89
    /**
90
     *
91
     * @param Boolean $b
92
     */
93
    public function setAllowCaching($b)
94
    {
95
        $this->allowCaching = $b;
96
    }
97
98
    /**
99
     *
100
     * @return Boolean
101
     */
102
    public function getAllowCaching()
103
    {
104
        return $this->allowCaching;
105
    }
106
107
    /**
108
     * provides the Authorisation Array
109
     * @return Array
110
     */
111
    protected function getAuth()
112
    {
113
        if ($auth = $this->getFromCache("getAuth")) {
114
            return $auth;
115
        } else {
116
            if ($apiKey = $this->Config()->get("api_key")) {
117
                $auth = array('api_key' => $apiKey);
118
            } else {
119
                $client_id = $this->Config()->get("client_id");
120
                $client_secret = $this->Config()->get("client_secret");
121
                $redirect_uri = $this->Config()->get("redirect_uri");
122
                $code = $this->Config()->get("code");
123
124
                $result = CS_REST_General::exchange_token($client_id, $client_secret, $redirect_uri, $code);
125
126
                if ($result->was_successful()) {
127
                    $auth = array(
128
                        'access_token' => $result->response->access_token,
129
                        'refresh_token' => $result->response->refresh_token
130
                    );
131
                    //TODO: do we need to check expiry date?
132
                    //$expires_in = $result->response->expires_in;
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...
133
                    # Save $access_token, $expires_in, and $refresh_token.
0 ignored issues
show
Unused Code Comprehensibility introduced by
47% 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...
134
                    if ($this->debug) {
135
                        "access token: ".$result->response->access_token."\n";
136
                        "expires in (seconds): ".$result->response->expires_in."\n";
137
                        "refresh token: ".$result->response->refresh_token."\n";
138
                    }
139
                } else {
140
                    # If you receive '121: Expired OAuth Token', refresh the access token
141
                    if ($result->response->Code == 121) {
142
                        $wrap = new CS_REST_General($auth);
143
                        list($new_access_token, $new_expires_in, $new_refresh_token) = $wrap->refresh_token();
0 ignored issues
show
Unused Code introduced by
The assignment to $new_expires_in is unused. Consider omitting it like so list($first,,$third).

This checks looks for assignemnts to variables using the list(...) function, where not all assigned variables are subsequently used.

Consider the following code example.

<?php

function returnThreeValues() {
    return array('a', 'b', 'c');
}

list($a, $b, $c) = returnThreeValues();

print $a . " - " . $c;

Only the variables $a and $c are used. There was no need to assign $b.

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
144
                    }
145
                    $auth = array(
146
                        'access_token' => $new_access_token,
0 ignored issues
show
Bug introduced by
The variable $new_access_token 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...
147
                        'refresh_token' => $new_refresh_token
0 ignored issues
show
Bug introduced by
The variable $new_refresh_token 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...
148
                    );
149
                    if ($this->debug) {
150
                        'An error occurred:\n';
151
                        $result->response->error.': '.$result->response->error_description."\n";
152
                    }
153
                }
154
            }
155
            $this->saveToCache($auth, "getAuth");
156
            return $auth;
157
        }
158
    }
159
160
    /**
161
     * returns the result or NULL in case of an error
162
     * @param CS_REST_Wrapper_Result
163
     * @return Mixed | Null
164
     */
165
    protected function returnResult($result, $apiCall, $description)
166
    {
167
        if ($this->debug) {
168
            echo "<h1>$description ( $apiCall ) ...</h1>";
169
            if ($result->was_successful()) {
170
                echo "<h2>SUCCESS</h2>";
171
            } else {
172
                echo "<h2>FAILURE: ".$result->http_status_code."</h2>";
173
            }
174
            echo "<pre>";
175
            print_r($result);
176
            echo "</pre>";
177
            echo "<hr /><hr /><hr />";
178
            ob_flush();
179
            flush();
180
        }
181
        if ($result->was_successful()) {
182
            if (isset($result->response)) {
183
                return $result->response;
184
            }
185
            return true;
186
        } else {
187
            $this->httpStatusCode = $result->http_status_code;
188
            return null;
189
        }
190
    }
191
192
    /**
193
     * returns the HTTP code for the response.
194
     * This can be handy for debuging purposes.
195
     * @return Int
196
     */
197
    public function getHttpStatusCode()
198
    {
199
        return $this->httpStatusCode;
200
    }
201
202
    /*******************************************************
203
     * caching
204
     *
205
     *******************************************************/
206
207
    /**
208
     * @param String $name
209
     * @return Mixed
210
     */
211 View Code Duplication
    protected function getFromCache($name)
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...
212
    {
213
        if ($this->getAllowCaching()) {
214
            $name = "CampaignMonitorAPIConnector_".$name;
215
            $cache = SS_Cache::factory($name);
216
            $value = $cache->load($name);
217
            if (!$value) {
218
                return null;
219
            }
220
            return unserialize($value);
221
        }
222
    }
223
224
    /**
225
     * @param Mixed $unserializedValue
226
     * @param String $name
227
     */
228 View Code Duplication
    protected function saveToCache($unserializedValue, $name)
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...
229
    {
230
        if ($this->getAllowCaching()) {
231
            $serializedValue = serialize($unserializedValue);
232
            $name = "CampaignMonitorAPIConnector_".$name;
233
            $cache = SS_Cache::factory($name);
234
            $cache->save($serializedValue, $name);
235
            return true;
236
        }
237
    }
238
239
240
    /*******************************************************
241
     * client
242
     *
243
     *******************************************************/
244
245
    /**
246
     *
247
     * @return CS_REST_Wrapper_Result A successful response will be an object of the form
248
     * array(
249
     *     {
250
     *         'WebVersionURL' => The web version url of the campaign
251
     *         'WebVersionTextURL' => The web version url of the text version of the campaign
252
     *         'CampaignID' => The id of the campaign
253
     *         'Subject' => The campaign subject
254
     *         'Name' => The name of the campaign
255
     *         'FromName' => The from name for the campaign
256
     *         'FromEmail' => The from email address for the campaign
257
     *         'ReplyTo' => The reply to email address for the campaign
258
     *         'SentDate' => The sent data of the campaign
259
     *         'TotalRecipients' => The number of recipients of the campaign
260
     *     }
261
     */
262 View Code Duplication
    public function getCampaigns()
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...
263
    {
264
        //require_once '../../csrest_clients.php';
265
        $wrap = new CS_REST_Clients($this->Config()->get("client_id"), $this->getAuth());
266
        $result = $wrap->get_campaigns();
267
        return $this->returnResult(
268
            $result,
269
            "GET /api/v3.1/clients/{id}/campaigns",
270
            "Got sent campaigns"
271
        );
272
    }
273
274 View Code Duplication
    public function getDrafts()
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...
275
    {
276
        //require_once '../../csrest_clients.php';
277
        $wrap = new CS_REST_Clients($this->Config()->get("client_id"), $this->getAuth());
278
        $result = $wrap->get_drafts();
279
        return $this->returnResult(
280
            $result,
281
            "GET /api/v3.1/clients/{id}/drafts",
282
            "Got draft campaigns"
283
        );
284
    }
285
286
    /**
287
     * Gets all subscriber lists the current client has created
288
     * @return CS_REST_Wrapper_Result A successful response will be an object of the form
289
     * array(
290
     *     {
291
     *         'ListID' => The id of the list
292
     *         'Name' => The name of the list
293
     *     }
294
     * )
295
     */
296 View Code Duplication
    public function getLists()
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...
297
    {
298
        //require_once '../../csrest_clients.php';
299
        $wrap = new CS_REST_Clients($this->Config()->get("client_id"), $this->getAuth());
300
        $result = $wrap->get_lists();
301
        return $this->returnResult(
302
            $result,
303
            "GET /api/v3.1/clients/{id}/lists",
304
            "Got Lists"
305
        );
306
    }
307
308
    public function getScheduled()
309
    {
310
        user_error("This method is still to be implemented, see samples for an example");
311
    }
312
313
    /**
314
     * list of people that are definitely suppressed...
315
     * @param  int $page     page number
316
     * @param  int $pageSize size of page
317
     * @param  string $sortByField (email)
318
     * @param  string $sortDirection (asc)
319
     *
320
     * @return [type]                 [description]
0 ignored issues
show
Documentation introduced by
The doc-type [type] could not be parsed: Unknown type name "" at position 0. [(view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
321
     */
322
    public function getSuppressionlist($page, $pageSize, $sortByField = 'email', $sortDirection = 'asc')
323
    {
324
        $wrap = new CS_REST_Clients(
325
            $this->Config()->get("client_id"),
326
            $this->getAuth()
327
        );
328
        $result = $wrap->get_suppressionlist(
329
            $page,
330
            $pageSize,
331
            $sortByField,
332
            $sortDirection
333
        );
334
        return $this->returnResult(
335
            $result,
336
            "GET /api/v3/clients/{id}/suppressionlist",
337
            "Get suppression list"
338
        );
339
    }
340
341 View Code Duplication
    public function getTemplates()
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...
342
    {
343
        $wrap = new CS_REST_Clients(
344
            $this->Config()->get("client_id"),
345
            $this->getAuth()
346
        );
347
        $result = $wrap->get_templates();
348
        return $this->returnResult(
349
            $result,
350
            "GET /api/v3/clients/{id}/templates",
351
            "Get Templates"
352
        );
353
    }
354
355 View Code Duplication
    public function getTemplate($templatID)
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...
356
    {
357
        $wrap = new CS_REST_Templates(
358
            $templatID,
359
            $this->getAuth()
360
        );
361
        $result = $wrap->get();
362
        return $this->returnResult(
363
            $result,
364
            "GET /api/v3/templates/{ID}",
365
            "Got Summary"
366
        );
367
    }
368
369
    /**
370
     *
371
     * @param CampaignMonitorCampaign $campaignMonitorCampaign
372
     *
373
     * @return CS_REST_Wrapper_Result
374
     */
375 View Code Duplication
    public function createTemplate($campaignMonitorCampaign)
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...
376
    {
377
        $siteConfig = SiteConfig::current_site_config();
0 ignored issues
show
Unused Code introduced by
$siteConfig 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...
378
379
        $name = "Template for ".$campaignMonitorCampaign->Name;
0 ignored issues
show
Documentation introduced by
The property Name does not exist on object<CampaignMonitorCampaign>. 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...
380
        if (!$name) {
381
            $name = "no name set";
382
        }
383
384
        $wrap = new CS_REST_Templates(null, $this->getAuth());
385
        $result = $wrap->create(
386
            $this->Config()->get("client_id"),
387
            array(
388
                'Name' => $name,
389
                'HtmlPageURL' => $campaignMonitorCampaign->PreviewLink(),
390
                'ZipFileURL' => ''
391
            )
392
        );
393
        if (isset($result->http_status_code) && ($result->http_status_code == 201 || $result->http_status_code == 201)) {
394
            $code = $result->response;
395
            $campaignMonitorCampaign->CreateFromWebsite = false;
0 ignored issues
show
Documentation introduced by
The property CreateFromWebsite does not exist on object<CampaignMonitorCampaign>. 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...
396
            $campaignMonitorCampaign->CreatedFromWebsite = true;
0 ignored issues
show
Bug introduced by
The property CreatedFromWebsite does not seem to exist. Did you mean Created?

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...
397
            $campaignMonitorCampaign->TemplateID = $code;
0 ignored issues
show
Documentation introduced by
The property TemplateID does not exist on object<CampaignMonitorCampaign>. 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...
398
        } else {
399
            $campaignMonitorCampaign->CreateFromWebsite = false;
0 ignored issues
show
Documentation introduced by
The property CreateFromWebsite does not exist on object<CampaignMonitorCampaign>. 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...
400
            $campaignMonitorCampaign->CreatedFromWebsite = false;
0 ignored issues
show
Bug introduced by
The property CreatedFromWebsite does not seem to exist. Did you mean Created?

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...
401
            $code = "Error";
402
            if (is_object($result->response)) {
403
                $code = $result->response->Code.":".$result->response->Message;
404
            }
405
            $campaignMonitorCampaign->MessageFromNewsletterServer = $code;
0 ignored issues
show
Documentation introduced by
The property MessageFromNewsletterServer does not exist on object<CampaignMonitorCampaign>. 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...
406
        }
407
        $campaignMonitorCampaign->write();
408
        return $this->returnResult(
409
            $result,
410
            "POST /api/v3/templates/{clientID}",
411
            "Created Template"
412
        );
413
    }
414
415
    /**
416
     *
417
     * @param CampaignMonitorCampaign $campaignMonitorCampaign
418
     * @param string $templateID
419
     *
420
     * @return CS_REST_Wrapper_Result
421
     */
422 View Code Duplication
    public function updateTemplate($campaignMonitorCampaign, $templateID)
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...
423
    {
424
        $siteConfig = SiteConfig::current_site_config();
0 ignored issues
show
Unused Code introduced by
$siteConfig 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...
425
426
        $name = "Template for ".$campaignMonitorCampaign->Name;
0 ignored issues
show
Documentation introduced by
The property Name does not exist on object<CampaignMonitorCampaign>. 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...
427
        if (!$name) {
428
            $name = "no name set";
429
        }
430
        $wrap = new CS_REST_Templates($templateID, $this->getAuth());
431
        $result = $wrap->create(
432
            $this->Config()->get("client_id"),
433
            array(
434
                'Name' => $name,
435
                'HtmlPageURL' => $campaignMonitorCampaign->PreviewLink(),
436
                'ZipFileURL' => ''
437
            )
438
        );
439
        if (isset($result->http_status_code) && ($result->http_status_code == 201 || $result->http_status_code == 201)) {
440
            $code = $result->response;
0 ignored issues
show
Unused Code introduced by
$code 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...
441
            $campaignMonitorCampaign->CreateFromWebsite = false;
0 ignored issues
show
Documentation introduced by
The property CreateFromWebsite does not exist on object<CampaignMonitorCampaign>. 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...
442
            $campaignMonitorCampaign->CreatedFromWebsite = true;
0 ignored issues
show
Bug introduced by
The property CreatedFromWebsite does not seem to exist. Did you mean Created?

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...
443
        } else {
444
            $campaignMonitorCampaign->CreateFromWebsite = false;
0 ignored issues
show
Documentation introduced by
The property CreateFromWebsite does not exist on object<CampaignMonitorCampaign>. 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...
445
            $campaignMonitorCampaign->CreatedFromWebsite = false;
0 ignored issues
show
Bug introduced by
The property CreatedFromWebsite does not seem to exist. Did you mean Created?

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...
446
            $code = "Error";
447
            if (is_object($result->response)) {
448
                $code = $result->response->Code.":".$result->response->Message;
449
            }
450
            $campaignMonitorCampaign->MessageFromNewsletterServer = $code;
0 ignored issues
show
Documentation introduced by
The property MessageFromNewsletterServer does not exist on object<CampaignMonitorCampaign>. 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...
451
        }
452
        $campaignMonitorCampaign->write();
453
        return $this->returnResult(
454
            $result,
455
            "PUT /api/v3/templates/{ID}",
456
            "Updated Template"
457
        );
458
    }
459
460 View Code Duplication
    public function deleteTemplate($templateID)
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...
461
    {
462
        $wrap = new CS_REST_Templates($templateID, $this->getAuth());
463
        $result = $wrap->delete();
464
        return $this->returnResult(
465
            $result,
466
            "DELETE /api/v3/templates/{ID}",
467
            "Deleted Template"
468
        );
469
    }
470
471
    /*******************************************************
472
     * lists
473
     *
474
     *******************************************************/
475
476
    /**
477
     * Creates a new list based on the provided details.
478
     * Both the UnsubscribePage and the ConfirmationSuccessPage parameters are optional
479
     *
480
     * @param string $title - the page to redirect subscribers to when they unsubscribeThe list title
481
     * @param string $unsubscribePage - The page to redirect subscribers to when they unsubscribe
482
     * @param boolean $confirmedOptIn - Whether this list requires confirmation of subscription
483
     * @param string $confirmationSuccessPage - The page to redirect subscribers to when they confirm their subscription
484
     * @param string $unsubscribeSetting - Unsubscribe setting must be CS_REST_LIST_UNSUBSCRIBE_SETTING_ALL_CLIENT_LISTS or CS_REST_LIST_UNSUBSCRIBE_SETTING_ONLY_THIS_LIST.  See the documentation for details: http://www.campaignmonitor.com/api/lists/#creating_a_list
0 ignored issues
show
Documentation introduced by
Should the type for parameter $unsubscribeSetting not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
485
     *
486
     * @return CS_REST_Wrapper_Result A successful response will be the ID of the newly created list
487
     */
488
    public function createList($title, $unsubscribePage, $confirmedOptIn = false, $confirmationSuccessPage, $unsubscribeSetting = null)
0 ignored issues
show
Coding Style introduced by
Parameters which have default values should be placed at the end.

If you place a parameter with a default value before a parameter with a default value, the default value of the first parameter will never be used as it will always need to be passed anyway:

// $a must always be passed; it's default value is never used.
function someFunction($a = 5, $b) { }
Loading history...
489
    {
490
        //require_once '../../csrest_lists.php';
491
        $wrap = new CS_REST_Lists(null, $this->getAuth());
492
        //we need to do this afterwards otherwise the definition below
493
        //is not recognised
494
        if (!$unsubscribeSetting) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $unsubscribeSetting of type string|null is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
495
            $unsubscribeSetting = CS_REST_LIST_UNSUBSCRIBE_SETTING_ALL_CLIENT_LISTS;
496
        }
497
        $result = $wrap->create(
498
            $this->Config()->get("client_id"),
499
            array(
500
                'Title' => $title,
501
                'UnsubscribePage' => $unsubscribePage,
502
                'ConfirmedOptIn' => $confirmedOptIn,
503
                'ConfirmationSuccessPage' => $confirmationSuccessPage,
504
                'UnsubscribeSetting' => $unsubscribeSetting
505
            )
506
        );
507
        return $this->returnResult(
508
            $result,
509
            "POST /api/v3.1/lists/{clientID}",
510
            "Created with ID"
511
        );
512
    }
513
514
    /**
515
     * Creates custom field for list
516
     *
517
     * @param string $listID - list ID
518
     * @param string $type - type of custom field
519
     * @param string $title - field type
520
     * @param array $options - options for dropdown field type
521
     *
522
     * @return CS_REST_Wrapper_Result A successful response will be the key of the newly created custom field
523
     */
524
    public function createCustomField($listID, $visible, $type, $title, $options = array())
525
    {
526
        $wrap = new CS_REST_Lists($listID, $this->getAuth());
527
        switch ($type) {
528
            case "text":
529
                $type = CS_REST_CUSTOM_FIELD_TYPE_TEXT;
530
                break;
531
            case "number":
532
                $type = CS_REST_CUSTOM_FIELD_TYPE_NUMBER;
533
                break;
534
            case "multi_select_one":
535
                $type = CS_REST_CUSTOM_FIELD_TYPE_MULTI_SELECTONE;
536
                break;
537
            case "multi_select_many":
538
                $type = CS_REST_CUSTOM_FIELD_TYPE_MULTI_SELECTMANY;
539
                break;
540
            case "date":
541
                $type = CS_REST_CUSTOM_FIELD_TYPE_DATE;
542
                break;
543
            default:
544
                user_error("You must select one from text, number, multi_select_one, multi_select_many, date)");
545
        }
546
        $result = $wrap->create_custom_field(array(
547
            'FieldName' => $title,
548
            'DataType' => $type,
549
            'Options' => $options,
550
            'VisibleInPreferenceCenter' => $visible ? true : false
551
        ));
552
        return $this->returnResult(
553
            $result,
554
            "POST /api/v3/lists/{ID}/customfields",
555
            "Created Custom Field for $listID "
556
        );
557
    }
558
559
    /**
560
     * Creates custom field for list
561
     *
562
     * @param string $listID - list ID
563
     * @param string $key
564
     *
565
     * @return CS_REST_Wrapper_Result
566
     */
567 View Code Duplication
    public function deleteCustomField($listID, $key)
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...
568
    {
569
        $wrap = new CS_REST_Lists($listID, $this->getAuth());
570
        $result = $wrap->delete_custom_field($key);
571
        return $this->returnResult(
572
            $result,
573
            "DELETE /api/v3/lists/{ID}/{Key}",
574
            "Delete Custom Field for $listID with key $key"
575
        );
576
    }
577
578
    /**
579
     * Deletes an existing list from the system
580
     * @param Int $listID
581
     * @return CS_REST_Wrapper_Result A successful response will be empty
582
     */
583 View Code Duplication
    public function deleteList($listID)
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...
584
    {
585
        //require_once '../../csrest_lists.php';
586
        $wrap = new CS_REST_Lists($listID, $this->getAuth());
587
        $result = $wrap->delete();
588
        return $this->returnResult(
589
            $result,
590
            "DELETE /api/v3.1/lists/{ID}",
591
            "Deleted with code"
592
        );
593
    }
594
595
    /**
596
     * Gets the basic details of the current list
597
     *
598
     * @param Int $listID
599
     *
600
     * @return CS_REST_Wrapper_Result A successful response will be an object of the form
601
     * {
602
     *     'ListID' => The id of the list
603
     *     'Title' => The title of the list
604
     *     'UnsubscribePage' => The page which subscribers are redirected to upon unsubscribing
605
     *     'ConfirmedOptIn' => Whether the list is Double-Opt In
606
     *     'ConfirmationSuccessPage' => The page which subscribers are
607
     *         redirected to upon confirming their subscription
608
     *     'UnsubscribeSetting' => The unsubscribe setting for the list. Will
609
     *         be either CS_REST_LIST_UNSUBSCRIBE_SETTING_ALL_CLIENT_LISTS or
610
     *         CS_REST_LIST_UNSUBSCRIBE_SETTING_ONLY_THIS_LIST.
611
     * }
612
     */
613 View Code Duplication
    public function getList($listID)
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...
614
    {
615
        //require_once '../../csrest_lists.php';
616
        $wrap = new CS_REST_Lists($listID, $this->getAuth());
617
        $result = $wrap->get();
618
        return $this->returnResult(
619
            $result,
620
            "GET /api/v3.1/lists/{ID}",
621
            "Got list details"
622
        );
623
    }
624
625
    /**
626
     * Gets all active subscribers added since the given date
627
     *
628
     * @param Int $listID
629
     * @param string $daysAgo The date to start getting subscribers from
0 ignored issues
show
Documentation introduced by
Should the type for parameter $daysAgo not be integer?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
630
     * @param int $page The page number to get
631
     * @param int $pageSize The number of records per page
632
     * @param string $sortByField ('EMAIL', 'NAME', 'DATE')
633
     * @param string $sortDirection ('ASC', 'DESC')
634
     *
635
     * @return CS_REST_Wrapper_Result A successful response will be an object of the form
636
     * {
637
     *     'ResultsOrderedBy' => The field the results are ordered by
638
     *     'OrderDirection' => The order direction
639
     *     'PageNumber' => The page number for the result set
640
     *     'PageSize' => The page size used
641
     *     'RecordsOnThisPage' => The number of records returned
642
     *     'TotalNumberOfRecords' => The total number of records available
643
     *     'NumberOfPages' => The total number of pages for this collection
644
     *     'Results' => array(
645
     *         {
646
     *             'EmailAddress' => The email address of the subscriber
647
     *             'Name' => The name of the subscriber
648
     *             'Date' => The date that the subscriber was added to the list
649
     *             'State' => The current state of the subscriber, will be 'Active'
650
     *             'CustomFields' => array (
651
     *                 {
652
     *                     'Key' => The personalisation tag of the custom field
653
     *                     'Value' => The value of the custom field for this subscriber
654
     *                 }
655
     *             )
656
     *         }
657
     *     )
658
     * }
659
     */
660 View Code Duplication
    public function getActiveSubscribers($listID, $daysAgo = 3650, $page = 1, $pageSize = 999, $sortByField = "DATE", $sortDirection = "DESC")
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...
661
    {
662
        //require_once '../../csrest_lists.php';
663
        $wrap = new CS_REST_Lists($listID, $this->getAuth());
664
        $result = $wrap->get_active_subscribers(
665
            date('Y-m-d', strtotime('-'.$daysAgo.' days')),
666
            $page,
667
            $pageSize,
668
            $sortByField,
669
            $sortDirection
670
        );
671
        return $this->returnResult(
672
            $result,
673
            "GET /api/v3.1/lists/{ID}/active",
674
            "Got active subscribers"
675
        );
676
    }
677
678
    /**
679
     * Gets all unconfirmed subscribers added since the given date
680
     *
681
     * @param Int $listID
682
     * @param string $daysAgo The date to start getting subscribers from
0 ignored issues
show
Documentation introduced by
Should the type for parameter $daysAgo not be integer?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
683
     * @param int $page The page number to get
684
     * @param int $pageSize The number of records per page
685
     * @param string $sortByField ('EMAIL', 'NAME', 'DATE')
686
     * @param string $sortDirection ('ASC', 'DESC')
687
     *
688
     * @return CS_REST_Wrapper_Result A successful response will be an object of the form
689
     * {
690
     *     'ResultsOrderedBy' => The field the results are ordered by
691
     *     'OrderDirection' => The order direction
692
     *     'PageNumber' => The page number for the result set
693
     *     'PageSize' => The page size used
694
     *     'RecordsOnThisPage' => The number of records returned
695
     *     'TotalNumberOfRecords' => The total number of records available
696
     *     'NumberOfPages' => The total number of pages for this collection
697
     *     'Results' => array(
698
     *         {
699
     *             'EmailAddress' => The email address of the subscriber
700
     *             'Name' => The name of the subscriber
701
     *             'Date' => The date that the subscriber was added to the list
702
     *             'State' => The current state of the subscriber, will be 'Unconfirmed'
703
     *             'CustomFields' => array (
704
     *                 {
705
     *                     'Key' => The personalisation tag of the custom field
706
     *                     'Value' => The value of the custom field for this subscriber
707
     *                 }
708
     *             )
709
     *         }
710
     *     )
711
     * }
712
     */
713 View Code Duplication
    public function getUnconfirmedSubscribers($listID, $daysAgo = 3650, $page = 1, $pageSize = 999, $sortByField = "DATE", $sortDirection = "DESC")
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...
714
    {
715
        //require_once '../../csrest_lists.php';
716
        $wrap = new CS_REST_Lists($listID, $this->getAuth());
717
        $result = $wrap->get_unconfirmed_subscribers(
718
            date('Y-m-d', strtotime('-'.$daysAgo.' days')),
719
            $page,
720
            $pageSize,
721
            $sortByField,
722
            $sortDirection
723
        );
724
        return $this->returnResult(
725
            $result,
726
            "GET /api/v3.1/lists/{ID}/unconfirmed",
727
            "Got unconfimred subscribers"
728
        );
729
    }
730
731
    /**
732
     * Gets all bounced subscribers who have bounced out since the given date
733
     *
734
     * @param Int $listID
735
     * @param string $daysAgo The date to start getting subscribers from
0 ignored issues
show
Documentation introduced by
Should the type for parameter $daysAgo not be integer?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
736
     * @param int $page The page number to get
737
     * @param int $pageSize The number of records per page
738
     * @param string $sortByField ('EMAIL', 'NAME', 'DATE')
739
     * @param string $sortDirection ('ASC', 'DESC')
740
     *
741
     * @return CS_REST_Wrapper_Result A successful response will be an object of the form
742
     * {
743
     *     'ResultsOrderedBy' => The field the results are ordered by
744
     *     'OrderDirection' => The order direction
745
     *     'PageNumber' => The page number for the result set
746
     *     'PageSize' => The page size used
747
     *     'RecordsOnThisPage' => The number of records returned
748
     *     'TotalNumberOfRecords' => The total number of records available
749
     *     'NumberOfPages' => The total number of pages for this collection
750
     *     'Results' => array(
751
     *         {
752
     *             'EmailAddress' => The email address of the subscriber
753
     *             'Name' => The name of the subscriber
754
     *             'Date' => The date that the subscriber bounced out of the list
755
     *             'State' => The current state of the subscriber, will be 'Bounced'
756
     *             'CustomFields' => array (
757
     *                 {
758
     *                     'Key' => The personalisation tag of the custom field
759
     *                     'Value' => The value of the custom field for this subscriber
760
     *                 }
761
     *             )
762
     *         }
763
     *     )
764
     * }
765
     */
766 View Code Duplication
    public function getBouncedSubscribers($listID, $daysAgo = 3650, $page = 1, $pageSize = 999, $sortByField = "DATE", $sortDirection = "DESC")
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...
767
    {
768
        //require_once '../../csrest_lists.php';
769
        $wrap = new CS_REST_Lists($listID, $this->getAuth());
770
        $result = $wrap->get_bounced_subscribers(
771
            date('Y-m-d', strtotime('-'.$daysAgo.' days')),
772
            $page,
773
            $pageSize,
774
            $sortByField,
775
            $sortDirection
776
        );
777
        return $this->returnResult(
778
            $result,
779
            "GET /api/v3.1/lists/{ID}/bounced",
780
            "Got bounced subscribers"
781
        );
782
    }
783
784
785
    /**
786
     * Gets all unsubscribed subscribers who have unsubscribed since the given date
787
     *
788
     * @param Int $listID
789
     * @param string $daysAgo The date to start getting subscribers from
0 ignored issues
show
Documentation introduced by
Should the type for parameter $daysAgo not be integer?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
790
     * @param int $page The page number to get
791
     * @param int $pageSize The number of records per page
792
     * @param string $sortByField ('EMAIL', 'NAME', 'DATE')
793
     * @param string $sortDirection ('ASC', 'DESC')
794
     *
795
     * @return CS_REST_Wrapper_Result A successful response will be an object of the form
796
     * {
797
     *     'ResultsOrderedBy' => The field the results are ordered by
798
     *     'OrderDirection' => The order direction
799
     *     'PageNumber' => The page number for the result set
800
     *     'PageSize' => The page size used
801
     *     'RecordsOnThisPage' => The number of records returned
802
     *     'TotalNumberOfRecords' => The total number of records available
803
     *     'NumberOfPages' => The total number of pages for this collection
804
     *     'Results' => array(
805
     *         {
806
     *             'EmailAddress' => The email address of the subscriber
807
     *             'Name' => The name of the subscriber
808
     *             'Date' => The date that the subscriber was unsubscribed from the list
809
     *             'State' => The current state of the subscriber, will be 'Unsubscribed'
810
     *             'CustomFields' => array (
811
     *                 {
812
     *                     'Key' => The personalisation tag of the custom field
813
     *                     'Value' => The value of the custom field for this subscriber
814
     *                 }
815
     *             )
816
     *         }
817
     *     )
818
     * }
819
     */
820 View Code Duplication
    public function getUnsubscribedSubscribers($listID, $daysAgo = 3650, $page = 1, $pageSize = 999, $sortByField = "DATE", $sortDirection = "DESC")
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...
821
    {
822
        //require_once '../../csrest_lists.php';
823
        $wrap = new CS_REST_Lists($listID, $this->getAuth());
824
        $result = $wrap->get_unsubscribed_subscribers(
825
            date('Y-m-d', strtotime('-'.$daysAgo.' days')),
826
            $page,
827
            $pageSize,
828
            $sortByField,
829
            $sortDirection
830
        );
831
        return $this->returnResult(
832
            $result,
833
            "GET /api/v3.1/lists/{ID}/unsubscribed",
834
            "Got unsubscribed subscribers"
835
        );
836
    }
837
838
    /**
839
     * Gets all unsubscribed subscribers who have unsubscribed since the given date
840
     *
841
     * @param Int $listID
842
     * @param string $daysAgo The date to start getting subscribers from
0 ignored issues
show
Documentation introduced by
Should the type for parameter $daysAgo not be integer?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
843
     * @param int $page The page number to get
844
     * @param int $pageSize The number of records per page
845
     * @param string $sortByField ('EMAIL', 'NAME', 'DATE')
846
     * @param string $sortDirection ('ASC', 'DESC')
847
     *
848
     * @return CS_REST_Wrapper_Result A successful response will be an object of the form
849
     * {
850
     *     'ResultsOrderedBy' => The field the results are ordered by
851
     *     'OrderDirection' => The order direction
852
     *     'PageNumber' => The page number for the result set
853
     *     'PageSize' => The page size used
854
     *     'RecordsOnThisPage' => The number of records returned
855
     *     'TotalNumberOfRecords' => The total number of records available
856
     *     'NumberOfPages' => The total number of pages for this collection
857
     *     'Results' => array(
858
     *         {
859
     *             'EmailAddress' => The email address of the subscriber
860
     *             'Name' => The name of the subscriber
861
     *             'Date' => The date that the subscriber was unsubscribed from the list
862
     *             'State' => The current state of the subscriber, will be 'Unsubscribed'
863
     *             'CustomFields' => array (
864
     *                 {
865
     *                     'Key' => The personalisation tag of the custom field
866
     *                     'Value' => The value of the custom field for this subscriber
867
     *                 }
868
     *             )
869
     *         }
870
     *     )
871
     * }
872
     */
873 View Code Duplication
    public function getDeletedSubscribers($listID, $daysAgo = 3650, $page = 1, $pageSize = 999, $sortByField = "email", $sortDirection = "asc")
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...
874
    {
875
        //require_once '../../csrest_lists.php';
876
        $wrap = new CS_REST_Lists($listID, $this->getAuth());
877
        $result = $wrap->get_deleted_subscribers(
878
            date('Y-m-d', strtotime('-'.$daysAgo.' days')),
879
            $page,
880
            $pageSize,
881
            $sortByField,
882
            $sortDirection
883
        );
884
        return $this->returnResult(
885
            $result,
886
            "GET /api/v3/lists/{ID}/delete",
887
            "Got deleted subscribers"
888
        );
889
    }
890
891
    /**
892
     * Updates the details of an existing list
893
     * Both the UnsubscribePage and the ConfirmationSuccessPage parameters are optional
894
     *
895
     * @param string $title - he page to redirect subscribers to when they unsubscribeThe list title
896
     * @param string $unsubscribePage - The page to redirect subscribers to when they unsubscribe
897
     * @param boolean $confirmedOptIn - Whether this list requires confirmation of subscription
898
     * @param string $confirmationSuccessPage - The page to redirect subscribers to when they confirm their subscription
899
     * @param string $unsubscribeSetting - Unsubscribe setting must be CS_REST_LIST_UNSUBSCRIBE_SETTING_ALL_CLIENT_LISTS or CS_REST_LIST_UNSUBSCRIBE_SETTING_ONLY_THIS_LIST.  See the documentation for details: http://www.campaignmonitor.com/api/lists/#creating_a_list
900
     * @param boolean $addUnsubscribesToSuppList -  When UnsubscribeSetting is CS_REST_LIST_UNSUBSCRIBE_SETTING_ALL_CLIENT_LISTS, whether unsubscribes from this list should be added to the suppression list.
901
     * @param boolean $acrubActiveWithSuppList - When UnsubscribeSetting is CS_REST_LIST_UNSUBSCRIBE_SETTING_ALL_CLIENT_LISTS, whether active subscribers should be scrubbed against the suppression list.
0 ignored issues
show
Documentation introduced by
There is no parameter named $acrubActiveWithSuppList. Did you maybe mean $scrubActiveWithSuppList?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function. It has, however, found a similar but not annotated parameter which might be a good fit.

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

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

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

Loading history...
902
     *
903
     * @return CS_REST_Wrapper_Result A successful response will be empty
904
     */
905
    public function updateList($listID, $title, $unsubscribePage, $confirmedOptIn = false, $confirmationSuccessPage, $unsubscribeSetting, $addUnsubscribesToSuppList = true, $scrubActiveWithSuppList = true)
0 ignored issues
show
Coding Style introduced by
Parameters which have default values should be placed at the end.

If you place a parameter with a default value before a parameter with a default value, the default value of the first parameter will never be used as it will always need to be passed anyway:

// $a must always be passed; it's default value is never used.
function someFunction($a = 5, $b) { }
Loading history...
906
    {
907
        //require_once '../../csrest_lists.php';
908
        if (!$unsubscribeSetting) {
909
            $unsubscribeSetting = CS_REST_LIST_UNSUBSCRIBE_SETTING_ALL_CLIENT_LISTS;
910
        }
911
        $wrap = new CS_REST_Lists($listID, $this->getAuth());
912
        $result = $wrap->update(array(
913
            'Title' => $title,
914
            'UnsubscribePage' => $unsubscribePage,
915
            'ConfirmedOptIn' => $confirmedOptIn,
916
            'ConfirmationSuccessPage' => $confirmationSuccessPage,
917
            'UnsubscribeSetting' => $unsubscribeSetting,
918
            'AddUnsubscribesToSuppList' => $addUnsubscribesToSuppList,
919
            'ScrubActiveWithSuppList' => $scrubActiveWithSuppList
920
        ));
921
        return $this->returnResult(
922
            $result,
923
            "PUT /api/v3.1/lists/{ID}",
924
            "Updated with code"
925
        );
926
    }
927
928 View Code Duplication
    public function getSegments($listID)
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...
929
    {
930
        //require_once '../../csrest_lists.php';
931
        $wrap = new CS_REST_Lists($listID, $this->getAuth());
932
        //we need to do this afterwards otherwise the definition below
933
        //is not recognised
934
        $result = $wrap->get_segments();
935
        return $this->returnResult(
936
            $result,
937
            "GET /api/v3.1/lists/{listid}/segments",
938
            "Got segment details"
939
        );
940
    }
941
942
    /**
943
     * Gets statistics for list subscriptions, deletions, bounces and unsubscriptions
944
     *
945
     * @param Int $listID
946
     *
947
     * @return CS_REST_Wrapper_Result A successful response will be an object of the form
948
     * {
949
     *     'TotalActiveSubscribers'
950
     *     'NewActiveSubscribersToday'
951
     *     'NewActiveSubscribersYesterday'
952
     *     'NewActiveSubscribersThisWeek'
953
     *     'NewActiveSubscribersThisMonth'
954
     *     'NewActiveSubscribersThisYeay'
955
     *     'TotalUnsubscribes'
956
     *     'UnsubscribesToday'
957
     *     'UnsubscribesYesterday'
958
     *     'UnsubscribesThisWeek'
959
     *     'UnsubscribesThisMonth'
960
     *     'UnsubscribesThisYear'
961
     *     'TotalDeleted'
962
     *     'DeletedToday'
963
     *     'DeletedYesterday'
964
     *     'DeletedThisWeek'
965
     *     'DeletedThisMonth'
966
     *     'DeletedThisYear'
967
     *     'TotalBounces'
968
     *     'BouncesToday'
969
     *     'BouncesYesterday'
970
     *     'BouncesThisWeek'
971
     *     'BouncesThisMonth'
972
     *     'BouncesThisYear'
973
     * }
974
     */
975 View Code Duplication
    public function getListStats($listID)
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...
976
    {
977
        //require_once '../../csrest_lists.php';
978
        $wrap = new CS_REST_Lists($listID, $this->getAuth());
979
        $result = $wrap->get_stats();
980
        return $this->returnResult(
981
            $result,
982
            "GET /api/v3.1/lists/{ID}/stats",
983
            "Got Lists Stats"
984
        );
985
    }
986
987 View Code Duplication
    public function getListCustomFields($listID)
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...
988
    {
989
        $wrap = new CS_REST_Lists($listID, $this->getAuth());
990
        $result = $wrap->get_custom_fields();
991
        return $this->returnResult(
992
            $result,
993
            "GET /api/v3.1/lists/{ID}/customfields",
994
            "Got Lists Custom Fields"
995
        );
996
    }
997
998
    /*******************************************************
999
     * create campaigns
1000
     *
1001
     *******************************************************/
1002
1003
    /**
1004
     *
1005
     *
1006
     * @param CampaignMonitorCampaign $campaignMonitorCampaign
1007
     * @param array listIDs
1008
     * @param array segmentIDs
1009
     * @param string templateID - OPTIONAL!
1010
     * @param array templateContent - OPTIONAL!
1011
     */
1012
    public function createCampaign(
1013
        $campaignMonitorCampaign,
1014
        $listIDs = array(),
0 ignored issues
show
Unused Code introduced by
The parameter $listIDs 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...
1015
        $segmentIDs = array(),
0 ignored issues
show
Unused Code introduced by
The parameter $segmentIDs 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...
1016
        $templateID = "",
1017
        $templateContent = array()
1018
    ) {
1019
        //require_once '../../csrest_lists.php';
1020
        $siteConfig = SiteConfig::current_site_config();
1021
1022
        $subject = $campaignMonitorCampaign->Subject;
0 ignored issues
show
Documentation introduced by
The property Subject does not exist on object<CampaignMonitorCampaign>. 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...
1023
        if (!$subject) {
1024
            $subject = "no subject set";
1025
        }
1026
1027
        $name = $campaignMonitorCampaign->Name;
0 ignored issues
show
Documentation introduced by
The property Name does not exist on object<CampaignMonitorCampaign>. 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...
1028
        if (!$name) {
1029
            $name = "no name set";
1030
        }
1031
1032
        $fromName = $campaignMonitorCampaign->FromName;
0 ignored issues
show
Documentation introduced by
The property FromName does not exist on object<CampaignMonitorCampaign>. 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...
1033
        if (!$fromName) {
1034
            $fromName = $siteConfig->Title;
1035
        }
1036
1037
        $fromEmail = $campaignMonitorCampaign->FromEmail;
0 ignored issues
show
Documentation introduced by
The property FromEmail does not exist on object<CampaignMonitorCampaign>. 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...
1038
        if (!$fromEmail) {
1039
            $fromEmail = Config::inst()->get('Email', 'admin_email');
1040
        }
1041
1042
        $replyTo = $campaignMonitorCampaign->ReplyTo;
0 ignored issues
show
Documentation introduced by
The property ReplyTo does not exist on object<CampaignMonitorCampaign>. 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...
1043
        if (!$replyTo) {
1044
            $replyTo = $fromEmail;
1045
        }
1046
1047
        $listID = $campaignMonitorCampaign->Pages()->first()->ListID;
0 ignored issues
show
Documentation Bug introduced by
The method Pages does not exist on object<CampaignMonitorCampaign>? 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...
1048
1049
        $wrap = new CS_REST_Campaigns(null, $this->getAuth());
1050
        if ($templateID) {
1051
            $result = $wrap->create_from_template(
1052
                $this->Config()->get("client_id"),
1053
                array(
1054
                    'Subject' => $subject,
1055
                    'Name' => $name,
1056
                    'FromName' => $fromName,
1057
                    'FromEmail' => $fromEmail,
1058
                    'ReplyTo' => $replyTo,
1059
                    'ListIDs' => array($listID),
1060
                    'SegmentIDs' => array(),
1061
                    'TemplateID' => $templateID,
1062
                    'TemplateContent' => $templateContent
1063
                )
1064
            );
1065
        } else {
1066
            $result = $wrap->create(
1067
                $this->Config()->get("client_id"),
1068
                array(
1069
                    'Subject' => $subject,
1070
                    'Name' => $name,
1071
                    'FromName' => $fromName,
1072
                    'FromEmail' => $fromEmail,
1073
                    'ReplyTo' => $replyTo,
1074
                    'HtmlUrl' => $campaignMonitorCampaign->PreviewLink(),
1075
                    'TextUrl' => $campaignMonitorCampaign->PreviewLink("textonly"),
1076
                    'ListIDs' => array($listID)
1077
                )
1078
            );
1079
        }
1080
        if (isset($result->http_status_code) && ($result->http_status_code == 201 || $result->http_status_code == 201)) {
1081
            $code = $result->response;
1082
            $campaignMonitorCampaign->CreateFromWebsite = false;
0 ignored issues
show
Documentation introduced by
The property CreateFromWebsite does not exist on object<CampaignMonitorCampaign>. 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...
1083
            $campaignMonitorCampaign->CreatedFromWebsite = true;
0 ignored issues
show
Bug introduced by
The property CreatedFromWebsite does not seem to exist. Did you mean Created?

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...
1084
            $campaignMonitorCampaign->CampaignID = $code;
0 ignored issues
show
Documentation introduced by
The property CampaignID does not exist on object<CampaignMonitorCampaign>. 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...
1085
        } else {
1086
            $campaignMonitorCampaign->CreateFromWebsite = false;
0 ignored issues
show
Documentation introduced by
The property CreateFromWebsite does not exist on object<CampaignMonitorCampaign>. 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...
1087
            $campaignMonitorCampaign->CreatedFromWebsite = false;
0 ignored issues
show
Bug introduced by
The property CreatedFromWebsite does not seem to exist. Did you mean Created?

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...
1088
            $code = "Error";
1089
            if (is_object($result->response)) {
1090
                $code = $result->response->Code.":".$result->response->Message;
1091
            }
1092
            $campaignMonitorCampaign->MessageFromNewsletterServer = $code;
0 ignored issues
show
Documentation introduced by
The property MessageFromNewsletterServer does not exist on object<CampaignMonitorCampaign>. 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...
1093
        }
1094
        $campaignMonitorCampaign->write();
1095
        return $this->returnResult(
1096
            $result,
1097
            "CREATE /api/v3/campaigns/{clientID}",
1098
            "Created Campaign"
1099
        );
1100
    }
1101
1102 View Code Duplication
    public function deleteCampaign($campaignID)
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...
1103
    {
1104
        $wrap = new CS_REST_Campaigns($campaignID, $this->getAuth());
1105
        $result = $wrap->delete();
1106
        return $this->returnResult(
1107
            $result,
1108
            "DELETE /api/v3/campaigns/{id}",
1109
            "Deleted Campaign"
1110
        );
1111
    }
1112
1113
    /*******************************************************
1114
     * information about the campaigns
1115
     *
1116
     *******************************************************/
1117
1118
    public function getBounces()
1119
    {
1120
        user_error("This method is still to be implemented, see samples for an example");
1121
    }
1122
1123
    public function getClicks()
1124
    {
1125
        user_error("This method is still to be implemented, see samples for an example");
1126
    }
1127
1128
    /**
1129
     * Gets a summary of all campaign reporting statistics
1130
     *
1131
     * @param int $campaignID
1132
     *
1133
     * @return CS_REST_Wrapper_Result A successful response will be an object of the form
1134
     * {
1135
     *     'Recipients' => The total recipients of the campaign
1136
     *     'TotalOpened' => The total number of opens recorded
1137
     *     'Clicks' => The total number of recorded clicks
1138
     *     'Unsubscribed' => The number of recipients who unsubscribed
1139
     *     'Bounced' => The number of recipients who bounced
1140
     *     'UniqueOpened' => The number of recipients who opened
1141
     *     'WebVersionURL' => The url of the web version of the campaign
1142
     *     'WebVersionTextURL' => The url of the web version of the text version of the campaign
1143
     *     'WorldviewURL' => The public Worldview URL for the campaign
1144
     *     'Forwards' => The number of times the campaign has been forwarded to a friend
1145
     *     'Likes' => The number of times the campaign has been 'liked' on Facebook
1146
     *     'Mentions' => The number of times the campaign has been tweeted about
1147
     *     'SpamComplaints' => The number of recipients who marked the campaign as spam
1148
     * }
1149
     */
1150 View Code Duplication
    public function getSummary($campaignID)
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...
1151
    {
1152
        $wrap = new CS_REST_Campaigns($campaignID, $this->getAuth());
1153
        $result = $wrap->get_summary();
1154
        return $this->returnResult(
1155
            $result,
1156
            "GET /api/v3.1/campaigns/{id}/summary",
1157
            "Got Summary"
1158
        );
1159
    }
1160
1161
    /**
1162
     * Gets the email clients that subscribers used to open the campaign
1163
     *
1164
     * @param Int $campaignID
1165
     *
1166
     * @return CS_REST_Wrapper_Result A successful response will be an object of the form
1167
     * array(
1168
     *     {
1169
     *         Client => The email client name
1170
     *         Version => The email client version
1171
     *         Percentage => The percentage of subscribers who used this email client
1172
     *         Subscribers => The actual number of subscribers who used this email client
1173
     *     }
1174
     * )
1175
     */
1176 View Code Duplication
    public function getEmailClientUsage($campaignID)
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...
1177
    {
1178
        $wrap = new CS_REST_Campaigns($campaignID, $this->getAuth());
1179
        $result = $wrap->get_email_client_usage();
1180
        return $this->returnResult(
1181
            $result,
1182
            "GET /api/v3.1/campaigns/{id}/emailclientusage",
1183
            "Got email client usage"
1184
        );
1185
    }
1186
1187
    public function getListsAndSegments()
1188
    {
1189
        user_error("This method is still to be implemented, see samples for an example");
1190
    }
1191
1192
    public function getOpens()
1193
    {
1194
        user_error("This method is still to be implemented, see samples for an example");
1195
    }
1196
1197
    public function getRecipients()
1198
    {
1199
        user_error("This method is still to be implemented, see samples for an example");
1200
    }
1201
1202
    public function getSpam()
1203
    {
1204
        user_error("This method is still to be implemented, see samples for an example");
1205
    }
1206
1207
    /**
1208
     * Gets all unsubscribes recorded for a campaign since the provided date
1209
     *
1210
     * @param int $campaignID ID of the Campaign
1211
     * @param string $daysAgo The date to start getting subscribers from
0 ignored issues
show
Documentation introduced by
Should the type for parameter $daysAgo not be integer?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
1212
     * @param int $page The page number to get
1213
     * @param int $pageSize The number of records per page
1214
     * @param string $sortByField ('EMAIL', 'NAME', 'DATE')
1215
     * @param string $sortDirection ('ASC', 'DESC')
1216
     *
1217
     * @return CS_REST_Wrapper_Result A successful response will be an object of the form
1218
     * {
1219
     *     'ResultsOrderedBy' => The field the results are ordered by
1220
     *     'OrderDirection' => The order direction
1221
     *     'PageNumber' => The page number for the result set
1222
     *     'PageSize' => The page size used
1223
     *     'RecordsOnThisPage' => The number of records returned
1224
     *     'TotalNumberOfRecords' => The total number of records available
1225
     *     'NumberOfPages' => The total number of pages for this collection
1226
     *     'Results' => array(
1227
     *         {
1228
     *             'EmailAddress' => The email address of the subscriber who unsubscribed
1229
     *             'ListID' => The list id of the list containing the subscriber
1230
     *             'Date' => The date of the unsubscribe
1231
     *             'IPAddress' => The ip address where the unsubscribe originated
1232
     *         }
1233
     *     )
1234
     * }
1235
     */
1236 View Code Duplication
    public function getUnsubscribes($campaignID, $daysAgo = 3650, $page =1, $pageSize = 999, $sortByField = "EMAIL", $sortDirection = "ASC")
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...
1237
    {
1238
        //require_once '../../csrest_campaigns.php';
1239
        $wrap = new CS_REST_Campaigns($campaignID, $this->getAuth());
1240
        $result = $wrap->get_unsubscribes(
1241
            date('Y-m-d', strtotime('-'.$daysAgo.' days')),
1242
            $page,
1243
            $pageSize,
1244
            $sortByField,
1245
            $sortDirection
1246
        );
1247
        return $this->returnResult(
1248
            $result,
1249
            "GET /api/v3.1/campaigns/{id}/unsubscribes",
1250
            "Got unsubscribes"
1251
        );
1252
    }
1253
1254
1255
1256
    /*******************************************************
1257
     * user
1258
     *
1259
     * states:
1260
     *
1261
     * Active – Someone who is on a list and will receive any emails sent to that list.
1262
     *
1263
     * Unconfirmed – The individual signed up to a confirmed opt-in list
1264
     * but has not clicked the link in the verification email sent to them.
1265
     *
1266
     * Unsubscribed – The subscriber has removed themselves from a list, or lists,
1267
     * via an unsubscribe link or form.
1268
     * You can also change a subscriber's status to unsubscribed through your account.
1269
     *
1270
     * Bounced – This describes an email address that campaigns cannot be delivered to,
1271
     * which can happen for a number of reasons.
1272
     *
1273
     * Deleted – Means the subscriber has been deleted from a list through your account.
1274
     *
1275
     *******************************************************/
1276
1277
    /**
1278
     * Gets the lists across a client to which a subscriber with a particular
1279
     * email address belongs.
1280
     *
1281
     * @param string | Member $email Subscriber's email address (or Member)
1282
     *
1283
     * @return CS_REST_Wrapper_Result A successful response will be an object of the form
1284
     * array(
1285
     *     {
1286
     *         'ListID' => The id of the list
1287
     *         'ListName' => The name of the list
1288
     *         'SubscriberState' => The state of the subscriber in the list
1289
     *         'DateSubscriberAdded' => The date the subscriber was added
1290
     *     }
1291
     * )
1292
     */
1293
    public function getListsForEmail($member)
1294
    {
1295
        if ($member instanceof Member) {
1296
            $member = $member->Email;
1297
        }
1298
        //require_once '../../csrest_clients.php';
1299
        $wrap = new CS_REST_Clients($this->Config()->get("client_id"), $this->getAuth());
1300
        $result = $wrap->get_lists_for_email($member);
1301
        return $this->returnResult(
1302
            $result,
1303
            "/api/v3.1/clients/{id}/listsforemail",
1304
            "Got lists to which email address ".$member." is subscribed"
1305
        );
1306
    }
1307
1308
1309
    /**
1310
     * Adds a new subscriber to the specified list
1311
     *
1312
     * @param Int $listID
1313
     * @param Member $member
1314
     * @param Array $customFields
1315
     * @param array $customFields The subscriber details to use during creation.
1316
     * @param boolean $resubscribe Whether we should resubscribe this subscriber if they already exist in the list
1317
     * @param boolean $RestartSubscriptionBasedAutoResponders Whether we should restart subscription based auto responders which are sent when the subscriber first subscribes to a list.
0 ignored issues
show
Documentation introduced by
There is no parameter named $RestartSubscriptionBasedAutoResponders. Did you maybe mean $restartSubscriptionBasedAutoResponders?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function. It has, however, found a similar but not annotated parameter which might be a good fit.

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

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

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

Loading history...
1318
     *
1319
     * NOTE that for the custom fields they need to be formatted like this:
1320
     *    Array(
1321
     *        'Key' => The custom fields personalisation tag
1322
     *        'Value' => The value for this subscriber
1323
     *        'Clear' => true/false (pass true to remove this custom field. in the case of a [multi-option, select many] field, pass an option in the 'Value' field to clear that option or leave Value blank to remove all options)
1324
     *    )
1325
     *
1326
     * @return CS_REST_Wrapper_Result A successful response will be empty
1327
     */
1328
    public function addSubscriber(
1329
        $listID,
1330
        $member,
1331
        $customFields = array(),
1332
        $resubscribe = true,
1333
        $restartSubscriptionBasedAutoResponders = false
1334
    ) {
1335
        //require_once '../../csrest_subscribers.php';
1336
        $wrap = new CS_REST_Subscribers($listID, $this->getAuth());
1337 View Code Duplication
        foreach ($customFields as $key => $customFieldValue) {
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...
1338
            if (!is_array($customFields[$key])) {
1339
                $customFields[] = array(
1340
                    "Key" => $key,
1341
                    "Value" => $customFieldValue,
1342
                    "Clear" => $customFieldValue ? false : true
1343
                );
1344
                unset($customFields[$key]);
1345
            }
1346
        }
1347
        $result = $wrap->add(
1348
            $request = array(
1349
                'EmailAddress' => $member->Email,
1350
                'Name' => $member->getName(),
1351
                'CustomFields' => $customFields,
1352
                'Resubscribe' => $resubscribe,
1353
                'RestartSubscriptionBasedAutoResponders' => $restartSubscriptionBasedAutoResponders
1354
            )
1355
        );
1356
        return $this->returnResult(
1357
            $result,
1358
            "POST /api/v3.1/subscribers/{list id}.{format}",
1359
            "Subscribed with code ..."
1360
        );
1361
    }
1362
1363
    /**
1364
     * Updates an existing subscriber (email, name, state, or custom fields) in the specified list.
1365
     * The update is performed even for inactive subscribers, but will return an error in the event of the
1366
     * given email not existing in the list.
1367
     *
1368
     * @param Int $listID
1369
     * @param String $oldEmailAddress
1370
     * @param Member $member
1371
     * @param array $customFields The subscriber details to use during creation.
1372
     * @param boolean $resubscribe Whether we should resubscribe this subscriber if they already exist in the list
1373
     * @param boolean $restartSubscriptionBasedAutoResponders Whether we should restart subscription based auto responders which are sent when the subscriber first subscribes to a list.
1374
     *
1375
     * NOTE that for the custom fields they need to be formatted like this:
1376
     *    Array(
1377
     *        'Key' => The custom fields personalisation tag
1378
     *        'Value' => The value for this subscriber
1379
     *        'Clear' => true/false (pass true to remove this custom field. in the case of a [multi-option, select many] field, pass an option in the 'Value' field to clear that option or leave Value blank to remove all options)
1380
     *    )
1381
     *
1382
     * @return CS_REST_Wrapper_Result A successful response will be empty
1383
     */
1384
    public function updateSubscriber(
1385
        $listID,
1386
        $oldEmailAddress = "",
1387
        Member $member,
0 ignored issues
show
Coding Style introduced by
Parameters which have default values should be placed at the end.

If you place a parameter with a default value before a parameter with a default value, the default value of the first parameter will never be used as it will always need to be passed anyway:

// $a must always be passed; it's default value is never used.
function someFunction($a = 5, $b) { }
Loading history...
1388
        $customFields = array(),
1389
        $resubscribe = true,
1390
        $restartSubscriptionBasedAutoResponders = false
1391
    ) {
1392
        if (!$oldEmailAddress) {
1393
            $oldEmailAddress = $member->Email;
1394
        }
1395 View Code Duplication
        foreach ($customFields as $key => $customFieldValue) {
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...
1396
            if (!is_array($customFields[$key])) {
1397
                $customFields[] = array(
1398
                    "Key" => $key,
1399
                    "Value" => $customFieldValue,
1400
                    "Clear" => $customFieldValue ? false : true
1401
                );
1402
                unset($customFields[$key]);
1403
            }
1404
        }
1405
        //require_once '../../csrest_subscribers.php';
1406
        $wrap = new CS_REST_Subscribers($listID, $this->getAuth());
1407
        $result = $wrap->update(
1408
            $oldEmailAddress,
0 ignored issues
show
Bug introduced by
It seems like $oldEmailAddress defined by $member->Email on line 1393 can also be of type array; however, CS_REST_Subscribers::update() 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...
1409
            array(
1410
                'EmailAddress' => $member->Email,
1411
                'Name' => $member->getName(),
1412
                'CustomFields' => $customFields,
1413
                'Resubscribe' => $resubscribe,
1414
                'RestartSubscriptionBasedAutoResponders' => $restartSubscriptionBasedAutoResponders,
1415
            )
1416
        );
1417
        return $this->returnResult(
1418
            $result,
1419
            "PUT /api/v3.1/subscribers/{list id}.{format}?email={email}",
1420
            "updated with email $oldEmailAddress ..."
1421
        );
1422
    }
1423
1424
    /**
1425
     * Updates an existing subscriber (email, name, state, or custom fields) in the specified list.
1426
     * The update is performed even for inactive subscribers, but will return an error in the event of the
1427
     * given email not existing in the list.
1428
     *
1429
     * @param Int $listID
1430
     * @param ArraySet $memberSet - list of mebers
0 ignored issues
show
Documentation introduced by
There is no parameter named $memberSet. Did you maybe mean $membersSet?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function. It has, however, found a similar but not annotated parameter which might be a good fit.

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

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

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

Loading history...
1431
     * @param array $customFields The subscriber details to use during creation. Each array item needs to have the same key as the member ID - e.g. array( 123 => array( [custom fields here] ), 456 => array( [custom fields here] ) )
1432
     * @param $resubscribe Whether we should resubscribe any existing subscribers
1433
     * @param $queueSubscriptionBasedAutoResponders By default, subscription based auto responders do not trigger during an import. Pass a value of true to override this behaviour
1434
     * @param $restartSubscriptionBasedAutoResponders By default, subscription based auto responders will not be restarted
1435
     *
1436
     * NOTE that for the custom fields they need to be formatted like this:
1437
     *    Array(
1438
     *        'Key' => The custom fields personalisation tag
1439
     *        'Value' => The value for this subscriber
1440
     *        'Clear' => true/false (pass true to remove this custom field. in the case of a [multi-option, select many] field, pass an option in the 'Value' field to clear that option or leave Value blank to remove all options)
1441
     *    )
1442
1443
     * @return CS_REST_Wrapper_Result A successful response will be empty
1444
     */
1445
    public function addSubscribers(
1446
        $listID,
1447
        $membersSet,
1448
        $customFields = array(),
1449
        $resubscribe,
0 ignored issues
show
Coding Style introduced by
Parameters which have default values should be placed at the end.

If you place a parameter with a default value before a parameter with a default value, the default value of the first parameter will never be used as it will always need to be passed anyway:

// $a must always be passed; it's default value is never used.
function someFunction($a = 5, $b) { }
Loading history...
1450
        $queueSubscriptionBasedAutoResponders = false,
1451
        $restartSubscriptionBasedAutoResponders = false
1452
    ) {
1453
        //require_once '../../csrest_subscribers.php';
1454
        $wrap = new CS_REST_Subscribers($listID, $this->getAuth());
1455
        $importArray = array();
1456
        foreach ($membersSet as $member) {
1457
            $customFieldsForMember = array();
1458
            if (isset($customFields[$member->ID])) {
1459
                $customFieldsForMember = $customFields[$member->ID];
1460
            } elseif (isset($customFields[$member->Email])) {
1461
                $customFieldsForMember = $customFields[$member->Email];
1462
            }
1463 View Code Duplication
            foreach ($customFieldsForMember as $key => $customFieldValue) {
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...
1464
                if (!is_array($customFieldsForMember[$key])) {
1465
                    $customFieldsForMember[] = array(
1466
                        "Key" => $key,
1467
                        "Value" => $customFieldValue,
1468
                        "Clear" => $customFieldValue ? false : true
1469
                    );
1470
                    unset($customFieldsForMember[$key]);
1471
                }
1472
            }
1473
            if ($member instanceof Member) {
1474
                $importArray[] = array(
1475
                    'EmailAddress' => $member->Email,
1476
                    'Name' => $member->getName(),
1477
                    'CustomFields' => $customFieldsForMember
1478
                );
1479
            }
1480
        }
1481
        $result = $wrap->import(
1482
            $importArray,
1483
            $resubscribe,
1484
            $queueSubscriptionBasedAutoResponders,
1485
            $restartSubscriptionBasedAutoResponders
1486
        );
1487
        return $this->returnResult(
1488
            $result,
1489
            "POST /api/v3.1/subscribers/{list id}/import.{format}",
1490
            "review details ..."
1491
        );
1492
    }
1493
1494
    /**
1495
     * @param Int $listID
1496
     * @param Member | String $member - email address or Member Object
1497
     *
1498
     * @return CS_REST_Wrapper_Result A successful response will be empty
1499
     */
1500 View Code Duplication
    public function deleteSubscriber($listID, $member)
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...
1501
    {
1502
        if ($member instanceof Member) {
1503
            $member = $member->Email;
1504
        }
1505
        $wrap = new CS_REST_Subscribers($listID, $this->getAuth());
1506
        $result = $wrap->delete($member);
1507
        return $this->returnResult(
1508
            $result,
1509
            "DELETE /api/v3.1/subscribers/{list id}.{format}?email={emailAddress}",
1510
            "Unsubscribed with code  ..."
1511
        );
1512
    }
1513
1514
    /**
1515
     * Unsubscribes the given subscriber from the current list
1516
     *
1517
     * @param Int $listID
1518
     * @param Member | String $member
1519
     *
1520
     * @return CS_REST_Wrapper_Result A successful response will be empty
1521
     */
1522 View Code Duplication
    public function unsubscribeSubscriber($listID, $member)
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...
1523
    {
1524
        if ($member instanceof Member) {
1525
            $member = $member->Email;
1526
        }
1527
        $wrap = new CS_REST_Subscribers($listID, $this->getAuth());
1528
        $result = $wrap->unsubscribe($member);
1529
        return $this->returnResult(
1530
            $result,
1531
            "GET /api/v3.1/subscribers/{list id}/unsubscribe.{format}",
1532
            "Unsubscribed with code  ..."
1533
        );
1534
    }
1535
1536
    /**
1537
     * Is this user part of this list at all?
1538
     *
1539
     * @param Int $listID
1540
     * @param Member | String $member
1541
     *
1542
     * @return Boolean
1543
     */
1544 View Code Duplication
    public function getSubscriberExistsForThisList($listID, $member)
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...
1545
    {
1546
        if ($member instanceof Member) {
1547
            $member = $member->Email;
1548
        }
1549
        $outcome = $this->getSubscriber($listID, $member);
1550
        if ($outcome && isset($outcome->State)) {
1551
            if ($this->debug) {
1552
                echo "<h3>Subscriber Exists For This List</h3>";
1553
            }
1554
            return true;
1555
        }
1556
        if ($this->debug) {
1557
            echo "<h3>Subscriber does *** NOT *** Exist For This List</h3>";
1558
        }
1559
        return false;
1560
    }
1561
1562
    /**
1563
     * Can we send e-mails to this person in the future for this list?
1564
     *
1565
     * @param Int $listID
1566
     * @param Member | String $member
1567
     *
1568
     * @return Boolean
1569
     */
1570 View Code Duplication
    public function getSubscriberCanReceiveEmailsForThisList($listID, $member)
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...
1571
    {
1572
        if ($member instanceof Member) {
1573
            $member = $member->Email;
1574
        }
1575
        $outcome = $this->getSubscriber($listID, $member);
1576
        if ($outcome && isset($outcome->State)) {
1577
            if ($outcome->State == "Active") {
0 ignored issues
show
Bug introduced by
The property State 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...
1578
                if ($this->debug) {
1579
                    echo "<h3>Subscriber Can Receive Emails For This List</h3>";
1580
                }
1581
                return true;
1582
            }
1583
        }
1584
        if ($this->debug) {
1585
            echo "<h3>Subscriber Can *** NOT *** Receive Emails For This List</h3>";
1586
        }
1587
        return false;
1588
    }
1589
1590
    /**
1591
     * This e-mail / user has been banned from a list.
1592
     *
1593
     * @param Int $listID
1594
     * @param Member | String $member
1595
     *
1596
     * @return Boolean
1597
     */
1598
    public function getSubscriberCanNoLongerReceiveEmailsForThisList($listID, $member)
1599
    {
1600
        $subscriberExistsForThisList = $this->getSubscriberExistsForThisList($listID, $member);
1601
        $subscriberCanReceiveEmailsForThisList = $this->getSubscriberCanReceiveEmailsForThisList($listID, $member);
1602
        if ($subscriberExistsForThisList) {
1603
            if (!$subscriberCanReceiveEmailsForThisList) {
1604
                if ($this->debug) {
1605
                    echo "<h3>Subscriber Can No Longer Receive Emails For This List</h3>";
1606
                }
1607
                return true;
1608
            }
1609
        }
1610
        if ($this->debug) {
1611
            echo "<h3>Subscriber Can *** STILL *** Receive Emails For This List</h3>";
1612
        }
1613
        return false;
1614
    }
1615
1616
    private static $_get_subscriber = array();
1617
1618
    /**
1619
     * Gets a subscriber details, including custom fields
1620
     *
1621
     * @param Int $listID
1622
     * @param Member | String $member
1623
     *
1624
     * @return CS_REST_Wrapper_Result A successful response will be an object of the form
1625
     * {
1626
     *     'EmailAddress' => The subscriber email address
1627
     *     'Name' => The subscribers name
1628
     *     'Date' => The date the subscriber was added to the list
1629
     *     'State' => The current state of the subscriber
1630
     *     'CustomFields' => array(
1631
     *         {
1632
     *             'Key' => The custom fields personalisation tag
1633
     *             'Value' => The custom field value for this subscriber
1634
     *         }
1635
     *     )
1636
     * }
1637
     *
1638
     */
1639
    public function getSubscriber($listID, $member, $cacheIsOK = true)
1640
    {
1641
        if ($member instanceof Member) {
1642
            $member = $member->Email;
1643
        }
1644
        $key = $listID."_".$member;
1645
        if (isset(self::$_get_subscriber[$key]) && $cacheIsOK) {
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...
1646
            //do nothing
1647
        } else {
1648
            $wrap = new CS_REST_Subscribers($listID, $this->getAuth());
1649
            $result = $wrap->get($member);
1650
            self::$_get_subscriber[$key] = $this->returnResult(
1651
                $result,
1652
                "GET /api/v3.1/subscribers/{list id}.{format}?email={email}",
1653
                "got subscribed subscriber"
1654
            );
1655
        }
1656
        return self::$_get_subscriber[$key];
1657
    }
1658
1659
    /**
1660
     * Gets a subscriber details, including custom fields
1661
     *
1662
     * @param Int $listID
1663
     * @param Member | String $member
1664
     *
1665
     * @return CS_REST_Wrapper_Result A successful response will be an object of the form
1666
     * {
1667
     *     'EmailAddress' => The subscriber email address
1668
     *     'Name' => The subscribers name
1669
     *     'Date' => The date the subscriber was added to the list
1670
     *     'State' => The current state of the subscriber
1671
     *     'CustomFields' => array(
1672
     *         {
1673
     *             'Key' => The custom fields personalisation tag
1674
     *             'Value' => The custom field value for this subscriber
1675
     *         }
1676
     *     )
1677
     * }
1678
     *
1679
     */
1680 View Code Duplication
    public function getHistory($listID, $member)
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...
1681
    {
1682
        if ($member instanceof Member) {
1683
            $member = $member->Email;
1684
        }
1685
        $wrap = new CS_REST_Subscribers($listID, $this->getAuth());
1686
        $result = $wrap->get_history($member);
1687
        return $this->returnResult(
1688
            $result,
1689
            "GET /api/v3.1/subscribers/{list id}/history.{format}?email={email}",
1690
            "got subscriber history"
1691
        );
1692
    }
1693
}
1694