Completed
Push — EZP-29891 ( 916cf6...0402ff )
by
unknown
16:53
created

RoleServiceTest   F

Complexity

Total Complexity 124

Size/Duplication

Total Lines 2883
Duplicated Lines 35.97 %

Coupling/Cohesion

Components 1
Dependencies 17

Importance

Changes 0
Metric Value
dl 1037
loc 2883
rs 0.8
c 0
b 0
f 0
wmc 124
lcom 1
cbo 17

79 Methods

Rating   Name   Duplication   Size   Complexity  
A testNewRoleCreateStruct() 0 9 1
A testNewRoleCreateStructSetsNamePropertyOnStruct() 0 13 1
A testCreateRole() 0 26 1
A testRoleCreateStructValues() 0 19 1
A testCreateRoleWithPolicy() 0 40 1
A testRoleCreateStructValuesWithPolicy() 0 23 1
A testCreateRoleDraft() 24 24 1
A testCreateRoleThrowsInvalidArgumentException() 0 17 1
A testCreateRoleThrowsLimitationValidationException() 32 32 1
A testLoadRoleDraft() 0 21 1
A testLoadRoleDraftByRoleId() 0 25 1
A testLoadRoleThrowsNotFoundException() 14 14 1
A testLoadRoleDraftThrowsNotFoundException() 14 14 1
A testLoadRoleDraftByRoleIdThrowsNotFoundException() 14 14 1
A testLoadRoleByIdentifier() 22 22 1
A testLoadRoleByIdentifierThrowsNotFoundException() 0 13 1
A testLoadRolesReturnsExpectedSetOfDefaultRoles() 0 28 2
A testNewRoleUpdateStruct() 0 11 1
A testUpdateRole() 0 26 1
A testUpdateRoleDraft() 24 24 1
A testUpdateRoleThrowsInvalidArgumentException() 22 22 1
A testUpdateRoleDraftThrowsInvalidArgumentException() 0 20 1
A testDeleteRoleDraft() 0 19 1
A testNewPolicyCreateStruct() 0 11 1
A testNewPolicyCreateStructSetsStructProperties() 0 14 1
A testAddPolicy() 54 54 2
A testAddPolicyByRoleDraft() 6 52 2
A testAddPolicyUpdatesRole() 0 34 4
A testAddPolicyByRoleDraftUpdatesRole() 0 32 4
A testAddPolicySetsPolicyProperties() 9 9 1
A testAddPolicyByRoleDraftSetsPolicyProperties() 9 9 1
A testAddPolicyThrowsLimitationValidationException() 0 32 1
A testAddPolicyByRoleDraftThrowsLimitationValidationException() 30 30 1
A testCreateRoleWithAddPolicy() 3 53 2
A testCreateRoleDraftWithAddPolicy() 3 50 2
A testNewPolicyUpdateStruct() 0 14 1
A testUpdatePolicyNoLimitation() 0 45 4
B testUpdatePolicy() 0 61 4
A testUpdatePolicyUpdatesLimitations() 0 17 1
A testUpdatePolicyUpdatesRole() 0 23 3
B testUpdatePolicyThrowsLimitationValidationException() 0 55 4
A testRemovePolicy() 34 34 2
A testRemovePolicyByRoleDraft() 32 32 2
A testDeletePolicy() 35 35 2
A testLoadRoleAssignment() 0 42 1
A testGetRoleAssignments() 0 27 1
A testGetRoleAssignmentsContainExpectedLimitation() 0 7 1
A testAssignRoleToUser() 21 21 1
B testAssignRoleToUserWithRoleLimitation() 98 98 5
A testAssignRoleToUserWithRoleLimitationThrowsLimitationValidationException() 0 27 1
A testAssignRoleToUserThrowsInvalidArgumentException() 31 31 2
A testAssignRoleToUserWithRoleLimitationThrowsInvalidArgumentException() 0 41 2
A testUnassignRoleFromUser() 24 24 1
A testUnassignRoleFromUserThrowsInvalidArgumentException() 16 16 1
A testGetRoleAssignmentsForUserDirect() 42 42 1
A testGetRoleAssignmentsForUserEmpty() 0 14 1
A testGetRoleAssignmentsForUserInherited() 0 18 1
A testAssignRoleToUserGroup() 21 21 1
B testAssignRoleToUserGroupWithRoleLimitation() 94 94 5
A testAssignRoleToUserGroupWithRoleLimitationThrowsLimitationValidationException() 0 30 1
A testAssignRoleToUserGroupThrowsInvalidArgumentException() 0 34 2
A testAssignRoleToUserGroupWithRoleLimitationThrowsInvalidArgumentException() 0 44 2
A testUnassignRoleFromUserGroup() 24 24 1
A testUnassignRoleFromUserGroupThrowsInvalidArgumentException() 16 16 1
A testUnassignRoleByAssignment() 0 19 1
A testUnassignRoleByAssignmentThrowsUnauthorizedException() 17 17 2
A testUnassignRoleByAssignmentThrowsNotFoundException() 17 17 2
A testGetRoleAssignmentsForUserGroup() 42 42 1
B testLoadPoliciesByUserId() 0 63 2
A testLoadPoliciesByUserIdThrowsNotFoundException() 0 13 1
A testPublishRoleDraft() 30 30 1
A testPublishRoleDraftAddPolicies() 54 54 2
A createUserGroupVersion1() 0 27 1
A testCreateRoleDraftThrowsInvalidArgumentException() 0 22 1
A testCreateRoleInTransactionWithRollback() 29 29 2
A testCreateRoleDraftInTransactionWithRollback() 29 29 2
A testLoadRole() 22 22 1
A testLoadRoles() 29 29 3
A testDeleteRole() 0 20 1

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like RoleServiceTest often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use RoleServiceTest, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
/**
4
 * File containing the RoleServiceTest class.
5
 *
6
 * @copyright Copyright (C) eZ Systems AS. All rights reserved.
7
 * @license For full copyright and license information view LICENSE file distributed with this source code.
8
 */
9
namespace eZ\Publish\API\Repository\Tests;
10
11
use eZ\Publish\API\Repository\Values\User\Limitation\ContentTypeLimitation;
12
use eZ\Publish\API\Repository\Values\User\Limitation\LanguageLimitation;
13
use eZ\Publish\API\Repository\Values\User\Limitation\SubtreeLimitation;
14
use eZ\Publish\API\Repository\Exceptions\NotFoundException;
15
use Exception;
16
17
/**
18
 * Test case for operations in the RoleService using in memory storage.
19
 *
20
 * The following IDs from the default eZ community edition database are used in
21
 * this test:
22
 *
23
 * <ul>
24
 *   <li>
25
 *     ContentType
26
 *     <ul>
27
 *       <li><strong>28</strong>: File</li>
28
 *       <li><strong>29</strong>: Flash</li>
29
 *       <li><strong>30</strong>: Image</li>
30
 *     </ul>
31
 *   </li>
32
 * <ul>
33
 *
34
 * @see eZ\Publish\API\Repository\RoleService
35
 * @group role
36
 */
