Issues (51)

Security Analysis    no request data  

This project does not seem to handle request data directly as such no vulnerable execution paths were found.

  Cross-Site Scripting
Cross-Site Scripting enables an attacker to inject code into the response of a web-request that is viewed by other users. It can for example be used to bypass access controls, or even to take over other users' accounts.
  File Exposure
File Exposure allows an attacker to gain access to local files that he should not be able to access. These files can for example include database credentials, or other configuration files.
  File Manipulation
File Manipulation enables an attacker to write custom data to files. This potentially leads to injection of arbitrary code on the server.
  Object Injection
Object Injection enables an attacker to inject an object into PHP code, and can lead to arbitrary code execution, file exposure, or file manipulation attacks.
  Code Injection
Code Injection enables an attacker to execute arbitrary code on the server.
  Response Splitting
Response Splitting can be used to send arbitrary responses.
  File Inclusion
File Inclusion enables an attacker to inject custom files into PHP's file loading mechanism, either explicitly passed to include, or for example via PHP's auto-loading mechanism.
  Command Injection
Command Injection enables an attacker to inject a shell command that is execute with the privileges of the web-server. This can be used to expose sensitive data, or gain access of your server.
  SQL Injection
SQL Injection enables an attacker to execute arbitrary SQL code on your database server gaining access to user data, or manipulating user data.
  XPath Injection
XPath Injection enables an attacker to modify the parts of XML document that are read. If that XML document is for example used for authentication, this can lead to further vulnerabilities similar to SQL Injection.
  LDAP Injection
LDAP Injection enables an attacker to inject LDAP statements potentially granting permission to run unauthorized queries, or modify content inside the LDAP tree.
  Header Injection
  Other Vulnerability
This category comprises other attack vectors such as manipulating the PHP runtime, loading custom extensions, freezing the runtime, or similar.
  Regex Injection
Regex Injection enables an attacker to execute arbitrary code in your PHP process.
  XML Injection
XML Injection enables an attacker to read files on your local filesystem including configuration files, or can be abused to freeze your web-server process.
  Variable Injection
Variable Injection enables an attacker to overwrite program variables with custom data, and can lead to further vulnerabilities.
Unfortunately, the security analysis is currently not available for your project. If you are a non-commercial open-source project, please contact support to gain access.

