Completed
Push — master ( b3dee4...afaada )
by
unknown
24:51
created

RoleServiceTest   F

Complexity

Total Complexity 135

Size/Duplication

Total Lines 3008
Duplicated Lines 30.75 %

Coupling/Cohesion

Components 1
Dependencies 21

Importance

Changes 0
Metric Value
dl 925
loc 3008
rs 0.8
c 0
b 0
f 0
wmc 135
lcom 1
cbo 21

81 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
C testCreateRoleWithMultiplePolicies() 24 85 11
A testCreateRoleDraft() 24 24 1
A testCreateRoleThrowsInvalidArgumentException() 0 17 1
A testCreateRoleDraftThrowsInvalidArgumentException() 22 22 1
A testCreateRoleThrowsLimitationValidationException() 32 32 1
A testCreateRoleInTransactionWithRollback() 0 29 2
A testCreateRoleDraftInTransactionWithRollback() 0 29 2
A testLoadRole() 0 22 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 testLoadRoles() 0 29 3
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 testDeleteRole() 20 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 testRemovePolicyByRoleDraft() 32 32 2
A testDeletePolicy() 0 35 2
A testAddPolicyWithRoleAssignment() 0 39 1
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
A testAssignRoleToUserGroupAffectsRoleAssignmentsForUser() 0 22 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

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;
12
use eZ\Publish\API\Repository\Values\User\Limitation\ContentTypeLimitation;
13
use eZ\Publish\API\Repository\Values\User\Limitation\LanguageLimitation;
14
use eZ\Publish\API\Repository\Values\User\Limitation\SubtreeLimitation;
15
use eZ\Publish\API\Repository\Values\User\Policy;
16
use eZ\Publish\API\Repository\Values\User\Role;
17
use eZ\Publish\API\Repository\Exceptions\NotFoundException;
18
use Exception;
19
20
/**
21
 * Test case for operations in the RoleService using in memory storage.
22
 *
23
 * The following IDs from the default eZ community edition database are used in
24
 * this test:
25
 *
26
 * <ul>
27
 *   <li>
28
 *     ContentType
29
 *     <ul>
30
 *       <li><strong>28</strong>: File</li>
31
 *       <li><strong>29</strong>: Flash</li>
32
 *       <li><strong>30</strong>: Image</li>
33
 *     </ul>
34
 *   </li>
35
 * <ul>
36
 *
37
 * @see eZ\Publish\API\Repository\RoleService
38
 * @group role
39
 */
40
class RoleServiceTest extends BaseTest
41
{
42
    /**
43
     * Test for the newRoleCreateStruct() method.
44
     *
45
     * @see \eZ\Publish\API\Repository\RoleService::newRoleCreateStruct()
46
     */
47
    public function testNewRoleCreateStruct()
48
    {
49
        $repository = $this->getRepository();
50
51
        $roleService = $repository->getRoleService();
52
        $roleCreate = $roleService->newRoleCreateStruct('roleName');
53
54
        $this->assertInstanceOf('\\eZ\\Publish\\API\\Repository\\Values\\User\\RoleCreateStruct', $roleCreate);
55
    }
56
57
    /**
58
     * Test for the newRoleCreateStruct() method.
59
     *
60
     * @see \eZ\Publish\API\Repository\RoleService::newRoleCreateStruct()
61
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewRoleCreateStruct
62
     */
63
    public function testNewRoleCreateStructSetsNamePropertyOnStruct()
64
    {
65
        $repository = $this->getRepository();
66
67
        /* BEGIN: Use Case */
68
69
        $roleService = $repository->getRoleService();
70
        $roleCreate = $roleService->newRoleCreateStruct('roleName');
71
72
        /* END: Use Case */
73
74
        $this->assertEquals('roleName', $roleCreate->identifier);
75
    }
76
77
    /**
78
     * Test for the createRole() method.
79
     *
80
     * @see \eZ\Publish\API\Repository\RoleService::createRole()
81
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewRoleCreateStruct
82
     */
83
    public function testCreateRole()
84
    {
85
        $repository = $this->getRepository();
86
87
        /* BEGIN: Use Case */
88
89
        $roleService = $repository->getRoleService();
90
        $roleCreate = $roleService->newRoleCreateStruct('roleName');
91
92
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
93
        // $roleCreate->mainLanguageCode = 'eng-US';
94
95
        $role = $roleService->createRole($roleCreate);
96
97
        /* END: Use Case */
98
99
        $this->assertInstanceOf(
100
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\RoleDraft',
101
            $role
102
        );
103
104
        return [
105
            'createStruct' => $roleCreate,
106
            'role' => $role,
107
        ];
108
    }
109
110
    /**
111
     * Test for the createRole() method.
112
     *
113
     * @see \eZ\Publish\API\Repository\RoleService::createRole()
114
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRole
115
     */
116
    public function testRoleCreateStructValues(array $data)
117
    {
118
        $createStruct = $data['createStruct'];
119
        $role = $data['role'];
120
121
        $this->assertEquals(
122
            [
123
                'identifier' => $createStruct->identifier,
124
                'policies' => $createStruct->policies,
125
            ],
126
            [
127
                'identifier' => $role->identifier,
128
                'policies' => $role->policies,
129
            ]
130
        );
131
        $this->assertNotNull($role->id);
132
133
        return $data;
134
    }
135
136
    /**
137
     * Test for the createRole() method.
138
     *
139
     * @see \eZ\Publish\API\Repository\RoleService::createRole()
140
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewRoleCreateStruct
141
     */
142
    public function testCreateRoleWithPolicy()
143
    {
144
        $repository = $this->getRepository();
145
146
        /* BEGIN: Use Case */
147
148
        $roleService = $repository->getRoleService();
149
        $roleCreate = $roleService->newRoleCreateStruct('roleName');
150
151
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
152
        // $roleCreate->mainLanguageCode = 'eng-US';
153
154
        // Create new subtree limitation
155
        $limitation = new SubtreeLimitation(
156
            array(
157
                'limitationValues' => array('/1/2/'),
158
            )
159
        );
160
161
        // Create policy create struct and add limitation to it
162
        $policyCreate = $roleService->newPolicyCreateStruct('content', 'read');
163
        $policyCreate->addLimitation($limitation);
164
165
        // Add policy create struct to role create struct
166
        $roleCreate->addPolicy($policyCreate);
167
168
        $role = $roleService->createRole($roleCreate);
169
170
        /* END: Use Case */
171
172
        $this->assertInstanceOf(
173
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\RoleDraft',
174
            $role
175
        );
176
177
        return [
178
            'createStruct' => $roleCreate,
179
            'role' => $role,
180
        ];
181
    }
182
183
    /**
184
     * Test for the createRole() method.
185
     *
186
     * @see \eZ\Publish\API\Repository\RoleService::createRole()
187
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRoleWithPolicy
188
     */
189
    public function testRoleCreateStructValuesWithPolicy(array $data)
190
    {
191
        $createStruct = $data['createStruct'];
192
        $role = $data['role'];
193
194
        $this->assertEquals(
195
            [
196
                'identifier' => $createStruct->identifier,
197
                'policy_module' => $createStruct->policies[0]->module,
198
                'policy_function' => $createStruct->policies[0]->function,
199
                'policy_limitation' => array_values($createStruct->policies[0]->limitations),
200
            ],
201
            [
202
                'identifier' => $role->identifier,
203
                'policy_module' => $role->policies[0]->module,
204
                'policy_function' => $role->policies[0]->function,
205
                'policy_limitation' => array_values($role->policies[0]->limitations),
206
            ]
207
        );
208
        $this->assertNotNull($role->id);
209
210
        return $data;
211
    }
212
213
    /**
214
     * Test creating a role with multiple policies.
215
     *
216
     * @covers \eZ\Publish\API\Repository\RoleService::createRole
217
     */
218
    public function testCreateRoleWithMultiplePolicies()
219
    {
220
        $repository = $this->getRepository();
221
        $roleService = $repository->getRoleService();
222
223
        $limitation1 = new Limitation\ContentTypeLimitation();
224
        $limitation1->limitationValues = ['1', '3', '13'];
225
226
        $limitation2 = new Limitation\SectionLimitation();
227
        $limitation2->limitationValues = ['2', '3'];
228
229
        $limitation3 = new Limitation\OwnerLimitation();
230
        $limitation3->limitationValues = ['1', '2'];
231
232
        $limitation4 = new Limitation\UserGroupLimitation();
233
        $limitation4->limitationValues = ['1'];
234
235
        $policyCreateStruct1 = $roleService->newPolicyCreateStruct('content', 'read');
236
        $policyCreateStruct1->addLimitation($limitation1);
237
        $policyCreateStruct1->addLimitation($limitation2);
238
239
        $policyCreateStruct2 = $roleService->newPolicyCreateStruct('content', 'edit');
240
        $policyCreateStruct2->addLimitation($limitation3);
241
        $policyCreateStruct2->addLimitation($limitation4);
242
243
        $roleCreateStruct = $roleService->newRoleCreateStruct('ultimate_permissions');
244
        $roleCreateStruct->addPolicy($policyCreateStruct1);
245
        $roleCreateStruct->addPolicy($policyCreateStruct2);
246
247
        $createdRole = $roleService->createRole($roleCreateStruct);
248
249
        self::assertInstanceOf(Role::class, $createdRole);
250
        self::assertGreaterThan(0, $createdRole->id);
251
252
        $this->assertPropertiesCorrect(
253
            [
254
                'identifier' => $roleCreateStruct->identifier,
255
            ],
256
            $createdRole
257
        );
258
259
        self::assertCount(2, $createdRole->getPolicies());
260
261
        foreach ($createdRole->getPolicies() as $policy) {
262
            self::assertInstanceOf(Policy::class, $policy);
263
            self::assertGreaterThan(0, $policy->id);
264
            self::assertEquals($createdRole->id, $policy->roleId);
265
266
            self::assertCount(2, $policy->getLimitations());
267
268
            foreach ($policy->getLimitations() as $limitation) {
269
                self::assertInstanceOf(Limitation::class, $limitation);
270
271
                if ($policy->module == 'content' && $policy->function == 'read') {
272 View Code Duplication
                    switch ($limitation->getIdentifier()) {
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...
273
                        case Limitation::CONTENTTYPE:
274
                            self::assertEquals($limitation1->limitationValues, $limitation->limitationValues);
275
                            break;
276
277
                        case Limitation::SECTION:
278
                            self::assertEquals($limitation2->limitationValues, $limitation->limitationValues);
279
                            break;
280
281
                        default:
282
                            self::fail('Created role contains limitations not defined with create struct');
283
                    }
284
                } elseif ($policy->module == 'content' && $policy->function == 'edit') {
285 View Code Duplication
                    switch ($limitation->getIdentifier()) {
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...
286
                        case Limitation::OWNER:
287
                            self::assertEquals($limitation3->limitationValues, $limitation->limitationValues);
288
                            break;
289
290
                        case Limitation::USERGROUP:
291
                            self::assertEquals($limitation4->limitationValues, $limitation->limitationValues);
292
                            break;
293
294
                        default:
295
                            self::fail('Created role contains limitations not defined with create struct');
296
                    }
297
                } else {
298
                    self::fail('Created role contains policy not defined with create struct');
299
                }
300
            }
301
        }
302
    }
303
304
    /**
305
     * Test for the createRoleDraft() method.
306
     *
307
     * @see \eZ\Publish\API\Repository\RoleService::createRoleDraft()
308
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewRoleCreateStruct
309
     */
310 View Code Duplication
    public function testCreateRoleDraft()
311
    {
312
        $repository = $this->getRepository();
313
314
        /* BEGIN: Use Case */
315
316
        $roleService = $repository->getRoleService();
317
        $roleCreate = $roleService->newRoleCreateStruct('roleName');
318
319
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
320
        // $roleCreate->mainLanguageCode = 'eng-US';
321
322
        $roleDraft = $roleService->createRole($roleCreate);
323
        $roleService->publishRoleDraft($roleDraft);
324
        $role = $roleService->loadRole($roleDraft->id);
325
        $newRoleDraft = $roleService->createRoleDraft($role);
326
327
        /* END: Use Case */
328
329
        $this->assertInstanceOf(
330
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\RoleDraft',
331
            $newRoleDraft
332
        );
333
    }
334
335
    /**
336
     * Test for the createRole() method.
337
     *
338
     * @see \eZ\Publish\API\Repository\RoleService::createRole()
339
     * @expectedException \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException
340
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRole
341
     */
342
    public function testCreateRoleThrowsInvalidArgumentException()
343
    {
344
        $repository = $this->getRepository();
345
346
        /* BEGIN: Use Case */
347
348
        $roleService = $repository->getRoleService();
349
        $roleCreate = $roleService->newRoleCreateStruct('Editor');
350
351
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
352
        // $roleCreate->mainLanguageCode = 'eng-US';
353
354
        // This call will fail with an InvalidArgumentException, because Editor exists
355
        $roleService->createRole($roleCreate);
356
357
        /* END: Use Case */
358
    }
359
360
    /**
361
     * Test for the createRoleDraft() method.
362
     *
363
     * @see \eZ\Publish\API\Repository\RoleService::createRoleDraft()
364
     * @expectedException \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException
365
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRoleDraft
366
     */
367 View Code Duplication
    public function testCreateRoleDraftThrowsInvalidArgumentException()
368
    {
369
        $repository = $this->getRepository();
370
371
        /* BEGIN: Use Case */
372
373
        $roleService = $repository->getRoleService();
374
        $roleCreate = $roleService->newRoleCreateStruct('Editor');
375
376
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
377
        // $roleCreate->mainLanguageCode = 'eng-US';
378
379
        $roleDraft = $roleService->createRole($roleCreate);
380
        $roleService->publishRoleDraft($roleDraft);
381
        $role = $roleService->loadRole($roleDraft->id);
382
        $roleService->createRoleDraft($role); // First role draft
383
384
        // This call will fail with an InvalidArgumentException, because there is already a draft
385
        $roleService->createRoleDraft($role);
386
387
        /* END: Use Case */
388
    }
389
390
    /**
391
     * Test for the createRole() method.
392
     *
393
     * @see \eZ\Publish\API\Repository\RoleService::createRole()
394
     * @expectedException \eZ\Publish\API\Repository\Exceptions\LimitationValidationException
395
     */
396 View Code Duplication
    public function testCreateRoleThrowsLimitationValidationException()
397
    {
398
        $repository = $this->getRepository();
399
400
        /* BEGIN: Use Case */
401
        $roleService = $repository->getRoleService();
402
403
        // Create new role create struct
404
        $roleCreate = $roleService->newRoleCreateStruct('Lumberjack');
405
406
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
407
        // $roleCreate->mainLanguageCode = 'eng-US';
408
409
        // Create new subtree limitation
410
        $limitation = new SubtreeLimitation(
411
            array(
412
                'limitationValues' => array('/mountain/forest/tree/42/'),
413
            )
414
        );
415
416
        // Create policy create struct and add limitation to it
417
        $policyCreate = $roleService->newPolicyCreateStruct('content', 'remove');
418
        $policyCreate->addLimitation($limitation);
419
420
        // Add policy create struct to role create struct
421
        $roleCreate->addPolicy($policyCreate);
422
423
        // This call will fail with an LimitationValidationException, because subtree
424
        // "/mountain/forest/tree/42/" does not exist
425
        $roleService->createRole($roleCreate);
426
        /* END: Use Case */
427
    }
428
429
    /**
430
     * Test for the createRole() method.
431
     *
432
     * @see \eZ\Publish\API\Repository\RoleService::createRole()
433
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewRoleCreateStruct
434
     */
435
    public function testCreateRoleInTransactionWithRollback()
436
    {
437
        $repository = $this->getRepository();
438
439
        /* BEGIN: Use Case */
440
441
        $roleService = $repository->getRoleService();
442
443
        $repository->beginTransaction();
444
445
        $roleCreate = $roleService->newRoleCreateStruct('roleName');
446
447
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
448
        // $roleCreate->mainLanguageCode = 'eng-US';
449
450
        $createdRoleId = $roleService->createRole($roleCreate)->id;
451
452
        $repository->rollback();
453
454
        try {
455
            // This call will fail with a "NotFoundException"
456
            $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...
457
        } catch (NotFoundException $e) {
458
            return;
459
        }
460
        /* END: Use Case */
461
462
        $this->fail('Role object still exists after rollback.');
463
    }
464
465
    /**
466
     * Test for the createRoleDraft() method.
467
     *
468
     * @see \eZ\Publish\API\Repository\RoleService::createRoleDraft()
469
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewRoleCreateStruct
470
     */
471
    public function testCreateRoleDraftInTransactionWithRollback()
472
    {
473
        $repository = $this->getRepository();
474
475
        /* BEGIN: Use Case */
476
477
        $roleService = $repository->getRoleService();
478
479
        $repository->beginTransaction();
480
481
        $roleCreate = $roleService->newRoleCreateStruct('roleName');
482
483
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
484
        // $roleCreate->mainLanguageCode = 'eng-US';
485
486
        $createdRoleId = $roleService->createRole($roleCreate)->id;
487
488
        $repository->rollback();
489
490
        try {
491
            // This call will fail with a "NotFoundException"
492
            $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...
493
        } catch (NotFoundException $e) {
494
            return;
495
        }
496
        /* END: Use Case */
497
498
        $this->fail('Role draft object still exists after rollback.');
499
    }
500
501
    /**
502
     * Test for the loadRole() method.
503
     *
504
     * @see \eZ\Publish\API\Repository\RoleService::loadRole()
505
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRole
506
     */
507
    public function testLoadRole()
508
    {
509
        $repository = $this->getRepository();
510
511
        /* BEGIN: Use Case */
512
513
        $roleService = $repository->getRoleService();
514
        $roleCreate = $roleService->newRoleCreateStruct('roleName');
515
516
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
517
        // $roleCreate->mainLanguageCode = 'eng-US';
518
519
        $roleDraft = $roleService->createRole($roleCreate);
520
        $roleService->publishRoleDraft($roleDraft);
521
522
        // Load the newly created role by its ID
523
        $role = $roleService->loadRole($roleDraft->id);
524
525
        /* END: Use Case */
526
527
        $this->assertEquals('roleName', $role->identifier);
528
    }
529
530
    /**
531
     * Test for the loadRoleDraft() method.
532
     *
533
     * @see \eZ\Publish\API\Repository\RoleService::loadRoleDraft()
534
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRoleDraft
535
     */
536
    public function testLoadRoleDraft()
537
    {
538
        $repository = $this->getRepository();
539
540
        /* BEGIN: Use Case */
541
542
        $roleService = $repository->getRoleService();
543
        $roleCreate = $roleService->newRoleCreateStruct('roleName');
544
545
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
546
        // $roleCreate->mainLanguageCode = 'eng-US';
547
548
        $roleDraft = $roleService->createRole($roleCreate);
549
550
        // Load the newly created role by its ID
551
        $role = $roleService->loadRoleDraft($roleDraft->id);
552
553
        /* END: Use Case */
554
555
        $this->assertEquals('roleName', $role->identifier);
556
    }
557
558
    public function testLoadRoleDraftByRoleId()
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
        $role = $roleService->createRole($roleCreate);
571
        $roleService->publishRoleDraft($role);
572
573
        // Now create a new draft based on the role
574
        $newDraft = $roleService->createRoleDraft($role);
575
        $loadedRoleDraft = $roleService->loadRoleDraftByRoleId($role->id);
576
577
        /* END: Use Case */
578
579
        self::assertEquals('roleName', $role->identifier);
580
        self::assertInstanceOf('eZ\Publish\API\Repository\Values\User\RoleDraft', $loadedRoleDraft);
581
        self::assertEquals($newDraft, $loadedRoleDraft);
582
    }
