Completed
Push — master ( fe2892...6427ed )
by Oleg
03:03
created

AudiencesTest::testIntegration()   C

Complexity

Conditions 7
Paths 34

Size

Total Lines 98
Code Lines 64

Duplication

Lines 17
Ratio 17.35 %

Importance

Changes 0
Metric Value
cc 7
eloc 64
nc 34
nop 0
dl 17
loc 98
rs 6.4687
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
namespace OptimizelyPHPTest\Service\v2;
3
4
use OptimizelyPHPTest\Service\v2\BaseServiceTest;
5
use WebMarketingROI\OptimizelyPHP\OptimizelyApiClient;
6
use WebMarketingROI\OptimizelyPHP\Result;
7
use WebMarketingROI\OptimizelyPHP\Service\v2\Audiences;
8
use WebMarketingROI\OptimizelyPHP\Resource\v2\Audience;
9
use WebMarketingROI\OptimizelyPHP\Resource\v2\Project;
10
11
class AudiencesTest extends BaseServiceTest
12
{
13 View Code Duplication
    public function testListAll()
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...
14
    {
15
        // Mock 'OptimizelyApiClient' object to avoid real API calls
16
        $optimizelyApiClientMock = $this->getMockBuilder('\WebMarketingROI\OptimizelyPHP\OptimizelyApiClient')
17
                            ->disableOriginalConstructor()
18
                            ->getMock();
19
20
        $result = new Result(array(
21
                        array(
22
                            "project_id" => 1000,
23
                            "archived" => false,
24
                            "conditions" => "\"[\"and\", {\"type\": \"language\", \"value\": \"es\"}, {\"type\": \"location\", \"value\": \"US-CA-SANFRANCISCO\"}]\"",
25
                            "description" => "People that speak spanish and are in San Francisco",
26
                            "name" => "Spanish speaking San Franciscans",
27
                            "segmentation" => true,
28
                            "created" => "2016-10-18T05:07:04.066Z",
29
                            "id" => 5000,
30
                            "last_modified" => "2016-10-18T05:07:04.066Z"
31
                        )
32
                    ), 200);
33
        
34
        
35
        $optimizelyApiClientMock->method('sendApiRequest')
36
                    ->willReturn($result);
37
        
38
        $audiencesService = new Audiences($optimizelyApiClientMock);
39
        
40
        $result = $audiencesService->listAll(1000);
41
        $audiences = $result->getPayload();
42
        
43
        $this->assertTrue(count($audiences)==1);
44
        $this->assertTrue($audiences[0] instanceOf Audience);
45
        $this->assertTrue($audiences[0]->getName()=='Spanish speaking San Franciscans');        
46
    }
47
    
48
    /**
49
     * @expectedException Exception
50
     */
51 View Code Duplication
    public function testListAll_InvalidPage()
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...
52
    {
53
        // Mock 'OptimizelyApiClient' object to avoid real API calls
54
        $optimizelyApiClientMock = $this->getMockBuilder('\WebMarketingROI\OptimizelyPHP\OptimizelyApiClient')
55
                            ->disableOriginalConstructor()
56
                            ->getMock();
57
        
58
        $audiencesService = new Audiences($optimizelyApiClientMock);
59
        
60
        $result = $audiencesService->listAll(1000, -1, 25);
0 ignored issues
show
Unused Code introduced by
$result 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...
61
    }
62
    
63
    /**
64
     * @expectedException Exception
65
     */
66 View Code Duplication
    public function testListAll_InvalidPerPage()
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...
67
    {
68
        // Mock 'OptimizelyApiClient' object to avoid real API calls
69
        $optimizelyApiClientMock = $this->getMockBuilder('\WebMarketingROI\OptimizelyPHP\OptimizelyApiClient')
70
                            ->disableOriginalConstructor()
71
                            ->getMock();
72
        
73
        $audiencesService = new Audiences($optimizelyApiClientMock);
74
        
75
        $result = $audiencesService->listAll(1000, 1, 1000);
0 ignored issues
show
Unused Code introduced by
$result 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...
76
    }
77
    
78
    public function testGet()
79
    {
80
        // Mock 'OptimizelyApiClient' object to avoid real API calls
81
        $optimizelyApiClientMock = $this->getMockBuilder('\WebMarketingROI\OptimizelyPHP\OptimizelyApiClient')
82
                            ->disableOriginalConstructor()
83
                            ->getMock();
84
85
        $result = new Result(array(
86
                            "project_id" => 1000,
87
                            "archived" => false,
88
                            "conditions" => array(
89
                              "and",
90
                              array(
91
                                "type" => "language",
92
                                "value" => "es"
93
                              ),
94
                              array(
95
                                "type" => "location",
96
                                "value" => "US-CA-SANFRANCISCO"
97
                              )
98
                            ),
99
                            "description" => "People that speak spanish and are in San Francisco",
100
                            "name" => "Spanish speaking San Franciscans",
101
                            "segmentation" => true,
102
                            "created" => "2016-10-18T05:07:04.073Z",
103
                            "id" => 5000,
104
                            "last_modified" => "2016-10-18T05:07:04.074Z"
105
                        ), 200);
106
        
107
        $optimizelyApiClientMock->method('sendApiRequest')
108
                    ->willReturn($result);
109
        
110
        $audiencesService = new Audiences($optimizelyApiClientMock);
111
        
112
        $result = $audiencesService->get(5000);
0 ignored issues
show
Documentation introduced by
5000 is of type integer, but the function expects a object<WebMarketingROI\O...elyPHP\Service\v2\type>.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
113
        $audience = $result->getPayload();
114
        
115
        $this->assertTrue($audience instanceOf Audience);
116
        $this->assertTrue($audience->getName()=='Spanish speaking San Franciscans');        
117
    }
118
    
119 View Code Duplication
    public function testCreate()
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...
120
    {
121
        // Mock 'OptimizelyApiClient' object to avoid real API calls
122
        $optimizelyApiClientMock = $this->getMockBuilder('\WebMarketingROI\OptimizelyPHP\OptimizelyApiClient')
123
                            ->disableOriginalConstructor()
124
                            ->getMock();
125
126
        $result = new Result(array(
127
                            "project_id" => 1000,
128
                            "archived" => false,
129
                            "conditions" => array(
130
                              "and",
131
                              array(
132
                                "type" => "language",
133
                                "value" => "es"
134
                              ),
135
                              array(
136
                                "type" => "location",
137
                                "value" => "US-CA-SANFRANCISCO"
138
                              )
139
                            ),
140
                            "description" => "People that speak spanish and are in San Francisco",
141
                            "name" => "Spanish speaking San Franciscans",
142
                            "segmentation" => true,
143
                            "created" => "2016-10-18T05:07:04.083Z",
144
                            "id" => 5000,
145
                            "last_modified" => "2016-10-18T05:07:04.083Z"
146
                        ), 201);
147
        
148
        $optimizelyApiClientMock->method('sendApiRequest')
149
                    ->willReturn($result);
150
        
151
        $audiencesService = new Audiences($optimizelyApiClientMock);
152
        
153
        $audience = new Audience(array(
154
                "project_id" => 1000,
155
                "archived" => false,
156
                "conditions" => array(
157
                  "and",
158
                  array(
159
                    "type" => "language",
160
                    "value" => "es"
161
                  ),
162
                  array(
163
                    "type" => "location",
164
                    "value" => "US-CA-SANFRANCISCO"
165
                  )
166
                ),
167
                "description" => "People that speak spanish and are in San Francisco",
168
                "name" => "Spanish speaking San Franciscans",
169
                "segmentation" => true
170
        ));
171
        
172
        $result = $audiencesService->create($audience);
173
        $createdAudience = $result->getPayload();
174
        
175
        $this->assertTrue($createdAudience instanceOf Audience);
176
        $this->assertTrue($createdAudience->getName()=='Spanish speaking San Franciscans');                
177
    }
178
    
179 View Code Duplication
    public function testUpdate()
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...
180
    {
181
        // Mock 'OptimizelyApiClient' object to avoid real API calls
182
        $optimizelyApiClientMock = $this->getMockBuilder('\WebMarketingROI\OptimizelyPHP\OptimizelyApiClient')
183
                            ->disableOriginalConstructor()
184
                            ->getMock();
185
186
        $result = new Result(array(
187
                            "project_id" => 1000,
188
                            "archived" => false,
189
                            "conditions" => array(
190
                              "and",
191
                              array(
192
                                "type" => "language",
193
                                "value" => "es"
194
                              ),
195
                              array(
196
                                "type" => "location",
197
                                "value" => "US-CA-SANFRANCISCO"
198
                              )
199
                            ),
200
                            "description" => "People that speak spanish and are in San Francisco",
201
                            "name" => "Spanish speaking San Franciscans",
202
                            "segmentation" => true,
203
                            "created" => "2016-10-18T05:07:04.083Z",
204
                            "id" => 5000,
205
                            "last_modified" => "2016-10-18T05:07:04.083Z"
206
                        ), 200);
207
        
208
        $optimizelyApiClientMock->method('sendApiRequest')
209
                    ->willReturn($result);
210
        
211
        $audiencesService = new Audiences($optimizelyApiClientMock);
212
        
213
        $audience = new Audience(array(
214
                "project_id" => 1000,
215
                "archived" => false,
216
                "conditions" => array(
217
                  "and",
218
                  array(
219
                    "type" => "language",
220
                    "value" => "es"
221
                  ),
222
                  array(
223
                    "type" => "location",
224
                    "value" => "US-CA-SANFRANCISCO"
225
                  )
226
                ),
227
                "description" => "People that speak spanish and are in San Francisco",
228
                "name" => "Spanish speaking San Franciscans",
229
                "segmentation" => true
230
        ));
231
        
232
        $result = $audiencesService->update(5000, $audience);
233
        $createdAudience = $result->getPayload();
234
        
235
        $this->assertTrue($createdAudience instanceOf Audience);
236
        $this->assertTrue($createdAudience->getName()=='Spanish speaking San Franciscans');                
237
    }
238
    
239
    public function testIntegration()
240
    {
241
        if (!getenv('OPTIMIZELY_PHP_TEST_INTEGRATION')) 
242
            $this->markTestSkipped('OPTIMIZELY_PHP_TEST_INTEGRATION env var is not set');
243
        
244
        $credentials = $this->loadCredentialsFromFile();
245
        
246
        $optimizelyClient = new OptimizelyApiClient($credentials, 'v2');
0 ignored issues
show
Bug introduced by
It seems like $credentials defined by $this->loadCredentialsFromFile() on line 244 can also be of type null; however, WebMarketingROI\Optimize...piClient::__construct() does only seem to accept array, 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...
247
        $this->assertTrue($optimizelyClient!=null);
248
        
249
        // Create new project        
250
        $curDate = date('Y-m-d H:i:s');
251
        $newProject = new Project(array(
252
            "name" => "Test Project $curDate",
253
            "account_id" => 12345,
254
            "confidence_threshold" => 0.9,
255
            "platform" => "web",
256
            "status" => "active",
257
            "web_snippet" => array(
258
              "enable_force_variation" => false,
259
              "exclude_disabled_experiments" => false,
260
              "exclude_names" => true,
261
              "include_jquery" => true,
262
              "ip_anonymization" => false,
263
              "ip_filter" => "^206\\.23\\.100\\.([5-9][0-9]|1([0-4][0-9]|50))$",
264
              "library" => "jquery-1.11.3-trim",
265
              "project_javascript" => "alert(\"Active Experiment\")"
266
            )
267
        ));
268
        
269
        $result = $optimizelyClient->projects()->create($newProject);
0 ignored issues
show
Documentation Bug introduced by
The method projects does not exist on object<WebMarketingROI\O...HP\OptimizelyApiClient>? 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...
270
        $createdProject = $result->getPayload();
271
        
272
        // Create new audience in the project
273
        $audience = new Audience(array(
274
            "project_id" => $createdProject->getId(),
275
            "archived" => false,
276
            "conditions" => "[\"and\", {\"type\": \"language\", \"value\": \"es\"}, {\"type\": \"location\", \"value\": \"US\"}]",
277
            "description" => "People that speak spanish and are in San Francisco",
278
            "name" => "Spanish speaking San Franciscans",
279
            "segmentation" => true
280
        ));
281
        
282
        $result = $optimizelyClient->audiences()->create($audience);
0 ignored issues
show
Documentation Bug introduced by
The method audiences does not exist on object<WebMarketingROI\O...HP\OptimizelyApiClient>? 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...
283
        $createdAudience = $result->getPayload();
284
        
285
        $this->assertTrue($createdAudience instanceOf Audience);
286
        $this->assertTrue($createdAudience->getName()=='Spanish speaking San Franciscans');  
287
        
288
        // List all existing audiences and try to find the created audience
289
        $audienceFound = false;        
290
        try {
291
            $page = 1;
292 View Code Duplication
            for (;;) {                            
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...
293
                $result = $optimizelyClient->audiences()->listAll($createdProject->getId(), $page);
0 ignored issues
show
Documentation Bug introduced by
The method audiences does not exist on object<WebMarketingROI\O...HP\OptimizelyApiClient>? 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...
294
295
                $audiences = $result->getPayload();
296
297
                foreach ($audiences as $audience) {
298
                    if ($audience->getName()=="Spanish speaking San Franciscans") {
299
                        $audienceFound = true;
300
                        break;
301
                    }
302
                }
303
304
                if ($result->getNextPage()==null)
305
                    break;
306
307
                $page ++;
308
            }
309
        }
310
        catch (Exception $e) {
0 ignored issues
show
Bug introduced by
The class OptimizelyPHPTest\Service\v2\Exception does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
311
            // Handle error.
312
            $code = $e->getCode();
313
            $httpCode = $e->getHttpCode();
314
            $message = $e->getMessage();
315
            $uuid = $e->getUuid();
316
            echo "Exception caught: $message (code=$code http_code=$httpCode uuid=$uuid)\n";
317
        }
318
        
319
        $this->assertTrue($audienceFound);
320
        
321
        // Update audience
322
        $createdAudience->setName('Some new audience name');
323
        $result = $optimizelyClient->audiences()->update($createdAudience->getId(), $createdAudience);
0 ignored issues
show
Documentation Bug introduced by
The method audiences does not exist on object<WebMarketingROI\O...HP\OptimizelyApiClient>? 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...
324
        $updatedAudience = $result->getPayload();                
325
        
326
        $this->assertTrue($updatedAudience instanceOf Audience);
327
        $this->assertTrue($updatedAudience->getName()=='Some new audience name');  
328
        
329
        // Make project archived
330
        
331
        $createdProject->setStatus('archived');
332
        $result = $optimizelyClient->projects()->update($createdProject->getId(), $createdProject);
0 ignored issues
show
Documentation Bug introduced by
The method projects does not exist on object<WebMarketingROI\O...HP\OptimizelyApiClient>? 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...
333
        $updatedProject = $result->getPayload();
334
        
335
        $this->assertEquals('archived', $updatedProject->getStatus());
336
    }
337
}
338
339