tests/Connection/ClientTest.php (13 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
namespace Wonnova\SDK\Test\Connection;
3
4
use Doctrine\Common\Cache\ArrayCache;
5
use GuzzleHttp\Message\Response;
6
use GuzzleHttp\Stream\Stream;
7
use GuzzleHttp\Subscriber\History;
8
use GuzzleHttp\Subscriber\Mock;
9
use PHPUnit_Framework_TestCase as TestCase;
10
use Wonnova\SDK\Auth\Credentials;
11
use Wonnova\SDK\Connection\Client;
12
use Wonnova\SDK\Model\Achievement;
13
use Wonnova\SDK\Model\Action;
14
use Wonnova\SDK\Model\Item;
15
use Wonnova\SDK\Model\User;
16
17
class ClientTest extends TestCase
18
{
19
    /**
20
     * @var Client
21
     */
22
    private $client;
23
    /**
24
     * @var Mock
25
     */
26
    private $subscriber;
27
28
    public function setUp()
29
    {
30
        $this->client = new Client(new Credentials('123'), 'es', new ArrayCache());
31
32
        $this->subscriber = new Mock([
33
            // Add the auth token response that will be requested before every test
34
            new Response(200, [], new Stream(fopen('data://text/plain,{"token": "foobar"}', 'r')))
35
        ]);
36
        $this->client->getEmitter()->attach($this->subscriber);
37
    }
38
39 View Code Duplication
    public function testGetUser()
0 ignored issues
show
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...
40
    {
41
        $userData = json_decode(file_get_contents(__DIR__ . '/../dummy_response_data/getUser.json'), true);
42
        // Set mocked response
43
        $body = new Stream(fopen(__DIR__ . '/../dummy_response_data/getUser.json', 'r'));
44
        $this->subscriber->addResponse(new Response(200, [], $body));
45
46
        $user = $this->client->getUser($userData['userId']);
47
        $this->assertInstanceOf('Wonnova\SDK\Model\User', $user);
48
        $this->assertEquals($userData['userId'], $user->getUserId());
49
        $this->assertEquals($userData['username'], $user->getUsername());
50
        $this->assertEquals($userData['provider'], $user->getProvider());
51
        $this->assertInstanceOf('DateTime', $user->getDateOfBirth());
52
        $this->assertEquals($userData['dateOfBirth']['date'], $user->getDateOfBirth()->format('Y-m-d H:i:s'));
53
        $this->assertNull($user->getTimezone());
54
    }
55
56
    public function testGetUsers()
57
    {
58
        $usersData = json_decode(file_get_contents(__DIR__ . '/../dummy_response_data/getUsers.json'), true);
59
        // Set mocked response
60
        $body = new Stream(fopen(__DIR__ . '/../dummy_response_data/getUsers.json', 'r'));
61
        $this->subscriber->addResponse(new Response(200, [], $body));
62
63
        $users = $this->client->getUsers();
64
        $this->assertCount(3, $users);
65
        foreach ($users as $key => $user) {
66
            $this->assertInstanceOf('Wonnova\SDK\Model\User', $user);
67
            $this->assertEquals($usersData[$key]['userId'], $user->getUserId());
68
            $this->assertEquals($usersData[$key]['username'], $user->getUsername());
69
            $this->assertEquals($usersData[$key]['provider'], $user->getProvider());
70
            $this->assertInstanceOf('DateTime', $user->getDateOfBirth());
71
            $this->assertEquals(
72
                $usersData[$key]['dateOfBirth']['date'],
73
                $user->getDateOfBirth()->format('Y-m-d H:i:s')
74
            );
75
        }
76
    }
77
78
    public function testCreateUser()
79
    {
80
        $expectedId = 'foobar123';
81
        // Set mocked response
82
        $body = new Stream(fopen(sprintf('data://text/plain,{"userId": "%s"}', $expectedId), 'r'));
83
        $this->subscriber->addResponse(new Response(200, [], $body));
84
85
        $newUser = new User();
86
        $newUser->setEmail('[email protected]')
87
                ->setDateOfBirth(new \DateTime('1970-01-01 00:00:00'))
88
                ->setFullName('John Doe');
89
        $this->assertNull($newUser->getUserId());
90
        $this->client->createUser($newUser);
91
        $this->assertEquals($expectedId, $newUser->getUserId());
92
    }
93
94 View Code Duplication
    public function testUpdateUser()
0 ignored issues
show
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...
95
    {
96
        $userData = json_decode(file_get_contents(__DIR__ . '/../dummy_response_data/getUser.json'), true);
97
        // Set mocked response
98
        $body = new Stream(fopen(__DIR__ . '/../dummy_response_data/getUser.json', 'r'));
99
        $this->subscriber->addResponse(new Response(200, [], $body));
100
101
        $user = new User();
102
        $user->setUserId('123')
103
             ->setEmail('[email protected]')
104
             ->setFullName('EDITED');
105
        $this->client->updateUser($user);
106
107
        // Test that the user has been populated with the response data
108
        $this->assertEquals($userData['userId'], $user->getUserId());
109
        $this->assertEquals($userData['username'], $user->getUsername());
110
        $this->assertEquals($userData['provider'], $user->getProvider());
111
        $this->assertInstanceOf('DateTime', $user->getDateOfBirth());
112
        $this->assertEquals($userData['dateOfBirth']['date'], $user->getDateOfBirth()->format('Y-m-d H:i:s'));
113
        $this->assertNull($user->getTimezone());
114
    }
115
116
    /**
117
     * @expectedException \Wonnova\SDK\Exception\InvalidArgumentException
118
     */
119
    public function testUpdateUserWithoutIdThrowsException()
120
    {
121
        $this->client->updateUser(new User());
122
    }
123
124
    public function testGetUserNotifications()
125
    {
126
        // Set mocked response
127
        $body = new Stream(fopen(__DIR__ . '/../dummy_response_data/getUserNotifications.json', 'r'));
128
        $this->subscriber->addResponse(new Response(200, [], $body));
129
130
        $notifications = $this->client->getUserNotifications('');
131
        $this->assertCount(3, $notifications);
132
        $this->assertEquals(Achievement::TYPE_POINTS, $notifications->get(0)->getType());
133
        $this->assertEquals('First pending notification', $notifications->get(0)->getMessage());
134
        $this->assertEquals(Achievement::TYPE_POINTS, $notifications->get(1)->getType());
135
        $this->assertEquals('Second pending notification', $notifications->get(1)->getMessage());
136
        $this->assertEquals(Achievement::TYPE_BADGE, $notifications->get(2)->getType());
137
        $this->assertEquals('Third pending notification', $notifications->get(2)->getMessage());
138
    }
139
140 View Code Duplication
    public function testGetUserBadges()
0 ignored issues
show
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...
141
    {
142
        $badgesData = json_decode(file_get_contents(__DIR__ . '/../dummy_response_data/getUserBadges.json'), true);
143
        $badgesData = $badgesData['badges'];
144
        // Set mocked response
145
        $body = new Stream(fopen(__DIR__ . '/../dummy_response_data/getUserBadges.json', 'r'));
146
        $this->subscriber->addResponse(new Response(200, [], $body));
147
148
        $badges = $this->client->getUserBadges('');
149
        $this->assertCount(2, $badges);
150
        foreach ($badges as $key => $badge) {
151
            $this->assertEquals($badgesData[$key]['type'], $badge->getType());
152
            $this->assertInstanceOf('DateTime', $badge->getNotificationDate());
153
            $this->assertEquals($badgesData[$key]['imageUrl'], $badge->getImageUrl());
154
            $this->assertEquals($badgesData[$key]['name'], $badge->getName());
155
            $this->assertEquals($badgesData[$key]['description'], $badge->getDescription());
156
        }
157
    }
158
159
    public function testGetUserAchievements()
160
    {
161
        // Set mocked response
162
        $body = new Stream(fopen(__DIR__ . '/../dummy_response_data/getUserAchievements.json', 'r'));
163
        $this->subscriber->addResponse(new Response(200, [], $body));
164
165
        $achievements = $this->client->getUserAchievements('');
166
        $this->assertCount(2, $achievements);
167
        $this->assertEquals(Achievement::TYPE_POINTS, $achievements->get(0)->getType());
168
        $this->assertEquals(165, $achievements->get(0)->getValue());
169
        $this->assertEquals(Achievement::TYPE_BADGE, $achievements->get(1)->getType());
170
        $this->assertEquals(2, $achievements->get(1)->getValue());
171
    }
172
173
    public function testGetUserProgressInQuest()
174
    {
175
        $progressData = json_decode(
176
            file_get_contents(__DIR__ . '/../dummy_response_data/getUserProgressInQuest.json'),
177
            true
178
        );
179
        $progressData = $progressData['questSteps'];
180
        // Set mocked response
181
        $body = new Stream(fopen(__DIR__ . '/../dummy_response_data/getUserProgressInQuest.json', 'r'));
182
        $this->subscriber->addResponse(new Response(200, [], $body));
183
184
        $questSteps = $this->client->getUserProgressInQuest('', '');
185
        $this->assertCount(4, $questSteps);
186
        foreach ($questSteps as $key => $questStep) {
187
            $this->assertEquals($progressData[$key]['type'], $questStep->getType());
188
            $this->assertEquals($progressData[$key]['code'], $questStep->getCode());
189
            $this->assertEquals($progressData[$key]['name'], $questStep->getName());
190
            $this->assertEquals($progressData[$key]['description'], $questStep->getDescription());
191
            $this->assertEquals($progressData[$key]['completed'], $questStep->isCompleted());
192
        }
193
    }
194
195 View Code Duplication
    public function testGetQuests()
0 ignored issues
show
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
196
    {
197
        $questsData = json_decode(file_get_contents(__DIR__ . '/../dummy_response_data/getQuests.json'), true);
198
        $questsData = $questsData['quests'];
199
        // Set mocked response
200
        $body = new Stream(fopen(__DIR__ . '/../dummy_response_data/getQuests.json', 'r'));
201
        $this->subscriber->addResponse(new Response(200, [], $body));
202
203
        $quests = $this->client->getQuests();
204
        $this->assertCount(3, $quests);
205
        foreach ($quests as $key => $quest) {
206
            $this->assertInstanceof('DateTime', $quest->getStartDate());
207
            $this->assertEquals($questsData[$key]['code'], $quest->getCode());
208
            $this->assertEquals($questsData[$key]['generatesNotification'], $quest->getGeneratesNotification());
209
            $this->assertEquals($questsData[$key]['name'], $quest->getName());
210
            $this->assertEquals($questsData[$key]['description'], $quest->getDescription());
211
        }
212
    }
213
214
    public function testGetLevels()
215
    {
216
        $levelsData = json_decode(file_get_contents(__DIR__ . '/../dummy_response_data/getLevels.json'), true);
217
        $levelsData = $levelsData['levels'];
218
        // Set mocked response
219
        $body = new Stream(fopen(__DIR__ . '/../dummy_response_data/getLevels.json', 'r'));
220
        $this->subscriber->addResponse(new Response(200, [], $body));
221
222
        $levels = $this->client->getLevels();
223
        $this->assertCount(2, $levels);
224
        foreach ($levels as $key => $level) {
225
            $this->assertEquals($levelsData[$key]['code'], $level->getCode());
226
            $this->assertEquals($levelsData[$key]['name'], $level->getName());
227
            $this->assertEquals($levelsData[$key]['score'], $level->getScore());
228
            $this->assertEquals($levelsData[$key]['generatesNotification'], $level->getGeneratesNotification());
229
            $this->assertEquals($levelsData[$key]['categoryEnabled'], $level->isCategoryEnabled());
230
            $this->assertEquals($levelsData[$key]['imageUrl'], $level->getImageUrl());
231
            $this->assertInstanceOf('DateTime', $level->getDateCreated());
232
            if (! is_null($level->getBadge())) {
233
                $this->assertInstanceOf('Wonnova\SDK\Model\Badge', $level->getBadge());
234
            }
235
            if (! is_null($level->getScenario())) {
236
                $this->assertInstanceOf('Wonnova\SDK\Model\Scenario', $level->getScenario());
237
            }
238
        }
239
    }
240
241 View Code Duplication
    public function testGetUserLevel()
0 ignored issues
show
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...
242
    {
243
        // Set mocked response
244
        $body = new Stream(fopen(__DIR__ . '/../dummy_response_data/getUserLevelInScenario.json', 'r'));
245
        $this->subscriber->addResponse(new Response(200, [], $body));
246
247
        $level = $this->client->getUserLevelInScenario('1234');
248
        $this->assertEquals('LEARNER', $level->getCode());
249
        $this->assertEquals(true, $level->getGeneratesNotification());
250
        $this->assertEquals('default.png', $level->getImageUrl());
251
        $this->assertInstanceOf('DateTime', $level->getDateCreated());
252
        $this->assertInstanceOf('Wonnova\SDK\Model\Badge', $level->getBadge());
253
        $this->assertEquals('The badge', $level->getBadge()->getName());
254
        $this->assertInstanceOf('Wonnova\SDK\Model\Scenario', $level->getScenario());
255
        $this->assertEquals('VCM', $level->getScenario()->getName());
256
    }
257
258 View Code Duplication
    public function testGetUserLevelInScenario()
0 ignored issues
show
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...
259
    {
260
        // Set mocked response
261
        $body = new Stream(fopen(__DIR__ . '/../dummy_response_data/getUserLevelInScenario.json', 'r'));
262
        $this->subscriber->addResponse(new Response(200, [], $body));
263
264
        $level = $this->client->getUserLevelInScenario('1234', 'GENERAL');
265
        $this->assertEquals('LEARNER', $level->getCode());
266
        $this->assertEquals(true, $level->getGeneratesNotification());
267
        $this->assertEquals('default.png', $level->getImageUrl());
268
        $this->assertInstanceOf('DateTime', $level->getDateCreated());
269
        $this->assertInstanceOf('Wonnova\SDK\Model\Badge', $level->getBadge());
270
        $this->assertEquals('The badge', $level->getBadge()->getName());
271
        $this->assertInstanceOf('Wonnova\SDK\Model\Scenario', $level->getScenario());
272
        $this->assertEquals('VCM', $level->getScenario()->getName());
273
    }
274
275 View Code Duplication
    public function testGetTeamsLeaderboard()
0 ignored issues
show
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...
276
    {
277
        $teamsData = json_decode(file_get_contents(__DIR__ . '/../dummy_response_data/getTeamsLeaderboard.json'), true);
278
        $teamsData = $teamsData['scores'];
279
        // Set mocked response
280
        $body = new Stream(fopen(__DIR__ . '/../dummy_response_data/getTeamsLeaderboard.json', 'r'));
281
        $this->subscriber->addResponse(new Response(200, [], $body));
282
283
        $teams = $this->client->getTeamsLeaderboard();
284
        $this->assertCount(4, $teams);
285
        foreach ($teams as $key => $team) {
286
            $this->assertEquals($teamsData[$key]['teamName'], $team->getTeamName());
287
            $this->assertEquals($teamsData[$key]['avatar'], $team->getAvatar());
288
            $this->assertEquals($teamsData[$key]['description'], $team->getDescription());
289
            $this->assertEquals($teamsData[$key]['position'], $team->getPosition());
290
            $this->assertEquals($teamsData[$key]['score'], $team->getScore());
291
        }
292
    }
293
294
    public function testGetTeamsLeaderboardWithParams()
295
    {
296
        $history = new History();
297
        $this->client->getEmitter()->attach($history);
298
299
        $body = new Stream(fopen(__DIR__ . '/../dummy_response_data/getTeamsLeaderboard.json', 'r'));
300
        $this->subscriber->addResponse(new Response(200, [], $body));
301
        $this->client->getTeamsLeaderboard(10);
302
        $queryParams = $history->getLastRequest()->getQuery()->toArray();
303
        $this->assertArrayHasKey('maxCount', $queryParams);
304
        $this->assertEquals(10, $queryParams['maxCount']);
305
306
        $body = new Stream(fopen(__DIR__ . '/../dummy_response_data/getTeamsLeaderboard.json', 'r'));
307
        $this->subscriber->addResponse(new Response(200, [], $body));
308
        $this->client->getTeamsLeaderboard(null, '12345');
309
        $queryParams = $history->getLastRequest()->getQuery()->toArray();
310
        $this->assertArrayHasKey('userId', $queryParams);
311
        $this->assertEquals('12345', $queryParams['userId']);
312
    }
313
314 View Code Duplication
    public function testGetItemsLeaderboard()
0 ignored issues
show
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...
315
    {
316
        $itemsData = json_decode(file_get_contents(__DIR__ . '/../dummy_response_data/getItemsLeaderboard.json'), true);
317
        $itemsData = $itemsData['leaderboard'];
318
        // Set mocked response
319
        $body = new Stream(fopen(__DIR__ . '/../dummy_response_data/getItemsLeaderboard.json', 'r'));
320
        $this->subscriber->addResponse(new Response(200, [], $body));
321
322
        $items = $this->client->getItemsLeaderboard();
323
        $this->assertCount(3, $items);
324
        foreach ($items as $key => $item) {
325
            $this->assertEquals($itemsData[$key]['id'], $item->getItemId());
326
            $this->assertEquals($itemsData[$key]['title'], $item->getTitle());
327
            $this->assertEquals($itemsData[$key]['description'], $item->getDescription());
328
            $this->assertEquals($itemsData[$key]['author'], $item->getAuthor());
329
            $this->assertInstanceOf('DateTime', $item->getDateCreated());
330
        }
331
    }
332
333
    public function testRateItem()
334
    {
335
        // Set mocked response
336
        $body = new Stream(fopen(__DIR__ . '/../dummy_response_data/rateItem.json', 'r'));
337
        $this->subscriber->addResponse(new Response(200, [], $body));
338
339
        $item = $this->client->rateItem('', '');
340
        $this->assertEquals('3333', $item->getItemId());
341
        $this->assertEquals('the title', $item->getTitle());
342
        $this->assertNull($item->getDescription());
343
        $this->assertNull($item->getAuthor());
344
        $this->assertEquals(2400, $item->getScore());
345
        $this->assertInstanceOf('DateTime', $item->getDateCreated());
346
    }
347
348
    public function testRateSeveralItems()
349
    {
350
        // Set mocked response
351
        $body = new Stream(fopen(__DIR__ . '/../dummy_response_data/rateSeveralItems.json', 'r'));
352
        $this->subscriber->addResponse(new Response(200, [], $body));
353
354
        $item1 = new Item();
355
        $item2 = new Item();
356
357
        $items = $this->client->rateSeveralItems('1234', [$item1, $item2]);
358
359
        $item1 = $items[0];
360
        $this->assertEquals('1234', $item1->getItemId());
361
        $this->assertEquals('the title', $item1->getTitle());
362
        $this->assertNull($item1->getDescription());
363
        $this->assertNull($item1->getAuthor());
364
        $this->assertEquals(2400, $item1->getScore());
365
        $this->assertInstanceOf('DateTime', $item1->getDateCreated());
366
367
        $item2 = $items[1];
368
        $this->assertEquals('5678', $item2->getItemId());
369
        $this->assertEquals('the second title', $item2->getTitle());
370
        $this->assertEquals('the second description', $item2->getDescription());
371
        $this->assertEquals('the second author', $item2->getAuthor());
372
        $this->assertEquals(666, $item2->getScore());
373
        $this->assertInstanceOf('DateTime', $item2->getDateCreated());
374
    }
375
376 View Code Duplication
    public function testDeleteItem()
0 ignored issues
show
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...
377
    {
378
        // Set mocked response
379
        $body = new Stream(fopen('data://text/plain,[]', 'r'));
380
        $this->subscriber->addResponse(new Response(200, [], $body));
381
382
        $this->client->deleteItem('');
383
        // If we reach this point, the everything worked
384
        $this->assertTrue(true);
385
    }
386
387 View Code Duplication
    public function testResetItemScore()
0 ignored issues
show
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...
388
    {
389
        // Set mocked response
390
        $body = new Stream(fopen('data://text/plain,[]', 'r'));
391
        $this->subscriber->addResponse(new Response(200, [], $body));
392
393
        $this->client->resetItemScore('');
394
        // If we reach this point, the everything worked
395
        $this->assertTrue(true);
396
    }
397
398
    public function testGetUserData()
399
    {
400
        // Set mocked response
401
        $body = new Stream(fopen(__DIR__ . '/../dummy_response_data/getUserData.json', 'r'));
402
        $this->subscriber->addResponse(new Response(200, [], $body));
403
404
        $expectedId = '12345';
405
        $user = $this->client->getUserData($expectedId);
406
407
        $this->assertEquals($expectedId, $user->getUserId());
408
        $this->assertEquals('john.doe', $user->getUsername());
409
        $this->assertEquals('John Doe', $user->getFullName());
410
        $this->assertEquals('http://www.avatar.com/john.doe', $user->getAvatar());
411
        $this->assertEquals(175, $user->getScore());
412
    }
413
414
    public function testGetInteractionStatus()
415
    {
416
        // Set mocked response
417
        $body = new Stream(fopen(__DIR__ . '/../dummy_response_data/getInteractionStatus.json', 'r'));
418
        $this->subscriber->addResponse(new Response(200, [], $body));
419
420
        $data = $this->client->getInteractionStatus('', '', '', '');
421
        $this->assertEquals(0, $data['score']);
422
        $this->assertEquals('ok', $data['message']);
423
    }
424
425
    public function testGetUserStatusInQuest()
426
    {
427
        $questsData = json_decode(
428
            file_get_contents(__DIR__ . '/../dummy_response_data/getUserStatusInQuest.json'),
429
            true
430
        );
431
        $questsData = $questsData['quests'];
432
        // Set mocked response
433
        $body = new Stream(fopen(__DIR__ . '/../dummy_response_data/getUserStatusInQuest.json', 'r'));
434
        $this->subscriber->addResponse(new Response(200, [], $body));
435
436
        $quests = $this->client->getUserStatusInQuests('');
437
        $this->assertCount(5, $quests);
438
        foreach ($quests as $key => $quest) {
439
            $this->assertEquals($questsData[$key]['name'], $quest->getName());
440
            $this->assertEquals($questsData[$key]['code'], $quest->getCode());
441
            $this->assertEquals($questsData[$key]['progress'], $quest->getProgress());
442
            $this->assertCount(count($questsData[$key]['questSteps']), $quest->getQuestSteps());
443
444
            foreach ($quest->getQuestSteps() as $stepKey => $step) {
445
                $this->assertEquals($questsData[$key]['questSteps'][$stepKey]['type'], $step->getType());
446
                $this->assertEquals($questsData[$key]['questSteps'][$stepKey]['code'], $step->getCode());
447
                $this->assertEquals($questsData[$key]['questSteps'][$stepKey]['completed'], $step->isCompleted());
448
            }
449
        }
450
    }
451
452
    public function testNotifyAction()
453
    {
454
        $history = new History();
455
        $this->client->getEmitter()->attach($history);
456
457
        $this->subscriber->addResponse(new Response(200, [], new Stream(fopen('data://text/plain,[]', 'r'))));
458
        $this->client->notifyAction('12345', 'LOGIN');
459
        $contents = $history->getLastRequest()->getBody()->__toString();
460
        $request = json_decode($contents, true);
461
        $this->assertEquals([
462
            'userId' => '12345',
463
            'actionCode' => 'LOGIN'
464
        ], $request);
465
    }
466
467
    public function testNotifyActionWIthItem()
468
    {
469
        $history = new History();
470
        $this->client->getEmitter()->attach($history);
471
472
        $this->subscriber->addResponse(new Response(200, [], new Stream(fopen('data://text/plain,[]', 'r'))));
473
        $this->client->notifyAction('12345', 'LOGIN', 'the-item');
474
        $contents = $history->getLastRequest()->getBody()->__toString();
475
        $request = json_decode($contents, true);
476
        $this->assertEquals([
477
            'userId' => '12345',
478
            'actionCode' => 'LOGIN',
479
            'item' => [
480
                'id' => 'the-item'
481
            ]
482
        ], $request);
483
484
        $this->subscriber->addResponse(new Response(200, [], new Stream(fopen('data://text/plain,[]', 'r'))));
485
        $item = new Item();
486
        $item->setItemId('the-item')
487
             ->setAuthor('the-author');
488
        $this->client->notifyAction('12345', 'LOGIN', $item);
489
        $contents = $history->getLastRequest()->getBody()->__toString();
490
        $request = json_decode($contents, true);
491
        $this->assertEquals([
492
            'userId' => '12345',
493
            'actionCode' => 'LOGIN',
494
            'item' => $item->toArray()
495
        ], $request);
496
    }
497
498 View Code Duplication
    public function testNotifyActionWithCategories()
0 ignored issues
show
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...
499
    {
500
        $history = new History();
501
        $this->client->getEmitter()->attach($history);
502
503
        $this->subscriber->addResponse(new Response(200, [], new Stream(fopen('data://text/plain,[]', 'r'))));
504
        $this->client->notifyAction('12345', 'LOGIN', null, ['foo', 'bar']);
505
        $contents = $history->getLastRequest()->getBody()->__toString();
506
        $request = json_decode($contents, true);
507
        $this->assertEquals([
508
            'userId' => '12345',
509
            'actionCode' => 'LOGIN',
510
            'categories' => ['foo', 'bar']
511
        ], $request);
512
    }
513
514 View Code Duplication
    public function testNotifySeveralActionsAsString()
0 ignored issues
show
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...
515
    {
516
        $history = new History();
517
        $this->client->getEmitter()->attach($history);
518
519
        $this->subscriber->addResponse(new Response(200, [], new Stream(fopen('data://text/plain,[]', 'r'))));
520
        $this->client->notifySeveralActions('12345', ['LOGIN', 'SIGNUP']);
521
        $contents = $history->getLastRequest()->getBody()->__toString();
522
        $request = json_decode($contents, true);
523
        $this->assertEquals([
524
            'userId' => '12345',
525
            'actions' => [
526
                ['actionCode' => 'LOGIN'],
527
                ['actionCode' => 'SIGNUP'],
528
            ]
529
        ], $request);
530
    }
531
532
    public function testNotifySeveralActionsAsActionClass()
533
    {
534
        $history = new History();
535
        $this->client->getEmitter()->attach($history);
536
537
        $this->subscriber->addResponse(new Response(200, [], new Stream(fopen('data://text/plain,[]', 'r'))));
538
539
        $actionLogin = new Action();
540
        $actionLogin->setActionCode('LOGIN');
541
542
        $actionSignup = new Action();
543
        $actionSignup->setActionCode('SIGNUP');
544
545
        $this->client->notifySeveralActions('12345', [$actionLogin, $actionSignup]);
546
        $contents = $history->getLastRequest()->getBody()->__toString();
547
        $request = json_decode($contents, true);
548
        $this->assertEquals([
549
            'userId' => '12345',
550
            'actions' => [
551
                ['actionCode' => 'LOGIN'],
552
                ['actionCode' => 'SIGNUP'],
553
            ]
554
        ], $request);
555
    }
556
557
    public function testNotifySeveralActionsWIthItem()
558
    {
559
        $history = new History();
560
        $this->client->getEmitter()->attach($history);
561
562
        $this->subscriber->addResponse(new Response(200, [], new Stream(fopen('data://text/plain,[]', 'r'))));
563
564
        $item = new Item();
565
        $item->setItemId('the-item');
566
        $actionLogin = new Action();
567
        $actionLogin->setActionCode('LOGIN')
568
        ->setItem($item);
569
570
        $actionSignup = new Action();
571
        $actionSignup->setActionCode('SIGNUP');
572
573
        $this->client->notifySeveralActions('12345', [$actionLogin, $actionSignup]);
574
        $contents = $history->getLastRequest()->getBody()->__toString();
575
        $request = json_decode($contents, true);
576
        $this->assertEquals([
577
            'userId' => '12345',
578
            'actions' => [
579
                [
580
                    'actionCode' => 'LOGIN',
581
                    'item' => [
582
                        'id' => 'the-item',
583
                        'title' => null,
584
                        'description' => null,
585
                        'author' => null,
586
                    ]
587
                ],
588
                ['actionCode' => 'SIGNUP'],
589
            ],
590
        ], $request);
591
    }
592
593
    public function testNotifySeveralActionsWithCategories()
594
    {
595
        $history = new History();
596
        $this->client->getEmitter()->attach($history);
597
598
        $this->subscriber->addResponse(new Response(200, [], new Stream(fopen('data://text/plain,[]', 'r'))));
599
600
        $item = new Item();
601
        $item->setItemId('the-item');
602
        $actionLogin = new Action();
603
        $actionLogin->setActionCode('LOGIN')
604
            ->setItem($item);
605
606
        $actionSignup = new Action();
607
        $actionSignup->setActionCode('SIGNUP')
608
            ->setCategories(['foo', 'bar']);
609
610
        $this->client->notifySeveralActions('12345', [$actionLogin, $actionSignup]);
611
        $contents = $history->getLastRequest()->getBody()->__toString();
612
        $request = json_decode($contents, true);
613
        $this->assertEquals([
614
            'userId' => '12345',
615
            'actions' => [
616
                [
617
                    'actionCode' => 'LOGIN',
618
                    'item' => [
619
                        'id' => 'the-item',
620
                        'title' => null,
621
                        'description' => null,
622
                        'author' => null,
623
                    ]
624
                ],
625
                [
626
                    'actionCode' => 'SIGNUP',
627
                    'categories' => ['foo', 'bar'],
628
                ],
629
            ],
630
        ], $request);
631
    }
632
633
    public function testNotifyInteraction()
634
    {
635
        $history = new History();
636
        $this->client->getEmitter()->attach($history);
637
638
        $this->subscriber->addResponse(new Response(200, [], new Stream(fopen('data://text/plain,[]', 'r'))));
639
        $this->client->notifyInteraction('user', 'target-user', 'RATE');
640
        $contents = $history->getLastRequest()->getBody()->__toString();
641
        $request = json_decode($contents, true);
642
        $this->assertEquals([
643
            'userId' => 'user',
644
            'interactionCode' => 'RATE',
645
            'targetUserId' => 'target-user'
646
        ], $request);
647
    }
648
649
    public function testNotifyInteractionWIthItem()
650
    {
651
        $history = new History();
652
        $this->client->getEmitter()->attach($history);
653
654
        $this->subscriber->addResponse(new Response(200, [], new Stream(fopen('data://text/plain,[]', 'r'))));
655
        $this->client->notifyInteraction('user', 'target-user', 'RATE', 'the-item');
0 ignored issues
show
'the-item' is of type string, but the function expects a object<Wonnova\SDK\Model\Item>|null.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
656
        $contents = $history->getLastRequest()->getBody()->__toString();
657
        $request = json_decode($contents, true);
658
        $this->assertEquals([
659
            'userId' => 'user',
660
            'interactionCode' => 'RATE',
661
            'targetUserId' => 'target-user',
662
            'item' => [
663
                'id' => 'the-item'
664
            ]
665
        ], $request);
666
667
        $this->subscriber->addResponse(new Response(200, [], new Stream(fopen('data://text/plain,[]', 'r'))));
668
        $item = new Item();
669
        $item->setItemId('the-item')
670
             ->setAuthor('the-author');
671
        $this->client->notifyInteraction('user', 'target-user', 'RATE', $item);
672
        $contents = $history->getLastRequest()->getBody()->__toString();
673
        $request = json_decode($contents, true);
674
        $this->assertEquals([
675
            'userId' => 'user',
676
            'interactionCode' => 'RATE',
677
            'targetUserId' => 'target-user',
678
            'item' => $item->toArray()
679
        ], $request);
680
    }
681
682
    public function testNotifyInteractionWithCategories()
683
    {
684
        $history = new History();
685
        $this->client->getEmitter()->attach($history);
686
687
        $this->subscriber->addResponse(new Response(200, [], new Stream(fopen('data://text/plain,[]', 'r'))));
688
        $this->client->notifyInteraction('user', 'target-user', 'RATE', null, ['foo', 'bar']);
689
        $contents = $history->getLastRequest()->getBody()->__toString();
690
        $request = json_decode($contents, true);
691
        $this->assertEquals([
692
            'userId' => 'user',
693
            'interactionCode' => 'RATE',
694
            'targetUserId' => 'target-user',
695
            'categories' => ['foo', 'bar']
696
        ], $request);
697
    }
698
699
    public function testGetUserActionOccurrences()
700
    {
701
        // Set mocked response
702
        $body = new Stream(fopen(__DIR__ . '/../dummy_response_data/getUserActionOccurrences.json', 'r'));
703
        $this->subscriber->addResponse(new Response(200, [], $body));
704
705
        $expected = 7;
706
        $this->assertEquals($expected, $this->client->getUserActionOccurrences('', ''));
707
    }
708
709
    public function testGetUserLastUpdates()
710
    {
711
        $lastUpdatesData = json_decode(
712
            file_get_contents(__DIR__ . '/../dummy_response_data/getUserLastUpdates.json'),
713
            true
714
        );
715
        $lastUpdatesData = $lastUpdatesData['lastUpdates'];
716
        // Set mocked response
717
        $body = new Stream(fopen(__DIR__ . '/../dummy_response_data/getUserLastUpdates.json', 'r'));
718
        $this->subscriber->addResponse(new Response(200, [], $body));
719
720
        $lastUpdates = $this->client->getUserLastUpdates('', 4);
721
        $this->assertCount(4, $lastUpdates);
722
        foreach ($lastUpdates as $key => $update) {
723
            $this->assertEquals($lastUpdatesData[$key]['text'], $update->getText());
724
            $this->assertInstanceOf('DateTime', $update->getDate());
725
            $this->assertEquals($lastUpdatesData[$key]['type'], $update->getType());
726
        }
727
    }
728
729
    public function testExpiredAuthTokenPerformsAuthentication()
730
    {
731
        $history = new History();
732
        $this->client->getEmitter()->attach($history);
733
734
        // Add invalid token response to the stack
735
        $body = new Stream(fopen(__DIR__ . '/../dummy_response_data/invalidToken.json', 'r'));
736
        $this->subscriber->addResponse(new Response(401, [], $body));
737
        // Add the token response that will be used for reauthentication
738
        $this->subscriber->addResponse(new Response(200, [], new Stream(
739
            fopen('data://text/plain,{"token": "foobar"}', 'r')
740
        )));
741
        // Add a valid response that will be used after the new authentication
742
        $body = new Stream(fopen(__DIR__ . '/../dummy_response_data/getUser.json', 'r'));
743
        $this->subscriber->addResponse(new Response(200, [], $body));
744
745
        $this->client->getUser('');
746
        $this->assertCount(4, $history);
747
    }
748
749
    /**
750
     * @expectedException \Wonnova\SDK\Exception\UnauthorizedException
751
     */
752
    public function test401ThrowsUnauthorizedException()
753
    {
754
        $body = new Stream(fopen('data://text/plain,[]', 'r'));
755
        $this->subscriber->addResponse(new Response(401, [], $body));
756
        $this->client->getUsers();
757
    }
758
759
    /**
760
     * @expectedException \Wonnova\SDK\Exception\InvalidRequestException
761
     */
762
    public function test400ThrowsInvalidRequestException()
763
    {
764
        $body = new Stream(fopen('data://text/plain,[]', 'r'));
765
        $this->subscriber->addResponse(new Response(400, [], $body));
766
        $this->client->getUsers();
767
    }
768
769
    /**
770
     * @expectedException \Wonnova\SDK\Exception\NotFoundException
771
     */
772
    public function test404ThrowsNotFoundException()
773
    {
774
        $body = new Stream(fopen('data://text/plain,[]', 'r'));
775
        $this->subscriber->addResponse(new Response(404, [], $body));
776
        $this->client->getUsers();
777
    }
778
779
    /**
780
     * @expectedException \Wonnova\SDK\Exception\ServerException
781
     */
782
    public function test500ThrowsServerException()
783
    {
784
        $body = new Stream(fopen('data://text/plain,[]', 'r'));
785
        $this->subscriber->addResponse(new Response(500, [], $body));
786
        $this->client->getUsers();
787
    }
788
789
    /**
790
     * @expectedException \Wonnova\SDK\Exception\RuntimeException
791
     */
792
    public function testUnsupportedStatusThrowsRuntimeException()
793
    {
794
        $body = new Stream(fopen('data://text/plain,[]', 'r'));
795
        $this->subscriber->addResponse(new Response(403, [], $body));
796
        $this->client->getUsers();
797
    }
798
799
    public function testCachedTokenDoNotPerformAditionalRequests()
800
    {
801
        $cache = new ArrayCache();
802
        $cache->save(sprintf('%s_123', Client::TOKEN_KEY), 'foobar');
803
        $this->client = new Client(new Credentials('123'), 'es', $cache);
804
805
        $history = new History();
806
        $this->client->getEmitter()->attach($history);
807
        $subscriber = new Mock();
808
        $this->client->getEmitter()->attach($subscriber);
809
810
        // Set mocked response
811
        $body = new Stream(fopen(__DIR__ . '/../dummy_response_data/getUsers.json', 'r'));
812
        $subscriber->addResponse(new Response(200, [], $body));
813
814
        $this->client->getUsers();
815
        $this->assertCount(1, $history);
816
    }
817
818
    public function testStatusAsStringIsParsed()
819
    {
820
        $userData = json_decode(file_get_contents(__DIR__ . '/../dummy_response_data/getUser.json'), true);
821
        // Set mocked response
822
        $body = new Stream(fopen(__DIR__ . '/../dummy_response_data/getUser.json', 'r'));
823
        $this->subscriber->addResponse(new Response('200', [], $body));
824
825
        $user = $this->client->getUser($userData['userId']);
826
        $this->assertInstanceOf('Wonnova\SDK\Model\User', $user);
827
    }
828
}
829