583
584
    /**
585
     * Test for the loadRole() method.
586
     *
587
     * @see \eZ\Publish\API\Repository\RoleService::loadRole()
588
     * @expectedException \eZ\Publish\API\Repository\Exceptions\NotFoundException
589
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRole
590
     */
591 View Code Duplication
    public function testLoadRoleThrowsNotFoundException()
592
    {
593
        $repository = $this->getRepository();
594
595
        $nonExistingRoleId = $this->generateId('role', self::DB_INT_MAX);
596
        /* BEGIN: Use Case */
597
598
        $roleService = $repository->getRoleService();
599
600
        // This call will fail with a NotFoundException, because no such role exists.
601
        $roleService->loadRole($nonExistingRoleId);
602
603
        /* END: Use Case */
604
    }
605
606
    /**
607
     * Test for the loadRoleDraft() method.
608
     *
609
     * @see \eZ\Publish\API\Repository\RoleService::loadRoleDraft()
610
     * @expectedException \eZ\Publish\API\Repository\Exceptions\NotFoundException
611
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleDraft
612
     */
613 View Code Duplication
    public function testLoadRoleDraftThrowsNotFoundException()
614
    {
615
        $repository = $this->getRepository();
616
617
        $nonExistingRoleId = $this->generateId('role', self::DB_INT_MAX);
618
        /* BEGIN: Use Case */
619
620
        $roleService = $repository->getRoleService();
621
622
        // This call will fail with a NotFoundException, because no such role exists.
623
        $roleService->loadRoleDraft($nonExistingRoleId);
624
625
        /* END: Use Case */
626
    }
627
628
    /**
629
     * @expectedException \eZ\Publish\API\Repository\Exceptions\NotFoundException
630
     */
631 View Code Duplication
    public function testLoadRoleDraftByRoleIdThrowsNotFoundException()
632
    {
633
        $repository = $this->getRepository();
634
635
        $nonExistingRoleId = $this->generateId('role', self::DB_INT_MAX);
636
        /* BEGIN: Use Case */
637
638
        $roleService = $repository->getRoleService();
639
640
        // This call will fail with a NotFoundException, because no such role exists.
641
        $roleService->loadRoleDraftByRoleId($nonExistingRoleId);
642
643
        /* END: Use Case */
644
    }
645
646
    /**
647
     * Test for the loadRoleByIdentifier() method.
648
     *
649
     * @see \eZ\Publish\API\Repository\RoleService::loadRoleByIdentifier()
650
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRole
651
     */
652 View Code Duplication
    public function testLoadRoleByIdentifier()
653
    {
654
        $repository = $this->getRepository();
655
656
        /* BEGIN: Use Case */
657
658
        $roleService = $repository->getRoleService();
659
        $roleCreate = $roleService->newRoleCreateStruct('roleName');
660
661
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
662
        // $roleCreate->mainLanguageCode = 'eng-US';
663
664
        $roleDraft = $roleService->createRole($roleCreate);
665
        $roleService->publishRoleDraft($roleDraft);
666
667
        // Load the newly created role by its identifier
668
        $role = $roleService->loadRoleByIdentifier('roleName');
669
670
        /* END: Use Case */
671
672
        $this->assertEquals('roleName', $role->identifier);
673
    }
674
675
    /**
676
     * Test for the loadRoleByIdentifier() method.
677
     *
678
     * @see \eZ\Publish\API\Repository\RoleService::loadRoleByIdentifier()
679
     * @expectedException \eZ\Publish\API\Repository\Exceptions\NotFoundException
680
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleByIdentifier
681
     */
682
    public function testLoadRoleByIdentifierThrowsNotFoundException()
683
    {
684
        $repository = $this->getRepository();
685
686
        /* BEGIN: Use Case */
687
688
        $roleService = $repository->getRoleService();
689
690
        // This call will fail with a NotFoundException, because no such role exists.
691
        $roleService->loadRoleByIdentifier('MissingRole');
692
693
        /* END: Use Case */
694
    }
695
696
    /**
697
     * Test for the loadRoles() method.
698
     *
699
     * @see \eZ\Publish\API\Repository\RoleService::loadRoles()
700
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRole
701
     */
702
    public function testLoadRoles()
703
    {
704
        $repository = $this->getRepository();
705
706
        /* BEGIN: Use Case */
707
708
        // First create a custom role
709
        $roleService = $repository->getRoleService();
710
        $roleCreate = $roleService->newRoleCreateStruct('roleName');
711
712
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
713
        // $roleCreate->mainLanguageCode = 'eng-US';
714
715
        $roleDraft = $roleService->createRole($roleCreate);
716
        $roleService->publishRoleDraft($roleDraft);
717
718
        // Now load all available roles
719
        $roles = $roleService->loadRoles();
720
721
        foreach ($roles as $role) {
722
            if ($role->identifier === 'roleName') {
723
                break;
724
            }
725
        }
726
727
        /* END: Use Case */
728
729
        $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 721. 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...
730
    }
731
732
    /**
733
     * Test for the loadRoles() method.
734
     *
735
     * @see \eZ\Publish\API\Repository\RoleService::loadRoles()
736
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoles
737
     */
738
    public function testLoadRolesReturnsExpectedSetOfDefaultRoles()
739
    {
740
        $repository = $this->getRepository();
741
742
        /* BEGIN: Use Case */
743
        $roleService = $repository->getRoleService();
744
745
        $roles = $roleService->loadRoles();
746
747
        $roleNames = array();
748
        foreach ($roles as $role) {
749
            $roleNames[] = $role->identifier;
750
        }
751
        /* END: Use Case */
752
753
        sort($roleNames);
754
755
        $this->assertEquals(
756
            array(
757
                'Administrator',
758
                'Anonymous',
759
                'Editor',
760
                'Member',
761
                'Partner',
762
            ),
763
            $roleNames
764
        );
765
    }
766
767
    /**
768
     * Test for the newRoleUpdateStruct() method.
769
     *
770
     * @see \eZ\Publish\API\Repository\RoleService::newRoleUpdateStruct()
771
     */
772
    public function testNewRoleUpdateStruct()
773
    {
774
        $repository = $this->getRepository();
775
776
        /* BEGIN: Use Case */
777
        $roleService = $repository->getRoleService();
778
        $roleUpdate = $roleService->newRoleUpdateStruct('newRole');
779
        /* END: Use Case */
780
781
        $this->assertInstanceOf('\\eZ\\Publish\\API\\Repository\\Values\\User\\RoleUpdateStruct', $roleUpdate);
782
    }
783
784
    /**
785
     * Test for the updateRole() method.
786
     *
787
     * @see \eZ\Publish\API\Repository\RoleService::updateRole()
788
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewRoleUpdateStruct
789
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleByIdentifier
790
     */
791
    public function testUpdateRole()