37
class RoleServiceTest extends BaseTest
38
{
39
    /**
40
     * Test for the newRoleCreateStruct() method.
41
     *
42
     * @see \eZ\Publish\API\Repository\RoleService::newRoleCreateStruct()
43
     */
44
    public function testNewRoleCreateStruct()
45
    {
46
        $repository = $this->getRepository();
47
48
        $roleService = $repository->getRoleService();
49
        $roleCreate = $roleService->newRoleCreateStruct('roleName');
50
51
        $this->assertInstanceOf('\\eZ\\Publish\\API\\Repository\\Values\\User\\RoleCreateStruct', $roleCreate);
52
    }
53
54
    /**
55
     * Test for the newRoleCreateStruct() method.
56
     *
57
     * @see \eZ\Publish\API\Repository\RoleService::newRoleCreateStruct()
58
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewRoleCreateStruct
59
     */
60
    public function testNewRoleCreateStructSetsNamePropertyOnStruct()
61
    {
62
        $repository = $this->getRepository();
63
64
        /* BEGIN: Use Case */
65
66
        $roleService = $repository->getRoleService();
67
        $roleCreate = $roleService->newRoleCreateStruct('roleName');
68
69
        /* END: Use Case */
70
71
        $this->assertEquals('roleName', $roleCreate->identifier);
72
    }
73
74
    /**
75
     * Test for the createRole() method.
76
     *
77
     * @see \eZ\Publish\API\Repository\RoleService::createRole()
78
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewRoleCreateStruct
79
     */
80
    public function testCreateRole()
81
    {
82
        $repository = $this->getRepository();
83
84
        /* BEGIN: Use Case */
85
86
        $roleService = $repository->getRoleService();
87
        $roleCreate = $roleService->newRoleCreateStruct('roleName');
88
89
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
90
        // $roleCreate->mainLanguageCode = 'eng-US';
91
92
        $role = $roleService->createRole($roleCreate);
93
94
        /* END: Use Case */
95
96
        $this->assertInstanceOf(
97
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\RoleDraft',
98
            $role
99
        );
100
101
        return [
102
            'createStruct' => $roleCreate,
103
            'role' => $role,
104
        ];
105
    }
106
107
    /**
108
     * Test for the createRole() method.
109
     *
110
     * @see \eZ\Publish\API\Repository\RoleService::createRole()
111
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRole
112
     */
113
    public function testRoleCreateStructValues(array $data)
114
    {
115
        $createStruct = $data['createStruct'];
116
        $role = $data['role'];
117
118
        $this->assertEquals(
119
            [
120
                'identifier' => $createStruct->identifier,
121
                'policies' => $createStruct->policies,
122
            ],
123
            [
124
                'identifier' => $role->identifier,
125
                'policies' => $role->policies,
126
            ]
127
        );
128
        $this->assertNotNull($role->id);
129
130
        return $data;
131
    }
132
133
    /**
134
     * Test for the createRole() method.
135
     *
136
     * @see \eZ\Publish\API\Repository\RoleService::createRole()
137
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewRoleCreateStruct
138
     */
139
    public function testCreateRoleWithPolicy()
140
    {
141
        $repository = $this->getRepository();
142
143
        /* BEGIN: Use Case */
144
145
        $roleService = $repository->getRoleService();
146
        $roleCreate = $roleService->newRoleCreateStruct('roleName');
147
148
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
149
        // $roleCreate->mainLanguageCode = 'eng-US';
150
151
        // Create new subtree limitation
152
        $limitation = new SubtreeLimitation(
153
            array(
154
                'limitationValues' => array('/1/2/'),
155
            )
156
        );
157
158
        // Create policy create struct and add limitation to it
159
        $policyCreate = $roleService->newPolicyCreateStruct('content', 'read');
160
        $policyCreate->addLimitation($limitation);
161
162
        // Add policy create struct to role create struct
163
        $roleCreate->addPolicy($policyCreate);
164
165
        $role = $roleService->createRole($roleCreate);
166
167
        /* END: Use Case */
168
169
        $this->assertInstanceOf(
170
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\RoleDraft',
171
            $role
172
        );
173
174
        return [
175
            'createStruct' => $roleCreate,
176
            'role' => $role,
177
        ];
178
    }
179
180
    /**
181
     * Test for the createRole() method.
182
     *
183
     * @see \eZ\Publish\API\Repository\RoleService::createRole()
184
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRoleWithPolicy
185
     */
186
    public function testRoleCreateStructValuesWithPolicy(array $data)
187
    {
188
        $createStruct = $data['createStruct'];
189
        $role = $data['role'];
190
191
        $this->assertEquals(
192
            [
193
                'identifier' => $createStruct->identifier,
194
                'policy_module' => $createStruct->policies[0]->module,
195
                'policy_function' => $createStruct->policies[0]->function,
196
                'policy_limitation' => array_values($createStruct->policies[0]->limitations),
197
            ],
198
            [
199
                'identifier' => $role->identifier,
200
                'policy_module' => $role->policies[0]->module,
201
                'policy_function' => $role->policies[0]->function,
202
                'policy_limitation' => array_values($role->policies[0]->limitations),
203
            ]
204
        );
205
        $this->assertNotNull($role->id);
206
207
        return $data;
208
    }
209
210
    /**
211
     * Test for the createRoleDraft() method.
212
     *
213
     * @see \eZ\Publish\API\Repository\RoleService::createRoleDraft()
214
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewRoleCreateStruct
215
     */
216 View Code Duplication
    public function testCreateRoleDraft()
217
    {
218
        $repository = $this->getRepository();
219
220
        /* BEGIN: Use Case */
221
222
        $roleService = $repository->getRoleService();
223
        $roleCreate = $roleService->newRoleCreateStruct('roleName');
224
225
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
226
        // $roleCreate->mainLanguageCode = 'eng-US';
227
228
        $roleDraft = $roleService->createRole($roleCreate);
229
        $roleService->publishRoleDraft($roleDraft);
230
        $role = $roleService->loadRole($roleDraft->id);
231
        $newRoleDraft = $roleService->createRoleDraft($role);
232
233
        /* END: Use Case */
234
235
        $this->assertInstanceOf(
236
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\RoleDraft',
237
            $newRoleDraft
238
        );
239
    }
240
241
    /**
242
     * Test for the createRole() method.
243
     *
244
     * @see \eZ\Publish\API\Repository\RoleService::createRole()
245
     * @expectedException \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException
246
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRole
247
     */
248
    public function testCreateRoleThrowsInvalidArgumentException()
249
    {
250
        $repository = $this->getRepository();
251
252
        /* BEGIN: Use Case */
253
254
        $roleService = $repository->getRoleService();
255
        $roleCreate = $roleService->newRoleCreateStruct('Editor');
256
257
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
258
        // $roleCreate->mainLanguageCode = 'eng-US';
259
260
        // This call will fail with an InvalidArgumentException, because Editor exists
261
        $roleService->createRole($roleCreate);
262
263
        /* END: Use Case */
264
    }
265
266
    /**
267
     * Test for the createRoleDraft() method.
268
     *
269
     * @see \eZ\Publish\API\Repository\RoleService::createRoleDraft()
270
     * @expectedException \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException
271
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRoleDraft
272
     */
273
    public function testCreateRoleDraftThrowsInvalidArgumentException()
274
    {
275
        $repository = $this->getRepository();
276
277
        /* BEGIN: Use Case */
278
279
        $roleService = $repository->getRoleService();
280
        $roleCreate = $roleService->newRoleCreateStruct('Editor');
281
282
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
283
        // $roleCreate->mainLanguageCode = 'eng-US';
284
285
        $roleDraft = $roleService->createRole($roleCreate);
286
        $roleService->publishRoleDraft($roleDraft);
287
        $role = $roleService->loadRole($roleDraft->id);
288
        $roleService->createRoleDraft($role); // First role draft
289
290
        // This call will fail with an InvalidArgumentException, because there is already a draft
291
        $roleService->createRoleDraft($role);
292
293
        /* END: Use Case */
294
    }
295
296
    /**
297
     * Test for the createRole() method.
298
     *
299
     * @see \eZ\Publish\API\Repository\RoleService::createRole()
300
     * @expectedException \eZ\Publish\API\Repository\Exceptions\LimitationValidationException
301
     */
302 View Code Duplication
    public function testCreateRoleThrowsLimitationValidationException()
303
    {
304
        $repository = $this->getRepository();
305
306
        /* BEGIN: Use Case */
307
        $roleService = $repository->getRoleService();
308
309
        // Create new role create struct
310
        $roleCreate = $roleService->newRoleCreateStruct('Lumberjack');
311
312
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
313
        // $roleCreate->mainLanguageCode = 'eng-US';
314
315
        // Create new subtree limitation
316
        $limitation = new SubtreeLimitation(
317
            array(
318
                'limitationValues' => array('/mountain/forest/tree/42/'),
319
            )
320
        );
321
322
        // Create policy create struct and add limitation to it
323
        $policyCreate = $roleService->newPolicyCreateStruct('content', 'remove');
324
        $policyCreate->addLimitation($limitation);
325
326
        // Add policy create struct to role create struct
327
        $roleCreate->addPolicy($policyCreate);
328
329
        // This call will fail with an LimitationValidationException, because subtree
330
        // "/mountain/forest/tree/42/" does not exist
331
        $roleService->createRole($roleCreate);
332
        /* END: Use Case */
333
    }
334
335
    /**
336
     * Test for the createRole() method.
337
     *
338
     * @see \eZ\Publish\API\Repository\RoleService::createRole()
339
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewRoleCreateStruct
340
     */
341 View Code Duplication
    public function testCreateRoleInTransactionWithRollback()
342
    {
343
        $repository = $this->getRepository();
344
345
        /* BEGIN: Use Case */
346
347
        $roleService = $repository->getRoleService();
348
349
        $repository->beginTransaction();
350
351
        $roleCreate = $roleService->newRoleCreateStruct('roleName');
352
353
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
354
        // $roleCreate->mainLanguageCode = 'eng-US';
355
356
        $createdRoleId = $roleService->createRole($roleCreate)->id;
357
358
        $repository->rollback();
359
360
        try {
361
            // This call will fail with a "NotFoundException"
362
            $role = $roleService->loadRole($createdRoleId);
0 ignored issues
show
Unused Code introduced by
$role 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...
363
        } catch (NotFoundException $e) {
364
            return;
365
        }
366
        /* END: Use Case */
367
368
        $this->fail('Role object still exists after rollback.');
369
    }
370
371
    /**
372
     * Test for the createRoleDraft() method.
373
     *
374
     * @see \eZ\Publish\API\Repository\RoleService::createRoleDraft()
375
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewRoleCreateStruct
376
     */
377 View Code Duplication
    public function testCreateRoleDraftInTransactionWithRollback()
378
    {
379
        $repository = $this->getRepository();
380
381
        /* BEGIN: Use Case */
382
383
        $roleService = $repository->getRoleService();
384
385
        $repository->beginTransaction();
386
387
        $roleCreate = $roleService->newRoleCreateStruct('roleName');
388
389
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
390
        // $roleCreate->mainLanguageCode = 'eng-US';
391
392
        $createdRoleId = $roleService->createRole($roleCreate)->id;
393
394
        $repository->rollback();
395
396
        try {
397
            // This call will fail with a "NotFoundException"
398
            $role = $roleService->loadRoleDraft($createdRoleId);
0 ignored issues
show
Unused Code introduced by
$role 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...
399
        } catch (NotFoundException $e) {
400
            return;
401
        }
402
        /* END: Use Case */
403
404
        $this->fail('Role draft object still exists after rollback.');
405
    }
406
407
    /**
408
     * Test for the loadRole() method.
409
     *
410
     * @see \eZ\Publish\API\Repository\RoleService::loadRole()
411
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRole
412
     */
413 View Code Duplication
    public function testLoadRole()
414
    {
415
        $repository = $this->getRepository();
416
417
        /* BEGIN: Use Case */
418
419
        $roleService = $repository->getRoleService();
420
        $roleCreate = $roleService->newRoleCreateStruct('roleName');
421
422
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
423
        // $roleCreate->mainLanguageCode = 'eng-US';
424
425
        $roleDraft = $roleService->createRole($roleCreate);
426
        $roleService->publishRoleDraft($roleDraft);
427
428
        // Load the newly created role by its ID
429
        $role = $roleService->loadRole($roleDraft->id);
430
431
        /* END: Use Case */
432
433
        $this->assertEquals('roleName', $role->identifier);
434
    }
435
436
    /**
437
     * Test for the loadRoleDraft() method.
438
     *
439
     * @see \eZ\Publish\API\Repository\RoleService::loadRoleDraft()
440
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRoleDraft
441
     */
442
    public function testLoadRoleDraft()
443
    {
444
        $repository = $this->getRepository();
445
446
        /* BEGIN: Use Case */
447
448
        $roleService = $repository->getRoleService();
449
        $roleCreate = $roleService->newRoleCreateStruct('roleName');
450
451
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
452
        // $roleCreate->mainLanguageCode = 'eng-US';
453
454
        $roleDraft = $roleService->createRole($roleCreate);
455
456
        // Load the newly created role by its ID
457
        $role = $roleService->loadRoleDraft($roleDraft->id);
458
459
        /* END: Use Case */
460
461
        $this->assertEquals('roleName', $role->identifier);
462
    }
463
464
    public function testLoadRoleDraftByRoleId()
465
    {
466
        $repository = $this->getRepository();
467
468
        /* BEGIN: Use Case */
469
470
        $roleService = $repository->getRoleService();
471
        $roleCreate = $roleService->newRoleCreateStruct('roleName');
472
473
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
474
        // $roleCreate->mainLanguageCode = 'eng-US';
475
476
        $role = $roleService->createRole($roleCreate);
477
        $roleService->publishRoleDraft($role);
478
479
        // Now create a new draft based on the role
480
        $newDraft = $roleService->createRoleDraft($role);
481
        $loadedRoleDraft = $roleService->loadRoleDraftByRoleId($role->id);
482
483
        /* END: Use Case */
484
485
        self::assertEquals('roleName', $role->identifier);
486
        self::assertInstanceOf('eZ\Publish\API\Repository\Values\User\RoleDraft', $loadedRoleDraft);
487
        self::assertEquals($newDraft, $loadedRoleDraft);
488
    }
489
490
    /**
491
     * Test for the loadRole() method.
492
     *
493
     * @see \eZ\Publish\API\Repository\RoleService::loadRole()
494
     * @expectedException \eZ\Publish\API\Repository\Exceptions\NotFoundException
495
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRole
496
     */
497 View Code Duplication
    public function testLoadRoleThrowsNotFoundException()
498
    {
499
        $repository = $this->getRepository();
500
501
        $nonExistingRoleId = $this->generateId('role', self::DB_INT_MAX);
502
        /* BEGIN: Use Case */
503
504
        $roleService = $repository->getRoleService();
505
506
        // This call will fail with a NotFoundException, because no such role exists.
507
        $roleService->loadRole($nonExistingRoleId);
508
509
        /* END: Use Case */
510
    }
511
512
    /**
513
     * Test for the loadRoleDraft() method.
514
     *
515
     * @see \eZ\Publish\API\Repository\RoleService::loadRoleDraft()
516
     * @expectedException \eZ\Publish\API\Repository\Exceptions\NotFoundException
517
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleDraft
518
     */
519 View Code Duplication
    public function testLoadRoleDraftThrowsNotFoundException()
520
    {
521
        $repository = $this->getRepository();
522
523
        $nonExistingRoleId = $this->generateId('role', self::DB_INT_MAX);
524
        /* BEGIN: Use Case */
525
526
        $roleService = $repository->getRoleService();
527
528
        // This call will fail with a NotFoundException, because no such role exists.
529
        $roleService->loadRoleDraft($nonExistingRoleId);
530
531
        /* END: Use Case */
532
    }
533
534
    /**
535
     * @expectedException \eZ\Publish\API\Repository\Exceptions\NotFoundException
536
     */
537 View Code Duplication
    public function testLoadRoleDraftByRoleIdThrowsNotFoundException()
538
    {
539
        $repository = $this->getRepository();
540
541
        $nonExistingRoleId = $this->generateId('role', self::DB_INT_MAX);
542
        /* BEGIN: Use Case */
543
544
        $roleService = $repository->getRoleService();
545
546
        // This call will fail with a NotFoundException, because no such role exists.
547
        $roleService->loadRoleDraftByRoleId($nonExistingRoleId);
548
549
        /* END: Use Case */
550
    }
551
552
    /**
553
     * Test for the loadRoleByIdentifier() method.
554
     *
555
     * @see \eZ\Publish\API\Repository\RoleService::loadRoleByIdentifier()
556
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRole
557
     */
558 View Code Duplication
    public function testLoadRoleByIdentifier()
559
    {
560
        $repository = $this->getRepository();
561
562
        /* BEGIN: Use Case */
563
564
        $roleService = $repository->getRoleService();
565
        $roleCreate = $roleService->newRoleCreateStruct('roleName');
566
567
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
568
        // $roleCreate->mainLanguageCode = 'eng-US';
569
570
        $roleDraft = $roleService->createRole($roleCreate);
571
        $roleService->publishRoleDraft($roleDraft);
572
573
        // Load the newly created role by its identifier
574
        $role = $roleService->loadRoleByIdentifier('roleName');
575
576
        /* END: Use Case */
577
578
        $this->assertEquals('roleName', $role->identifier);
579
    }
580
581
    /**
582
     * Test for the loadRoleByIdentifier() method.
583
     *
584
     * @see \eZ\Publish\API\Repository\RoleService::loadRoleByIdentifier()
585
     * @expectedException \eZ\Publish\API\Repository\Exceptions\NotFoundException
586
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleByIdentifier
587
     */
588
    public function testLoadRoleByIdentifierThrowsNotFoundException()
589
    {
590
        $repository = $this->getRepository();
591
592
        /* BEGIN: Use Case */
593
594
        $roleService = $repository->getRoleService();
595
596
        // This call will fail with a NotFoundException, because no such role exists.
597
        $roleService->loadRoleByIdentifier('MissingRole');
598
599
        /* END: Use Case */
600
    }
601
602
    /**
603
     * Test for the loadRoles() method.
604
     *
605
     * @see \eZ\Publish\API\Repository\RoleService::loadRoles()
606
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRole
607
     */
608 View Code Duplication
    public function testLoadRoles()
609
    {
610
        $repository = $this->getRepository();
611
612
        /* BEGIN: Use Case */
613
614
        // First create a custom role
615
        $roleService = $repository->getRoleService();
616
        $roleCreate = $roleService->newRoleCreateStruct('roleName');
617
618
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
619
        // $roleCreate->mainLanguageCode = 'eng-US';
620
621
        $roleDraft = $roleService->createRole($roleCreate);
622
        $roleService->publishRoleDraft($roleDraft);
623
624
        // Now load all available roles
625
        $roles = $roleService->loadRoles();
626
627
        foreach ($roles as $role) {
628
            if ($role->identifier === 'roleName') {
629
                break;
630
            }
631
        }
632
633
        /* END: Use Case */
634
635
        $this->assertEquals('roleName', $role->identifier);
0 ignored issues
show
Bug introduced by
The variable $role seems to be defined by a foreach iteration on line 627. Are you sure the iterator is never empty, otherwise this variable is not defined?

It seems like you are relying on a variable being defined by an iteration:

foreach ($a as $b) {
}

// $b is defined here only if $a has elements, for example if $a is array()
// then $b would not be defined here. To avoid that, we recommend to set a
// default value for $b.


// Better
$b = 0; // or whatever default makes sense in your context
foreach ($a as $b) {
}

// $b is now guaranteed to be defined here.
Loading history...
636
    }
637
638
    /**
639
     * Test for the loadRoles() method.
640
     *
641
     * @see \eZ\Publish\API\Repository\RoleService::loadRoles()
642
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoles
643
     */
644
    public function testLoadRolesReturnsExpectedSetOfDefaultRoles()
645
    {
646
        $repository = $this->getRepository();
647
648
        /* BEGIN: Use Case */
649
        $roleService = $repository->getRoleService();
650
651
        $roles = $roleService->loadRoles();
652
653
        $roleNames = array();
654
        foreach ($roles as $role) {
655
            $roleNames[] = $role->identifier;
656
        }
657
        /* END: Use Case */
658
659
        sort($roleNames);
660
661
        $this->assertEquals(
662
            array(
663
                'Administrator',
664
                'Anonymous',
665
                'Editor',
666
                'Member',
667
                'Partner',
668
            ),
669
            $roleNames
670
        );
671
    }
672
673
    /**
674
     * Test for the newRoleUpdateStruct() method.
675
     *
676
     * @see \eZ\Publish\API\Repository\RoleService::newRoleUpdateStruct()
677
     */
678
    public function testNewRoleUpdateStruct()
679
    {
680
        $repository = $this->getRepository();
681
682
        /* BEGIN: Use Case */
683
        $roleService = $repository->getRoleService();
684
        $roleUpdate = $roleService->newRoleUpdateStruct('newRole');
685
        /* END: Use Case */
686
687
        $this->assertInstanceOf('\\eZ\\Publish\\API\\Repository\\Values\\User\\RoleUpdateStruct', $roleUpdate);
688
    }
689
690
    /**
691
     * Test for the updateRole() method.
692
     *
693
     * @see \eZ\Publish\API\Repository\RoleService::updateRole()
694
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewRoleUpdateStruct
695
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleByIdentifier
696
     */
697
    public function testUpdateRole()
698
    {
699
        $repository = $this->getRepository();
700
701
        /* BEGIN: Use Case */
702
        $roleService = $repository->getRoleService();
703
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
704
705
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
706
        // $roleCreate->mainLanguageCode = 'eng-US';
707
708
        $roleDraft = $roleService->createRole($roleCreate);
709
        $roleService->publishRoleDraft($roleDraft);
710
        $role = $roleService->loadRole($roleDraft->id);
711
712
        $roleUpdate = $roleService->newRoleUpdateStruct();
713
        $roleUpdate->identifier = 'updatedRole';
714
715
        $updatedRole = $roleService->updateRole($role, $roleUpdate);
0 ignored issues
show
Deprecated Code introduced by
The method eZ\Publish\API\Repositor...leService::updateRole() has been deprecated with message: since 6.0, use {@see updateRoleDraft}

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
716
        /* END: Use Case */
717
718
        // Now verify that our change was saved
719
        $role = $roleService->loadRoleByIdentifier('updatedRole');
720
721
        $this->assertEquals($role->id, $updatedRole->id);
722
    }
723
724
    /**
725
     * Test for the updateRoleDraft() method.
726
     *
727
     * @see \eZ\Publish\API\Repository\RoleService::updateRoleDraft()
728
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewRoleUpdateStruct
729
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleDraft
730
     */
731 View Code Duplication
    public function testUpdateRoleDraft()
732
    {
733
        $repository = $this->getRepository();
734
735
        /* BEGIN: Use Case */
736
        $roleService = $repository->getRoleService();
737
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
738
739
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
740
        // $roleCreate->mainLanguageCode = 'eng-US';
741
742
        $roleDraft = $roleService->createRole($roleCreate);
743
744
        $roleUpdate = $roleService->newRoleUpdateStruct();
745
        $roleUpdate->identifier = 'updatedRole';
746
747
        $updatedRole = $roleService->updateRoleDraft($roleDraft, $roleUpdate);
748
        /* END: Use Case */
749
750
        // Now verify that our change was saved
751
        $role = $roleService->loadRoleDraft($updatedRole->id);
752
753
        $this->assertEquals($role->identifier, 'updatedRole');
754
    }
755
756
    /**
757
     * Test for the updateRole() method.
758
     *
759
     * @see \eZ\Publish\API\Repository\RoleService::updateRole()
760
     * @expectedException \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException
761
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testUpdateRole
762
     */
763 View Code Duplication
    public function testUpdateRoleThrowsInvalidArgumentException()
764
    {
765
        $repository = $this->getRepository();
766
767
        /* BEGIN: Use Case */
768
        $roleService = $repository->getRoleService();
769
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
770
771
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
772
        // $roleCreate->mainLanguageCode = 'eng-US';
773
774
        $roleDraft = $roleService->createRole($roleCreate);
775
        $roleService->publishRoleDraft($roleDraft);
776
        $role = $roleService->loadRole($roleDraft->id);
777
778
        $roleUpdate = $roleService->newRoleUpdateStruct();
779
        $roleUpdate->identifier = 'Editor';
780
781
        // This call will fail with an InvalidArgumentException, because Editor is a predefined role
782
        $roleService->updateRole($role, $roleUpdate);
0 ignored issues
show
Deprecated Code introduced by
The method eZ\Publish\API\Repositor...leService::updateRole() has been deprecated with message: since 6.0, use {@see updateRoleDraft}

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
783
        /* END: Use Case */
784
    }
785
786
    /**
787
     * Test for the updateRoleDraft() method.
788
     *
789
     * @see \eZ\Publish\API\Repository\RoleService::updateRoleDraft()
790
     * @expectedException \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException
791
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testUpdateRoleDraft
792
     */
793
    public function testUpdateRoleDraftThrowsInvalidArgumentException()
794
    {
795
        $repository = $this->getRepository();
796
797
        /* BEGIN: Use Case */
798
        $roleService = $repository->getRoleService();
799
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
800
801
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
802
        // $roleCreate->mainLanguageCode = 'eng-US';
803
804
        $roleDraft = $roleService->createRole($roleCreate);
805
806
        $roleUpdate = $roleService->newRoleUpdateStruct();
807
        $roleUpdate->identifier = 'Editor';
808
809
        // This call will fail with an InvalidArgumentException, because Editor is a predefined role
810
        $roleService->updateRoleDraft($roleDraft, $roleUpdate);
811
        /* END: Use Case */
812
    }
813
814
    /**
815
     * Test for the deleteRole() method.
816
     *
817
     * @see \eZ\Publish\API\Repository\RoleService::deleteRole()
818
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRole
819
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoles
820
     */
821
    public function testDeleteRole()
822
    {
823
        $repository = $this->getRepository();
824
825
        /* BEGIN: Use Case */
826
        $roleService = $repository->getRoleService();
827
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
828
829
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
830
        // $roleCreate->mainLanguageCode = 'eng-US';
831
832
        $roleDraft = $roleService->createRole($roleCreate);
833
        $roleService->publishRoleDraft($roleDraft);
834
        $role = $roleService->loadRole($roleDraft->id);
835
836
        $roleService->deleteRole($role);
837
        /* END: Use Case */
838
839
        $this->assertEquals(5, count($roleService->loadRoles()));
840
    }
841
842
    /**
843
     * Test for the deleteRoleDraft() method.
844
     *
845
     * @see \eZ\Publish\API\Repository\RoleService::deleteRoleDraft()
846
     * @expectedException \eZ\Publish\API\Repository\Exceptions\NotFoundException
847
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleDraft
848
     */
849
    public function testDeleteRoleDraft()
850
    {
851
        $repository = $this->getRepository();
852
853
        /* BEGIN: Use Case */
854
        $roleService = $repository->getRoleService();
855
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
856
857
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
858
        // $roleCreate->mainLanguageCode = 'eng-US';
859
860
        $roleDraft = $roleService->createRole($roleCreate);
861
        $roleID = $roleDraft->id;
862
        $roleService->deleteRoleDraft($roleDraft);
863
864
        // This call will fail with a NotFoundException, because the draft no longer exists
865
        $roleService->loadRoleDraft($roleID);
866
        /* END: Use Case */
867
    }
868
869
    /**
870
     * Test for the newPolicyCreateStruct() method.
871
     *
872
     * @see \eZ\Publish\API\Repository\RoleService::newPolicyCreateStruct()
873
     */
874
    public function testNewPolicyCreateStruct()
875
    {
876
        $repository = $this->getRepository();
877
878
        /* BEGIN: Use Case */
879
        $roleService = $repository->getRoleService();
880
        $policyCreate = $roleService->newPolicyCreateStruct('content', 'create');
881
        /* END: Use Case */
882
883
        $this->assertInstanceOf('\\eZ\\Publish\\API\\Repository\\Values\\User\\PolicyCreateStruct', $policyCreate);
884
    }
885
886
    /**
887
     * Test for the newPolicyCreateStruct() method.
888
     *
889
     * @see \eZ\Publish\API\Repository\RoleService::newPolicyCreateStruct()
890
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewPolicyCreateStruct
891
     */
892
    public function testNewPolicyCreateStructSetsStructProperties()
893
    {
894
        $repository = $this->getRepository();
895
896
        /* BEGIN: Use Case */
897
        $roleService = $repository->getRoleService();
898
        $policyCreate = $roleService->newPolicyCreateStruct('content', 'create');
899
        /* END: Use Case */
900
901
        $this->assertEquals(
902
            array('content', 'create'),
903
            array($policyCreate->module, $policyCreate->function)
904
        );
905
    }
906
907
    /**
908
     * Test for the addPolicy() method.
909
     *
910
     * @see \eZ\Publish\API\Repository\RoleService::addPolicy()
911
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleByIdentifier
912
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewPolicyCreateStruct
913
     */
914 View Code Duplication
    public function testAddPolicy()
915
    {
916
        $repository = $this->getRepository();
917
918
        /* BEGIN: Use Case */
919
        $roleService = $repository->getRoleService();
920
921
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
922
923
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
924
        // $roleCreate->mainLanguageCode = 'eng-US';
925
926
        $roleDraft = $roleService->createRole($roleCreate);
927
        $roleService->publishRoleDraft($roleDraft);
928
        $role = $roleService->loadRole($roleDraft->id);
929
930
        $role = $roleService->addPolicy(
0 ignored issues
show
Deprecated Code introduced by
The method eZ\Publish\API\Repository\RoleService::addPolicy() has been deprecated with message: since 6.0, use {@see addPolicyByRoleDraft}

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
931
            $role,
932
            $roleService->newPolicyCreateStruct('content', 'delete')
933
        );
934
        $role = $roleService->addPolicy(
0 ignored issues
show
Deprecated Code introduced by
The method eZ\Publish\API\Repository\RoleService::addPolicy() has been deprecated with message: since 6.0, use {@see addPolicyByRoleDraft}

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
935
            $role,
936
            $roleService->newPolicyCreateStruct('content', 'create')
937
        );
938
        /* END: Use Case */
939
940
        $actual = array();
941
        foreach ($role->getPolicies() as $policy) {
942
            $actual[] = array(
943
                'module' => $policy->module,
944
                'function' => $policy->function,
945
            );
946
        }
947
        usort(
948
            $actual,
949
            function ($p1, $p2) {
950
                return strcasecmp($p1['function'], $p2['function']);
951
            }
952
        );
953
954
        $this->assertEquals(
955
            array(
956
                array(
957
                    'module' => 'content',
958
                    'function' => 'create',
959
                ),
960
                array(
961
                    'module' => 'content',
962
                    'function' => 'delete',
963
                ),
964
            ),
965
            $actual
966
        );
967
    }
968
969
    /**
970
     * Test for the addPolicyByRoleDraft() method.
971
     *
972
     * @see \eZ\Publish\API\Repository\RoleService::addPolicyByRoleDraft()
973
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRoleDraft
974
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewPolicyCreateStruct
975
     */
976
    public function testAddPolicyByRoleDraft()
977
    {
978
        $repository = $this->getRepository();
979
980
        /* BEGIN: Use Case */
981
        $roleService = $repository->getRoleService();
982
983
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
984
985
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
986
        // $roleCreate->mainLanguageCode = 'eng-US';
987
988
        $roleDraft = $roleService->createRole($roleCreate);
989
990
        $roleDraft = $roleService->addPolicyByRoleDraft(
991
            $roleDraft,
992
            $roleService->newPolicyCreateStruct('content', 'delete')
993
        );
994
        $roleDraft = $roleService->addPolicyByRoleDraft(
995
            $roleDraft,
996
            $roleService->newPolicyCreateStruct('content', 'create')
997
        );
998
        /* END: Use Case */
999
1000
        $actual = array();
1001 View Code Duplication
        foreach ($roleDraft->getPolicies() as $policy) {
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...
1002
            $actual[] = array(
1003
                'module' => $policy->module,
1004
                'function' => $policy->function,
1005
            );
1006
        }
1007
        usort(
1008
            $actual,
1009
            function ($p1, $p2) {
1010
                return strcasecmp($p1['function'], $p2['function']);
1011
            }
1012
        );
1013
1014
        $this->assertEquals(
1015
            array(
1016
                array(
1017
                    'module' => 'content',
1018
                    'function' => 'create',
1019
                ),
1020
                array(
1021
                    'module' => 'content',
1022
                    'function' => 'delete',
1023
                ),
1024
            ),
1025
            $actual
1026
        );
1027
    }
1028
1029
    /**
1030
     * Test for the addPolicy() method.
1031
     *
1032
     * @return array [\eZ\Publish\API\Repository\Values\User\Role, \eZ\Publish\API\Repository\Values\User\Policy]
1033
     *
1034
     * @see \eZ\Publish\API\Repository\RoleService::addPolicy()
1035
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicy
1036
     */
1037
    public function testAddPolicyUpdatesRole()
1038
    {
1039
        $repository = $this->getRepository();
1040
1041
        /* BEGIN: Use Case */
1042
        $roleService = $repository->getRoleService();
1043
1044
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
1045
1046
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1047
        // $roleCreate->mainLanguageCode = 'eng-US';
1048
1049
        $roleDraft = $roleService->createRole($roleCreate);
1050
        $roleService->publishRoleDraft($roleDraft);
1051
        $role = $roleService->loadRole($roleDraft->id);
1052
1053
        $policyCreate = $roleService->newPolicyCreateStruct('content', 'create');
1054
        $role = $roleService->addPolicy($role, $policyCreate);
0 ignored issues
show
Deprecated Code introduced by
The method eZ\Publish\API\Repository\RoleService::addPolicy() has been deprecated with message: since 6.0, use {@see addPolicyByRoleDraft}

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
1055
1056
        $policy = null;
1057
        foreach ($role->getPolicies() as $policy) {
1058
            if ($policy->module === 'content' && $policy->function === 'create') {
1059
                break;
1060
            }
1061
        }
1062
        /* END: Use Case */
1063
1064
        $this->assertInstanceOf(
1065
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\Policy',
1066
            $policy
1067
        );
1068
1069
        return array($role, $policy);
1070
    }
1071
1072
    /**
1073
     * Test for the addPolicyByRoleDraft() method.
1074
     *
1075
     * @return array [\eZ\Publish\API\Repository\Values\User\RoleDraft, \eZ\Publish\API\Repository\Values\User\Policy]
1076
     *
1077
     * @see \eZ\Publish\API\Repository\RoleService::addPolicyByRoleDraft()
1078
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicyByRoleDraft
1079
     */
1080
    public function testAddPolicyByRoleDraftUpdatesRole()
1081
    {
1082
        $repository = $this->getRepository();
1083
1084
        /* BEGIN: Use Case */
1085
        $roleService = $repository->getRoleService();
1086
1087
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
1088
1089
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1090
        // $roleCreate->mainLanguageCode = 'eng-US';
1091
1092
        $roleDraft = $roleService->createRole($roleCreate);
1093
1094
        $policyCreate = $roleService->newPolicyCreateStruct('content', 'create');
1095
        $roleDraft = $roleService->addPolicyByRoleDraft($roleDraft, $policyCreate);
1096
1097
        $policy = null;
1098
        foreach ($roleDraft->getPolicies() as $policy) {
1099
            if ($policy->module === 'content' && $policy->function === 'create') {
1100
                break;
1101
            }
1102
        }
1103
        /* END: Use Case */
1104
1105
        $this->assertInstanceOf(
1106
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\Policy',
1107
            $policy
1108
        );
1109
1110
        return array($roleDraft, $policy);
1111
    }
1112
1113
    /**
1114
     * Test for the addPolicy() method.
1115
     *
1116
     * @param array $roleAndPolicy
1117
     *
1118
     * @see \eZ\Publish\API\Repository\RoleService::addPolicy()
1119
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicyUpdatesRole
1120
     */
1121 View Code Duplication
    public function testAddPolicySetsPolicyProperties($roleAndPolicy)
1122
    {
1123
        list($role, $policy) = $roleAndPolicy;
1124
1125
        $this->assertEquals(
1126
            array($role->id, 'content', 'create'),
1127
            array($policy->roleId, $policy->module, $policy->function)
1128
        );
1129
    }
1130
1131
    /**
1132
     * Test for the addPolicyByRoleDraft() method.
1133
     *
1134
     * @param array $roleAndPolicy
1135
     *
1136
     * @see \eZ\Publish\API\Repository\RoleService::addPolicyByRoleDraft()
1137
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicyByRoleDraftUpdatesRole
1138
     */
1139 View Code Duplication
    public function testAddPolicyByRoleDraftSetsPolicyProperties($roleAndPolicy)
1140
    {
1141
        list($role, $policy) = $roleAndPolicy;
1142
1143
        $this->assertEquals(
1144
            array($role->id, 'content', 'create'),
1145
            array($policy->roleId, $policy->module, $policy->function)
1146
        );
1147
    }
1148
1149
    /**
1150
     * Test for the addPolicy() method.
1151
     *
1152
     * @see \eZ\Publish\API\Repository\RoleService::addPolicy()
1153
     * @expectedException \eZ\Publish\API\Repository\Exceptions\LimitationValidationException
1154
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewPolicyCreateStruct
1155
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRole
1156
     */
1157
    public function testAddPolicyThrowsLimitationValidationException()
1158
    {
1159
        $repository = $this->getRepository();
1160
1161
        /* BEGIN: Use Case */
1162
        $roleService = $repository->getRoleService();
1163
1164
        $roleCreate = $roleService->newRoleCreateStruct('Lumberjack');
1165
1166
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1167
        // $roleCreate->mainLanguageCode = 'eng-US';
1168
1169
        $roleDraft = $roleService->createRole($roleCreate);
1170
        $roleService->publishRoleDraft($roleDraft);
1171
        $role = $roleService->loadRole($roleDraft->id);
1172
1173
        // Create new subtree limitation
1174
        $limitation = new SubtreeLimitation(
1175
            array(
1176
                'limitationValues' => array('/mountain/forest/tree/42/'),
1177
            )
1178
        );
1179
1180
        // Create policy create struct and add limitation to it
1181
        $policyCreateStruct = $roleService->newPolicyCreateStruct('content', 'remove');
1182
        $policyCreateStruct->addLimitation($limitation);
1183
1184
        // This call will fail with an LimitationValidationException, because subtree
1185
        // "/mountain/forest/tree/42/" does not exist
1186
        $roleService->addPolicy($role, $policyCreateStruct);
0 ignored issues
show
Deprecated Code introduced by
The method eZ\Publish\API\Repository\RoleService::addPolicy() has been deprecated with message: since 6.0, use {@see addPolicyByRoleDraft}

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
1187
        /* END: Use Case */
1188
    }
1189
1190
    /**
1191
     * Test for the addPolicyByRoleDraft() method.
1192
     *
1193
     * @see \eZ\Publish\API\Repository\RoleService::addPolicyByRoleDraft()
1194
     * @expectedException \eZ\Publish\API\Repository\Exceptions\LimitationValidationException
1195
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewPolicyCreateStruct
1196
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRoleDraft
1197
     */
1198 View Code Duplication
    public function testAddPolicyByRoleDraftThrowsLimitationValidationException()
1199
    {
1200
        $repository = $this->getRepository();
1201
1202
        /* BEGIN: Use Case */
1203
        $roleService = $repository->getRoleService();
1204
1205
        $roleCreate = $roleService->newRoleCreateStruct('Lumberjack');
1206
1207
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1208
        // $roleCreate->mainLanguageCode = 'eng-US';
1209
1210
        $roleDraft = $roleService->createRole($roleCreate);
1211
1212
        // Create new subtree limitation
1213
        $limitation = new SubtreeLimitation(
1214
            array(
1215
                'limitationValues' => array('/mountain/forest/tree/42/'),
1216
            )
1217
        );
1218
1219
        // Create policy create struct and add limitation to it
1220
        $policyCreateStruct = $roleService->newPolicyCreateStruct('content', 'remove');
1221
        $policyCreateStruct->addLimitation($limitation);
1222
1223
        // This call will fail with an LimitationValidationException, because subtree
1224
        // "/mountain/forest/tree/42/" does not exist
1225
        $roleService->addPolicyByRoleDraft($roleDraft, $policyCreateStruct);
1226
        /* END: Use Case */
1227
    }
1228
1229
    /**
1230
     * Test for the createRole() method.
1231
     *
1232
     * @see \eZ\Publish\API\Repository\RoleService::createRole()
1233
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicyUpdatesRole
1234
     */
1235
    public function testCreateRoleWithAddPolicy()
1236
    {
1237
        $repository = $this->getRepository();
1238
1239
        /* BEGIN: Use Case */
1240
        $roleService = $repository->getRoleService();
1241
1242
        // Instantiate a new create struct
1243
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
1244
1245
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1246
        // $roleCreate->mainLanguageCode = 'eng-US';
1247
1248
        // Add some role policies
1249
        $roleCreate->addPolicy(
1250
            $roleService->newPolicyCreateStruct(
1251
                'content',
1252
                'read'
1253
            )
1254
        );
1255
        $roleCreate->addPolicy(
1256
            $roleService->newPolicyCreateStruct(
1257
                'content',
1258
                'translate'
1259
            )
1260
        );
1261
1262
        // Create new role instance
1263
        $roleDraft = $roleService->createRole($roleCreate);
1264
        $roleService->publishRoleDraft($roleDraft);
1265
        $role = $roleService->loadRole($roleDraft->id);
1266
1267
        $policies = array();
1268 View Code Duplication
        foreach ($role->getPolicies() as $policy) {
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...
1269
            $policies[] = array('module' => $policy->module, 'function' => $policy->function);
1270
        }
1271
        /* END: Use Case */
1272
        array_multisort($policies);
1273
1274
        $this->assertEquals(
1275
            array(
1276
                array(
1277
                    'module' => 'content',
1278
                    'function' => 'read',
1279
                ),
1280
                array(
1281
                    'module' => 'content',
1282
                    'function' => 'translate',
1283
                ),
1284
            ),
1285
            $policies
1286
        );
1287
    }
1288
1289
    /**
1290
     * Test for the createRoleDraft() method.
1291
     *
1292
     * @see \eZ\Publish\API\Repository\RoleService::createRoleDraft()
1293
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicyByRoleDraftUpdatesRole
1294
     */
1295
    public function testCreateRoleDraftWithAddPolicy()
1296
    {
1297
        $repository = $this->getRepository();
1298
1299
        /* BEGIN: Use Case */
1300
        $roleService = $repository->getRoleService();
1301
1302
        // Instantiate a new create struct
1303
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
1304
1305
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1306
        // $roleCreate->mainLanguageCode = 'eng-US';
1307
1308
        // Add some role policies
1309
        $roleCreate->addPolicy(
1310
            $roleService->newPolicyCreateStruct(
1311
                'content',
1312
                'read'
1313
            )
1314
        );
1315
        $roleCreate->addPolicy(
1316
            $roleService->newPolicyCreateStruct(
1317
                'content',
1318
                'translate'
1319
            )
1320
        );
1321
1322
        // Create new role instance
1323
        $roleDraft = $roleService->createRole($roleCreate);
1324
1325
        $policies = array();
1326 View Code Duplication
        foreach ($roleDraft->getPolicies() as $policy) {
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...
1327
            $policies[] = array('module' => $policy->module, 'function' => $policy->function);
1328
        }
1329
        /* END: Use Case */
1330
1331
        $this->assertEquals(
1332
            array(
1333
                array(
1334
                    'module' => 'content',
1335
                    'function' => 'read',
1336
                ),
1337
                array(
1338
                    'module' => 'content',
1339
                    'function' => 'translate',
1340
                ),
1341
            ),
1342
            $policies
1343
        );
1344
    }
1345
1346
    /**
1347
     * Test for the newPolicyUpdateStruct() method.
1348
     *
1349
     * @see \eZ\Publish\API\Repository\RoleService::newPolicyUpdateStruct()
1350
     */
1351
    public function testNewPolicyUpdateStruct()
1352
    {
1353
        $repository = $this->getRepository();
1354
1355
        /* BEGIN: Use Case */
1356
        $roleService = $repository->getRoleService();
1357
        $policyUpdate = $roleService->newPolicyUpdateStruct();
1358
        /* END: Use Case */
1359
1360
        $this->assertInstanceOf(
1361
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\PolicyUpdateStruct',
1362
            $policyUpdate
1363
        );
1364
    }
1365
1366
    public function testUpdatePolicyNoLimitation()
1367
    {
1368
        $repository = $this->getRepository();
1369
1370
        /* BEGIN: Use Case */
1371
        $roleService = $repository->getRoleService();
1372
1373
        // Instantiate new policy create
1374
        $policyCreate = $roleService->newPolicyCreateStruct('foo', 'bar');
1375
1376
        // Instantiate a role create and add the policy create
1377
        $roleCreate = $roleService->newRoleCreateStruct('myRole');
1378
1379
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1380
        // $roleCreate->mainLanguageCode = 'eng-US';
1381
1382
        $roleCreate->addPolicy($policyCreate);
1383
1384
        // Create a new role instance.
1385
        $roleDraft = $roleService->createRole($roleCreate);
1386
        $roleService->publishRoleDraft($roleDraft);
1387
        $role = $roleService->loadRole($roleDraft->id);
1388
1389
        // Search for the new policy instance
1390
        $policy = null;
1391
        foreach ($role->getPolicies() as $policy) {
1392
            if ($policy->module === 'foo' && $policy->function === 'bar') {
1393
                break;
1394
            }
1395
        }
1396
1397
        // Create an update struct
1398
        $policyUpdate = $roleService->newPolicyUpdateStruct();
1399
1400
        // Update the the policy
1401
        $policy = $roleService->updatePolicy($policy, $policyUpdate);
0 ignored issues
show
Bug introduced by
It seems like $policy can be null; however, updatePolicy() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
Deprecated Code introduced by
The method eZ\Publish\API\Repositor...Service::updatePolicy() has been deprecated with message: since 6.0, use {@link updatePolicyByRoleDraft()} instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
1402
        /* END: Use Case */
1403
1404
        $this->assertInstanceOf(
1405
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\Policy',
1406
            $policy
1407
        );
1408
1409
        self::assertEquals(array(), $policy->getLimitations());
1410
    }
1411
1412
    /**
1413
     * Test for the updatePolicy() method.
1414
     *
1415
     * @return array
1416
     *
1417
     * @see \eZ\Publish\API\Repository\RoleService::updatePolicy()
1418
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicy
1419
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewPolicyUpdateStruct
1420
     */
1421
    public function testUpdatePolicy()
1422
    {
1423
        $repository = $this->getRepository();
1424
1425
        /* BEGIN: Use Case */
1426
        $roleService = $repository->getRoleService();
1427
1428
        // Instantiate new policy create
1429
        $policyCreate = $roleService->newPolicyCreateStruct('content', 'translate');
1430
1431
        // Add some limitations for the new policy
1432
        $policyCreate->addLimitation(
1433
            new LanguageLimitation(
1434
                array(
1435
                    'limitationValues' => array('eng-US', 'eng-GB'),
1436
                )
1437
            )
1438
        );
1439
1440
        // Instantiate a role create and add the policy create
1441
        $roleCreate = $roleService->newRoleCreateStruct('myRole');
1442
1443
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1444
        // $roleCreate->mainLanguageCode = 'eng-US';
1445
1446
        $roleCreate->addPolicy($policyCreate);
1447
1448
        // Create a new role instance.
1449
        $roleDraft = $roleService->createRole($roleCreate);
1450
        $roleService->publishRoleDraft($roleDraft);
1451
        $role = $roleService->loadRole($roleDraft->id);
1452
1453
        // Search for the new policy instance
1454
        $policy = null;
1455
        foreach ($role->getPolicies() as $policy) {
1456
            if ($policy->module === 'content' && $policy->function === 'translate') {
1457
                break;
1458
            }
1459
        }
1460
1461
        // Create an update struct and set a modified limitation
1462
        $policyUpdate = $roleService->newPolicyUpdateStruct();
1463
        $policyUpdate->addLimitation(
1464
            new ContentTypeLimitation(
1465
                array(
1466
                    'limitationValues' => array(29, 30),
1467
                )
1468
            )
1469
        );
1470
1471
        // Update the the policy
1472
        $policy = $roleService->updatePolicy($policy, $policyUpdate);
0 ignored issues
show
Deprecated Code introduced by
The method eZ\Publish\API\Repositor...Service::updatePolicy() has been deprecated with message: since 6.0, use {@link updatePolicyByRoleDraft()} instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
Bug introduced by
It seems like $policy can be null; however, updatePolicy() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
1473
        /* END: Use Case */
1474
1475
        $this->assertInstanceOf(
1476
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\Policy',
1477
            $policy
1478
        );
1479
1480
        return array($roleService->loadRole($role->id), $policy);
1481
    }
1482
1483
    /**
1484
     * Test for the updatePolicy() method.
1485
     *
1486
     * @param array $roleAndPolicy
1487
     *
1488
     * @see \eZ\Publish\API\Repository\RoleService::updatePolicy()
1489
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testUpdatePolicy
1490
     */
1491
    public function testUpdatePolicyUpdatesLimitations($roleAndPolicy)
1492
    {
1493
        list($role, $policy) = $roleAndPolicy;
1494
1495
        $this->assertEquals(
1496
            array(
1497
                new ContentTypeLimitation(
1498
                    array(
1499
                        'limitationValues' => array(29, 30),
1500
                    )
1501
                ),
1502
            ),
1503
            $policy->getLimitations()
1504
        );
1505
1506
        return $role;
1507
    }
1508
1509
    /**
1510
     * Test for the updatePolicy() method.
1511
     *
1512
     * @param \eZ\Publish\API\Repository\Values\User\Role $role
1513
     *
1514
     * @see \eZ\Publish\API\Repository\RoleService::updatePolicy()
1515
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testUpdatePolicyUpdatesLimitations
1516
     */
1517
    public function testUpdatePolicyUpdatesRole($role)
1518
    {
1519
        $limitations = array();
1520
        foreach ($role->getPolicies() as $policy) {
1521
            foreach ($policy->getLimitations() as $limitation) {
1522
                $limitations[] = $limitation;
1523
            }
1524
        }
1525
1526
        $this->assertCount(1, $limitations);
1527
        $this->assertInstanceOf(
1528
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\Limitation',
1529
            $limitations[0]
1530
        );
1531
1532
        $expectedData = array(
1533
            'limitationValues' => array(29, 30),
1534
        );
1535
        $this->assertPropertiesCorrectUnsorted(
1536
            $expectedData,
1537
            $limitations[0]
1538
        );
1539
    }
1540
1541
    /**
1542
     * Test for the updatePolicy() method.
1543
     *
1544
     * @see \eZ\Publish\API\Repository\RoleService::updatePolicy()
1545
     * @expectedException \eZ\Publish\API\Repository\Exceptions\LimitationValidationException
1546
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicy
1547
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewPolicyCreateStruct
1548
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewPolicyUpdateStruct
1549
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewRoleCreateStruct
1550
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRole
1551
     */
1552
    public function testUpdatePolicyThrowsLimitationValidationException()
1553
    {
1554
        $repository = $this->getRepository();
1555
1556
        /* BEGIN: Use Case */
1557
        $roleService = $repository->getRoleService();
1558
1559
        // Instantiate new policy create
1560
        $policyCreate = $roleService->newPolicyCreateStruct('content', 'remove');
1561
1562
        // Add some limitations for the new policy
1563
        $policyCreate->addLimitation(
1564
            new SubtreeLimitation(
1565
                array(
1566
                    'limitationValues' => array('/1/2/'),
1567
                )
1568
            )
1569
        );
1570
1571
        // Instantiate a role create and add the policy create
1572
        $roleCreate = $roleService->newRoleCreateStruct('myRole');
1573
1574
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1575
        // $roleCreate->mainLanguageCode = 'eng-US';
1576
1577
        $roleCreate->addPolicy($policyCreate);
1578
1579
        // Create a new role instance.
1580
        $roleDraft = $roleService->createRole($roleCreate);
1581
        $roleService->publishRoleDraft($roleDraft);
1582
        $role = $roleService->loadRole($roleDraft->id);
1583
1584
        // Search for the new policy instance
1585
        $policy = null;
1586
        foreach ($role->getPolicies() as $policy) {
1587
            if ($policy->module === 'content' && $policy->function === 'remove') {
1588
                break;
1589
            }
1590
        }
1591
1592
        // Create an update struct and set a modified limitation
1593
        $policyUpdate = $roleService->newPolicyUpdateStruct();
1594
        $policyUpdate->addLimitation(
1595
            new SubtreeLimitation(
1596
                array(
1597
                    'limitationValues' => array('/mountain/forest/tree/42/'),
1598
                )
1599
            )
1600
        );
1601
1602
        // This call will fail with an LimitationValidationException, because subtree
1603
        // "/mountain/forest/tree/42/" does not exist
1604
        $policy = $roleService->updatePolicy($policy, $policyUpdate);
0 ignored issues
show
Unused Code introduced by
$policy 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...
Bug introduced by
It seems like $policy can be null; however, updatePolicy() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
Deprecated Code introduced by
The method eZ\Publish\API\Repositor...Service::updatePolicy() has been deprecated with message: since 6.0, use {@link updatePolicyByRoleDraft()} instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
1605
        /* END: Use Case */
1606
    }
1607
1608
    /**
1609
     * Test for the removePolicy() method.
1610
     *
1611
     * @see \eZ\Publish\API\Repository\RoleService::removePolicy()
1612
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicy
1613
     */
1614 View Code Duplication
    public function testRemovePolicy()
1615
    {
1616
        $repository = $this->getRepository();
1617
1618
        /* BEGIN: Use Case */
1619
        $roleService = $repository->getRoleService();
1620
1621
        // Instantiate a new role create
1622
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
1623
1624
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1625
        // $roleCreate->mainLanguageCode = 'eng-US';
1626
1627
        // Create a new role with two policies
1628
        $roleDraft = $roleService->createRole($roleCreate);
1629
        $roleService->addPolicyByRoleDraft(
1630
            $roleDraft,
1631
            $roleService->newPolicyCreateStruct('content', 'create')
1632
        );
1633
        $roleService->addPolicyByRoleDraft(
1634
            $roleDraft,
1635
            $roleService->newPolicyCreateStruct('content', 'delete')
1636
        );
1637
        $roleService->publishRoleDraft($roleDraft);
1638
        $role = $roleService->loadRole($roleDraft->id);
1639
1640
        // Delete all policies from the new role
1641
        foreach ($role->getPolicies() as $policy) {
1642
            $role = $roleService->removePolicy($role, $policy);
0 ignored issues
show
Deprecated Code introduced by
The method eZ\Publish\API\Repositor...Service::removePolicy() has been deprecated with message: since 5.3, use {@link removePolicyByRoleDraft()} instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
1643
        }
1644
        /* END: Use Case */
1645
1646
        $this->assertSame(array(), $role->getPolicies());
1647
    }
1648
1649
    /**
1650
     * Test for the removePolicyByRoleDraft() method.
1651
     *
1652
     * @see \eZ\Publish\API\Repository\RoleService::removePolicyByRoleDraft()
1653
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicyByRoleDraft
1654
     */
1655 View Code Duplication
    public function testRemovePolicyByRoleDraft()
1656
    {
1657
        $repository = $this->getRepository();
1658
1659
        /* BEGIN: Use Case */
1660
        $roleService = $repository->getRoleService();
1661
1662
        // Instantiate a new role create
1663
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
1664
1665
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1666
        // $roleCreate->mainLanguageCode = 'eng-US';
1667
1668
        // Create a new role with two policies
1669
        $roleDraft = $roleService->createRole($roleCreate);
1670
        $roleService->addPolicyByRoleDraft(
1671
            $roleDraft,
1672
            $roleService->newPolicyCreateStruct('content', 'create')
1673
        );
1674
        $roleService->addPolicyByRoleDraft(
1675
            $roleDraft,
1676
            $roleService->newPolicyCreateStruct('content', 'delete')
1677
        );
1678
1679
        // Delete all policies from the new role
1680
        foreach ($roleDraft->getPolicies() as $policy) {
1681
            $roleDraft = $roleService->removePolicyByRoleDraft($roleDraft, $policy);
0 ignored issues
show
Compatibility introduced by
$policy of type object<eZ\Publish\API\Re...ory\Values\User\Policy> is not a sub-type of object<eZ\Publish\API\Re...alues\User\PolicyDraft>. It seems like you assume a child class of the class eZ\Publish\API\Repository\Values\User\Policy to be always present.

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

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

Loading history...
1682
        }
1683
        /* END: Use Case */
1684
1685
        $this->assertSame(array(), $roleDraft->getPolicies());
1686
    }
1687
1688
    /**
1689
     * Test for the deletePolicy() method.
1690
     *
1691
     * @see \eZ\Publish\API\Repository\RoleService::deletePolicy()
1692
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRole
1693
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicy
1694
     */
1695 View Code Duplication
    public function testDeletePolicy()
1696
    {
1697
        $repository = $this->getRepository();
1698
1699
        /* BEGIN: Use Case */
1700
        $roleService = $repository->getRoleService();
1701
1702
        // Instantiate a new role create
1703
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
1704
1705
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1706
        // $roleCreate->mainLanguageCode = 'eng-US';
1707
1708
        // Create a new role with two policies
1709
        $roleDraft = $roleService->createRole($roleCreate);
1710
        $roleService->addPolicyByRoleDraft(
1711
            $roleDraft,
1712
            $roleService->newPolicyCreateStruct('content', 'create')
1713
        );
1714
        $roleService->addPolicyByRoleDraft(
1715
            $roleDraft,
1716
            $roleService->newPolicyCreateStruct('content', 'delete')
1717
        );
1718
        $roleService->publishRoleDraft($roleDraft);
1719
        $role = $roleService->loadRole($roleDraft->id);
1720
1721
        // Delete all policies from the new role
1722
        foreach ($role->getPolicies() as $policy) {
1723
            $roleService->deletePolicy($policy);
0 ignored issues
show
Deprecated Code introduced by
The method eZ\Publish\API\Repositor...Service::deletePolicy() has been deprecated with message: since 6.0, use {@link removePolicyByRoleDraft()} instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
1724
        }
1725
        /* END: Use Case */
1726
1727
        $role = $roleService->loadRole($role->id);
1728
        $this->assertSame(array(), $role->getPolicies());
1729
    }
1730
1731
    /**
1732
     * Test loading user/group role assignments.
1733
     *
1734
     * @return \eZ\Publish\API\Repository\Values\User\UserGroupRoleAssignment
1735
     *
1736
     * @covers \eZ\Publish\API\Repository\RoleService::loadRoleAssignment
1737
     */
1738
    public function testLoadRoleAssignment()
1739
    {
1740
        $repository = $this->getRepository();
1741
1742
        /* BEGIN: Use Case */
1743
        $roleService = $repository->getRoleService();
1744
1745
        // Assignment to user group
1746
        $groupRoleAssignment = $roleService->loadRoleAssignment(25);
1747
1748
        // Assignment to user
1749
        $role = $roleService->loadRole(2);
1750
        $user = $repository->getUserService()->loadUser(14);
1751
        $roleService->assignRoleToUser($role, $user);
1752
        $userRoleAssignments = $roleService->getRoleAssignmentsForUser($user);
1753
1754
        $userRoleAssignment = $roleService->loadRoleAssignment($userRoleAssignments[0]->id);
1755
        /* END: Use Case */
1756
1757
        $this->assertInstanceOf(
1758
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\UserGroupRoleAssignment',
1759
            $groupRoleAssignment
1760
        );
1761
1762
        $this->assertEquals(
1763
            [
1764
                12,
1765
                2,
1766
                25,
1767
            ],
1768
            [
1769
                $groupRoleAssignment->userGroup->id,
0 ignored issues
show
Documentation introduced by
The property userGroup does not exist on object<eZ\Publish\API\Re...es\User\RoleAssignment>. 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...
1770
                $groupRoleAssignment->role->id,
1771
                $groupRoleAssignment->id,
1772
            ]
1773
        );
1774
1775
        self::assertInstanceOf('\\eZ\\Publish\\API\\Repository\\Values\\User\\UserRoleAssignment', $userRoleAssignment);
1776
        self::assertEquals(14, $userRoleAssignment->user->id);
0 ignored issues
show
Documentation introduced by
The property user does not exist on object<eZ\Publish\API\Re...es\User\RoleAssignment>. 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...
1777
1778
        return $groupRoleAssignment;
1779
    }
1780
1781
    /**
1782
     * Test for the getRoleAssignments() method.
1783
     *
1784
     * @return \eZ\Publish\API\Repository\Values\User\RoleAssignment[]
1785
     *
1786
     * @see \eZ\Publish\API\Repository\RoleService::getRoleAssignments()
1787
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleByIdentifier
1788
     */
1789
    public function testGetRoleAssignments()
1790
    {
1791
        $repository = $this->getRepository();
1792
1793
        /* BEGIN: Use Case */
1794
        $roleService = $repository->getRoleService();
1795
1796
        // Load the editor role
1797
        $role = $roleService->loadRoleByIdentifier('Editor');
1798
1799
        // Load all assigned users and user groups
1800
        $roleAssignments = $roleService->getRoleAssignments($role);
1801
1802
        /* END: Use Case */
1803
1804
        $this->assertEquals(2, count($roleAssignments));
1805
        $this->assertInstanceOf(
1806
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\UserGroupRoleAssignment',
1807
            $roleAssignments[0]
1808
        );
1809
        $this->assertInstanceOf(
1810
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\UserGroupRoleAssignment',
1811
            $roleAssignments[1]
1812
        );
1813
1814
        return $roleAssignments;
1815
    }
1816
1817
    /**
1818
     * Test for the getRoleAssignments() method.
1819
     *
1820
     * @param \eZ\Publish\API\Repository\Values\User\RoleAssignment[] $roleAssignments
1821
     *
1822
     * @see \eZ\Publish\API\Repository\RoleService::getRoleAssignments()
1823
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testGetRoleAssignments
1824
     */
1825
    public function testGetRoleAssignmentsContainExpectedLimitation(array $roleAssignments)
1826
    {
1827
        $this->assertEquals(
1828
            'Subtree',
1829
            reset($roleAssignments)->limitation->getIdentifier()
1830
        );
1831
    }
1832
1833
    /**
1834
     * Test for the assignRoleToUser() method.
1835
     *
1836
     * @see \eZ\Publish\API\Repository\RoleService::assignRoleToUser()
1837
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testGetRoleAssignments
1838
     */
1839 View Code Duplication
    public function testAssignRoleToUser()
1840
    {
1841
        $repository = $this->getRepository();
1842
        $roleService = $repository->getRoleService();
1843
1844
        /* BEGIN: Use Case */
1845
        $user = $this->createUserVersion1();
1846
1847
        // Load the existing "Administrator" role
1848
        $role = $roleService->loadRoleByIdentifier('Administrator');
1849
1850
        // Assign the "Administrator" role to the newly created user
1851
        $roleService->assignRoleToUser($role, $user);
1852
1853
        // The assignments array will contain the new role<->user assignment
1854
        $roleAssignments = $roleService->getRoleAssignments($role);
1855
        /* END: Use Case */
1856
1857
        // Administrator + Example User
1858
        $this->assertEquals(2, count($roleAssignments));
1859
    }
1860
1861
    /**
1862
     * Test for the assignRoleToUser() method.
1863
     *
1864
     * @see \eZ\Publish\API\Repository\RoleService::assignRoleToUser($role, $user, $roleLimitation)
1865
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUser
1866
     */
1867 View Code Duplication
    public function testAssignRoleToUserWithRoleLimitation()
1868
    {
1869
        $repository = $this->getRepository();
1870
        $roleService = $repository->getRoleService();
1871
1872
        /* BEGIN: Use Case */
1873
        $user = $this->createUserVersion1();
1874
1875
        // Load the existing "Anonymous" role
1876
        $role = $roleService->loadRoleByIdentifier('Anonymous');
1877
1878
        // Assign the "Anonymous" role to the newly created user
1879
        $roleService->assignRoleToUser(
1880
            $role,
1881
            $user,
1882
            new SubtreeLimitation(
1883
                array(
1884
                    'limitationValues' => array('/1/43/'),
1885
                )
1886
            )
1887
        );
1888
1889
        // The assignments array will contain the new role<->user assignment
1890
        $roleAssignments = $roleService->getRoleAssignments($role);
1891
        /* END: Use Case */
1892
1893
        // Members + Partners + Anonymous + Example User
1894
        $this->assertEquals(4, count($roleAssignments));
1895
1896
        // Get the role limitation
1897
        $roleLimitation = null;
1898
        foreach ($roleAssignments as $roleAssignment) {
1899
            $roleLimitation = $roleAssignment->getRoleLimitation();
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $roleLimitation is correct as $roleAssignment->getRoleLimitation() (which targets eZ\Publish\API\Repositor...nt::getRoleLimitation()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
1900
            if ($roleLimitation) {
1901
                $this->assertInstanceOf(
1902
                    '\\eZ\\Publish\\API\\Repository\\Values\\User\\UserRoleAssignment',
1903
                    $roleAssignment
1904
                );
1905
                break;
1906
            }
1907
        }
1908
1909
        $this->assertEquals(
1910
            new SubtreeLimitation(
1911
                array(
1912
                    'limitationValues' => array('/1/43/'),
1913
                )
1914
            ),
1915
            $roleLimitation
1916
        );
1917
1918
        // Test again to see values being merged
1919
        $roleService->assignRoleToUser(
1920
            $role,
1921
            $user,
1922
            new SubtreeLimitation(
1923
                array(
1924
                    'limitationValues' => array('/1/43/', '/1/2/'),
1925
                )
1926
            )
1927
        );
1928
1929
        // The assignments array will contain the new role<->user assignment
1930
        $roleAssignments = $roleService->getRoleAssignments($role);
1931
1932
        // Members + Partners + Anonymous + Example User
1933
        $this->assertEquals(5, count($roleAssignments));
1934
1935
        // Get the role limitation
1936
        $roleLimitations = [];
1937
        foreach ($roleAssignments as $roleAssignment) {
1938
            $roleLimitation = $roleAssignment->getRoleLimitation();
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $roleLimitation is correct as $roleAssignment->getRoleLimitation() (which targets eZ\Publish\API\Repositor...nt::getRoleLimitation()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
1939
            if ($roleLimitation) {
1940
                $this->assertInstanceOf(
1941
                    '\\eZ\\Publish\\API\\Repository\\Values\\User\\UserRoleAssignment',
1942
                    $roleAssignment
1943
                );
1944
                $roleLimitations[] = $roleLimitation;
1945
            }
1946
        }
1947
        array_multisort($roleLimitations);
1948
1949
        $this->assertEquals(
1950
            [
1951
                new SubtreeLimitation(
1952
                    array(
1953
                        'limitationValues' => array('/1/2/'),
1954
                    )
1955
                ),
1956
                new SubtreeLimitation(
1957
                    array(
1958
                        'limitationValues' => array('/1/43/'),
1959
                    )
1960
                ),
1961
            ],
1962
            $roleLimitations
1963
        );
1964
    }
1965
1966
    /**
1967
     * Test for the assignRoleToUser() method.
1968
     *
1969
     * @see \eZ\Publish\API\Repository\RoleService::assignRoleToUser($role, $user, $roleLimitation)
1970
     * @expectedException \eZ\Publish\API\Repository\Exceptions\LimitationValidationException
1971
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUser
1972
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleByIdentifier
1973
     */
1974
    public function testAssignRoleToUserWithRoleLimitationThrowsLimitationValidationException()
1975
    {
1976
        $repository = $this->getRepository();
1977
1978
        /* BEGIN: Use Case */
1979
        $roleService = $repository->getRoleService();
1980
1981
        // Load the existing "Anonymous" role
1982
        $role = $roleService->loadRoleByIdentifier('Anonymous');
1983
1984
        // Get current user
1985
        $currentUser = $repository->getCurrentUser();
0 ignored issues
show
Deprecated Code introduced by
The method eZ\Publish\API\Repositor...itory::getCurrentUser() has been deprecated with message: since 6.6, to be removed. Use PermissionResolver::getCurrentUserReference() instead. Get current user. Loads the full user object if not already loaded, if you only need to know user id use {@see getCurrentUserReference()}

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
1986
1987
        // Assign the "Anonymous" role to the current user
1988
        // This call will fail with an LimitationValidationException, because subtree "/lorem/ipsum/42/"
1989
        // does not exists
1990
        $roleService->assignRoleToUser(
1991
            $role,
1992
            $currentUser,
1993
            new SubtreeLimitation(
1994
                array(
1995
                    'limitationValues' => array('/lorem/ipsum/42/'),
1996
                )
1997
            )
1998
        );
1999
        /* END: Use Case */
2000
    }
2001
2002
    /**
2003
     * Test for the assignRoleToUser() method.
2004
     *
2005
     * Makes sure assigning role several times throws.
2006
     *
2007
     * @see \eZ\Publish\API\Repository\RoleService::assignRoleToUser($role, $user, $roleLimitation)
2008
     * @expectedException \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException
2009
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUser
2010
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleByIdentifier
2011
     */
2012 View Code Duplication
    public function testAssignRoleToUserThrowsInvalidArgumentException()
2013
    {
2014
        $repository = $this->getRepository();
2015
2016
        /* BEGIN: Use Case */
2017
        $roleService = $repository->getRoleService();
2018
2019
        // Load the existing "Anonymous" role
2020
        $role = $roleService->loadRoleByIdentifier('Anonymous');
2021
2022
        // Get current user
2023
        $currentUser = $repository->getCurrentUser();
0 ignored issues
show
Deprecated Code introduced by
The method eZ\Publish\API\Repositor...itory::getCurrentUser() has been deprecated with message: since 6.6, to be removed. Use PermissionResolver::getCurrentUserReference() instead. Get current user. Loads the full user object if not already loaded, if you only need to know user id use {@see getCurrentUserReference()}

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
2024
2025
        // Assign the "Anonymous" role to the current user
2026
        try {
2027
            $roleService->assignRoleToUser(
2028
                $role,
2029
                $currentUser
2030
            );
2031
        } catch (Exception $e) {
2032
            $this->fail('Got exception at first valid attempt to assign role');
2033
        }
2034
2035
        // Re-Assign the "Anonymous" role to the current user
2036
        // This call will fail with an InvalidArgumentException, because limitation is already assigned
2037
        $roleService->assignRoleToUser(
2038
            $role,
2039
            $currentUser
2040
        );
2041
        /* END: Use Case */
2042
    }
2043
2044
    /**
2045
     * Test for the assignRoleToUser() method.
2046
     *
2047
     * Makes sure assigning role several times with same limitations throws.
2048
     *
2049
     * @see \eZ\Publish\API\Repository\RoleService::assignRoleToUser($role, $user, $roleLimitation)
2050
     * @expectedException \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException
2051
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUser
2052
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleByIdentifier
2053
     */
2054
    public function testAssignRoleToUserWithRoleLimitationThrowsInvalidArgumentException()
2055
    {
2056
        $repository = $this->getRepository();
2057
2058
        /* BEGIN: Use Case */
2059
        $roleService = $repository->getRoleService();
2060
2061
        // Load the existing "Anonymous" role
2062
        $role = $roleService->loadRoleByIdentifier('Anonymous');
2063
2064
        // Get current user
2065
        $currentUser = $repository->getCurrentUser();
0 ignored issues
show
Deprecated Code introduced by
The method eZ\Publish\API\Repositor...itory::getCurrentUser() has been deprecated with message: since 6.6, to be removed. Use PermissionResolver::getCurrentUserReference() instead. Get current user. Loads the full user object if not already loaded, if you only need to know user id use {@see getCurrentUserReference()}

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
2066
2067
        // Assign the "Anonymous" role to the current user
2068
        try {
2069
            $roleService->assignRoleToUser(
2070
                $role,
2071
                $currentUser,
2072
                new SubtreeLimitation(
2073
                    array(
2074
                        'limitationValues' => array('/1/43/', '/1/2/'),
2075
                    )
2076
                )
2077
            );
2078
        } catch (Exception $e) {
2079
            $this->fail('Got exception at first valid attempt to assign role');
2080
        }
2081
2082
        // Re-Assign the "Anonymous" role to the current user
2083
        // This call will fail with an InvalidArgumentException, because limitation is already assigned
2084
        $roleService->assignRoleToUser(
2085
            $role,
2086
            $currentUser,
2087
            new SubtreeLimitation(
2088
                array(
2089
                    'limitationValues' => array('/1/43/'),
2090
                )
2091
            )
2092
        );
2093
        /* END: Use Case */
2094
    }
2095
2096
    /**
2097
     * Test for the unassignRoleFromUser() method.
2098
     *
2099
     * @see \eZ\Publish\API\Repository\RoleService::unassignRoleFromUser()
2100
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUser
2101
     */
2102 View Code Duplication
    public function testUnassignRoleFromUser()
2103
    {
2104
        $repository = $this->getRepository();
2105
        $roleService = $repository->getRoleService();
2106
2107
        /* BEGIN: Use Case */
2108
        $user = $this->createUserVersion1();
2109
2110
        // Load the existing "Member" role
2111
        $role = $roleService->loadRoleByIdentifier('Member');
2112
2113
        // Assign the "Member" role to the newly created user
2114
        $roleService->assignRoleToUser($role, $user);
2115
2116
        // Unassign user from role
2117
        $roleService->unassignRoleFromUser($role, $user);
0 ignored issues
show
Deprecated Code introduced by
The method eZ\Publish\API\Repositor...:unassignRoleFromUser() has been deprecated with message: since 6.0, use {@see removeRoleAssignment} instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
2118
2119
        // The assignments array will not contain the new role<->user assignment
2120
        $roleAssignments = $roleService->getRoleAssignments($role);
2121
        /* END: Use Case */
2122
2123
        // Members + Editors + Partners
2124
        $this->assertEquals(3, count($roleAssignments));
2125
    }
2126
2127
    /**
2128
     * Test for the unassignRoleFromUser() method.
2129
     *
2130
     * @see \eZ\Publish\API\Repository\RoleService::unassignRoleFromUser()
2131
     * @expectedException \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException
2132
     */
2133 View Code Duplication
    public function testUnassignRoleFromUserThrowsInvalidArgumentException()
2134
    {
2135
        $repository = $this->getRepository();
2136
        $roleService = $repository->getRoleService();
2137
2138
        /* BEGIN: Use Case */
2139
        $user = $this->createUserVersion1();
2140
2141
        // Load the existing "Member" role
2142
        $role = $roleService->loadRoleByIdentifier('Member');
2143
2144
        // This call will fail with a "InvalidArgumentException", because the
2145
        // user does not have the "Member" role.
2146
        $roleService->unassignRoleFromUser($role, $user);
0 ignored issues
show
Deprecated Code introduced by
The method eZ\Publish\API\Repositor...:unassignRoleFromUser() has been deprecated with message: since 6.0, use {@see removeRoleAssignment} instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
2147
        /* END: Use Case */
2148
    }
2149
2150
    /**
2151
     * Test for the getRoleAssignmentsForUser() method.
2152
     *
2153
     * @see \eZ\Publish\API\Repository\RoleService::getRoleAssignmentsForUser()
2154
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUser
2155
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRoleWithAddPolicy
2156
     */
2157 View Code Duplication
    public function testGetRoleAssignmentsForUserDirect()
2158
    {
2159
        $repository = $this->getRepository();
2160
        $roleService = $repository->getRoleService();
2161
2162
        /* BEGIN: Use Case */
2163
        $user = $this->createUserVersion1();
2164
2165
        // Instantiate a role create and add some policies
2166
        $roleCreate = $roleService->newRoleCreateStruct('Example Role');
2167
2168
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
2169
        // $roleCreate->mainLanguageCode = 'eng-US';
2170
2171
        $roleCreate->addPolicy(
2172
            $roleService->newPolicyCreateStruct('user', 'login')
2173
        );
2174
        $roleCreate->addPolicy(
2175
            $roleService->newPolicyCreateStruct('content', 'read')
2176
        );
2177
        $roleCreate->addPolicy(
2178
            $roleService->newPolicyCreateStruct('content', 'edit')
2179
        );
2180
2181
        // Create the new role instance
2182
        $roleDraft = $roleService->createRole($roleCreate);
2183
        $roleService->publishRoleDraft($roleDraft);
2184
        $role = $roleService->loadRole($roleDraft->id);
2185
2186
        // Assign role to new user
2187
        $roleService->assignRoleToUser($role, $user);
2188
2189
        // Load the currently assigned role
2190
        $roleAssignments = $roleService->getRoleAssignmentsForUser($user);
2191
        /* END: Use Case */
2192
2193
        $this->assertEquals(1, count($roleAssignments));
2194
        $this->assertInstanceOf(
2195
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\UserRoleAssignment',
2196
            reset($roleAssignments)
2197
        );
2198
    }
2199
2200
    /**
2201
     * Test for the getRoleAssignmentsForUser() method.
2202
     *
2203
     * @see \eZ\Publish\API\Repository\RoleService::getRoleAssignmentsForUser()
2204
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUser
2205
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRoleWithAddPolicy
2206
     */
2207
    public function testGetRoleAssignmentsForUserEmpty()
2208
    {
2209
        $repository = $this->getRepository();
2210
        $roleService = $repository->getRoleService();
2211
2212
        /* BEGIN: Use Case */
2213
        $adminUser = $repository->getCurrentUser();
0 ignored issues
show
Deprecated Code introduced by
The method eZ\Publish\API\Repositor...itory::getCurrentUser() has been deprecated with message: since 6.6, to be removed. Use PermissionResolver::getCurrentUserReference() instead. Get current user. Loads the full user object if not already loaded, if you only need to know user id use {@see getCurrentUserReference()}

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
2214
2215
        // Load the currently assigned role
2216
        $roleAssignments = $roleService->getRoleAssignmentsForUser($adminUser);
2217
        /* END: Use Case */
2218
2219
        $this->assertEquals(0, count($roleAssignments));
2220
    }
2221
2222
    /**
2223
     * Test for the getRoleAssignmentsForUser() method.
2224
     *
2225
     * @see \eZ\Publish\API\Repository\RoleService::getRoleAssignmentsForUser()
2226
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUser
2227
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRoleWithAddPolicy
2228
     */
2229
    public function testGetRoleAssignmentsForUserInherited()
2230
    {
2231
        $repository = $this->getRepository();
2232
        $roleService = $repository->getRoleService();
2233
2234
        /* BEGIN: Use Case */
2235
        $adminUser = $repository->getCurrentUser();
0 ignored issues
show
Deprecated Code introduced by
The method eZ\Publish\API\Repositor...itory::getCurrentUser() has been deprecated with message: since 6.6, to be removed. Use PermissionResolver::getCurrentUserReference() instead. Get current user. Loads the full user object if not already loaded, if you only need to know user id use {@see getCurrentUserReference()}

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
2236
2237
        // Load the currently assigned role + inherited role assignments
2238
        $roleAssignments = $roleService->getRoleAssignmentsForUser($adminUser, true);
2239
        /* END: Use Case */
2240
2241
        $this->assertEquals(1, count($roleAssignments));
2242
        $this->assertInstanceOf(
2243
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\UserGroupRoleAssignment',
2244
            reset($roleAssignments)
2245
        );
2246
    }
2247
2248
    /**
2249
     * Test for the assignRoleToUserGroup() method.
2250
     *
2251
     * @see \eZ\Publish\API\Repository\RoleService::assignRoleToUserGroup()
2252
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testGetRoleAssignments
2253
     */
2254 View Code Duplication
    public function testAssignRoleToUserGroup()
2255
    {
2256
        $repository = $this->getRepository();
2257
        $roleService = $repository->getRoleService();
2258
2259
        /* BEGIN: Use Case */
2260
        $userGroup = $this->createUserGroupVersion1();
2261
2262
        // Load the existing "Administrator" role
2263
        $role = $roleService->loadRoleByIdentifier('Administrator');
2264
2265
        // Assign the "Administrator" role to the newly created user group
2266
        $roleService->assignRoleToUserGroup($role, $userGroup);
2267
2268
        // The assignments array will contain the new role<->group assignment
2269
        $roleAssignments = $roleService->getRoleAssignments($role);
2270
        /* END: Use Case */
2271
2272
        // Administrator + Example Group
2273
        $this->assertEquals(2, count($roleAssignments));
2274
    }
2275
2276
    /**
2277
     * Test for the assignRoleToUserGroup() method.
2278
     *
2279
     * @see \eZ\Publish\API\Repository\RoleService::assignRoleToUserGroup($role, $userGroup, $roleLimitation)
2280
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUserGroup
2281
     */
2282 View Code Duplication
    public function testAssignRoleToUserGroupWithRoleLimitation()
2283
    {
2284
        $repository = $this->getRepository();
2285
        $roleService = $repository->getRoleService();
2286
2287
        /* BEGIN: Use Case */
2288
        $userGroup = $this->createUserGroupVersion1();
2289
2290
        // Load the existing "Anonymous" role
2291
        $role = $roleService->loadRoleByIdentifier('Anonymous');
2292
2293
        // Assign the "Anonymous" role to the newly created user group
2294
        $roleService->assignRoleToUserGroup(
2295
            $role,
2296
            $userGroup,
2297
            new SubtreeLimitation(
2298
                array(
2299
                    'limitationValues' => array('/1/43/'),
2300
                )
2301
            )
2302
        );
2303
2304
        // The assignments array will contain the new role<->group assignment
2305
        $roleAssignments = $roleService->getRoleAssignments($role);
2306
        /* END: Use Case */
2307
2308
        // Members + Partners + Anonymous + Example Group
2309
        $this->assertEquals(4, count($roleAssignments));
2310
2311
        // Get the role limitation
2312
        $roleLimitation = null;
2313
        foreach ($roleAssignments as $roleAssignment) {
2314
            $roleLimitation = $roleAssignment->getRoleLimitation();
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $roleLimitation is correct as $roleAssignment->getRoleLimitation() (which targets eZ\Publish\API\Repositor...nt::getRoleLimitation()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
2315
            if ($roleLimitation) {
2316
                break;
2317
            }
2318
        }
2319
2320
        $this->assertEquals(
2321
            new SubtreeLimitation(
2322
                array(
2323
                    'limitationValues' => array('/1/43/'),
2324
                )
2325
            ),
2326
            $roleLimitation
2327
        );
2328
2329
        // Test again to see values being merged
2330
        $roleService->assignRoleToUserGroup(
2331
            $role,
2332
            $userGroup,
2333
            new SubtreeLimitation(
2334
                array(
2335
                    'limitationValues' => array('/1/43/', '/1/2/'),
2336
                )
2337
            )
2338
        );
2339
2340
        // The assignments array will contain the new role<->user assignment
2341
        $roleAssignments = $roleService->getRoleAssignments($role);
2342
2343
        // Members + Partners + Anonymous + Example User
2344
        $this->assertEquals(5, count($roleAssignments));
2345
2346
        // Get the role limitation
2347
        $roleLimitations = [];
2348
        foreach ($roleAssignments as $roleAssignment) {
2349
            $roleLimitation = $roleAssignment->getRoleLimitation();
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $roleLimitation is correct as $roleAssignment->getRoleLimitation() (which targets eZ\Publish\API\Repositor...nt::getRoleLimitation()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
2350
            if ($roleLimitation) {
2351
                $this->assertInstanceOf(
2352
                    '\\eZ\\Publish\\API\\Repository\\Values\\User\\UserGroupRoleAssignment',
2353
                    $roleAssignment
2354
                );
2355
                $roleLimitations[] = $roleLimitation;
2356
            }
2357
        }
2358
        array_multisort($roleLimitations);
2359
2360
        $this->assertEquals(
2361
            [
2362
                new SubtreeLimitation(
2363
                    array(
2364
                        'limitationValues' => array('/1/2/'),
2365
                    )
2366
                ),
2367
                new SubtreeLimitation(
2368
                    array(
2369
                        'limitationValues' => array('/1/43/'),
2370
                    )
2371
                ),
2372
            ],
2373
            $roleLimitations
2374
        );
2375
    }
2376
2377
    /**
2378
     * Test for the assignRoleToUserGroup() method.
2379
     *
2380
     * @see \eZ\Publish\API\Repository\RoleService::assignRoleToUserGroup($role, $userGroup, $roleLimitation)
2381
     * @expectedException \eZ\Publish\API\Repository\Exceptions\LimitationValidationException
2382
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleByIdentifier
2383
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUserGroup
2384
     */
2385
    public function testAssignRoleToUserGroupWithRoleLimitationThrowsLimitationValidationException()
2386
    {
2387
        $repository = $this->getRepository();
2388
2389
        $mainGroupId = $this->generateId('group', 4);
2390
        /* BEGIN: Use Case */
2391
        // $mainGroupId is the ID of the main "Users" group
2392
2393
        $userService = $repository->getUserService();
2394
        $roleService = $repository->getRoleService();
2395
2396
        $userGroup = $userService->loadUserGroup($mainGroupId);
2397
2398
        // Load the existing "Anonymous" role
2399
        $role = $roleService->loadRoleByIdentifier('Anonymous');
2400
2401
        // Assign the "Anonymous" role to the newly created user group
2402
        // This call will fail with an LimitationValidationException, because subtree "/lorem/ipsum/42/"
2403
        // does not exists
2404
        $roleService->assignRoleToUserGroup(
2405
            $role,
2406
            $userGroup,
2407
            new SubtreeLimitation(
2408
                array(
2409
                    'limitationValues' => array('/lorem/ipsum/42/'),
2410
                )
2411
            )
2412
        );
2413
        /* END: Use Case */
2414
    }
2415
2416
    /**
2417
     * Test for the assignRoleToUserGroup() method.
2418
     *
2419
     * Makes sure assigning role several times throws.
2420
     *
2421
     * @see \eZ\Publish\API\Repository\RoleService::assignRoleToUserGroup($role, $userGroup, $roleLimitation)
2422
     * @expectedException \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException
2423
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleByIdentifier
2424
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUserGroup
2425
     */
2426
    public function testAssignRoleToUserGroupThrowsInvalidArgumentException()
2427
    {
2428
        $repository = $this->getRepository();
2429
2430
        $mainGroupId = $this->generateId('group', 4);
2431
        /* BEGIN: Use Case */
2432
        // $mainGroupId is the ID of the main "Users" group
2433
2434
        $userService = $repository->getUserService();
2435
        $roleService = $repository->getRoleService();
2436
2437
        $userGroup = $userService->loadUserGroup($mainGroupId);
2438
2439
        // Load the existing "Anonymous" role
2440
        $role = $roleService->loadRoleByIdentifier('Anonymous');
2441
2442
        // Assign the "Anonymous" role to the newly created user group
2443
        try {
2444
            $roleService->assignRoleToUserGroup(
2445
                $role,
2446
                $userGroup
2447
            );
2448
        } catch (Exception $e) {
2449
            $this->fail('Got exception at first valid attempt to assign role');
2450
        }
2451
2452
        // Re-Assign the "Anonymous" role to the newly created user group
2453
        // This call will fail with an InvalidArgumentException, because role is already assigned
2454
        $roleService->assignRoleToUserGroup(
2455
            $role,
2456
            $userGroup
2457
        );
2458
        /* END: Use Case */
2459
    }
2460
2461
    /**
2462
     * Test for the assignRoleToUserGroup() method.
2463
     *
2464
     * Makes sure assigning role several times with same limitations throws.
2465
     *
2466
     * @see \eZ\Publish\API\Repository\RoleService::assignRoleToUserGroup($role, $userGroup, $roleLimitation)
2467
     * @expectedException \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException
2468
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleByIdentifier
2469
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUserGroup
2470
     */
2471
    public function testAssignRoleToUserGroupWithRoleLimitationThrowsInvalidArgumentException()
2472
    {
2473
        $repository = $this->getRepository();
2474
2475
        $mainGroupId = $this->generateId('group', 4);
2476
        /* BEGIN: Use Case */
2477
        // $mainGroupId is the ID of the main "Users" group
2478
2479
        $userService = $repository->getUserService();
2480
        $roleService = $repository->getRoleService();
2481
2482
        $userGroup = $userService->loadUserGroup($mainGroupId);
2483
2484
        // Load the existing "Anonymous" role
2485
        $role = $roleService->loadRoleByIdentifier('Anonymous');
2486
2487
        // Assign the "Anonymous" role to the newly created user group
2488
        try {
2489
            $roleService->assignRoleToUserGroup(
2490
                $role,
2491
                $userGroup,
2492
                new SubtreeLimitation(
2493
                    array(
2494
                        'limitationValues' => array('/1/43/', '/1/2/'),
2495
                    )
2496
                )
2497
            );
2498
        } catch (Exception $e) {
2499
            $this->fail('Got exception at first valid attempt to assign role');
2500
        }
2501
2502
        // Re-Assign the "Anonymous" role to the newly created user group
2503
        // This call will fail with an InvalidArgumentException, because limitation is already assigned
2504
        $roleService->assignRoleToUserGroup(
2505
            $role,
2506
            $userGroup,
2507
            new SubtreeLimitation(
2508
                array(
2509
                    'limitationValues' => array('/1/43/'),
2510
                )
2511
            )
2512
        );
2513
        /* END: Use Case */
2514
    }
2515
2516
    /**
2517
     * Test for the unassignRoleFromUserGroup() method.
2518
     *
2519
     * @see \eZ\Publish\API\Repository\RoleService::unassignRoleFromUserGroup()
2520
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUserGroup
2521
     */
2522 View Code Duplication
    public function testUnassignRoleFromUserGroup()
2523
    {
2524
        $repository = $this->getRepository();
2525
        $roleService = $repository->getRoleService();
2526
2527
        /* BEGIN: Use Case */
2528
        $userGroup = $this->createUserGroupVersion1();
2529
2530
        // Load the existing "Member" role
2531
        $role = $roleService->loadRoleByIdentifier('Member');
2532
2533
        // Assign the "Member" role to the newly created user group
2534
        $roleService->assignRoleToUserGroup($role, $userGroup);
2535
2536
        // Unassign group from role
2537
        $roleService->unassignRoleFromUserGroup($role, $userGroup);
0 ignored issues
show
Deprecated Code introduced by
The method eZ\Publish\API\Repositor...signRoleFromUserGroup() has been deprecated with message: since 6.0, use {@see removeRoleAssignment} instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
2538
2539
        // The assignments array will not contain the new role<->group assignment
2540
        $roleAssignments = $roleService->getRoleAssignments($role);
2541
        /* END: Use Case */
2542
2543
        // Members + Editors + Partners
2544
        $this->assertEquals(3, count($roleAssignments));
2545
    }
2546
2547
    /**
2548
     * Test for the unassignRoleFromUserGroup() method.
2549
     *
2550
     * @see \eZ\Publish\API\Repository\RoleService::unassignRoleFromUserGroup()
2551
     * @expectedException \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException
2552
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testUnassignRoleFromUserGroup
2553
     */
2554 View Code Duplication
    public function testUnassignRoleFromUserGroupThrowsInvalidArgumentException()
2555
    {
2556
        $repository = $this->getRepository();
2557
        $roleService = $repository->getRoleService();
2558
2559
        /* BEGIN: Use Case */
2560
        $userGroup = $this->createUserGroupVersion1();
2561
2562
        // Load the existing "Member" role
2563
        $role = $roleService->loadRoleByIdentifier('Member');
2564
2565
        // This call will fail with a "InvalidArgumentException", because the
2566
        // user group does not have the "Member" role.
2567
        $roleService->unassignRoleFromUserGroup($role, $userGroup);
0 ignored issues
show
Deprecated Code introduced by
The method eZ\Publish\API\Repositor...signRoleFromUserGroup() has been deprecated with message: since 6.0, use {@see removeRoleAssignment} instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
2568
        /* END: Use Case */
2569
    }
2570
2571
    /**
2572
     * Test unassigning role by assignment.
2573
     *
2574
     * @covers \eZ\Publish\API\Repository\RoleService::removeRoleAssignment
2575
     */
2576
    public function testUnassignRoleByAssignment()
2577
    {
2578
        $repository = $this->getRepository();
2579
        $roleService = $repository->getRoleService();
2580
2581
        $role = $roleService->loadRole(2);
2582
        $user = $repository->getUserService()->loadUser(14);
2583
2584
        $originalAssignmentCount = count($roleService->getRoleAssignmentsForUser($user));
2585
2586
        $roleService->assignRoleToUser($role, $user);
2587
        $newAssignmentCount = count($roleService->getRoleAssignmentsForUser($user));
2588
        self::assertEquals($originalAssignmentCount + 1, $newAssignmentCount);
2589
2590
        $assignments = $roleService->getRoleAssignmentsForUser($user);
2591
        $roleService->removeRoleAssignment($assignments[0]);
2592
        $finalAssignmentCount = count($roleService->getRoleAssignmentsForUser($user));
2593
        self::assertEquals($newAssignmentCount - 1, $finalAssignmentCount);
2594
    }
2595
2596
    /**
2597
     * Test unassigning role by assignment.
2598
     *
2599
     * But on current admin user so he lacks access to read roles.
2600
     *
2601
     * @covers \eZ\Publish\API\Repository\RoleService::removeRoleAssignment
2602
     * @expectedException \eZ\Publish\API\Repository\Exceptions\UnauthorizedException
2603
     */
2604 View Code Duplication
    public function testUnassignRoleByAssignmentThrowsUnauthorizedException()
2605
    {
2606
        $repository = $this->getRepository();
2607
        $roleService = $repository->getRoleService();
2608
2609
        try {
2610
            $adminUserGroup = $repository->getUserService()->loadUserGroup(12);
2611
            $assignments = $roleService->getRoleAssignmentsForUserGroup($adminUserGroup);
2612
            $roleService->removeRoleAssignment($assignments[0]);
2613
        } catch (Exception $e) {
2614
            self::fail(
2615
                'Unexpected exception: ' . $e->getMessage() . " \n[" . $e->getFile() . ' (' . $e->getLine() . ')]'
2616
            );
2617
        }
2618
2619
        $roleService->removeRoleAssignment($assignments[0]);
0 ignored issues
show
Bug introduced by
The variable $assignments 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...
2620
    }
2621
2622
    /**
2623
     * Test unassigning role by non-existing assignment.
2624
     *
2625
     * @covers \eZ\Publish\API\Repository\RoleService::removeRoleAssignment
2626
     * @expectedException \eZ\Publish\API\Repository\Exceptions\NotFoundException
2627
     */
2628 View Code Duplication
    public function testUnassignRoleByAssignmentThrowsNotFoundException()
2629
    {
2630
        $repository = $this->getRepository();
2631
        $roleService = $repository->getRoleService();
2632
2633
        try {
2634
            $editorsUserGroup = $repository->getUserService()->loadUserGroup(13);
2635
            $assignments = $roleService->getRoleAssignmentsForUserGroup($editorsUserGroup);
2636
            $roleService->removeRoleAssignment($assignments[0]);
2637
        } catch (Exception $e) {
2638
            self::fail(
2639
                'Unexpected exception: ' . $e->getMessage() . " \n[" . $e->getFile() . ' (' . $e->getLine() . ')]'
2640
            );
2641
        }
2642
2643
        $roleService->removeRoleAssignment($assignments[0]);
0 ignored issues
show
Bug introduced by
The variable $assignments 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...
2644
    }
2645
2646
    /**
2647
     * Test for the getRoleAssignmentsForUserGroup() method.
2648
     *
2649
     * @see \eZ\Publish\API\Repository\RoleService::getRoleAssignmentsForUserGroup()
2650
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUserGroup
2651
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRoleWithAddPolicy
2652
     */
2653 View Code Duplication
    public function testGetRoleAssignmentsForUserGroup()
2654
    {
2655
        $repository = $this->getRepository();
2656
        $roleService = $repository->getRoleService();
2657
2658
        /* BEGIN: Use Case */
2659
        $userGroup = $this->createUserGroupVersion1();
2660
2661
        // Instantiate a role create and add some policies
2662
        $roleCreate = $roleService->newRoleCreateStruct('Example Role');
2663
2664
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
2665
        // $roleCreate->mainLanguageCode = 'eng-US';
2666
2667
        $roleCreate->addPolicy(
2668
            $roleService->newPolicyCreateStruct('user', 'login')
2669
        );
2670
        $roleCreate->addPolicy(
2671
            $roleService->newPolicyCreateStruct('content', 'read')
2672
        );
2673
        $roleCreate->addPolicy(
2674
            $roleService->newPolicyCreateStruct('content', 'edit')
2675
        );
2676
2677
        // Create the new role instance
2678
        $roleDraft = $roleService->createRole($roleCreate);
2679
        $roleService->publishRoleDraft($roleDraft);
2680
        $role = $roleService->loadRole($roleDraft->id);
2681
2682
        // Assign role to new user group
2683
        $roleService->assignRoleToUserGroup($role, $userGroup);
2684
2685
        // Load the currently assigned role
2686
        $roleAssignments = $roleService->getRoleAssignmentsForUserGroup($userGroup);
2687
        /* END: Use Case */
2688
2689
        $this->assertEquals(1, count($roleAssignments));
2690
        $this->assertInstanceOf(
2691
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\UserGroupRoleAssignment',
2692
            reset($roleAssignments)
2693
        );
2694
    }
2695
2696
    /**
2697
     * Test for the loadPoliciesByUserId() method.
2698
     *
2699
     * @see \eZ\Publish\API\Repository\RoleService::loadPoliciesByUserId()
2700
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUser
2701
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUserGroup
2702
     */
2703
    public function testLoadPoliciesByUserId()
2704
    {
2705
        $repository = $this->getRepository();
2706
2707
        $anonUserId = $this->generateId('user', 10);
2708
        /* BEGIN: Use Case */
2709
        // $anonUserId is the ID of the "Anonymous" user.
2710
2711
        $userService = $repository->getUserService();
2712
        $roleService = $repository->getRoleService();
2713
2714
        // Load "Anonymous" user
2715
        $user = $userService->loadUser($anonUserId);
2716
2717
        // Instantiate a role create and add some policies
2718
        $roleCreate = $roleService->newRoleCreateStruct('User Role');
2719
2720
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
2721
        // $roleCreate->mainLanguageCode = 'eng-US';
2722
2723
        $roleCreate->addPolicy(
2724
            $roleService->newPolicyCreateStruct('notification', 'use')
2725
        );
2726
        $roleCreate->addPolicy(
2727
            $roleService->newPolicyCreateStruct('user', 'password')
2728
        );
2729
        $roleCreate->addPolicy(
2730
            $roleService->newPolicyCreateStruct('user', 'selfedit')
2731
        );
2732
2733
        // Create the new role instance
2734
        $roleDraft = $roleService->createRole($roleCreate);
2735
        $roleService->publishRoleDraft($roleDraft);
2736
        $role = $roleService->loadRole($roleDraft->id);
2737
2738
        // Assign role to anon user
2739
        $roleService->assignRoleToUser($role, $user);
2740
2741
        // Load the currently assigned role
2742
        $policies = array();
2743
        foreach ($roleService->loadPoliciesByUserId($user->id) as $policy) {
2744
            $policies[] = array($policy->roleId, $policy->module, $policy->function);
2745
        }
2746
        /* END: Use Case */
2747
        array_multisort($policies);
2748
2749
        $this->assertEquals(
2750
            array(
2751
                array(1, 'content', 'pdf'),
2752
                array(1, 'content', 'read'),
2753
                array(1, 'content', 'read'),
2754
                array(1, 'rss', 'feed'),
2755
                array(1, 'user', 'login'),
2756
                array(1, 'user', 'login'),
2757
                array(1, 'user', 'login'),
2758
                array(1, 'user', 'login'),
2759
                array($role->id, 'notification', 'use'),
2760
                array($role->id, 'user', 'password'),
2761
                array($role->id, 'user', 'selfedit'),
2762
            ),
2763
            $policies
2764
        );
2765
    }
2766
2767
    /**
2768
     * Test for the loadPoliciesByUserId() method.
2769
     *
2770
     * @see \eZ\Publish\API\Repository\RoleService::loadPoliciesByUserId()
2771
     * @expectedException \eZ\Publish\API\Repository\Exceptions\NotFoundException
2772
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadPoliciesByUserId
2773
     */
2774
    public function testLoadPoliciesByUserIdThrowsNotFoundException()
2775
    {
2776
        $repository = $this->getRepository();
2777
2778
        $nonExistingUserId = $this->generateId('user', self::DB_INT_MAX);
2779
        /* BEGIN: Use Case */
2780
        $roleService = $repository->getRoleService();
2781
2782
        // This call will fail with a "NotFoundException", because hopefully no
2783
        // user with an ID equal to self::DB_INT_MAX exists.
2784
        $roleService->loadPoliciesByUserId($nonExistingUserId);
2785
        /* END: Use Case */
2786
    }
2787
2788
    /**
2789
     * Test for the publishRoleDraft() method.
2790
     *
2791
     * @see \eZ\Publish\API\Repository\RoleService::publishRoleDraft()
2792
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRoleDraft
2793
     */
2794 View Code Duplication
    public function testPublishRoleDraft()
2795
    {
2796
        $repository = $this->getRepository();
2797
2798
        /* BEGIN: Use Case */
2799
        $roleService = $repository->getRoleService();
2800
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
2801
2802
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
2803
        // $roleCreate->mainLanguageCode = 'eng-US';
2804
2805
        $roleDraft = $roleService->createRole($roleCreate);
2806
2807
        $roleDraft = $roleService->addPolicyByRoleDraft(
2808
            $roleDraft,
2809
            $roleService->newPolicyCreateStruct('content', 'delete')
2810
        );
2811
        $roleDraft = $roleService->addPolicyByRoleDraft(
2812
            $roleDraft,
2813
            $roleService->newPolicyCreateStruct('content', 'create')
2814
        );
2815
2816
        $roleService->publishRoleDraft($roleDraft);
2817
        /* END: Use Case */
2818
2819
        $this->assertInstanceOf(
2820
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\Role',
2821
            $roleService->loadRoleByIdentifier($roleCreate->identifier)
2822
        );
2823
    }
2824
2825
    /**
2826
     * Test for the publishRoleDraft() method.
2827
     *
2828
     * @see \eZ\Publish\API\Repository\RoleService::publishRoleDraft()
2829
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRoleDraft
2830
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicyByRoleDraft
2831
     */
2832 View Code Duplication
    public function testPublishRoleDraftAddPolicies()
2833
    {
2834
        $repository = $this->getRepository();
2835
2836
        /* BEGIN: Use Case */
2837
        $roleService = $repository->getRoleService();
2838
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
2839
2840
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
2841
        // $roleCreate->mainLanguageCode = 'eng-US';
2842
2843
        $roleDraft = $roleService->createRole($roleCreate);
2844
2845
        $roleDraft = $roleService->addPolicyByRoleDraft(
2846
            $roleDraft,
2847
            $roleService->newPolicyCreateStruct('content', 'delete')
2848
        );
2849
        $roleDraft = $roleService->addPolicyByRoleDraft(
2850
            $roleDraft,
2851
            $roleService->newPolicyCreateStruct('content', 'create')
2852
        );
2853
2854
        $roleService->publishRoleDraft($roleDraft);
2855
        $role = $roleService->loadRoleByIdentifier($roleCreate->identifier);
2856
        /* END: Use Case */
2857
2858
        $actual = array();
2859
        foreach ($role->getPolicies() as $policy) {
2860
            $actual[] = array(
2861
                'module' => $policy->module,
2862
                'function' => $policy->function,
2863
            );
2864
        }
2865
        usort(
2866
            $actual,
2867
            function ($p1, $p2) {
2868
                return strcasecmp($p1['function'], $p2['function']);
2869
            }
2870
        );
2871
2872
        $this->assertEquals(
2873
            array(
2874
                array(
2875
                    'module' => 'content',
2876
                    'function' => 'create',
2877
                ),
2878
                array(
2879
                    'module' => 'content',
2880
                    'function' => 'delete',
2881
                ),
2882
            ),
2883
            $actual
2884
        );
2885
    }
2886
2887
    /**
2888
     * Create a user group fixture in a variable named <b>$userGroup</b>,.
2889
     *
2890
     * @return \eZ\Publish\API\Repository\Values\User\UserGroup
2891
     */
2892
    private function createUserGroupVersion1()
2893
    {
2894
        $repository = $this->getRepository();
2895
2896
        $mainGroupId = $this->generateId('group', 4);
2897
        /* BEGIN: Inline */
2898
        // $mainGroupId is the ID of the main "Users" group
2899
2900
        $roleService = $repository->getRoleService();
0 ignored issues
show
Unused Code introduced by
$roleService 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...
2901
        $userService = $repository->getUserService();
2902
2903
        // Load main group
2904
        $parentUserGroup = $userService->loadUserGroup($mainGroupId);
2905
2906
        // Instantiate a new create struct
2907
        $userGroupCreate = $userService->newUserGroupCreateStruct('eng-US');
2908
        $userGroupCreate->setField('name', 'Example Group');
2909
2910
        // Create the new user group
2911
        $userGroup = $userService->createUserGroup(
2912
            $userGroupCreate,
2913
            $parentUserGroup
2914
        );
2915
        /* END: Inline */
2916
2917
        return $userGroup;
2918
    }
2919
}
2920