792
    {
793
        $repository = $this->getRepository();
794
795
        /* BEGIN: Use Case */
796
        $roleService = $repository->getRoleService();
797
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
798
799
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
800
        // $roleCreate->mainLanguageCode = 'eng-US';
801
802
        $roleDraft = $roleService->createRole($roleCreate);
803
        $roleService->publishRoleDraft($roleDraft);
804
        $role = $roleService->loadRole($roleDraft->id);
805
806
        $roleUpdate = $roleService->newRoleUpdateStruct();
807
        $roleUpdate->identifier = 'updatedRole';
808
809
        $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...
810
        /* END: Use Case */
811
812
        // Now verify that our change was saved
813
        $role = $roleService->loadRoleByIdentifier('updatedRole');
814
815
        $this->assertEquals($role->id, $updatedRole->id);
816
    }
817
818
    /**
819
     * Test for the updateRoleDraft() method.
820
     *
821
     * @see \eZ\Publish\API\Repository\RoleService::updateRoleDraft()
822
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewRoleUpdateStruct
823
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleDraft
824
     */
825 View Code Duplication
    public function testUpdateRoleDraft()
826
    {
827
        $repository = $this->getRepository();
828
829
        /* BEGIN: Use Case */
830
        $roleService = $repository->getRoleService();
831
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
832
833
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
834
        // $roleCreate->mainLanguageCode = 'eng-US';
835
836
        $roleDraft = $roleService->createRole($roleCreate);
837
838
        $roleUpdate = $roleService->newRoleUpdateStruct();
839
        $roleUpdate->identifier = 'updatedRole';
840
841
        $updatedRole = $roleService->updateRoleDraft($roleDraft, $roleUpdate);
842
        /* END: Use Case */
843
844
        // Now verify that our change was saved
845
        $role = $roleService->loadRoleDraft($updatedRole->id);
846
847
        $this->assertEquals($role->identifier, 'updatedRole');
848
    }
849
850
    /**
851
     * Test for the updateRole() method.
852
     *
853
     * @see \eZ\Publish\API\Repository\RoleService::updateRole()
854
     * @expectedException \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException
855
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testUpdateRole
856
     */
857 View Code Duplication
    public function testUpdateRoleThrowsInvalidArgumentException()
858
    {
859
        $repository = $this->getRepository();
860
861
        /* BEGIN: Use Case */
862
        $roleService = $repository->getRoleService();
863
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
864
865
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
866
        // $roleCreate->mainLanguageCode = 'eng-US';
867
868
        $roleDraft = $roleService->createRole($roleCreate);
869
        $roleService->publishRoleDraft($roleDraft);
870
        $role = $roleService->loadRole($roleDraft->id);
871
872
        $roleUpdate = $roleService->newRoleUpdateStruct();
873
        $roleUpdate->identifier = 'Editor';
874
875
        // This call will fail with an InvalidArgumentException, because Editor is a predefined role
876
        $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...
877
        /* END: Use Case */
878
    }
879
880
    /**
881
     * Test for the updateRoleDraft() method.
882
     *
883
     * @see \eZ\Publish\API\Repository\RoleService::updateRoleDraft()
884
     * @expectedException \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException
885
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testUpdateRoleDraft
886
     */
887
    public function testUpdateRoleDraftThrowsInvalidArgumentException()
888
    {
889
        $repository = $this->getRepository();
890
891
        /* BEGIN: Use Case */
892
        $roleService = $repository->getRoleService();
893
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
894
895
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
896
        // $roleCreate->mainLanguageCode = 'eng-US';
897
898
        $roleDraft = $roleService->createRole($roleCreate);
899
900
        $roleUpdate = $roleService->newRoleUpdateStruct();
901
        $roleUpdate->identifier = 'Editor';
902
903
        // This call will fail with an InvalidArgumentException, because Editor is a predefined role
904
        $roleService->updateRoleDraft($roleDraft, $roleUpdate);
905
        /* END: Use Case */
906
    }
907
908
    /**
909
     * Test for the deleteRole() method.
910
     *
911
     * @see \eZ\Publish\API\Repository\RoleService::deleteRole()
912
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRole
913
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoles
914
     */
915 View Code Duplication
    public function testDeleteRole()
916
    {
917
        $repository = $this->getRepository();
918
919
        /* BEGIN: Use Case */
920
        $roleService = $repository->getRoleService();
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
        $roleService->deleteRole($role);
931
        /* END: Use Case */
932
933
        $this->assertEquals(5, count($roleService->loadRoles()));
934
    }
935
936
    /**
937
     * Test for the deleteRoleDraft() method.
938
     *
939
     * @see \eZ\Publish\API\Repository\RoleService::deleteRoleDraft()
940
     * @expectedException \eZ\Publish\API\Repository\Exceptions\NotFoundException
941
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleDraft
942
     */
943
    public function testDeleteRoleDraft()
944
    {
945
        $repository = $this->getRepository();
946
947
        /* BEGIN: Use Case */
948
        $roleService = $repository->getRoleService();
949
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
950
951
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
952
        // $roleCreate->mainLanguageCode = 'eng-US';
953
954
        $roleDraft = $roleService->createRole($roleCreate);
955
        $roleID = $roleDraft->id;
956
        $roleService->deleteRoleDraft($roleDraft);
957
958
        // This call will fail with a NotFoundException, because the draft no longer exists
959
        $roleService->loadRoleDraft($roleID);
960
        /* END: Use Case */
961
    }
962
963
    /**
964
     * Test for the newPolicyCreateStruct() method.
965
     *
966
     * @see \eZ\Publish\API\Repository\RoleService::newPolicyCreateStruct()
967
     */
968
    public function testNewPolicyCreateStruct()
969
    {
970
        $repository = $this->getRepository();
971
972
        /* BEGIN: Use Case */
973
        $roleService = $repository->getRoleService();
974
        $policyCreate = $roleService->newPolicyCreateStruct('content', 'create');
975
        /* END: Use Case */
976
977
        $this->assertInstanceOf('\\eZ\\Publish\\API\\Repository\\Values\\User\\PolicyCreateStruct', $policyCreate);
978
    }
979
980
    /**
981
     * Test for the newPolicyCreateStruct() method.
982
     *
983
     * @see \eZ\Publish\API\Repository\RoleService::newPolicyCreateStruct()
984
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewPolicyCreateStruct
985
     */
986
    public function testNewPolicyCreateStructSetsStructProperties()
987
    {
988
        $repository = $this->getRepository();
989
990
        /* BEGIN: Use Case */
991
        $roleService = $repository->getRoleService();
992
        $policyCreate = $roleService->newPolicyCreateStruct('content', 'create');
993
        /* END: Use Case */
994
995
        $this->assertEquals(
996
            array('content', 'create'),
997
            array($policyCreate->module, $policyCreate->function)
998
        );
999
    }
1000
1001
    /**
1002
     * Test for the addPolicy() method.
1003
     *
1004
     * @see \eZ\Publish\API\Repository\RoleService::addPolicy()
1005
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleByIdentifier
1006
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewPolicyCreateStruct
1007
     */
1008 View Code Duplication
    public function testAddPolicy()
1009
    {
1010
        $repository = $this->getRepository();
1011
1012
        /* BEGIN: Use Case */
1013
        $roleService = $repository->getRoleService();
1014
1015
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
1016
1017
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1018
        // $roleCreate->mainLanguageCode = 'eng-US';
1019
1020
        $roleDraft = $roleService->createRole($roleCreate);
1021
        $roleService->publishRoleDraft($roleDraft);
1022
        $role = $roleService->loadRole($roleDraft->id);
1023
1024
        $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...
1025
            $role,
1026
            $roleService->newPolicyCreateStruct('content', 'delete')
1027
        );
1028
        $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...
1029
            $role,
1030
            $roleService->newPolicyCreateStruct('content', 'create')
1031
        );
1032
        /* END: Use Case */
1033
1034
        $actual = array();
1035
        foreach ($role->getPolicies() as $policy) {
1036
            $actual[] = array(
1037
                'module' => $policy->module,
1038
                'function' => $policy->function,
1039
            );
1040
        }
1041
        usort(
1042
            $actual,
1043
            function ($p1, $p2) {
1044
                return strcasecmp($p1['function'], $p2['function']);
1045
            }
1046
        );
1047
1048
        $this->assertEquals(
1049
            array(
1050
                array(
1051
                    'module' => 'content',
1052
                    'function' => 'create',
1053
                ),
1054
                array(
1055
                    'module' => 'content',
1056
                    'function' => 'delete',
1057
                ),
1058
            ),
1059
            $actual
1060
        );
1061
    }
1062
1063
    /**
1064
     * Test for the addPolicyByRoleDraft() method.
1065
     *
1066
     * @see \eZ\Publish\API\Repository\RoleService::addPolicyByRoleDraft()
1067
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRoleDraft
1068
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewPolicyCreateStruct
1069
     */
1070
    public function testAddPolicyByRoleDraft()
1071
    {
1072
        $repository = $this->getRepository();
1073
1074
        /* BEGIN: Use Case */
1075
        $roleService = $repository->getRoleService();
1076
1077
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
1078
1079
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1080
        // $roleCreate->mainLanguageCode = 'eng-US';
1081
1082
        $roleDraft = $roleService->createRole($roleCreate);
1083
1084
        $roleDraft = $roleService->addPolicyByRoleDraft(
1085
            $roleDraft,
1086
            $roleService->newPolicyCreateStruct('content', 'delete')
1087
        );
1088
        $roleDraft = $roleService->addPolicyByRoleDraft(
1089
            $roleDraft,
1090
            $roleService->newPolicyCreateStruct('content', 'create')
1091
        );
1092
        /* END: Use Case */
1093
1094
        $actual = array();
1095 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...
1096
            $actual[] = array(
1097
                'module' => $policy->module,
1098
                'function' => $policy->function,
1099
            );
1100
        }
1101
        usort(
1102
            $actual,
1103
            function ($p1, $p2) {
1104
                return strcasecmp($p1['function'], $p2['function']);
1105
            }
1106
        );
1107
1108
        $this->assertEquals(
1109
            array(
1110
                array(
1111
                    'module' => 'content',
1112
                    'function' => 'create',
1113
                ),
1114
                array(
1115
                    'module' => 'content',
1116
                    'function' => 'delete',
1117
                ),
1118
            ),
1119
            $actual
1120
        );
1121
    }
1122
1123
    /**
1124
     * Test for the addPolicy() method.
1125
     *
1126
     * @return array [\eZ\Publish\API\Repository\Values\User\Role, \eZ\Publish\API\Repository\Values\User\Policy]
1127
     *
1128
     * @see \eZ\Publish\API\Repository\RoleService::addPolicy()
1129
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicy
1130
     */
1131
    public function testAddPolicyUpdatesRole()
1132
    {
1133
        $repository = $this->getRepository();
1134
1135
        /* BEGIN: Use Case */
1136
        $roleService = $repository->getRoleService();
1137
1138
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
1139
1140
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1141
        // $roleCreate->mainLanguageCode = 'eng-US';
1142
1143
        $roleDraft = $roleService->createRole($roleCreate);
1144
        $roleService->publishRoleDraft($roleDraft);
1145
        $role = $roleService->loadRole($roleDraft->id);
1146
1147
        $policyCreate = $roleService->newPolicyCreateStruct('content', 'create');
1148
        $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...
1149
1150
        $policy = null;
1151
        foreach ($role->getPolicies() as $policy) {
1152
            if ($policy->module === 'content' && $policy->function === 'create') {
1153
                break;
1154
            }
1155
        }
1156
        /* END: Use Case */
1157
1158
        $this->assertInstanceOf(
1159
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\Policy',
1160
            $policy
1161
        );
1162
1163
        return array($role, $policy);
1164
    }
1165
1166
    /**
1167
     * Test for the addPolicyByRoleDraft() method.
1168
     *
1169
     * @return array [\eZ\Publish\API\Repository\Values\User\RoleDraft, \eZ\Publish\API\Repository\Values\User\Policy]
1170
     *
1171
     * @see \eZ\Publish\API\Repository\RoleService::addPolicyByRoleDraft()
1172
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicyByRoleDraft
1173
     */
1174
    public function testAddPolicyByRoleDraftUpdatesRole()
1175
    {
1176
        $repository = $this->getRepository();
1177
1178
        /* BEGIN: Use Case */
1179
        $roleService = $repository->getRoleService();
1180
1181
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
1182
1183
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1184
        // $roleCreate->mainLanguageCode = 'eng-US';
1185
1186
        $roleDraft = $roleService->createRole($roleCreate);
1187
1188
        $policyCreate = $roleService->newPolicyCreateStruct('content', 'create');
1189
        $roleDraft = $roleService->addPolicyByRoleDraft($roleDraft, $policyCreate);
1190
1191
        $policy = null;
1192
        foreach ($roleDraft->getPolicies() as $policy) {
1193
            if ($policy->module === 'content' && $policy->function === 'create') {
1194
                break;
1195
            }
1196
        }
1197
        /* END: Use Case */
1198
1199
        $this->assertInstanceOf(
1200
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\Policy',
1201
            $policy
1202
        );
1203
1204
        return array($roleDraft, $policy);
1205
    }
1206
1207
    /**
1208
     * Test for the addPolicy() method.
1209
     *
1210
     * @param array $roleAndPolicy
1211
     *
1212
     * @see \eZ\Publish\API\Repository\RoleService::addPolicy()
1213
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicyUpdatesRole
1214
     */
1215 View Code Duplication
    public function testAddPolicySetsPolicyProperties($roleAndPolicy)
1216
    {
1217
        list($role, $policy) = $roleAndPolicy;
1218
1219
        $this->assertEquals(
1220
            array($role->id, 'content', 'create'),
1221
            array($policy->roleId, $policy->module, $policy->function)
1222
        );
1223
    }
1224
1225
    /**
1226
     * Test for the addPolicyByRoleDraft() method.
1227
     *
1228
     * @param array $roleAndPolicy
1229
     *
1230
     * @see \eZ\Publish\API\Repository\RoleService::addPolicyByRoleDraft()
1231
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicyByRoleDraftUpdatesRole
1232
     */
1233 View Code Duplication
    public function testAddPolicyByRoleDraftSetsPolicyProperties($roleAndPolicy)
1234
    {
1235
        list($role, $policy) = $roleAndPolicy;
1236
1237
        $this->assertEquals(
1238
            array($role->id, 'content', 'create'),
1239
            array($policy->roleId, $policy->module, $policy->function)
1240
        );
1241
    }
1242
1243
    /**
1244
     * Test for the addPolicy() method.
1245
     *
1246
     * @see \eZ\Publish\API\Repository\RoleService::addPolicy()
1247
     * @expectedException \eZ\Publish\API\Repository\Exceptions\LimitationValidationException
1248
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewPolicyCreateStruct
1249
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRole
1250
     */
1251
    public function testAddPolicyThrowsLimitationValidationException()
1252
    {
1253
        $repository = $this->getRepository();
1254
1255
        /* BEGIN: Use Case */
1256
        $roleService = $repository->getRoleService();
1257
1258
        $roleCreate = $roleService->newRoleCreateStruct('Lumberjack');
1259
1260
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1261
        // $roleCreate->mainLanguageCode = 'eng-US';
1262
1263
        $roleDraft = $roleService->createRole($roleCreate);
1264
        $roleService->publishRoleDraft($roleDraft);
1265
        $role = $roleService->loadRole($roleDraft->id);
1266
1267
        // Create new subtree limitation
1268
        $limitation = new SubtreeLimitation(
1269
            array(
1270
                'limitationValues' => array('/mountain/forest/tree/42/'),
1271
            )
1272
        );
1273
1274
        // Create policy create struct and add limitation to it
1275
        $policyCreateStruct = $roleService->newPolicyCreateStruct('content', 'remove');
1276
        $policyCreateStruct->addLimitation($limitation);
1277
1278
        // This call will fail with an LimitationValidationException, because subtree
1279
        // "/mountain/forest/tree/42/" does not exist
1280
        $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...
1281
        /* END: Use Case */
1282
    }
1283
1284
    /**
1285
     * Test for the addPolicyByRoleDraft() method.
1286
     *
1287
     * @see \eZ\Publish\API\Repository\RoleService::addPolicyByRoleDraft()
1288
     * @expectedException \eZ\Publish\API\Repository\Exceptions\LimitationValidationException
1289
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewPolicyCreateStruct
1290
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRoleDraft
1291
     */
1292 View Code Duplication
    public function testAddPolicyByRoleDraftThrowsLimitationValidationException()
1293
    {
1294
        $repository = $this->getRepository();
1295
1296
        /* BEGIN: Use Case */
1297
        $roleService = $repository->getRoleService();
1298
1299
        $roleCreate = $roleService->newRoleCreateStruct('Lumberjack');
1300
1301
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1302
        // $roleCreate->mainLanguageCode = 'eng-US';
1303
1304
        $roleDraft = $roleService->createRole($roleCreate);
1305
1306
        // Create new subtree limitation
1307
        $limitation = new SubtreeLimitation(
1308
            array(
1309
                'limitationValues' => array('/mountain/forest/tree/42/'),
1310
            )
1311
        );
1312
1313
        // Create policy create struct and add limitation to it
1314
        $policyCreateStruct = $roleService->newPolicyCreateStruct('content', 'remove');
1315
        $policyCreateStruct->addLimitation($limitation);
1316
1317
        // This call will fail with an LimitationValidationException, because subtree
1318
        // "/mountain/forest/tree/42/" does not exist
1319
        $roleService->addPolicyByRoleDraft($roleDraft, $policyCreateStruct);
1320
        /* END: Use Case */
1321
    }
1322
1323
    /**
1324
     * Test for the createRole() method.
1325
     *
1326
     * @see \eZ\Publish\API\Repository\RoleService::createRole()
1327
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicyUpdatesRole
1328
     */
1329
    public function testCreateRoleWithAddPolicy()
1330
    {
1331
        $repository = $this->getRepository();
1332
1333
        /* BEGIN: Use Case */
1334
        $roleService = $repository->getRoleService();
1335
1336
        // Instantiate a new create struct
1337
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
1338
1339
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1340
        // $roleCreate->mainLanguageCode = 'eng-US';
1341
1342
        // Add some role policies
1343
        $roleCreate->addPolicy(
1344
            $roleService->newPolicyCreateStruct(
1345
                'content',
1346
                'read'
1347
            )
1348
        );
1349
        $roleCreate->addPolicy(
1350
            $roleService->newPolicyCreateStruct(
1351
                'content',
1352
                'translate'
1353
            )
1354
        );
1355
1356
        // Create new role instance
1357
        $roleDraft = $roleService->createRole($roleCreate);
1358
        $roleService->publishRoleDraft($roleDraft);
1359
        $role = $roleService->loadRole($roleDraft->id);
1360
1361
        $policies = array();
1362 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...
1363
            $policies[] = array('module' => $policy->module, 'function' => $policy->function);
1364
        }
1365
        /* END: Use Case */
1366
        array_multisort($policies);
1367
1368
        $this->assertEquals(
1369
            array(
1370
                array(
1371
                    'module' => 'content',
1372
                    'function' => 'read',
1373
                ),
1374
                array(
1375
                    'module' => 'content',
1376
                    'function' => 'translate',
1377
                ),
1378
            ),
1379
            $policies
1380
        );
1381
    }
1382
1383
    /**
1384
     * Test for the createRoleDraft() method.
1385
     *
1386
     * @see \eZ\Publish\API\Repository\RoleService::createRoleDraft()
1387
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicyByRoleDraftUpdatesRole
1388
     */
1389
    public function testCreateRoleDraftWithAddPolicy()
1390
    {
1391
        $repository = $this->getRepository();
1392
1393
        /* BEGIN: Use Case */
1394
        $roleService = $repository->getRoleService();
1395
1396
        // Instantiate a new create struct
1397
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
1398
1399
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1400
        // $roleCreate->mainLanguageCode = 'eng-US';
1401
1402
        // Add some role policies
1403
        $roleCreate->addPolicy(
1404
            $roleService->newPolicyCreateStruct(
1405
                'content',
1406
                'read'
1407
            )
1408
        );
1409
        $roleCreate->addPolicy(
1410
            $roleService->newPolicyCreateStruct(
1411
                'content',
1412
                'translate'
1413
            )
1414
        );
1415
1416
        // Create new role instance
1417
        $roleDraft = $roleService->createRole($roleCreate);
1418
1419
        $policies = array();
1420 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...
1421
            $policies[] = array('module' => $policy->module, 'function' => $policy->function);
1422
        }
1423
        /* END: Use Case */
1424
1425
        $this->assertEquals(
1426
            array(
1427
                array(
1428
                    'module' => 'content',
1429
                    'function' => 'read',
1430
                ),
1431
                array(
1432
                    'module' => 'content',
1433
                    'function' => 'translate',
1434
                ),
1435
            ),
1436
            $policies
1437
        );
1438
    }
1439
1440
    /**
1441
     * Test for the newPolicyUpdateStruct() method.
1442
     *
1443
     * @see \eZ\Publish\API\Repository\RoleService::newPolicyUpdateStruct()
1444
     */
1445
    public function testNewPolicyUpdateStruct()
1446
    {
1447
        $repository = $this->getRepository();
1448
1449
        /* BEGIN: Use Case */
1450
        $roleService = $repository->getRoleService();
1451
        $policyUpdate = $roleService->newPolicyUpdateStruct();
1452
        /* END: Use Case */
1453
1454
        $this->assertInstanceOf(
1455
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\PolicyUpdateStruct',
1456
            $policyUpdate
1457
        );
1458
    }
1459
1460
    public function testUpdatePolicyNoLimitation()
1461
    {
1462
        $repository = $this->getRepository();
1463
1464
        /* BEGIN: Use Case */
1465
        $roleService = $repository->getRoleService();
1466
1467
        // Instantiate new policy create
1468
        $policyCreate = $roleService->newPolicyCreateStruct('foo', 'bar');
1469
1470
        // Instantiate a role create and add the policy create
1471
        $roleCreate = $roleService->newRoleCreateStruct('myRole');
1472
1473
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1474
        // $roleCreate->mainLanguageCode = 'eng-US';
1475
1476
        $roleCreate->addPolicy($policyCreate);
1477
1478
        // Create a new role instance.
1479
        $roleDraft = $roleService->createRole($roleCreate);
1480
        $roleService->publishRoleDraft($roleDraft);
1481
        $role = $roleService->loadRole($roleDraft->id);
1482
1483
        // Search for the new policy instance
1484
        $policy = null;
1485
        foreach ($role->getPolicies() as $policy) {
1486
            if ($policy->module === 'foo' && $policy->function === 'bar') {
1487
                break;
1488
            }
1489
        }
1490
1491
        // Create an update struct
1492
        $policyUpdate = $roleService->newPolicyUpdateStruct();
1493
1494
        // Update the the policy
1495
        $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...
1496
        /* END: Use Case */
1497
1498
        $this->assertInstanceOf(
1499
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\Policy',
1500
            $policy
1501
        );
1502
1503
        self::assertEquals(array(), $policy->getLimitations());
1504
    }
1505
1506
    /**
1507
     * Test for the updatePolicy() method.
1508
     *
1509
     * @return array
1510
     *
1511
     * @see \eZ\Publish\API\Repository\RoleService::updatePolicy()
1512
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicy
1513
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewPolicyUpdateStruct
1514
     */
1515
    public function testUpdatePolicy()
1516
    {
1517
        $repository = $this->getRepository();
1518
1519
        /* BEGIN: Use Case */
1520
        $roleService = $repository->getRoleService();
1521
1522
        // Instantiate new policy create
1523
        $policyCreate = $roleService->newPolicyCreateStruct('content', 'translate');
1524
1525
        // Add some limitations for the new policy
1526
        $policyCreate->addLimitation(
1527
            new LanguageLimitation(
1528
                array(
1529
                    'limitationValues' => array('eng-US', 'eng-GB'),
1530
                )
1531
            )
1532
        );
1533
1534
        // Instantiate a role create and add the policy create
1535
        $roleCreate = $roleService->newRoleCreateStruct('myRole');
1536
1537
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1538
        // $roleCreate->mainLanguageCode = 'eng-US';
1539
1540
        $roleCreate->addPolicy($policyCreate);
1541
1542
        // Create a new role instance.
1543
        $roleDraft = $roleService->createRole($roleCreate);
1544
        $roleService->publishRoleDraft($roleDraft);
1545
        $role = $roleService->loadRole($roleDraft->id);
1546
1547
        // Search for the new policy instance
1548
        $policy = null;
1549
        foreach ($role->getPolicies() as $policy) {
1550
            if ($policy->module === 'content' && $policy->function === 'translate') {
1551
                break;
1552
            }
1553
        }
1554
1555
        // Create an update struct and set a modified limitation
1556
        $policyUpdate = $roleService->newPolicyUpdateStruct();
1557
        $policyUpdate->addLimitation(
1558
            new ContentTypeLimitation(
1559
                array(
1560
                    'limitationValues' => array(29, 30),
1561
                )
1562
            )
1563
        );
1564
1565
        // Update the the policy
1566
        $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...
1567
        /* END: Use Case */
1568
1569
        $this->assertInstanceOf(
1570
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\Policy',
1571
            $policy
1572
        );
1573
1574
        return array($roleService->loadRole($role->id), $policy);
1575
    }
1576
1577
    /**
1578
     * Test for the updatePolicy() method.
1579
     *
1580
     * @param array $roleAndPolicy
1581
     *
1582
     * @see \eZ\Publish\API\Repository\RoleService::updatePolicy()
1583
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testUpdatePolicy
1584
     */
1585
    public function testUpdatePolicyUpdatesLimitations($roleAndPolicy)
1586
    {
1587
        list($role, $policy) = $roleAndPolicy;
1588
1589
        $this->assertEquals(
1590
            array(
1591
                new ContentTypeLimitation(
1592
                    array(
1593
                        'limitationValues' => array(29, 30),
1594
                    )
1595
                ),
1596
            ),
1597
            $policy->getLimitations()
1598
        );
1599
1600
        return $role;
1601
    }
1602
1603
    /**
1604
     * Test for the updatePolicy() method.
1605
     *
1606
     * @param \eZ\Publish\API\Repository\Values\User\Role $role
1607
     *
1608
     * @see \eZ\Publish\API\Repository\RoleService::updatePolicy()
1609
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testUpdatePolicyUpdatesLimitations
1610
     */
1611
    public function testUpdatePolicyUpdatesRole($role)
1612
    {
1613
        $limitations = array();
1614
        foreach ($role->getPolicies() as $policy) {
1615
            foreach ($policy->getLimitations() as $limitation) {
1616
                $limitations[] = $limitation;
1617
            }
1618
        }
1619
1620
        $this->assertCount(1, $limitations);
1621
        $this->assertInstanceOf(
1622
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\Limitation',
1623
            $limitations[0]
1624
        );
1625
1626
        $expectedData = array(
1627
            'limitationValues' => array(29, 30),
1628
        );
1629
        $this->assertPropertiesCorrectUnsorted(
1630
            $expectedData,
1631
            $limitations[0]
1632
        );
1633
    }
1634
1635
    /**
1636
     * Test for the updatePolicy() method.
1637
     *
1638
     * @see \eZ\Publish\API\Repository\RoleService::updatePolicy()
1639
     * @expectedException \eZ\Publish\API\Repository\Exceptions\LimitationValidationException
1640
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicy
1641
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewPolicyCreateStruct
1642
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewPolicyUpdateStruct
1643
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewRoleCreateStruct
1644
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRole
1645
     */
1646
    public function testUpdatePolicyThrowsLimitationValidationException()
1647
    {
1648
        $repository = $this->getRepository();
1649
1650
        /* BEGIN: Use Case */
1651
        $roleService = $repository->getRoleService();
1652
1653
        // Instantiate new policy create
1654
        $policyCreate = $roleService->newPolicyCreateStruct('content', 'remove');
1655
1656
        // Add some limitations for the new policy
1657
        $policyCreate->addLimitation(
1658
            new SubtreeLimitation(
1659
                array(
1660
                    'limitationValues' => array('/1/2/'),
1661
                )
1662
            )
1663
        );
1664
1665
        // Instantiate a role create and add the policy create
1666
        $roleCreate = $roleService->newRoleCreateStruct('myRole');
1667
1668
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1669
        // $roleCreate->mainLanguageCode = 'eng-US';
1670
1671
        $roleCreate->addPolicy($policyCreate);
1672
1673
        // Create a new role instance.
1674
        $roleDraft = $roleService->createRole($roleCreate);
1675
        $roleService->publishRoleDraft($roleDraft);
1676
        $role = $roleService->loadRole($roleDraft->id);
1677
1678
        // Search for the new policy instance
1679
        $policy = null;
1680
        foreach ($role->getPolicies() as $policy) {
1681
            if ($policy->module === 'content' && $policy->function === 'remove') {
1682
                break;
1683
            }
1684
        }
1685
1686
        // Create an update struct and set a modified limitation
1687
        $policyUpdate = $roleService->newPolicyUpdateStruct();
1688
        $policyUpdate->addLimitation(
1689
            new SubtreeLimitation(
1690
                array(
1691
                    'limitationValues' => array('/mountain/forest/tree/42/'),
1692
                )
1693
            )
1694
        );
1695
1696
        // This call will fail with an LimitationValidationException, because subtree
1697
        // "/mountain/forest/tree/42/" does not exist
1698
        $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...
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...
1699
        /* END: Use Case */
1700
    }
1701
1702
    /**
1703
     * Test for the removePolicyByRoleDraft() method.
1704
     *
1705
     * @see \eZ\Publish\API\Repository\RoleService::removePolicyByRoleDraft()
1706
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicyByRoleDraft
1707
     */
1708 View Code Duplication
    public function testRemovePolicyByRoleDraft()
1709
    {
1710
        $repository = $this->getRepository();
1711
1712
        /* BEGIN: Use Case */
1713
        $roleService = $repository->getRoleService();
1714
1715
        // Instantiate a new role create
1716
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
1717
1718
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1719
        // $roleCreate->mainLanguageCode = 'eng-US';
1720
1721
        // Create a new role with two policies
1722
        $roleDraft = $roleService->createRole($roleCreate);
1723
        $roleService->addPolicyByRoleDraft(
1724
            $roleDraft,
1725
            $roleService->newPolicyCreateStruct('content', 'create')
1726
        );
1727
        $roleService->addPolicyByRoleDraft(
1728
            $roleDraft,
1729
            $roleService->newPolicyCreateStruct('content', 'delete')
1730
        );
1731
1732
        // Delete all policies from the new role
1733
        foreach ($roleDraft->getPolicies() as $policy) {
1734
            $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...
1735
        }
1736
        /* END: Use Case */
1737
1738
        $this->assertSame(array(), $roleDraft->getPolicies());
1739
    }
1740
1741
    /**
1742
     * Test for the deletePolicy() method.
1743
     *
1744
     * @see \eZ\Publish\API\Repository\RoleService::deletePolicy()
1745
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRole
1746
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicy
1747
     */
1748
    public function testDeletePolicy()
1749
    {
1750
        $repository = $this->getRepository();
1751
1752
        /* BEGIN: Use Case */
1753
        $roleService = $repository->getRoleService();
1754
1755
        // Instantiate a new role create
1756
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
1757
1758
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1759
        // $roleCreate->mainLanguageCode = 'eng-US';
1760
1761
        // Create a new role with two policies
1762
        $roleDraft = $roleService->createRole($roleCreate);
1763
        $roleService->addPolicyByRoleDraft(
1764
            $roleDraft,
1765
            $roleService->newPolicyCreateStruct('content', 'create')
1766
        );
1767
        $roleService->addPolicyByRoleDraft(
1768
            $roleDraft,
1769
            $roleService->newPolicyCreateStruct('content', 'delete')
1770
        );
1771
        $roleService->publishRoleDraft($roleDraft);
1772
        $role = $roleService->loadRole($roleDraft->id);
1773
1774
        // Delete all policies from the new role
1775
        foreach ($role->getPolicies() as $policy) {
1776
            $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...
1777
        }
1778
        /* END: Use Case */
1779
1780
        $role = $roleService->loadRole($role->id);
1781
        $this->assertSame(array(), $role->getPolicies());
1782
    }
1783
1784
    /**
1785
     * Test for the addPolicyByRoleDraft() method.
1786
     *
1787
     * @see \eZ\Publish\API\Repository\RoleService::addPolicyByRoleDraft()
1788
     */
1789
    public function testAddPolicyWithRoleAssignment()
1790
    {
1791
        $repository = $this->getRepository();
1792
1793
        /* BEGIN: Use Case */
1794
        $roleService = $repository->getRoleService();
1795
        $userService = $repository->getUserService();
1796
1797
        /* Create new user group */
1798
        $mainGroupId = $this->generateId('group', 4);
1799
        $parentUserGroup = $userService->loadUserGroup($mainGroupId);
1800
        $userGroupCreate = $userService->newUserGroupCreateStruct('eng-US');
1801
        $userGroupCreate->setField('name', 'newUserGroup');
1802
        $userGroup = $userService->createUserGroup($userGroupCreate, $parentUserGroup);
1803
1804
        /* Create Role */
1805
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
1806
        $roleDraft = $roleService->createRole($roleCreate);
1807
        $roleService->publishRoleDraft($roleDraft);
1808
1809
        $role = $roleService->loadRole($roleDraft->id);
1810
        $roleService->assignRoleToUserGroup($role, $userGroup);
1811
1812
        $roleAssignmentsBeforeNewPolicy = $roleService->getRoleAssignments($role)[0];
1813
1814
        /* Add new policy to existing role */
1815
        $roleUpdateDraft = $roleService->createRoleDraft($role);
1816
        $roleUpdateDraft = $roleService->addPolicyByRoleDraft(
1817
            $roleUpdateDraft,
1818
            $roleService->newPolicyCreateStruct('content', 'create')
1819
        );
1820
        $roleService->publishRoleDraft($roleUpdateDraft);
1821
1822
        $roleAfterUpdate = $roleService->loadRole($role->id);
1823
        $roleAssignmentsAfterNewPolicy = $roleService->getRoleAssignments($roleAfterUpdate)[0];
1824
        /* END: Use Case */
1825
1826
        $this->assertNotEquals($roleAssignmentsBeforeNewPolicy->id, $roleAssignmentsAfterNewPolicy->id);
1827
    }
1828
1829
    /**
1830
     * Test loading user/group role assignments.
1831
     *
1832
     * @return \eZ\Publish\API\Repository\Values\User\UserGroupRoleAssignment
1833
     *
1834
     * @covers \eZ\Publish\API\Repository\RoleService::loadRoleAssignment
1835
     */
1836
    public function testLoadRoleAssignment()
1837
    {
1838
        $repository = $this->getRepository();
1839
1840
        /* BEGIN: Use Case */
1841
        $roleService = $repository->getRoleService();
1842
1843
        // Assignment to user group
1844
        $groupRoleAssignment = $roleService->loadRoleAssignment(25);
1845
1846
        // Assignment to user
1847
        $role = $roleService->loadRole(2);
1848
        $user = $repository->getUserService()->loadUser(14);
1849
        $roleService->assignRoleToUser($role, $user);
1850
        $userRoleAssignments = $roleService->getRoleAssignmentsForUser($user);
1851
1852
        $userRoleAssignment = $roleService->loadRoleAssignment($userRoleAssignments[0]->id);
1853
        /* END: Use Case */
1854
1855
        $this->assertInstanceOf(
1856
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\UserGroupRoleAssignment',
1857
            $groupRoleAssignment
1858
        );
1859
1860
        $this->assertEquals(
1861
            [
1862
                12,
1863
                2,
1864
                25,
1865
            ],
1866
            [
1867
                $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...
1868
                $groupRoleAssignment->role->id,
1869
                $groupRoleAssignment->id,
1870
            ]
1871
        );
1872
1873
        self::assertInstanceOf('\\eZ\\Publish\\API\\Repository\\Values\\User\\UserRoleAssignment', $userRoleAssignment);
1874
        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...
1875
1876
        return $groupRoleAssignment;
1877
    }
1878
1879
    /**
1880
     * Test for the getRoleAssignments() method.
1881
     *
1882
     * @return \eZ\Publish\API\Repository\Values\User\RoleAssignment[]
1883
     *
1884
     * @see \eZ\Publish\API\Repository\RoleService::getRoleAssignments()
1885
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleByIdentifier
1886
     */
1887
    public function testGetRoleAssignments()
1888
    {
1889
        $repository = $this->getRepository();
1890
1891
        /* BEGIN: Use Case */
1892
        $roleService = $repository->getRoleService();
1893
1894
        // Load the editor role
1895
        $role = $roleService->loadRoleByIdentifier('Editor');
1896
1897
        // Load all assigned users and user groups
1898
        $roleAssignments = $roleService->getRoleAssignments($role);
1899
1900
        /* END: Use Case */
1901
1902
        $this->assertEquals(2, count($roleAssignments));
1903
        $this->assertInstanceOf(
1904
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\UserGroupRoleAssignment',
1905
            $roleAssignments[0]
1906
        );
1907
        $this->assertInstanceOf(
1908
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\UserGroupRoleAssignment',
1909
            $roleAssignments[1]
1910
        );
1911
1912
        return $roleAssignments;
1913
    }
1914
1915
    /**
1916
     * Test for the getRoleAssignments() method.
1917
     *
1918
     * @param \eZ\Publish\API\Repository\Values\User\RoleAssignment[] $roleAssignments
1919
     *
1920
     * @see \eZ\Publish\API\Repository\RoleService::getRoleAssignments()
1921
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testGetRoleAssignments
1922
     */
1923
    public function testGetRoleAssignmentsContainExpectedLimitation(array $roleAssignments)
1924
    {
1925
        $this->assertEquals(
1926
            'Subtree',
1927
            reset($roleAssignments)->limitation->getIdentifier()
1928
        );
1929
    }
1930
1931
    /**
1932
     * Test for the assignRoleToUser() method.
1933
     *
1934
     * @see \eZ\Publish\API\Repository\RoleService::assignRoleToUser()
1935
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testGetRoleAssignments
1936
     */
1937 View Code Duplication
    public function testAssignRoleToUser()
1938
    {
1939
        $repository = $this->getRepository();
1940
        $roleService = $repository->getRoleService();
1941
1942
        /* BEGIN: Use Case */
1943
        $user = $this->createUserVersion1();
1944
1945
        // Load the existing "Administrator" role
1946
        $role = $roleService->loadRoleByIdentifier('Administrator');
1947
1948
        // Assign the "Administrator" role to the newly created user
1949
        $roleService->assignRoleToUser($role, $user);
1950
1951
        // The assignments array will contain the new role<->user assignment
1952
        $roleAssignments = $roleService->getRoleAssignments($role);
1953
        /* END: Use Case */
1954
1955
        // Administrator + Example User
1956
        $this->assertEquals(2, count($roleAssignments));
1957
    }
1958
1959
    /**
1960
     * Test for the assignRoleToUser() method.
1961
     *
1962
     * @see \eZ\Publish\API\Repository\RoleService::assignRoleToUser($role, $user, $roleLimitation)
1963
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUser
1964
     */
1965 View Code Duplication
    public function testAssignRoleToUserWithRoleLimitation()
1966
    {
1967
        $repository = $this->getRepository();
1968
        $roleService = $repository->getRoleService();
1969
1970
        /* BEGIN: Use Case */
1971
        $user = $this->createUserVersion1();
1972
1973
        // Load the existing "Anonymous" role
1974
        $role = $roleService->loadRoleByIdentifier('Anonymous');
1975
1976
        // Assign the "Anonymous" role to the newly created user
1977
        $roleService->assignRoleToUser(
1978
            $role,
1979
            $user,
1980
            new SubtreeLimitation(
1981
                array(
1982
                    'limitationValues' => array('/1/43/'),
1983
                )
1984
            )
1985
        );
1986
1987
        // The assignments array will contain the new role<->user assignment
1988
        $roleAssignments = $roleService->getRoleAssignments($role);
1989
        /* END: Use Case */
1990
1991
        // Members + Partners + Anonymous + Example User
1992
        $this->assertEquals(4, count($roleAssignments));
1993
1994
        // Get the role limitation
1995
        $roleLimitation = null;
1996
        foreach ($roleAssignments as $roleAssignment) {
1997
            $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...
1998
            if ($roleLimitation) {
1999
                $this->assertInstanceOf(
2000
                    '\\eZ\\Publish\\API\\Repository\\Values\\User\\UserRoleAssignment',
2001
                    $roleAssignment
2002
                );
2003
                break;
2004
            }
2005
        }
2006
2007
        $this->assertEquals(
2008
            new SubtreeLimitation(
2009
                array(
2010
                    'limitationValues' => array('/1/43/'),
2011
                )
2012
            ),
2013
            $roleLimitation
2014
        );
2015
2016
        // Test again to see values being merged
2017
        $roleService->assignRoleToUser(
2018
            $role,
2019
            $user,
2020
            new SubtreeLimitation(
2021
                array(
2022
                    'limitationValues' => array('/1/43/', '/1/2/'),
2023
                )
2024
            )
2025
        );
2026
2027
        // The assignments array will contain the new role<->user assignment
2028
        $roleAssignments = $roleService->getRoleAssignments($role);
2029
2030
        // Members + Partners + Anonymous + Example User
2031
        $this->assertEquals(5, count($roleAssignments));
2032
2033
        // Get the role limitation
2034
        $roleLimitations = [];
2035
        foreach ($roleAssignments as $roleAssignment) {
2036
            $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...
2037
            if ($roleLimitation) {
2038
                $this->assertInstanceOf(
2039
                    '\\eZ\\Publish\\API\\Repository\\Values\\User\\UserRoleAssignment',
2040
                    $roleAssignment
2041
                );
2042
                $roleLimitations[] = $roleLimitation;
2043
            }
2044
        }
2045
        array_multisort($roleLimitations);
2046
2047
        $this->assertEquals(
2048
            [
2049
                new SubtreeLimitation(
2050
                    array(
2051
                        'limitationValues' => array('/1/2/'),
2052
                    )
2053
                ),
2054
                new SubtreeLimitation(
2055
                    array(
2056
                        'limitationValues' => array('/1/43/'),
2057
                    )
2058
                ),
2059
            ],
2060
            $roleLimitations
2061
        );
2062
    }
2063
2064
    /**
2065
     * Test for the assignRoleToUser() method.
2066
     *
2067
     * @see \eZ\Publish\API\Repository\RoleService::assignRoleToUser($role, $user, $roleLimitation)
2068
     * @expectedException \eZ\Publish\API\Repository\Exceptions\LimitationValidationException
2069
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUser
2070
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleByIdentifier
2071
     */
2072
    public function testAssignRoleToUserWithRoleLimitationThrowsLimitationValidationException()
2073
    {
2074
        $repository = $this->getRepository();
2075
2076
        /* BEGIN: Use Case */
2077
        $roleService = $repository->getRoleService();
2078
2079
        // Load the existing "Anonymous" role
2080
        $role = $roleService->loadRoleByIdentifier('Anonymous');
2081
2082
        // Get current user
2083
        $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...
2084
2085
        // Assign the "Anonymous" role to the current user
2086
        // This call will fail with an LimitationValidationException, because subtree "/lorem/ipsum/42/"
2087
        // does not exists
2088
        $roleService->assignRoleToUser(
2089
            $role,
2090
            $currentUser,
2091
            new SubtreeLimitation(
2092
                array(
2093
                    'limitationValues' => array('/lorem/ipsum/42/'),
2094
                )
2095
            )
2096
        );
2097
        /* END: Use Case */
2098
    }
2099
2100
    /**
2101
     * Test for the assignRoleToUser() method.
2102
     *
2103
     * Makes sure assigning role several times throws.
2104
     *
2105
     * @see \eZ\Publish\API\Repository\RoleService::assignRoleToUser($role, $user, $roleLimitation)
2106
     * @expectedException \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException
2107
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUser
2108
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleByIdentifier
2109
     */
2110 View Code Duplication
    public function testAssignRoleToUserThrowsInvalidArgumentException()
2111
    {
2112
        $repository = $this->getRepository();
2113
2114
        /* BEGIN: Use Case */
2115
        $roleService = $repository->getRoleService();
2116
2117
        // Load the existing "Anonymous" role
2118
        $role = $roleService->loadRoleByIdentifier('Anonymous');
2119
2120
        // Get current user
2121
        $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...
2122
2123
        // Assign the "Anonymous" role to the current user
2124
        try {
2125
            $roleService->assignRoleToUser(
2126
                $role,
2127
                $currentUser
2128
            );
2129
        } catch (Exception $e) {
2130
            $this->fail('Got exception at first valid attempt to assign role');
2131
        }
2132
2133
        // Re-Assign the "Anonymous" role to the current user
2134
        // This call will fail with an InvalidArgumentException, because limitation is already assigned
2135
        $roleService->assignRoleToUser(
2136
            $role,
2137
            $currentUser
2138
        );
2139
        /* END: Use Case */
2140
    }
2141
2142
    /**
2143
     * Test for the assignRoleToUser() method.
2144
     *
2145
     * Makes sure assigning role several times with same limitations throws.
2146
     *
2147
     * @see \eZ\Publish\API\Repository\RoleService::assignRoleToUser($role, $user, $roleLimitation)
2148
     * @expectedException \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException
2149
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUser
2150
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleByIdentifier
2151
     */
2152
    public function testAssignRoleToUserWithRoleLimitationThrowsInvalidArgumentException()
2153
    {
2154
        $repository = $this->getRepository();
2155
2156
        /* BEGIN: Use Case */
2157
        $roleService = $repository->getRoleService();
2158
2159
        // Load the existing "Anonymous" role
2160
        $role = $roleService->loadRoleByIdentifier('Anonymous');
2161
2162
        // Get current user
2163
        $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...
2164
2165
        // Assign the "Anonymous" role to the current user
2166
        try {
2167
            $roleService->assignRoleToUser(
2168
                $role,
2169
                $currentUser,
2170
                new SubtreeLimitation(
2171
                    array(
2172
                        'limitationValues' => array('/1/43/', '/1/2/'),
2173
                    )
2174
                )
2175
            );
2176
        } catch (Exception $e) {
2177
            $this->fail('Got exception at first valid attempt to assign role');
2178
        }
2179
2180
        // Re-Assign the "Anonymous" role to the current user
2181
        // This call will fail with an InvalidArgumentException, because limitation is already assigned
2182
        $roleService->assignRoleToUser(
2183
            $role,
2184
            $currentUser,
2185
            new SubtreeLimitation(
2186
                array(
2187
                    'limitationValues' => array('/1/43/'),
2188
                )
2189
            )
2190
        );
2191
        /* END: Use Case */
2192
    }
2193
2194
    /**
2195
     * Test for the unassignRoleFromUser() method.
2196
     *
2197
     * @see \eZ\Publish\API\Repository\RoleService::unassignRoleFromUser()
2198
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUser
2199
     */
2200 View Code Duplication
    public function testUnassignRoleFromUser()
2201
    {
2202
        $repository = $this->getRepository();
2203
        $roleService = $repository->getRoleService();
2204
2205
        /* BEGIN: Use Case */
2206
        $user = $this->createUserVersion1();
2207
2208
        // Load the existing "Member" role
2209
        $role = $roleService->loadRoleByIdentifier('Member');
2210
2211
        // Assign the "Member" role to the newly created user
2212
        $roleService->assignRoleToUser($role, $user);
2213
2214
        // Unassign user from role
2215
        $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...
2216
2217
        // The assignments array will not contain the new role<->user assignment
2218
        $roleAssignments = $roleService->getRoleAssignments($role);
2219
        /* END: Use Case */
2220
2221
        // Members + Editors + Partners
2222
        $this->assertEquals(3, count($roleAssignments));
2223
    }
2224
2225
    /**
2226
     * Test for the unassignRoleFromUser() method.
2227
     *
2228
     * @see \eZ\Publish\API\Repository\RoleService::unassignRoleFromUser()
2229
     * @expectedException \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException
2230
     */
2231 View Code Duplication
    public function testUnassignRoleFromUserThrowsInvalidArgumentException()
2232
    {
2233
        $repository = $this->getRepository();
2234
        $roleService = $repository->getRoleService();
2235
2236
        /* BEGIN: Use Case */
2237
        $user = $this->createUserVersion1();
2238
2239
        // Load the existing "Member" role
2240
        $role = $roleService->loadRoleByIdentifier('Member');
2241
2242
        // This call will fail with a "InvalidArgumentException", because the
2243
        // user does not have the "Member" role.
2244
        $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...
2245
        /* END: Use Case */
2246
    }
2247
2248
    /**
2249
     * Test for the getRoleAssignmentsForUser() method.
2250
     *
2251
     * @see \eZ\Publish\API\Repository\RoleService::getRoleAssignmentsForUser()
2252
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUser
2253
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRoleWithAddPolicy
2254
     */
2255 View Code Duplication
    public function testGetRoleAssignmentsForUserDirect()
2256
    {
2257
        $repository = $this->getRepository();
2258
        $roleService = $repository->getRoleService();
2259
2260
        /* BEGIN: Use Case */
2261
        $user = $this->createUserVersion1();
2262
2263
        // Instantiate a role create and add some policies
2264
        $roleCreate = $roleService->newRoleCreateStruct('Example Role');
2265
2266
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
2267
        // $roleCreate->mainLanguageCode = 'eng-US';
2268
2269
        $roleCreate->addPolicy(
2270
            $roleService->newPolicyCreateStruct('user', 'login')
2271
        );
2272
        $roleCreate->addPolicy(
2273
            $roleService->newPolicyCreateStruct('content', 'read')
2274
        );
2275
        $roleCreate->addPolicy(
2276
            $roleService->newPolicyCreateStruct('content', 'edit')
2277
        );
2278
2279
        // Create the new role instance
2280
        $roleDraft = $roleService->createRole($roleCreate);
2281
        $roleService->publishRoleDraft($roleDraft);
2282
        $role = $roleService->loadRole($roleDraft->id);
2283
2284
        // Assign role to new user
2285
        $roleService->assignRoleToUser($role, $user);
2286
2287
        // Load the currently assigned role
2288
        $roleAssignments = $roleService->getRoleAssignmentsForUser($user);
2289
        /* END: Use Case */
2290
2291
        $this->assertEquals(1, count($roleAssignments));
2292
        $this->assertInstanceOf(
2293
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\UserRoleAssignment',
2294
            reset($roleAssignments)
2295
        );
2296
    }
2297
2298
    /**
2299
     * Test for the getRoleAssignmentsForUser() method.
2300
     *
2301
     * @see \eZ\Publish\API\Repository\RoleService::getRoleAssignmentsForUser()
2302
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUser
2303
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRoleWithAddPolicy
2304
     */
2305
    public function testGetRoleAssignmentsForUserEmpty()
2306
    {
2307
        $repository = $this->getRepository();
2308
        $roleService = $repository->getRoleService();
2309
2310
        /* BEGIN: Use Case */
2311
        $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...
2312
2313
        // Load the currently assigned role
2314
        $roleAssignments = $roleService->getRoleAssignmentsForUser($adminUser);
2315
        /* END: Use Case */
2316
2317
        $this->assertEquals(0, count($roleAssignments));
2318
    }
2319
2320
    /**
2321
     * Test for the getRoleAssignmentsForUser() method.
2322
     *
2323
     * @see \eZ\Publish\API\Repository\RoleService::getRoleAssignmentsForUser()
2324
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUser
2325
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRoleWithAddPolicy
2326
     */
2327
    public function testGetRoleAssignmentsForUserInherited()
2328
    {
2329
        $repository = $this->getRepository();
2330
        $roleService = $repository->getRoleService();
2331
2332
        /* BEGIN: Use Case */
2333
        $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...
2334
2335
        // Load the currently assigned role + inherited role assignments
2336
        $roleAssignments = $roleService->getRoleAssignmentsForUser($adminUser, true);
2337
        /* END: Use Case */
2338
2339
        $this->assertEquals(1, count($roleAssignments));
2340
        $this->assertInstanceOf(
2341
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\UserGroupRoleAssignment',
2342
            reset($roleAssignments)
2343
        );
2344
    }
2345
2346
    /**
2347
     * Test for the assignRoleToUserGroup() method.
2348
     *
2349
     * @see \eZ\Publish\API\Repository\RoleService::assignRoleToUserGroup()
2350
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testGetRoleAssignments
2351
     */
2352 View Code Duplication
    public function testAssignRoleToUserGroup()
2353
    {
2354
        $repository = $this->getRepository();
2355
        $roleService = $repository->getRoleService();
2356
2357
        /* BEGIN: Use Case */
2358
        $userGroup = $this->createUserGroupVersion1();
2359
2360
        // Load the existing "Administrator" role
2361
        $role = $roleService->loadRoleByIdentifier('Administrator');
2362
2363
        // Assign the "Administrator" role to the newly created user group
2364
        $roleService->assignRoleToUserGroup($role, $userGroup);
2365
2366
        // The assignments array will contain the new role<->group assignment
2367
        $roleAssignments = $roleService->getRoleAssignments($role);
2368
        /* END: Use Case */
2369
2370
        // Administrator + Example Group
2371
        $this->assertEquals(2, count($roleAssignments));
2372
    }
2373
2374
    /**
2375
     * Test for the assignRoleToUserGroup() method.
2376
     *
2377
     * Related issue: EZP-29113
2378
     *
2379
     * @covers \eZ\Publish\API\Repository\RoleService::assignRoleToUserGroup()
2380
     */
2381
    public function testAssignRoleToUserGroupAffectsRoleAssignmentsForUser()
2382
    {
2383
        $roleService = $this->getRepository()->getRoleService();
2384
2385
        /* BEGIN: Use Case */
2386
        $userGroup = $this->createUserGroupVersion1();
2387
        $user = $this->createUser('user', 'John', 'Doe', $userGroup);
2388
2389
        $initRoleAssignments = $roleService->getRoleAssignmentsForUser($user, true);
2390
2391
        // Load the existing "Administrator" role
2392
        $role = $roleService->loadRoleByIdentifier('Administrator');
2393
2394
        // Assign the "Administrator" role to the newly created user group
2395
        $roleService->assignRoleToUserGroup($role, $userGroup);
2396
2397
        $updatedRoleAssignments = $roleService->getRoleAssignmentsForUser($user, true);
2398
        /* END: Use Case */
2399
2400
        $this->assertEmpty($initRoleAssignments);
2401
        $this->assertEquals(1, count($updatedRoleAssignments));
2402
    }
2403
2404
    /**
2405
     * Test for the assignRoleToUserGroup() method.
2406
     *
2407
     * @see \eZ\Publish\API\Repository\RoleService::assignRoleToUserGroup($role, $userGroup, $roleLimitation)
2408
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUserGroup
2409
     */
2410 View Code Duplication
    public function testAssignRoleToUserGroupWithRoleLimitation()
2411
    {
2412
        $repository = $this->getRepository();
2413
        $roleService = $repository->getRoleService();
2414
2415
        /* BEGIN: Use Case */
2416
        $userGroup = $this->createUserGroupVersion1();
2417
2418
        // Load the existing "Anonymous" role
2419
        $role = $roleService->loadRoleByIdentifier('Anonymous');
2420
2421
        // Assign the "Anonymous" role to the newly created user group
2422
        $roleService->assignRoleToUserGroup(
2423
            $role,
2424
            $userGroup,
2425
            new SubtreeLimitation(
2426
                array(
2427
                    'limitationValues' => array('/1/43/'),
2428
                )
2429
            )
2430
        );
2431
2432
        // The assignments array will contain the new role<->group assignment
2433
        $roleAssignments = $roleService->getRoleAssignments($role);
2434
        /* END: Use Case */
2435
2436
        // Members + Partners + Anonymous + Example Group
2437
        $this->assertEquals(4, count($roleAssignments));
2438
2439
        // Get the role limitation
2440
        $roleLimitation = null;
2441
        foreach ($roleAssignments as $roleAssignment) {
2442
            $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...
2443
            if ($roleLimitation) {
2444
                break;
2445
            }
2446
        }
2447
2448
        $this->assertEquals(
2449
            new SubtreeLimitation(
2450
                array(
2451
                    'limitationValues' => array('/1/43/'),
2452
                )
2453
            ),
2454
            $roleLimitation
2455
        );
2456
2457
        // Test again to see values being merged
2458
        $roleService->assignRoleToUserGroup(
2459
            $role,
2460
            $userGroup,
2461
            new SubtreeLimitation(
2462
                array(
2463
                    'limitationValues' => array('/1/43/', '/1/2/'),
2464
                )
2465
            )
2466
        );
2467
2468
        // The assignments array will contain the new role<->user assignment
2469
        $roleAssignments = $roleService->getRoleAssignments($role);
2470
2471
        // Members + Partners + Anonymous + Example User
2472
        $this->assertEquals(5, count($roleAssignments));
2473
2474
        // Get the role limitation
2475
        $roleLimitations = [];
2476
        foreach ($roleAssignments as $roleAssignment) {
2477
            $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...
2478
            if ($roleLimitation) {
2479
                $this->assertInstanceOf(
2480
                    '\\eZ\\Publish\\API\\Repository\\Values\\User\\UserGroupRoleAssignment',
2481
                    $roleAssignment
2482
                );
2483
                $roleLimitations[] = $roleLimitation;
2484
            }
2485
        }
2486
        array_multisort($roleLimitations);
2487
2488
        $this->assertEquals(
2489
            [
2490
                new SubtreeLimitation(
2491
                    array(
2492
                        'limitationValues' => array('/1/2/'),
2493
                    )
2494
                ),
2495
                new SubtreeLimitation(
2496
                    array(
2497
                        'limitationValues' => array('/1/43/'),
2498
                    )
2499
                ),
2500
            ],
2501
            $roleLimitations
2502
        );
2503
    }
2504
2505
    /**
2506
     * Test for the assignRoleToUserGroup() method.
2507
     *
2508
     * @see \eZ\Publish\API\Repository\RoleService::assignRoleToUserGroup($role, $userGroup, $roleLimitation)
2509
     * @expectedException \eZ\Publish\API\Repository\Exceptions\LimitationValidationException
2510
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleByIdentifier
2511
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUserGroup
2512
     */
2513
    public function testAssignRoleToUserGroupWithRoleLimitationThrowsLimitationValidationException()
2514
    {
2515
        $repository = $this->getRepository();
2516
2517
        $mainGroupId = $this->generateId('group', 4);
2518
        /* BEGIN: Use Case */
2519
        // $mainGroupId is the ID of the main "Users" group
2520
2521
        $userService = $repository->getUserService();
2522
        $roleService = $repository->getRoleService();
2523
2524
        $userGroup = $userService->loadUserGroup($mainGroupId);
2525
2526
        // Load the existing "Anonymous" role
2527
        $role = $roleService->loadRoleByIdentifier('Anonymous');
2528
2529
        // Assign the "Anonymous" role to the newly created user group
2530
        // This call will fail with an LimitationValidationException, because subtree "/lorem/ipsum/42/"
2531
        // does not exists
2532
        $roleService->assignRoleToUserGroup(
2533
            $role,
2534
            $userGroup,
2535
            new SubtreeLimitation(
2536
                array(
2537
                    'limitationValues' => array('/lorem/ipsum/42/'),
2538
                )
2539
            )
2540
        );
2541
        /* END: Use Case */
2542
    }
2543
2544
    /**
2545
     * Test for the assignRoleToUserGroup() method.
2546
     *
2547
     * Makes sure assigning role several times throws.
2548
     *
2549
     * @see \eZ\Publish\API\Repository\RoleService::assignRoleToUserGroup($role, $userGroup, $roleLimitation)
2550
     * @expectedException \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException
2551
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleByIdentifier
2552
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUserGroup
2553
     */
2554
    public function testAssignRoleToUserGroupThrowsInvalidArgumentException()
2555
    {
2556
        $repository = $this->getRepository();
2557
2558
        $mainGroupId = $this->generateId('group', 4);
2559
        /* BEGIN: Use Case */
2560
        // $mainGroupId is the ID of the main "Users" group
2561
2562
        $userService = $repository->getUserService();
2563
        $roleService = $repository->getRoleService();
2564
2565
        $userGroup = $userService->loadUserGroup($mainGroupId);
2566
2567
        // Load the existing "Anonymous" role
2568
        $role = $roleService->loadRoleByIdentifier('Anonymous');
2569
2570
        // Assign the "Anonymous" role to the newly created user group
2571
        try {
2572
            $roleService->assignRoleToUserGroup(
2573
                $role,
2574
                $userGroup
2575
            );
2576
        } catch (Exception $e) {
2577
            $this->fail('Got exception at first valid attempt to assign role');
2578
        }
2579
2580
        // Re-Assign the "Anonymous" role to the newly created user group
2581
        // This call will fail with an InvalidArgumentException, because role is already assigned
2582
        $roleService->assignRoleToUserGroup(
2583
            $role,
2584
            $userGroup
2585
        );
2586
        /* END: Use Case */
2587
    }
2588
2589
    /**
2590
     * Test for the assignRoleToUserGroup() method.
2591
     *
2592
     * Makes sure assigning role several times with same limitations throws.
2593
     *
2594
     * @see \eZ\Publish\API\Repository\RoleService::assignRoleToUserGroup($role, $userGroup, $roleLimitation)
2595
     * @expectedException \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException
2596
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleByIdentifier
2597
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUserGroup
2598
     */
2599
    public function testAssignRoleToUserGroupWithRoleLimitationThrowsInvalidArgumentException()
2600
    {
2601
        $repository = $this->getRepository();
2602
2603
        $mainGroupId = $this->generateId('group', 4);
2604
        /* BEGIN: Use Case */
2605
        // $mainGroupId is the ID of the main "Users" group
2606
2607
        $userService = $repository->getUserService();
2608
        $roleService = $repository->getRoleService();
2609
2610
        $userGroup = $userService->loadUserGroup($mainGroupId);
2611
2612
        // Load the existing "Anonymous" role
2613
        $role = $roleService->loadRoleByIdentifier('Anonymous');
2614
2615
        // Assign the "Anonymous" role to the newly created user group
2616
        try {
2617
            $roleService->assignRoleToUserGroup(
2618
                $role,
2619
                $userGroup,
2620
                new SubtreeLimitation(
2621
                    array(
2622
                        'limitationValues' => array('/1/43/', '/1/2/'),
2623
                    )
2624
                )
2625
            );
2626
        } catch (Exception $e) {
2627
            $this->fail('Got exception at first valid attempt to assign role');
2628
        }
2629
2630
        // Re-Assign the "Anonymous" role to the newly created user group
2631
        // This call will fail with an InvalidArgumentException, because limitation is already assigned
2632
        $roleService->assignRoleToUserGroup(
2633
            $role,
2634
            $userGroup,
2635
            new SubtreeLimitation(
2636
                array(
2637
                    'limitationValues' => array('/1/43/'),
2638
                )
2639
            )
2640
        );
2641
        /* END: Use Case */
2642
    }
2643
2644
    /**
2645
     * Test for the unassignRoleFromUserGroup() method.
2646
     *
2647
     * @see \eZ\Publish\API\Repository\RoleService::unassignRoleFromUserGroup()
2648
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUserGroup
2649
     */
2650 View Code Duplication
    public function testUnassignRoleFromUserGroup()
2651
    {
2652
        $repository = $this->getRepository();
2653
        $roleService = $repository->getRoleService();
2654
2655
        /* BEGIN: Use Case */
2656
        $userGroup = $this->createUserGroupVersion1();
2657
2658
        // Load the existing "Member" role
2659
        $role = $roleService->loadRoleByIdentifier('Member');
2660
2661
        // Assign the "Member" role to the newly created user group
2662
        $roleService->assignRoleToUserGroup($role, $userGroup);
2663
2664
        // Unassign group from role
2665
        $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...
2666
2667
        // The assignments array will not contain the new role<->group assignment
2668
        $roleAssignments = $roleService->getRoleAssignments($role);
2669
        /* END: Use Case */
2670
2671
        // Members + Editors + Partners
2672
        $this->assertEquals(3, count($roleAssignments));
2673
    }
2674
2675
    /**
2676
     * Test for the unassignRoleFromUserGroup() method.
2677
     *
2678
     * @see \eZ\Publish\API\Repository\RoleService::unassignRoleFromUserGroup()
2679
     * @expectedException \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException
2680
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testUnassignRoleFromUserGroup
2681
     */
2682 View Code Duplication
    public function testUnassignRoleFromUserGroupThrowsInvalidArgumentException()
2683
    {
2684
        $repository = $this->getRepository();
2685
        $roleService = $repository->getRoleService();
2686
2687
        /* BEGIN: Use Case */
2688
        $userGroup = $this->createUserGroupVersion1();
2689
2690
        // Load the existing "Member" role
2691
        $role = $roleService->loadRoleByIdentifier('Member');
2692
2693
        // This call will fail with a "InvalidArgumentException", because the
2694
        // user group does not have the "Member" role.
2695
        $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...
2696
        /* END: Use Case */
2697
    }
2698
2699
    /**
2700
     * Test unassigning role by assignment.
2701
     *
2702
     * @covers \eZ\Publish\API\Repository\RoleService::removeRoleAssignment
2703
     */
2704
    public function testUnassignRoleByAssignment()
2705
    {
2706
        $repository = $this->getRepository();
2707
        $roleService = $repository->getRoleService();
2708
2709
        $role = $roleService->loadRole(2);
2710
        $user = $repository->getUserService()->loadUser(14);
2711
2712
        $originalAssignmentCount = count($roleService->getRoleAssignmentsForUser($user));
2713
2714
        $roleService->assignRoleToUser($role, $user);
2715
        $newAssignmentCount = count($roleService->getRoleAssignmentsForUser($user));
2716
        self::assertEquals($originalAssignmentCount + 1, $newAssignmentCount);
2717
2718
        $assignments = $roleService->getRoleAssignmentsForUser($user);
2719
        $roleService->removeRoleAssignment($assignments[0]);
2720
        $finalAssignmentCount = count($roleService->getRoleAssignmentsForUser($user));
2721
        self::assertEquals($newAssignmentCount - 1, $finalAssignmentCount);
2722
    }
2723
2724
    /**
2725
     * Test unassigning role by assignment.
2726
     *
2727
     * But on current admin user so he lacks access to read roles.
2728
     *
2729
     * @covers \eZ\Publish\API\Repository\RoleService::removeRoleAssignment
2730
     * @expectedException \eZ\Publish\API\Repository\Exceptions\UnauthorizedException
2731
     */
2732 View Code Duplication
    public function testUnassignRoleByAssignmentThrowsUnauthorizedException()
2733
    {
2734
        $repository = $this->getRepository();
2735
        $roleService = $repository->getRoleService();
2736
2737
        try {
2738
            $adminUserGroup = $repository->getUserService()->loadUserGroup(12);
2739
            $assignments = $roleService->getRoleAssignmentsForUserGroup($adminUserGroup);
2740
            $roleService->removeRoleAssignment($assignments[0]);
2741
        } catch (Exception $e) {
2742
            self::fail(
2743
                'Unexpected exception: ' . $e->getMessage() . " \n[" . $e->getFile() . ' (' . $e->getLine() . ')]'
2744
            );
2745
        }
2746
2747
        $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...
2748
    }
2749
2750
    /**
2751
     * Test unassigning role by non-existing assignment.
2752
     *
2753
     * @covers \eZ\Publish\API\Repository\RoleService::removeRoleAssignment
2754
     * @expectedException \eZ\Publish\API\Repository\Exceptions\NotFoundException
2755
     */
2756 View Code Duplication
    public function testUnassignRoleByAssignmentThrowsNotFoundException()
2757
    {
2758
        $repository = $this->getRepository();
2759
        $roleService = $repository->getRoleService();
2760
2761
        try {
2762
            $editorsUserGroup = $repository->getUserService()->loadUserGroup(13);
2763
            $assignments = $roleService->getRoleAssignmentsForUserGroup($editorsUserGroup);
2764
            $roleService->removeRoleAssignment($assignments[0]);
2765
        } catch (Exception $e) {
2766
            self::fail(
2767
                'Unexpected exception: ' . $e->getMessage() . " \n[" . $e->getFile() . ' (' . $e->getLine() . ')]'
2768
            );
2769
        }
2770
2771
        $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...
2772
    }
2773
2774
    /**
2775
     * Test for the getRoleAssignmentsForUserGroup() method.
2776
     *
2777
     * @see \eZ\Publish\API\Repository\RoleService::getRoleAssignmentsForUserGroup()
2778
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUserGroup
2779
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRoleWithAddPolicy
2780
     */
2781 View Code Duplication
    public function testGetRoleAssignmentsForUserGroup()
2782
    {
2783
        $repository = $this->getRepository();
2784
        $roleService = $repository->getRoleService();
2785
2786
        /* BEGIN: Use Case */
2787
        $userGroup = $this->createUserGroupVersion1();
2788
2789
        // Instantiate a role create and add some policies
2790
        $roleCreate = $roleService->newRoleCreateStruct('Example Role');
2791
2792
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
2793
        // $roleCreate->mainLanguageCode = 'eng-US';
2794
2795
        $roleCreate->addPolicy(
2796
            $roleService->newPolicyCreateStruct('user', 'login')
2797
        );
2798
        $roleCreate->addPolicy(
2799
            $roleService->newPolicyCreateStruct('content', 'read')
2800
        );
2801
        $roleCreate->addPolicy(
2802
            $roleService->newPolicyCreateStruct('content', 'edit')
2803
        );
2804
2805
        // Create the new role instance
2806
        $roleDraft = $roleService->createRole($roleCreate);
2807
        $roleService->publishRoleDraft($roleDraft);
2808
        $role = $roleService->loadRole($roleDraft->id);
2809
2810
        // Assign role to new user group
2811
        $roleService->assignRoleToUserGroup($role, $userGroup);
2812
2813
        // Load the currently assigned role
2814
        $roleAssignments = $roleService->getRoleAssignmentsForUserGroup($userGroup);
2815
        /* END: Use Case */
2816
2817
        $this->assertEquals(1, count($roleAssignments));
2818
        $this->assertInstanceOf(
2819
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\UserGroupRoleAssignment',
2820
            reset($roleAssignments)
2821
        );
2822
    }
2823
2824
    /**
2825
     * Test for the loadPoliciesByUserId() method.
2826
     *
2827
     * @see \eZ\Publish\API\Repository\RoleService::loadPoliciesByUserId()
2828
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUser
2829
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUserGroup
2830
     */
2831
    public function testLoadPoliciesByUserId()
2832
    {
2833
        $repository = $this->getRepository();
2834
2835
        $anonUserId = $this->generateId('user', 10);
2836
        /* BEGIN: Use Case */
2837
        // $anonUserId is the ID of the "Anonymous" user.
2838
2839
        $userService = $repository->getUserService();
2840
        $roleService = $repository->getRoleService();
2841
2842
        // Load "Anonymous" user
2843
        $user = $userService->loadUser($anonUserId);
2844
2845
        // Instantiate a role create and add some policies
2846
        $roleCreate = $roleService->newRoleCreateStruct('User Role');
2847
2848
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
2849
        // $roleCreate->mainLanguageCode = 'eng-US';
2850
2851
        $roleCreate->addPolicy(
2852
            $roleService->newPolicyCreateStruct('notification', 'use')
2853
        );
2854
        $roleCreate->addPolicy(
2855
            $roleService->newPolicyCreateStruct('user', 'password')
2856
        );
2857
        $roleCreate->addPolicy(
2858
            $roleService->newPolicyCreateStruct('user', 'selfedit')
2859
        );
2860
2861
        // Create the new role instance
2862
        $roleDraft = $roleService->createRole($roleCreate);
2863
        $roleService->publishRoleDraft($roleDraft);
2864
        $role = $roleService->loadRole($roleDraft->id);
2865
2866
        // Assign role to anon user
2867
        $roleService->assignRoleToUser($role, $user);
2868
2869
        // Load the currently assigned role
2870
        $policies = array();
2871
        foreach ($roleService->loadPoliciesByUserId($user->id) as $policy) {
0 ignored issues
show
Deprecated Code introduced by
The method eZ\Publish\API\Repositor...:loadPoliciesByUserId() has been deprecated with message: Since 6.8, not currently in use as permission system needs to know about role assignment limitations.

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...
2872
            $policies[] = array($policy->roleId, $policy->module, $policy->function);
2873
        }
2874
        /* END: Use Case */
2875
        array_multisort($policies);
2876
2877
        $this->assertEquals(
2878
            array(
2879
                array(1, 'content', 'pdf'),
2880
                array(1, 'content', 'read'),
2881
                array(1, 'content', 'read'),
2882
                array(1, 'rss', 'feed'),
2883
                array(1, 'user', 'login'),
2884
                array(1, 'user', 'login'),
2885
                array(1, 'user', 'login'),
2886
                array(1, 'user', 'login'),
2887
                array($role->id, 'notification', 'use'),
2888
                array($role->id, 'user', 'password'),
2889
                array($role->id, 'user', 'selfedit'),
2890
            ),
2891
            $policies
2892
        );
2893
    }
2894
2895
    /**
2896
     * Test for the loadPoliciesByUserId() method.
2897
     *
2898
     * @see \eZ\Publish\API\Repository\RoleService::loadPoliciesByUserId()
2899
     * @expectedException \eZ\Publish\API\Repository\Exceptions\NotFoundException
2900
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadPoliciesByUserId
2901
     */
2902
    public function testLoadPoliciesByUserIdThrowsNotFoundException()
2903
    {
2904
        $repository = $this->getRepository();
2905
2906
        $nonExistingUserId = $this->generateId('user', self::DB_INT_MAX);
2907
        /* BEGIN: Use Case */
2908
        $roleService = $repository->getRoleService();
2909
2910
        // This call will fail with a "NotFoundException", because hopefully no
2911
        // user with an ID equal to self::DB_INT_MAX exists.
2912
        $roleService->loadPoliciesByUserId($nonExistingUserId);
0 ignored issues
show
Deprecated Code introduced by
The method eZ\Publish\API\Repositor...:loadPoliciesByUserId() has been deprecated with message: Since 6.8, not currently in use as permission system needs to know about role assignment limitations.

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...
2913
        /* END: Use Case */
2914
    }
2915
2916
    /**
2917
     * Test for the publishRoleDraft() method.
2918
     *
2919
     * @see \eZ\Publish\API\Repository\RoleService::publishRoleDraft()
2920
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRoleDraft
2921
     */
2922 View Code Duplication
    public function testPublishRoleDraft()
2923
    {
2924
        $repository = $this->getRepository();
2925
2926
        /* BEGIN: Use Case */
2927
        $roleService = $repository->getRoleService();
2928
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
2929
2930
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
2931
        // $roleCreate->mainLanguageCode = 'eng-US';
2932
2933
        $roleDraft = $roleService->createRole($roleCreate);
2934
2935
        $roleDraft = $roleService->addPolicyByRoleDraft(
2936
            $roleDraft,
2937
            $roleService->newPolicyCreateStruct('content', 'delete')
2938
        );
2939
        $roleDraft = $roleService->addPolicyByRoleDraft(
2940
            $roleDraft,
2941
            $roleService->newPolicyCreateStruct('content', 'create')
2942
        );
2943
2944
        $roleService->publishRoleDraft($roleDraft);
2945
        /* END: Use Case */
2946
2947
        $this->assertInstanceOf(
2948
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\Role',
2949
            $roleService->loadRoleByIdentifier($roleCreate->identifier)
2950
        );
2951
    }
2952
2953
    /**
2954
     * Test for the publishRoleDraft() method.
2955
     *
2956
     * @see \eZ\Publish\API\Repository\RoleService::publishRoleDraft()
2957
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRoleDraft
2958
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicyByRoleDraft
2959
     */
2960 View Code Duplication
    public function testPublishRoleDraftAddPolicies()
2961
    {
2962
        $repository = $this->getRepository();
2963
2964
        /* BEGIN: Use Case */
2965
        $roleService = $repository->getRoleService();
2966
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
2967
2968
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
2969
        // $roleCreate->mainLanguageCode = 'eng-US';
2970
2971
        $roleDraft = $roleService->createRole($roleCreate);
2972
2973
        $roleDraft = $roleService->addPolicyByRoleDraft(
2974
            $roleDraft,
2975
            $roleService->newPolicyCreateStruct('content', 'delete')
2976
        );
2977
        $roleDraft = $roleService->addPolicyByRoleDraft(
2978
            $roleDraft,
2979
            $roleService->newPolicyCreateStruct('content', 'create')
2980
        );
2981
2982
        $roleService->publishRoleDraft($roleDraft);
2983
        $role = $roleService->loadRoleByIdentifier($roleCreate->identifier);
2984
        /* END: Use Case */
2985
2986
        $actual = array();
2987
        foreach ($role->getPolicies() as $policy) {
2988
            $actual[] = array(
2989
                'module' => $policy->module,
2990
                'function' => $policy->function,
2991
            );
2992
        }
2993
        usort(
2994
            $actual,
2995
            function ($p1, $p2) {
2996
                return strcasecmp($p1['function'], $p2['function']);
2997
            }
2998
        );
2999
3000
        $this->assertEquals(
3001
            array(
3002
                array(
3003
                    'module' => 'content',
3004
                    'function' => 'create',
3005
                ),
3006
                array(
3007
                    'module' => 'content',
3008
                    'function' => 'delete',
3009
                ),
3010
            ),
3011
            $actual
3012
        );
3013
    }
3014
3015
    /**
3016
     * Create a user group fixture in a variable named <b>$userGroup</b>,.
3017
     *
3018
     * @return \eZ\Publish\API\Repository\Values\User\UserGroup
3019
     */
3020
    private function createUserGroupVersion1()
3021
    {
3022
        $repository = $this->getRepository();
3023
3024
        $mainGroupId = $this->generateId('group', 4);
3025
        /* BEGIN: Inline */
3026
        // $mainGroupId is the ID of the main "Users" group
3027
3028
        $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...
3029
        $userService = $repository->getUserService();
3030
3031
        // Load main group
3032
        $parentUserGroup = $userService->loadUserGroup($mainGroupId);
3033
3034
        // Instantiate a new create struct
3035
        $userGroupCreate = $userService->newUserGroupCreateStruct('eng-US');
3036
        $userGroupCreate->setField('name', 'Example Group');
3037
3038
        // Create the new user group
3039
        $userGroup = $userService->createUserGroup(
3040
            $userGroupCreate,
3041
            $parentUserGroup
3042
        );
3043
        /* END: Inline */
3044
3045
        return $userGroup;
3046
    }
3047
}
3048