Completed
Push — ezp29559_uncomment_sleeping_ro... ( d4e21c...4bba8d )
by
unknown
18:28
created

RoleServiceTest   F

Complexity

Total Complexity 125

Size/Duplication

Total Lines 2914
Duplicated Lines 33.87 %

Coupling/Cohesion

Components 1
Dependencies 17

Importance

Changes 0
Metric Value
dl 987
loc 2914
rs 0.8
c 0
b 0
f 0
wmc 125
lcom 1
cbo 17

80 Methods

Rating   Name   Duplication   Size   Complexity  
A testNewRoleCreateStruct() 0 9 1
A testNewRoleCreateStructSetsNamePropertyOnStruct() 0 13 1
A testCreateRole() 0 26 1
A testRoleCreateStructValues() 0 19 1
A testCreateRoleWithPolicy() 0 40 1
A testRoleCreateStructValuesWithPolicy() 0 23 1
A testCreateRoleDraft() 24 24 1
A testCreateRoleThrowsInvalidArgumentException() 0 17 1
A 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 testPublishEmptyRoleThrowsInvalidArgumentException() 17 17 1
A testAddPolicyThrowsLimitationValidationException() 0 37 1
A testAddPolicyByRoleDraftThrowsLimitationValidationException() 30 30 1
A testCreateRoleWithAddPolicy() 3 53 2
A testCreateRoleDraftWithAddPolicy() 3 50 2
A testNewPolicyUpdateStruct() 0 14 1
A testUpdatePolicyNoLimitation() 0 45 4
B testUpdatePolicy() 0 61 4
A testUpdatePolicyUpdatesLimitations() 0 17 1
A testUpdatePolicyUpdatesRole() 0 23 3
B testUpdatePolicyThrowsLimitationValidationException() 0 55 4
A testRemovePolicy() 34 34 2
A testRemovePolicyByRoleDraft() 32 32 2
A testDeletePolicy() 35 35 2
A testLoadRoleAssignment() 0 42 1
A testGetRoleAssignments() 0 27 1
A testGetRoleAssignmentsContainExpectedLimitation() 0 7 1
A testAssignRoleToUser() 21 21 1
B testAssignRoleToUserWithRoleLimitation() 98 98 5
A testAssignRoleToUserWithRoleLimitationThrowsLimitationValidationException() 0 27 1
A testAssignRoleToUserThrowsInvalidArgumentException() 31 31 2
A testAssignRoleToUserWithRoleLimitationThrowsInvalidArgumentException() 0 41 2
A testUnassignRoleFromUser() 24 24 1
A testUnassignRoleFromUserThrowsInvalidArgumentException() 16 16 1
A testGetRoleAssignmentsForUserDirect() 42 42 1
A testGetRoleAssignmentsForUserEmpty() 0 14 1
A testGetRoleAssignmentsForUserInherited() 0 18 1
A testAssignRoleToUserGroup() 21 21 1
B testAssignRoleToUserGroupWithRoleLimitation() 94 94 5
A testAssignRoleToUserGroupWithRoleLimitationThrowsLimitationValidationException() 0 30 1
A testAssignRoleToUserGroupThrowsInvalidArgumentException() 0 34 2
A testAssignRoleToUserGroupWithRoleLimitationThrowsInvalidArgumentException() 0 44 2
A testUnassignRoleFromUserGroup() 24 24 1
A testUnassignRoleFromUserGroupThrowsInvalidArgumentException() 16 16 1
A testUnassignRoleByAssignment() 0 19 1
A testUnassignRoleByAssignmentThrowsUnauthorizedException() 17 17 2
A testUnassignRoleByAssignmentThrowsNotFoundException() 17 17 2
A testGetRoleAssignmentsForUserGroup() 42 42 1
B testLoadPoliciesByUserId() 0 63 2
A testLoadPoliciesByUserIdThrowsNotFoundException() 0 13 1
A testPublishRoleDraft() 30 30 1
A testPublishRoleDraftAddPolicies() 54 54 2
A createUserGroupVersion1() 0 27 1

How to fix   Duplicated Code    Complexity   

Duplicated Code

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

Common duplication problems, and corresponding solutions are:

Complex Class

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

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

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

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

1
<?php
2
3
/**
4
 * File containing the RoleServiceTest class.
5
 *
6
 * @copyright Copyright (C) eZ Systems AS. All rights reserved.
7
 * @license For full copyright and license information view LICENSE file distributed with this source code.
8
 */
9
namespace eZ\Publish\API\Repository\Tests;
10
11
use eZ\Publish\API\Repository\Values\User\Limitation\ContentTypeLimitation;
12
use eZ\Publish\API\Repository\Values\User\Limitation\LanguageLimitation;
13
use eZ\Publish\API\Repository\Values\User\Limitation\SubtreeLimitation;
14
use eZ\Publish\API\Repository\Exceptions\NotFoundException;
15
use Exception;
16
17
/**
18
 * Test case for operations in the RoleService using in memory storage.
19
 *
20
 * The following IDs from the default eZ community edition database are used in
21
 * this test:
22
 *
23
 * <ul>
24
 *   <li>
25
 *     ContentType
26
 *     <ul>
27
 *       <li><strong>28</strong>: File</li>
28
 *       <li><strong>29</strong>: Flash</li>
29
 *       <li><strong>30</strong>: Image</li>
30
 *     </ul>
31
 *   </li>
32
 * <ul>
33
 *
34
 * @see eZ\Publish\API\Repository\RoleService
35
 * @group role
36
 */
37
class RoleServiceTest extends BaseTest
38
{
39
    /**
40
     * Test for the newRoleCreateStruct() method.
41
     *
42
     * @see \eZ\Publish\API\Repository\RoleService::newRoleCreateStruct()
43
     */
44
    public function testNewRoleCreateStruct()
45
    {
46
        $repository = $this->getRepository();
47
48
        $roleService = $repository->getRoleService();
49
        $roleCreate = $roleService->newRoleCreateStruct('roleName');
50
51
        $this->assertInstanceOf('\\eZ\\Publish\\API\\Repository\\Values\\User\\RoleCreateStruct', $roleCreate);
52
    }
53
54
    /**
55
     * Test for the newRoleCreateStruct() method.
56
     *
57
     * @see \eZ\Publish\API\Repository\RoleService::newRoleCreateStruct()
58
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewRoleCreateStruct
59
     */
60
    public function testNewRoleCreateStructSetsNamePropertyOnStruct()
61
    {
62
        $repository = $this->getRepository();
63
64
        /* BEGIN: Use Case */
65
66
        $roleService = $repository->getRoleService();
67
        $roleCreate = $roleService->newRoleCreateStruct('roleName');
68
69
        /* END: Use Case */
70
71
        $this->assertEquals('roleName', $roleCreate->identifier);
72
    }
73
74
    /**
75
     * Test for the createRole() method.
76
     *
77
     * @see \eZ\Publish\API\Repository\RoleService::createRole()
78
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewRoleCreateStruct
79
     */
80
    public function testCreateRole()
81
    {
82
        $repository = $this->getRepository();
83
84
        /* BEGIN: Use Case */
85
86
        $roleService = $repository->getRoleService();
87
        $roleCreate = $roleService->newRoleCreateStruct('roleName');
88
89
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
90
        // $roleCreate->mainLanguageCode = 'eng-US';
91
92
        $role = $roleService->createRole($roleCreate);
93
94
        /* END: Use Case */
95
96
        $this->assertInstanceOf(
97
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\RoleDraft',
98
            $role
99
        );
100
101
        return [
102
            'createStruct' => $roleCreate,
103
            'role' => $role,
104
        ];
105
    }
106
107
    /**
108
     * Test for the createRole() method.
109
     *
110
     * @see \eZ\Publish\API\Repository\RoleService::createRole()
111
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRole
112
     */
113
    public function testRoleCreateStructValues(array $data)
114
    {
115
        $createStruct = $data['createStruct'];
116
        $role = $data['role'];
117
118
        $this->assertEquals(
119
            [
120
                'identifier' => $createStruct->identifier,
121
                'policies' => $createStruct->policies,
122
            ],
123
            [
124
                'identifier' => $role->identifier,
125
                'policies' => $role->policies,
126
            ]
127
        );
128
        $this->assertNotNull($role->id);
129
130
        return $data;
131
    }
132
133
    /**
134
     * Test for the createRole() method.
135
     *
136
     * @see \eZ\Publish\API\Repository\RoleService::createRole()
137
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewRoleCreateStruct
138
     */
139
    public function testCreateRoleWithPolicy()
140
    {
141
        $repository = $this->getRepository();
142
143
        /* BEGIN: Use Case */
144
145
        $roleService = $repository->getRoleService();
146
        $roleCreate = $roleService->newRoleCreateStruct('roleName');
147
148
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
149
        // $roleCreate->mainLanguageCode = 'eng-US';
150
151
        // Create new subtree limitation
152
        $limitation = new SubtreeLimitation(
153
            array(
154
                'limitationValues' => array('/1/2/'),
155
            )
156
        );
157
158
        // Create policy create struct and add limitation to it
159
        $policyCreate = $roleService->newPolicyCreateStruct('content', 'read');
160
        $policyCreate->addLimitation($limitation);
161
162
        // Add policy create struct to role create struct
163
        $roleCreate->addPolicy($policyCreate);
164
165
        $role = $roleService->createRole($roleCreate);
166
167
        /* END: Use Case */
168
169
        $this->assertInstanceOf(
170
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\RoleDraft',
171
            $role
172
        );
173
174
        return [
175
            'createStruct' => $roleCreate,
176
            'role' => $role,
177
        ];
178
    }
179
180
    /**
181
     * Test for the createRole() method.
182
     *
183
     * @see \eZ\Publish\API\Repository\RoleService::createRole()
184
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRoleWithPolicy
185
     */
186
    public function testRoleCreateStructValuesWithPolicy(array $data)
187
    {
188
        $createStruct = $data['createStruct'];
189
        $role = $data['role'];
190
191
        $this->assertEquals(
192
            [
193
                'identifier' => $createStruct->identifier,
194
                'policy_module' => $createStruct->policies[0]->module,
195
                'policy_function' => $createStruct->policies[0]->function,
196
                'policy_limitation' => array_values($createStruct->policies[0]->limitations),
197
            ],
198
            [
199
                'identifier' => $role->identifier,
200
                'policy_module' => $role->policies[0]->module,
201
                'policy_function' => $role->policies[0]->function,
202
                'policy_limitation' => array_values($role->policies[0]->limitations),
203
            ]
204
        );
205
        $this->assertNotNull($role->id);
206
207
        return $data;
208
    }
209
210
    /**
211
     * Test for the createRoleDraft() method.
212
     *
213
     * @see \eZ\Publish\API\Repository\RoleService::createRoleDraft()
214
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewRoleCreateStruct
215
     */
216 View Code Duplication
    public function testCreateRoleDraft()
217
    {
218
        $repository = $this->getRepository();
219
220
        /* BEGIN: Use Case */
221
222
        $roleService = $repository->getRoleService();
223
        $roleCreate = $roleService->newRoleCreateStruct('roleName');
224
225
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
226
        // $roleCreate->mainLanguageCode = 'eng-US';
227
228
        $roleDraft = $roleService->createRole($roleCreate);
229
        $roleService->publishRoleDraft($roleDraft);
230
        $role = $roleService->loadRole($roleDraft->id);
231
        $newRoleDraft = $roleService->createRoleDraft($role);
232
233
        /* END: Use Case */
234
235
        $this->assertInstanceOf(
236
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\RoleDraft',
237
            $newRoleDraft
238
        );
239
    }
240
241
    /**
242
     * Test for the createRole() method.
243
     *
244
     * @see \eZ\Publish\API\Repository\RoleService::createRole()
245
     * @expectedException \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException
246
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRole
247
     */
248
    public function testCreateRoleThrowsInvalidArgumentException()
249
    {
250
        $repository = $this->getRepository();
251
252
        /* BEGIN: Use Case */
253
254
        $roleService = $repository->getRoleService();
255
        $roleCreate = $roleService->newRoleCreateStruct('Editor');
256
257
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
258
        // $roleCreate->mainLanguageCode = 'eng-US';
259
260
        // This call will fail with an InvalidArgumentException, because Editor exists
261
        $roleService->createRole($roleCreate);
262
263
        /* END: Use Case */
264
    }
265
266
    /**
267
     * Test for the createRoleDraft() method.
268
     *
269
     * @see \eZ\Publish\API\Repository\RoleService::createRoleDraft()
270
     * @expectedException \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException
271
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRoleDraft
272
     */
273 View Code Duplication
    public function testCreateRoleDraftThrowsInvalidArgumentException()
274
    {
275
        $repository = $this->getRepository();
276
277
        /* BEGIN: Use Case */
278
279
        $roleService = $repository->getRoleService();
280
        $roleCreate = $roleService->newRoleCreateStruct('Editor');
281
282
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
283
        // $roleCreate->mainLanguageCode = 'eng-US';
284
285
        $roleDraft = $roleService->createRole($roleCreate);
286
        $roleService->publishRoleDraft($roleDraft);
287
        $role = $roleService->loadRole($roleDraft->id);
288
        $roleService->createRoleDraft($role); // First role draft
289
290
        // This call will fail with an InvalidArgumentException, because there is already a draft
291
        $roleService->createRoleDraft($role);
292
293
        /* END: Use Case */
294
    }
295
296
    /**
297
     * Test for the createRole() method.
298
     *
299
     * @see \eZ\Publish\API\Repository\RoleService::createRole()
300
     * @expectedException \eZ\Publish\API\Repository\Exceptions\LimitationValidationException
301
     */
302 View Code Duplication
    public function testCreateRoleThrowsLimitationValidationException()
303
    {
304
        $repository = $this->getRepository();
305
306
        /* BEGIN: Use Case */
307
        $roleService = $repository->getRoleService();
308
309
        // Create new role create struct
310
        $roleCreate = $roleService->newRoleCreateStruct('Lumberjack');
311
312
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
313
        // $roleCreate->mainLanguageCode = 'eng-US';
314
315
        // Create new subtree limitation
316
        $limitation = new SubtreeLimitation(
317
            array(
318
                'limitationValues' => array('/mountain/forest/tree/42/'),
319
            )
320
        );
321
322
        // Create policy create struct and add limitation to it
323
        $policyCreate = $roleService->newPolicyCreateStruct('content', 'remove');
324
        $policyCreate->addLimitation($limitation);
325
326
        // Add policy create struct to role create struct
327
        $roleCreate->addPolicy($policyCreate);
328
329
        // This call will fail with an LimitationValidationException, because subtree
330
        // "/mountain/forest/tree/42/" does not exist
331
        $roleService->createRole($roleCreate);
332
        /* END: Use Case */
333
    }
334
335
    /**
336
     * Test for the createRole() method.
337
     *
338
     * @see \eZ\Publish\API\Repository\RoleService::createRole()
339
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewRoleCreateStruct
340
     */
341
    public function testCreateRoleInTransactionWithRollback()
342
    {
343
        $repository = $this->getRepository();
344
345
        /* BEGIN: Use Case */
346
347
        $roleService = $repository->getRoleService();
348
349
        $repository->beginTransaction();
350
351
        $roleCreate = $roleService->newRoleCreateStruct('roleName');
352
353
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
354
        // $roleCreate->mainLanguageCode = 'eng-US';
355
356
        $createdRoleId = $roleService->createRole($roleCreate)->id;
357
358
        $repository->rollback();
359
360
        try {
361
            // This call will fail with a "NotFoundException"
362
            $role = $roleService->loadRole($createdRoleId);
0 ignored issues
show
Unused Code introduced by
$role is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
363
        } catch (NotFoundException $e) {
364
            return;
365
        }
366
        /* END: Use Case */
367
368
        $this->fail('Role object still exists after rollback.');
369
    }
370
371
    /**
372
     * Test for the createRoleDraft() method.
373
     *
374
     * @see \eZ\Publish\API\Repository\RoleService::createRoleDraft()
375
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewRoleCreateStruct
376
     */
377
    public function testCreateRoleDraftInTransactionWithRollback()
378
    {
379
        $repository = $this->getRepository();
380
381
        /* BEGIN: Use Case */
382
383
        $roleService = $repository->getRoleService();
384
385
        $repository->beginTransaction();
386
387
        $roleCreate = $roleService->newRoleCreateStruct('roleName');
388
389
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
390
        // $roleCreate->mainLanguageCode = 'eng-US';
391
392
        $createdRoleId = $roleService->createRole($roleCreate)->id;
393
394
        $repository->rollback();
395
396
        try {
397
            // This call will fail with a "NotFoundException"
398
            $role = $roleService->loadRoleDraft($createdRoleId);
0 ignored issues
show
Unused Code introduced by
$role is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
399
        } catch (NotFoundException $e) {
400
            return;
401
        }
402
        /* END: Use Case */
403
404
        $this->fail('Role draft object still exists after rollback.');
405
    }
406
407
    /**
408
     * Test for the loadRole() method.
409
     *
410
     * @see \eZ\Publish\API\Repository\RoleService::loadRole()
411
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRole
412
     */
413
    public function testLoadRole()
414
    {
415
        $repository = $this->getRepository();
416
417
        /* BEGIN: Use Case */
418
419
        $roleService = $repository->getRoleService();
420
        $roleCreate = $roleService->newRoleCreateStruct('roleName');
421
422
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
423
        // $roleCreate->mainLanguageCode = 'eng-US';
424
425
        $roleDraft = $roleService->createRole($roleCreate);
426
        $roleService->publishRoleDraft($roleDraft);
427
428
        // Load the newly created role by its ID
429
        $role = $roleService->loadRole($roleDraft->id);
430
431
        /* END: Use Case */
432
433
        $this->assertEquals('roleName', $role->identifier);
434
    }
435
436
    /**
437
     * Test for the loadRoleDraft() method.
438
     *
439
     * @see \eZ\Publish\API\Repository\RoleService::loadRoleDraft()
440
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRoleDraft
441
     */
442
    public function testLoadRoleDraft()
443
    {
444
        $repository = $this->getRepository();
445
446
        /* BEGIN: Use Case */
447
448
        $roleService = $repository->getRoleService();
449
        $roleCreate = $roleService->newRoleCreateStruct('roleName');
450
451
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
452
        // $roleCreate->mainLanguageCode = 'eng-US';
453
454
        $roleDraft = $roleService->createRole($roleCreate);
455
456
        // Load the newly created role by its ID
457
        $role = $roleService->loadRoleDraft($roleDraft->id);
458
459
        /* END: Use Case */
460
461
        $this->assertEquals('roleName', $role->identifier);
462
    }
463
464
    public function testLoadRoleDraftByRoleId()
465
    {
466
        $repository = $this->getRepository();
467
468
        /* BEGIN: Use Case */
469
470
        $roleService = $repository->getRoleService();
471
        $roleCreate = $roleService->newRoleCreateStruct('roleName');
472
473
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
474
        // $roleCreate->mainLanguageCode = 'eng-US';
475
476
        $role = $roleService->createRole($roleCreate);
477
        $roleService->publishRoleDraft($role);
478
479
        // Now create a new draft based on the role
480
        $newDraft = $roleService->createRoleDraft($role);
481
        $loadedRoleDraft = $roleService->loadRoleDraftByRoleId($role->id);
482
483
        /* END: Use Case */
484
485
        self::assertEquals('roleName', $role->identifier);
486
        self::assertInstanceOf('eZ\Publish\API\Repository\Values\User\RoleDraft', $loadedRoleDraft);
487
        self::assertEquals($newDraft, $loadedRoleDraft);
488
    }
489
490
    /**
491
     * Test for the loadRole() method.
492
     *
493
     * @see \eZ\Publish\API\Repository\RoleService::loadRole()
494
     * @expectedException \eZ\Publish\API\Repository\Exceptions\NotFoundException
495
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRole
496
     */
497 View Code Duplication
    public function testLoadRoleThrowsNotFoundException()
498
    {
499
        $repository = $this->getRepository();
500
501
        $nonExistingRoleId = $this->generateId('role', self::DB_INT_MAX);
502
        /* BEGIN: Use Case */
503
504
        $roleService = $repository->getRoleService();
505
506
        // This call will fail with a NotFoundException, because no such role exists.
507
        $roleService->loadRole($nonExistingRoleId);
508
509
        /* END: Use Case */
510
    }
511
512
    /**
513
     * Test for the loadRoleDraft() method.
514
     *
515
     * @see \eZ\Publish\API\Repository\RoleService::loadRoleDraft()
516
     * @expectedException \eZ\Publish\API\Repository\Exceptions\NotFoundException
517
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleDraft
518
     */
519 View Code Duplication
    public function testLoadRoleDraftThrowsNotFoundException()
520
    {
521
        $repository = $this->getRepository();
522
523
        $nonExistingRoleId = $this->generateId('role', self::DB_INT_MAX);
524
        /* BEGIN: Use Case */
525
526
        $roleService = $repository->getRoleService();
527
528
        // This call will fail with a NotFoundException, because no such role exists.
529
        $roleService->loadRoleDraft($nonExistingRoleId);
530
531
        /* END: Use Case */
532
    }
533
534
    /**
535
     * @expectedException \eZ\Publish\API\Repository\Exceptions\NotFoundException
536
     */
537 View Code Duplication
    public function testLoadRoleDraftByRoleIdThrowsNotFoundException()
538
    {
539
        $repository = $this->getRepository();
540
541
        $nonExistingRoleId = $this->generateId('role', self::DB_INT_MAX);
542
        /* BEGIN: Use Case */
543
544
        $roleService = $repository->getRoleService();
545
546
        // This call will fail with a NotFoundException, because no such role exists.
547
        $roleService->loadRoleDraftByRoleId($nonExistingRoleId);
548
549
        /* END: Use Case */
550
    }
551
552
    /**
553
     * Test for the loadRoleByIdentifier() method.
554
     *
555
     * @see \eZ\Publish\API\Repository\RoleService::loadRoleByIdentifier()
556
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRole
557
     */
558 View Code Duplication
    public function testLoadRoleByIdentifier()
559
    {
560
        $repository = $this->getRepository();
561
562
        /* BEGIN: Use Case */
563
564
        $roleService = $repository->getRoleService();
565
        $roleCreate = $roleService->newRoleCreateStruct('roleName');
566
567
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
568
        // $roleCreate->mainLanguageCode = 'eng-US';
569
570
        $roleDraft = $roleService->createRole($roleCreate);
571
        $roleService->publishRoleDraft($roleDraft);
572
573
        // Load the newly created role by its identifier
574
        $role = $roleService->loadRoleByIdentifier('roleName');
575
576
        /* END: Use Case */
577
578
        $this->assertEquals('roleName', $role->identifier);
579
    }
580
581
    /**
582
     * Test for the loadRoleByIdentifier() method.
583
     *
584
     * @see \eZ\Publish\API\Repository\RoleService::loadRoleByIdentifier()
585
     * @expectedException \eZ\Publish\API\Repository\Exceptions\NotFoundException
586
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleByIdentifier
587
     */
588
    public function testLoadRoleByIdentifierThrowsNotFoundException()
589
    {
590
        $repository = $this->getRepository();
591
592
        /* BEGIN: Use Case */
593
594
        $roleService = $repository->getRoleService();
595
596
        // This call will fail with a NotFoundException, because no such role exists.
597
        $roleService->loadRoleByIdentifier('MissingRole');
598
599
        /* END: Use Case */
600
    }
601
602
    /**
603
     * Test for the loadRoles() method.
604
     *
605
     * @see \eZ\Publish\API\Repository\RoleService::loadRoles()
606
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRole
607
     */
608
    public function testLoadRoles()
609
    {
610
        $repository = $this->getRepository();
611
612
        /* BEGIN: Use Case */
613
614
        // First create a custom role
615
        $roleService = $repository->getRoleService();
616
        $roleCreate = $roleService->newRoleCreateStruct('roleName');
617
618
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
619
        // $roleCreate->mainLanguageCode = 'eng-US';
620
621
        $roleDraft = $roleService->createRole($roleCreate);
622
        $roleService->publishRoleDraft($roleDraft);
623
624
        // Now load all available roles
625
        $roles = $roleService->loadRoles();
626
627
        foreach ($roles as $role) {
628
            if ($role->identifier === 'roleName') {
629
                break;
630
            }
631
        }
632
633
        /* END: Use Case */
634
635
        $this->assertEquals('roleName', $role->identifier);
0 ignored issues
show
Bug introduced by
The variable $role seems to be defined by a foreach iteration on line 627. Are you sure the iterator is never empty, otherwise this variable is not defined?

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

foreach ($a as $b) {
}

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


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

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

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

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

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

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

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

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

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

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

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

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

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

Loading history...
935
            $role,
936
            $roleService->newPolicyCreateStruct('content', 'create')
937
        );
938
        /* END: Use Case */
939
940
        $actual = array();
941
        foreach ($role->getPolicies() as $policy) {
942
            $actual[] = array(
943
                'module' => $policy->module,
944
                'function' => $policy->function,
945
            );
946
        }
947
        usort(
948
            $actual,
949
            function ($p1, $p2) {
950
                return strcasecmp($p1['function'], $p2['function']);
951
            }
952
        );
953
954
        $this->assertEquals(
955
            array(
956
                array(
957
                    'module' => 'content',
958
                    'function' => 'create',
959
                ),
960
                array(
961
                    'module' => 'content',
962
                    'function' => 'delete',
963
                ),
964
            ),
965
            $actual
966
        );
967
    }
968
969
    /**
970
     * Test for the addPolicyByRoleDraft() method.
971
     *
972
     * @see \eZ\Publish\API\Repository\RoleService::addPolicyByRoleDraft()
973
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRoleDraft
974
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewPolicyCreateStruct
975
     */
976
    public function testAddPolicyByRoleDraft()
977
    {
978
        $repository = $this->getRepository();
979
980
        /* BEGIN: Use Case */
981
        $roleService = $repository->getRoleService();
982
983
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
984
985
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
986
        // $roleCreate->mainLanguageCode = 'eng-US';
987
988
        $roleDraft = $roleService->createRole($roleCreate);
989
990
        $roleDraft = $roleService->addPolicyByRoleDraft(
991
            $roleDraft,
992
            $roleService->newPolicyCreateStruct('content', 'delete')
993
        );
994
        $roleDraft = $roleService->addPolicyByRoleDraft(
995
            $roleDraft,
996
            $roleService->newPolicyCreateStruct('content', 'create')
997
        );
998
        /* END: Use Case */
999
1000
        $actual = array();
1001 View Code Duplication
        foreach ($roleDraft->getPolicies() as $policy) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
1002
            $actual[] = array(
1003
                'module' => $policy->module,
1004
                'function' => $policy->function,
1005
            );
1006
        }
1007
        usort(
1008
            $actual,
1009
            function ($p1, $p2) {
1010
                return strcasecmp($p1['function'], $p2['function']);
1011
            }
1012
        );
1013
1014
        $this->assertEquals(
1015
            array(
1016
                array(
1017
                    'module' => 'content',
1018
                    'function' => 'create',
1019
                ),
1020
                array(
1021
                    'module' => 'content',
1022
                    'function' => 'delete',
1023
                ),
1024
            ),
1025
            $actual
1026
        );
1027
    }
1028
1029
    /**
1030
     * Test for the addPolicy() method.
1031
     *
1032
     * @return array [\eZ\Publish\API\Repository\Values\User\Role, \eZ\Publish\API\Repository\Values\User\Policy]
1033
     *
1034
     * @see \eZ\Publish\API\Repository\RoleService::addPolicy()
1035
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicy
1036
     */
1037
    public function testAddPolicyUpdatesRole()
1038
    {
1039
        $repository = $this->getRepository();
1040
1041
        /* BEGIN: Use Case */
1042
        $roleService = $repository->getRoleService();
1043
1044
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
1045
1046
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1047
        // $roleCreate->mainLanguageCode = 'eng-US';
1048
1049
        $roleDraft = $roleService->createRole($roleCreate);
1050
        $roleService->publishRoleDraft($roleDraft);
1051
        $role = $roleService->loadRole($roleDraft->id);
1052
1053
        $policyCreate = $roleService->newPolicyCreateStruct('content', 'create');
1054
        $role = $roleService->addPolicy($role, $policyCreate);
0 ignored issues
show
Deprecated Code introduced by
The method eZ\Publish\API\Repository\RoleService::addPolicy() has been deprecated with message: since 6.0, use {@see addPolicyByRoleDraft}

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

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

Loading history...
1055
1056
        $policy = null;
1057
        foreach ($role->getPolicies() as $policy) {
1058
            if ($policy->module === 'content' && $policy->function === 'create') {
1059
                break;
1060
            }
1061
        }
1062
        /* END: Use Case */
1063
1064
        $this->assertInstanceOf(
1065
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\Policy',
1066
            $policy
1067
        );
1068
1069
        return array($role, $policy);
1070
    }
1071
1072
    /**
1073
     * Test for the addPolicyByRoleDraft() method.
1074
     *
1075
     * @return array [\eZ\Publish\API\Repository\Values\User\RoleDraft, \eZ\Publish\API\Repository\Values\User\Policy]
1076
     *
1077
     * @see \eZ\Publish\API\Repository\RoleService::addPolicyByRoleDraft()
1078
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicyByRoleDraft
1079
     */
1080
    public function testAddPolicyByRoleDraftUpdatesRole()
1081
    {
1082
        $repository = $this->getRepository();
1083
1084
        /* BEGIN: Use Case */
1085
        $roleService = $repository->getRoleService();
1086
1087
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
1088
1089
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1090
        // $roleCreate->mainLanguageCode = 'eng-US';
1091
1092
        $roleDraft = $roleService->createRole($roleCreate);
1093
1094
        $policyCreate = $roleService->newPolicyCreateStruct('content', 'create');
1095
        $roleDraft = $roleService->addPolicyByRoleDraft($roleDraft, $policyCreate);
1096
1097
        $policy = null;
1098
        foreach ($roleDraft->getPolicies() as $policy) {
1099
            if ($policy->module === 'content' && $policy->function === 'create') {
1100
                break;
1101
            }
1102
        }
1103
        /* END: Use Case */
1104
1105
        $this->assertInstanceOf(
1106
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\Policy',
1107
            $policy
1108
        );
1109
1110
        return array($roleDraft, $policy);
1111
    }
1112
1113
    /**
1114
     * Test for the addPolicy() method.
1115
     *
1116
     * @param array $roleAndPolicy
1117
     *
1118
     * @see \eZ\Publish\API\Repository\RoleService::addPolicy()
1119
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicyUpdatesRole
1120
     */
1121 View Code Duplication
    public function testAddPolicySetsPolicyProperties($roleAndPolicy)
1122
    {
1123
        list($role, $policy) = $roleAndPolicy;
1124
1125
        $this->assertEquals(
1126
            array($role->id, 'content', 'create'),
1127
            array($policy->roleId, $policy->module, $policy->function)
1128
        );
1129
    }
1130
1131
    /**
1132
     * Test for the addPolicyByRoleDraft() method.
1133
     *
1134
     * @param array $roleAndPolicy
1135
     *
1136
     * @see \eZ\Publish\API\Repository\RoleService::addPolicyByRoleDraft()
1137
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicyByRoleDraftUpdatesRole
1138
     */
1139 View Code Duplication
    public function testAddPolicyByRoleDraftSetsPolicyProperties($roleAndPolicy)
1140
    {
1141
        list($role, $policy) = $roleAndPolicy;
1142
1143
        $this->assertEquals(
1144
            array($role->id, 'content', 'create'),
1145
            array($policy->roleId, $policy->module, $policy->function)
1146
        );
1147
    }
1148
1149
    /**
1150
     * Test for the addPolicy() method.
1151
     *
1152
     * @see \eZ\Publish\API\Repository\RoleService::addPolicy()
1153
     * @expectedException \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException
1154
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewPolicyCreateStruct
1155
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRole
1156
     */
1157 View Code Duplication
    public function testPublishEmptyRoleThrowsInvalidArgumentException()
1158
    {
1159
        $repository = $this->getRepository();
1160
1161
        /* BEGIN: Use Case */
1162
        $roleService = $repository->getRoleService();
1163
1164
        $roleCreate = $roleService->newRoleCreateStruct('Lumberjack');
1165
1166
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1167
        // $roleCreate->mainLanguageCode = 'eng-US';
1168
1169
        $roleDraft = $roleService->createRole($roleCreate);
1170
        // This call will fail with an InvalidArgumentException, because the role has no policies
1171
        $roleService->publishRoleDraft($roleDraft);
1172
        /* END: Use Case */
1173
    }
1174
1175
    /**
1176
     * Test for the addPolicy() method.
1177
     *
1178
     * @see \eZ\Publish\API\Repository\RoleService::addPolicy()
1179
     * @expectedException \eZ\Publish\API\Repository\Exceptions\LimitationValidationException
1180
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewPolicyCreateStruct
1181
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRole
1182
     */
1183
    public function testAddPolicyThrowsLimitationValidationException()
1184
    {
1185
        $repository = $this->getRepository();
1186
1187
        /* BEGIN: Use Case */
1188
        $roleService = $repository->getRoleService();
1189
1190
        $roleCreate = $roleService->newRoleCreateStruct('Lumberjack');
1191
1192
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1193
        // $roleCreate->mainLanguageCode = 'eng-US';
1194
1195
        $roleDraft = $roleService->createRole($roleCreate);
1196
        $roleService->addPolicyByRoleDraft(
1197
            $roleDraft,
1198
            $roleService->newPolicyCreateStruct('content', 'create')
1199
        );
1200
1201
        $roleService->publishRoleDraft($roleDraft);
1202
        $role = $roleService->loadRole($roleDraft->id);
1203
1204
        // Create new subtree limitation
1205
        $limitation = new SubtreeLimitation(
1206
            array(
1207
                'limitationValues' => array('/mountain/forest/tree/42/'),
1208
            )
1209
        );
1210
1211
        // Create policy create struct and add limitation to it
1212
        $policyCreateStruct = $roleService->newPolicyCreateStruct('content', 'remove');
1213
        $policyCreateStruct->addLimitation($limitation);
1214
1215
        // This call will fail with an LimitationValidationException, because subtree
1216
        // "/mountain/forest/tree/42/" does not exist
1217
        $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...
1218
        /* END: Use Case */
1219
    }
1220
1221
    /**
1222
     * Test for the addPolicyByRoleDraft() method.
1223
     *
1224
     * @see \eZ\Publish\API\Repository\RoleService::addPolicyByRoleDraft()
1225
     * @expectedException \eZ\Publish\API\Repository\Exceptions\LimitationValidationException
1226
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewPolicyCreateStruct
1227
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRoleDraft
1228
     */
1229 View Code Duplication
    public function testAddPolicyByRoleDraftThrowsLimitationValidationException()
1230
    {
1231
        $repository = $this->getRepository();
1232
1233
        /* BEGIN: Use Case */
1234
        $roleService = $repository->getRoleService();
1235
1236
        $roleCreate = $roleService->newRoleCreateStruct('Lumberjack');
1237
1238
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1239
        // $roleCreate->mainLanguageCode = 'eng-US';
1240
1241
        $roleDraft = $roleService->createRole($roleCreate);
1242
1243
        // Create new subtree limitation
1244
        $limitation = new SubtreeLimitation(
1245
            array(
1246
                'limitationValues' => array('/mountain/forest/tree/42/'),
1247
            )
1248
        );
1249
1250
        // Create policy create struct and add limitation to it
1251
        $policyCreateStruct = $roleService->newPolicyCreateStruct('content', 'remove');
1252
        $policyCreateStruct->addLimitation($limitation);
1253
1254
        // This call will fail with an LimitationValidationException, because subtree
1255
        // "/mountain/forest/tree/42/" does not exist
1256
        $roleService->addPolicyByRoleDraft($roleDraft, $policyCreateStruct);
1257
        /* END: Use Case */
1258
    }
1259
1260
    /**
1261
     * Test for the createRole() method.
1262
     *
1263
     * @see \eZ\Publish\API\Repository\RoleService::createRole()
1264
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicyUpdatesRole
1265
     */
1266
    public function testCreateRoleWithAddPolicy()
1267
    {
1268
        $repository = $this->getRepository();
1269
1270
        /* BEGIN: Use Case */
1271
        $roleService = $repository->getRoleService();
1272
1273
        // Instantiate a new create struct
1274
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
1275
1276
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1277
        // $roleCreate->mainLanguageCode = 'eng-US';
1278
1279
        // Add some role policies
1280
        $roleCreate->addPolicy(
1281
            $roleService->newPolicyCreateStruct(
1282
                'content',
1283
                'read'
1284
            )
1285
        );
1286
        $roleCreate->addPolicy(
1287
            $roleService->newPolicyCreateStruct(
1288
                'content',
1289
                'translate'
1290
            )
1291
        );
1292
1293
        // Create new role instance
1294
        $roleDraft = $roleService->createRole($roleCreate);
1295
        $roleService->publishRoleDraft($roleDraft);
1296
        $role = $roleService->loadRole($roleDraft->id);
1297
1298
        $policies = array();
1299 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...
1300
            $policies[] = array('module' => $policy->module, 'function' => $policy->function);
1301
        }
1302
        /* END: Use Case */
1303
        array_multisort($policies);
1304
1305
        $this->assertEquals(
1306
            array(
1307
                array(
1308
                    'module' => 'content',
1309
                    'function' => 'read',
1310
                ),
1311
                array(
1312
                    'module' => 'content',
1313
                    'function' => 'translate',
1314
                ),
1315
            ),
1316
            $policies
1317
        );
1318
    }
1319
1320
    /**
1321
     * Test for the createRoleDraft() method.
1322
     *
1323
     * @see \eZ\Publish\API\Repository\RoleService::createRoleDraft()
1324
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicyByRoleDraftUpdatesRole
1325
     */
1326
    public function testCreateRoleDraftWithAddPolicy()
1327
    {
1328
        $repository = $this->getRepository();
1329
1330
        /* BEGIN: Use Case */
1331
        $roleService = $repository->getRoleService();
1332
1333
        // Instantiate a new create struct
1334
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
1335
1336
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1337
        // $roleCreate->mainLanguageCode = 'eng-US';
1338
1339
        // Add some role policies
1340
        $roleCreate->addPolicy(
1341
            $roleService->newPolicyCreateStruct(
1342
                'content',
1343
                'read'
1344
            )
1345
        );
1346
        $roleCreate->addPolicy(
1347
            $roleService->newPolicyCreateStruct(
1348
                'content',
1349
                'translate'
1350
            )
1351
        );
1352
1353
        // Create new role instance
1354
        $roleDraft = $roleService->createRole($roleCreate);
1355
1356
        $policies = array();
1357 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...
1358
            $policies[] = array('module' => $policy->module, 'function' => $policy->function);
1359
        }
1360
        /* END: Use Case */
1361
1362
        $this->assertEquals(
1363
            array(
1364
                array(
1365
                    'module' => 'content',
1366
                    'function' => 'read',
1367
                ),
1368
                array(
1369
                    'module' => 'content',
1370
                    'function' => 'translate',
1371
                ),
1372
            ),
1373
            $policies
1374
        );
1375
    }
1376
1377
    /**
1378
     * Test for the newPolicyUpdateStruct() method.
1379
     *
1380
     * @see \eZ\Publish\API\Repository\RoleService::newPolicyUpdateStruct()
1381
     */
1382
    public function testNewPolicyUpdateStruct()
1383
    {
1384
        $repository = $this->getRepository();
1385
1386
        /* BEGIN: Use Case */
1387
        $roleService = $repository->getRoleService();
1388
        $policyUpdate = $roleService->newPolicyUpdateStruct();
1389
        /* END: Use Case */
1390
1391
        $this->assertInstanceOf(
1392
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\PolicyUpdateStruct',
1393
            $policyUpdate
1394
        );
1395
    }
1396
1397
    public function testUpdatePolicyNoLimitation()
1398
    {
1399
        $repository = $this->getRepository();
1400
1401
        /* BEGIN: Use Case */
1402
        $roleService = $repository->getRoleService();
1403
1404
        // Instantiate new policy create
1405
        $policyCreate = $roleService->newPolicyCreateStruct('foo', 'bar');
1406
1407
        // Instantiate a role create and add the policy create
1408
        $roleCreate = $roleService->newRoleCreateStruct('myRole');
1409
1410
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1411
        // $roleCreate->mainLanguageCode = 'eng-US';
1412
1413
        $roleCreate->addPolicy($policyCreate);
1414
1415
        // Create a new role instance.
1416
        $roleDraft = $roleService->createRole($roleCreate);
1417
        $roleService->publishRoleDraft($roleDraft);
1418
        $role = $roleService->loadRole($roleDraft->id);
1419
1420
        // Search for the new policy instance
1421
        $policy = null;
1422
        foreach ($role->getPolicies() as $policy) {
1423
            if ($policy->module === 'foo' && $policy->function === 'bar') {
1424
                break;
1425
            }
1426
        }
1427
1428
        // Create an update struct
1429
        $policyUpdate = $roleService->newPolicyUpdateStruct();
1430
1431
        // Update the the policy
1432
        $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...
1433
        /* END: Use Case */
1434
1435
        $this->assertInstanceOf(
1436
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\Policy',
1437
            $policy
1438
        );
1439
1440
        self::assertEquals(array(), $policy->getLimitations());
1441
    }
1442
1443
    /**
1444
     * Test for the updatePolicy() method.
1445
     *
1446
     * @return array
1447
     *
1448
     * @see \eZ\Publish\API\Repository\RoleService::updatePolicy()
1449
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicy
1450
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewPolicyUpdateStruct
1451
     */
1452
    public function testUpdatePolicy()
1453
    {
1454
        $repository = $this->getRepository();
1455
1456
        /* BEGIN: Use Case */
1457
        $roleService = $repository->getRoleService();
1458
1459
        // Instantiate new policy create
1460
        $policyCreate = $roleService->newPolicyCreateStruct('content', 'translate');
1461
1462
        // Add some limitations for the new policy
1463
        $policyCreate->addLimitation(
1464
            new LanguageLimitation(
1465
                array(
1466
                    'limitationValues' => array('eng-US', 'eng-GB'),
1467
                )
1468
            )
1469
        );
1470
1471
        // Instantiate a role create and add the policy create
1472
        $roleCreate = $roleService->newRoleCreateStruct('myRole');
1473
1474
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1475
        // $roleCreate->mainLanguageCode = 'eng-US';
1476
1477
        $roleCreate->addPolicy($policyCreate);
1478
1479
        // Create a new role instance.
1480
        $roleDraft = $roleService->createRole($roleCreate);
1481
        $roleService->publishRoleDraft($roleDraft);
1482
        $role = $roleService->loadRole($roleDraft->id);
1483
1484
        // Search for the new policy instance
1485
        $policy = null;
1486
        foreach ($role->getPolicies() as $policy) {
1487
            if ($policy->module === 'content' && $policy->function === 'translate') {
1488
                break;
1489
            }
1490
        }
1491
1492
        // Create an update struct and set a modified limitation
1493
        $policyUpdate = $roleService->newPolicyUpdateStruct();
1494
        $policyUpdate->addLimitation(
1495
            new ContentTypeLimitation(
1496
                array(
1497
                    'limitationValues' => array(29, 30),
1498
                )
1499
            )
1500
        );
1501
1502
        // Update the the policy
1503
        $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...
1504
        /* END: Use Case */
1505
1506
        $this->assertInstanceOf(
1507
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\Policy',
1508
            $policy
1509
        );
1510
1511
        return array($roleService->loadRole($role->id), $policy);
1512
    }
1513
1514
    /**
1515
     * Test for the updatePolicy() method.
1516
     *
1517
     * @param array $roleAndPolicy
1518
     *
1519
     * @see \eZ\Publish\API\Repository\RoleService::updatePolicy()
1520
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testUpdatePolicy
1521
     */
1522
    public function testUpdatePolicyUpdatesLimitations($roleAndPolicy)
1523
    {
1524
        list($role, $policy) = $roleAndPolicy;
1525
1526
        $this->assertEquals(
1527
            array(
1528
                new ContentTypeLimitation(
1529
                    array(
1530
                        'limitationValues' => array(29, 30),
1531
                    )
1532
                ),
1533
            ),
1534
            $policy->getLimitations()
1535
        );
1536
1537
        return $role;
1538
    }
1539
1540
    /**
1541
     * Test for the updatePolicy() method.
1542
     *
1543
     * @param \eZ\Publish\API\Repository\Values\User\Role $role
1544
     *
1545
     * @see \eZ\Publish\API\Repository\RoleService::updatePolicy()
1546
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testUpdatePolicyUpdatesLimitations
1547
     */
1548
    public function testUpdatePolicyUpdatesRole($role)
1549
    {
1550
        $limitations = array();
1551
        foreach ($role->getPolicies() as $policy) {
1552
            foreach ($policy->getLimitations() as $limitation) {
1553
                $limitations[] = $limitation;
1554
            }
1555
        }
1556
1557
        $this->assertCount(1, $limitations);
1558
        $this->assertInstanceOf(
1559
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\Limitation',
1560
            $limitations[0]
1561
        );
1562
1563
        $expectedData = array(
1564
            'limitationValues' => array(29, 30),
1565
        );
1566
        $this->assertPropertiesCorrectUnsorted(
1567
            $expectedData,
1568
            $limitations[0]
1569
        );
1570
    }
1571
1572
    /**
1573
     * Test for the updatePolicy() method.
1574
     *
1575
     * @see \eZ\Publish\API\Repository\RoleService::updatePolicy()
1576
     * @expectedException \eZ\Publish\API\Repository\Exceptions\LimitationValidationException
1577
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicy
1578
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewPolicyCreateStruct
1579
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewPolicyUpdateStruct
1580
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewRoleCreateStruct
1581
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRole
1582
     */
1583
    public function testUpdatePolicyThrowsLimitationValidationException()
1584
    {
1585
        $repository = $this->getRepository();
1586
1587
        /* BEGIN: Use Case */
1588
        $roleService = $repository->getRoleService();
1589
1590
        // Instantiate new policy create
1591
        $policyCreate = $roleService->newPolicyCreateStruct('content', 'remove');
1592
1593
        // Add some limitations for the new policy
1594
        $policyCreate->addLimitation(
1595
            new SubtreeLimitation(
1596
                array(
1597
                    'limitationValues' => array('/1/2/'),
1598
                )
1599
            )
1600
        );
1601
1602
        // Instantiate a role create and add the policy create
1603
        $roleCreate = $roleService->newRoleCreateStruct('myRole');
1604
1605
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1606
        // $roleCreate->mainLanguageCode = 'eng-US';
1607
1608
        $roleCreate->addPolicy($policyCreate);
1609
1610
        // Create a new role instance.
1611
        $roleDraft = $roleService->createRole($roleCreate);
1612
        $roleService->publishRoleDraft($roleDraft);
1613
        $role = $roleService->loadRole($roleDraft->id);
1614
1615
        // Search for the new policy instance
1616
        $policy = null;
1617
        foreach ($role->getPolicies() as $policy) {
1618
            if ($policy->module === 'content' && $policy->function === 'remove') {
1619
                break;
1620
            }
1621
        }
1622
1623
        // Create an update struct and set a modified limitation
1624
        $policyUpdate = $roleService->newPolicyUpdateStruct();
1625
        $policyUpdate->addLimitation(
1626
            new SubtreeLimitation(
1627
                array(
1628
                    'limitationValues' => array('/mountain/forest/tree/42/'),
1629
                )
1630
            )
1631
        );
1632
1633
        // This call will fail with an LimitationValidationException, because subtree
1634
        // "/mountain/forest/tree/42/" does not exist
1635
        $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...
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...
1636
        /* END: Use Case */
1637
    }
1638
1639
    /**
1640
     * Test for the removePolicy() method.
1641
     *
1642
     * @see \eZ\Publish\API\Repository\RoleService::removePolicy()
1643
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicy
1644
     */
1645 View Code Duplication
    public function testRemovePolicy()
1646
    {
1647
        $repository = $this->getRepository();
1648
1649
        /* BEGIN: Use Case */
1650
        $roleService = $repository->getRoleService();
1651
1652
        // Instantiate a new role create
1653
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
1654
1655
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1656
        // $roleCreate->mainLanguageCode = 'eng-US';
1657
1658
        // Create a new role with two policies
1659
        $roleDraft = $roleService->createRole($roleCreate);
1660
        $roleService->addPolicyByRoleDraft(
1661
            $roleDraft,
1662
            $roleService->newPolicyCreateStruct('content', 'create')
1663
        );
1664
        $roleService->addPolicyByRoleDraft(
1665
            $roleDraft,
1666
            $roleService->newPolicyCreateStruct('content', 'delete')
1667
        );
1668
        $roleService->publishRoleDraft($roleDraft);
1669
        $role = $roleService->loadRole($roleDraft->id);
1670
1671
        // Delete all policies from the new role
1672
        foreach ($role->getPolicies() as $policy) {
1673
            $role = $roleService->removePolicy($role, $policy);
0 ignored issues
show
Deprecated Code introduced by
The method eZ\Publish\API\Repositor...Service::removePolicy() has been deprecated with message: since 5.3, use {@link removePolicyByRoleDraft()} instead.

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

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

Loading history...
1674
        }
1675
        /* END: Use Case */
1676
1677
        $this->assertSame(array(), $role->getPolicies());
1678
    }
1679
1680
    /**
1681
     * Test for the removePolicyByRoleDraft() method.
1682
     *
1683
     * @see \eZ\Publish\API\Repository\RoleService::removePolicyByRoleDraft()
1684
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicyByRoleDraft
1685
     */
1686 View Code Duplication
    public function testRemovePolicyByRoleDraft()
1687
    {
1688
        $repository = $this->getRepository();
1689
1690
        /* BEGIN: Use Case */
1691
        $roleService = $repository->getRoleService();
1692
1693
        // Instantiate a new role create
1694
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
1695
1696
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1697
        // $roleCreate->mainLanguageCode = 'eng-US';
1698
1699
        // Create a new role with two policies
1700
        $roleDraft = $roleService->createRole($roleCreate);
1701
        $roleService->addPolicyByRoleDraft(
1702
            $roleDraft,
1703
            $roleService->newPolicyCreateStruct('content', 'create')
1704
        );
1705
        $roleService->addPolicyByRoleDraft(
1706
            $roleDraft,
1707
            $roleService->newPolicyCreateStruct('content', 'delete')
1708
        );
1709
1710
        // Delete all policies from the new role
1711
        foreach ($roleDraft->getPolicies() as $policy) {
1712
            $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...
1713
        }
1714
        /* END: Use Case */
1715
1716
        $this->assertSame(array(), $roleDraft->getPolicies());
1717
    }
1718
1719
    /**
1720
     * Test for the deletePolicy() method.
1721
     *
1722
     * @see \eZ\Publish\API\Repository\RoleService::deletePolicy()
1723
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRole
1724
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicy
1725
     */
1726 View Code Duplication
    public function testDeletePolicy()
1727
    {
1728
        $repository = $this->getRepository();
1729
1730
        /* BEGIN: Use Case */
1731
        $roleService = $repository->getRoleService();
1732
1733
        // Instantiate a new role create
1734
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
1735
1736
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1737
        // $roleCreate->mainLanguageCode = 'eng-US';
1738
1739
        // Create a new role with two policies
1740
        $roleDraft = $roleService->createRole($roleCreate);
1741
        $roleService->addPolicyByRoleDraft(
1742
            $roleDraft,
1743
            $roleService->newPolicyCreateStruct('content', 'create')
1744
        );
1745
        $roleService->addPolicyByRoleDraft(
1746
            $roleDraft,
1747
            $roleService->newPolicyCreateStruct('content', 'delete')
1748
        );
1749
        $roleService->publishRoleDraft($roleDraft);
1750
        $role = $roleService->loadRole($roleDraft->id);
1751
1752
        // Delete all policies from the new role
1753
        foreach ($role->getPolicies() as $policy) {
1754
            $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...
1755
        }
1756
        /* END: Use Case */
1757
1758
        $role = $roleService->loadRole($role->id);
1759
        $this->assertSame(array(), $role->getPolicies());
1760
    }
1761
1762
    /**
1763
     * Test loading user/group role assignments.
1764
     *
1765
     * @return \eZ\Publish\API\Repository\Values\User\UserGroupRoleAssignment
1766
     *
1767
     * @covers \eZ\Publish\API\Repository\RoleService::loadRoleAssignment
1768
     */
1769
    public function testLoadRoleAssignment()
1770
    {
1771
        $repository = $this->getRepository();
1772
1773
        /* BEGIN: Use Case */
1774
        $roleService = $repository->getRoleService();
1775
1776
        // Assignment to user group
1777
        $groupRoleAssignment = $roleService->loadRoleAssignment(25);
1778
1779
        // Assignment to user
1780
        $role = $roleService->loadRole(2);
1781
        $user = $repository->getUserService()->loadUser(14);
1782
        $roleService->assignRoleToUser($role, $user);
1783
        $userRoleAssignments = $roleService->getRoleAssignmentsForUser($user);
1784
1785
        $userRoleAssignment = $roleService->loadRoleAssignment($userRoleAssignments[0]->id);
1786
        /* END: Use Case */
1787
1788
        $this->assertInstanceOf(
1789
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\UserGroupRoleAssignment',
1790
            $groupRoleAssignment
1791
        );
1792
1793
        $this->assertEquals(
1794
            [
1795
                12,
1796
                2,
1797
                25,
1798
            ],
1799
            [
1800
                $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...
1801
                $groupRoleAssignment->role->id,
1802
                $groupRoleAssignment->id,
1803
            ]
1804
        );
1805
1806
        self::assertInstanceOf('\\eZ\\Publish\\API\\Repository\\Values\\User\\UserRoleAssignment', $userRoleAssignment);
1807
        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...
1808
1809
        return $groupRoleAssignment;
1810
    }
1811
1812
    /**
1813
     * Test for the getRoleAssignments() method.
1814
     *
1815
     * @return \eZ\Publish\API\Repository\Values\User\RoleAssignment[]
1816
     *
1817
     * @see \eZ\Publish\API\Repository\RoleService::getRoleAssignments()
1818
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleByIdentifier
1819
     */
1820
    public function testGetRoleAssignments()
1821
    {
1822
        $repository = $this->getRepository();
1823
1824
        /* BEGIN: Use Case */
1825
        $roleService = $repository->getRoleService();
1826
1827
        // Load the editor role
1828
        $role = $roleService->loadRoleByIdentifier('Editor');
1829
1830
        // Load all assigned users and user groups
1831
        $roleAssignments = $roleService->getRoleAssignments($role);
1832
1833
        /* END: Use Case */
1834
1835
        $this->assertEquals(2, count($roleAssignments));
1836
        $this->assertInstanceOf(
1837
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\UserGroupRoleAssignment',
1838
            $roleAssignments[0]
1839
        );
1840
        $this->assertInstanceOf(
1841
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\UserGroupRoleAssignment',
1842
            $roleAssignments[1]
1843
        );
1844
1845
        return $roleAssignments;
1846
    }
1847
1848
    /**
1849
     * Test for the getRoleAssignments() method.
1850
     *
1851
     * @param \eZ\Publish\API\Repository\Values\User\RoleAssignment[] $roleAssignments
1852
     *
1853
     * @see \eZ\Publish\API\Repository\RoleService::getRoleAssignments()
1854
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testGetRoleAssignments
1855
     */
1856
    public function testGetRoleAssignmentsContainExpectedLimitation(array $roleAssignments)
1857
    {
1858
        $this->assertEquals(
1859
            'Subtree',
1860
            reset($roleAssignments)->limitation->getIdentifier()
1861
        );
1862
    }
1863
1864
    /**
1865
     * Test for the assignRoleToUser() method.
1866
     *
1867
     * @see \eZ\Publish\API\Repository\RoleService::assignRoleToUser()
1868
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testGetRoleAssignments
1869
     */
1870 View Code Duplication
    public function testAssignRoleToUser()
1871
    {
1872
        $repository = $this->getRepository();
1873
        $roleService = $repository->getRoleService();
1874
1875
        /* BEGIN: Use Case */
1876
        $user = $this->createUserVersion1();
1877
1878
        // Load the existing "Administrator" role
1879
        $role = $roleService->loadRoleByIdentifier('Administrator');
1880
1881
        // Assign the "Administrator" role to the newly created user
1882
        $roleService->assignRoleToUser($role, $user);
1883
1884
        // The assignments array will contain the new role<->user assignment
1885
        $roleAssignments = $roleService->getRoleAssignments($role);
1886
        /* END: Use Case */
1887
1888
        // Administrator + Example User
1889
        $this->assertEquals(2, count($roleAssignments));
1890
    }
1891
1892
    /**
1893
     * Test for the assignRoleToUser() method.
1894
     *
1895
     * @see \eZ\Publish\API\Repository\RoleService::assignRoleToUser($role, $user, $roleLimitation)
1896
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUser
1897
     */
1898 View Code Duplication
    public function testAssignRoleToUserWithRoleLimitation()
1899
    {
1900
        $repository = $this->getRepository();
1901
        $roleService = $repository->getRoleService();
1902
1903
        /* BEGIN: Use Case */
1904
        $user = $this->createUserVersion1();
1905
1906
        // Load the existing "Anonymous" role
1907
        $role = $roleService->loadRoleByIdentifier('Anonymous');
1908
1909
        // Assign the "Anonymous" role to the newly created user
1910
        $roleService->assignRoleToUser(
1911
            $role,
1912
            $user,
1913
            new SubtreeLimitation(
1914
                array(
1915
                    'limitationValues' => array('/1/43/'),
1916
                )
1917
            )
1918
        );
1919
1920
        // The assignments array will contain the new role<->user assignment
1921
        $roleAssignments = $roleService->getRoleAssignments($role);
1922
        /* END: Use Case */
1923
1924
        // Members + Partners + Anonymous + Example User
1925
        $this->assertEquals(4, count($roleAssignments));
1926
1927
        // Get the role limitation
1928
        $roleLimitation = null;
1929
        foreach ($roleAssignments as $roleAssignment) {
1930
            $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...
1931
            if ($roleLimitation) {
1932
                $this->assertInstanceOf(
1933
                    '\\eZ\\Publish\\API\\Repository\\Values\\User\\UserRoleAssignment',
1934
                    $roleAssignment
1935
                );
1936
                break;
1937
            }
1938
        }
1939
1940
        $this->assertEquals(
1941
            new SubtreeLimitation(
1942
                array(
1943
                    'limitationValues' => array('/1/43/'),
1944
                )
1945
            ),
1946
            $roleLimitation
1947
        );
1948
1949
        // Test again to see values being merged
1950
        $roleService->assignRoleToUser(
1951
            $role,
1952
            $user,
1953
            new SubtreeLimitation(
1954
                array(
1955
                    'limitationValues' => array('/1/43/', '/1/2/'),
1956
                )
1957
            )
1958
        );
1959
1960
        // The assignments array will contain the new role<->user assignment
1961
        $roleAssignments = $roleService->getRoleAssignments($role);
1962
1963
        // Members + Partners + Anonymous + Example User
1964
        $this->assertEquals(5, count($roleAssignments));
1965
1966
        // Get the role limitation
1967
        $roleLimitations = [];
1968
        foreach ($roleAssignments as $roleAssignment) {
1969
            $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...
1970
            if ($roleLimitation) {
1971
                $this->assertInstanceOf(
1972
                    '\\eZ\\Publish\\API\\Repository\\Values\\User\\UserRoleAssignment',
1973
                    $roleAssignment
1974
                );
1975
                $roleLimitations[] = $roleLimitation;
1976
            }
1977
        }
1978
        array_multisort($roleLimitations);
1979
1980
        $this->assertEquals(
1981
            [
1982
                new SubtreeLimitation(
1983
                    array(
1984
                        'limitationValues' => array('/1/2/'),
1985
                    )
1986
                ),
1987
                new SubtreeLimitation(
1988
                    array(
1989
                        'limitationValues' => array('/1/43/'),
1990
                    )
1991
                ),
1992
            ],
1993
            $roleLimitations
1994
        );
1995
    }
1996
1997
    /**
1998
     * Test for the assignRoleToUser() method.
1999
     *
2000
     * @see \eZ\Publish\API\Repository\RoleService::assignRoleToUser($role, $user, $roleLimitation)
2001
     * @expectedException \eZ\Publish\API\Repository\Exceptions\LimitationValidationException
2002
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUser
2003
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleByIdentifier
2004
     */
2005
    public function testAssignRoleToUserWithRoleLimitationThrowsLimitationValidationException()
2006
    {
2007
        $repository = $this->getRepository();
2008
2009
        /* BEGIN: Use Case */
2010
        $roleService = $repository->getRoleService();
2011
2012
        // Load the existing "Anonymous" role
2013
        $role = $roleService->loadRoleByIdentifier('Anonymous');
2014
2015
        // Get current user
2016
        $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...
2017
2018
        // Assign the "Anonymous" role to the current user
2019
        // This call will fail with an LimitationValidationException, because subtree "/lorem/ipsum/42/"
2020
        // does not exists
2021
        $roleService->assignRoleToUser(
2022
            $role,
2023
            $currentUser,
2024
            new SubtreeLimitation(
2025
                array(
2026
                    'limitationValues' => array('/lorem/ipsum/42/'),
2027
                )
2028
            )
2029
        );
2030
        /* END: Use Case */
2031
    }
2032
2033
    /**
2034
     * Test for the assignRoleToUser() method.
2035
     *
2036
     * Makes sure assigning role several times throws.
2037
     *
2038
     * @see \eZ\Publish\API\Repository\RoleService::assignRoleToUser($role, $user, $roleLimitation)
2039
     * @expectedException \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException
2040
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUser
2041
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleByIdentifier
2042
     */
2043 View Code Duplication
    public function testAssignRoleToUserThrowsInvalidArgumentException()
2044
    {
2045
        $repository = $this->getRepository();
2046
2047
        /* BEGIN: Use Case */
2048
        $roleService = $repository->getRoleService();
2049
2050
        // Load the existing "Anonymous" role
2051
        $role = $roleService->loadRoleByIdentifier('Anonymous');
2052
2053
        // Get current user
2054
        $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...
2055
2056
        // Assign the "Anonymous" role to the current user
2057
        try {
2058
            $roleService->assignRoleToUser(
2059
                $role,
2060
                $currentUser
2061
            );
2062
        } catch (Exception $e) {
2063
            $this->fail('Got exception at first valid attempt to assign role');
2064
        }
2065
2066
        // Re-Assign the "Anonymous" role to the current user
2067
        // This call will fail with an InvalidArgumentException, because limitation is already assigned
2068
        $roleService->assignRoleToUser(
2069
            $role,
2070
            $currentUser
2071
        );
2072
        /* END: Use Case */
2073
    }
2074
2075
    /**
2076
     * Test for the assignRoleToUser() method.
2077
     *
2078
     * Makes sure assigning role several times with same limitations throws.
2079
     *
2080
     * @see \eZ\Publish\API\Repository\RoleService::assignRoleToUser($role, $user, $roleLimitation)
2081
     * @expectedException \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException
2082
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUser
2083
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleByIdentifier
2084
     */
2085
    public function testAssignRoleToUserWithRoleLimitationThrowsInvalidArgumentException()
2086
    {
2087
        $repository = $this->getRepository();
2088
2089
        /* BEGIN: Use Case */
2090
        $roleService = $repository->getRoleService();
2091
2092
        // Load the existing "Anonymous" role
2093
        $role = $roleService->loadRoleByIdentifier('Anonymous');
2094
2095
        // Get current user
2096
        $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...
2097
2098
        // Assign the "Anonymous" role to the current user
2099
        try {
2100
            $roleService->assignRoleToUser(
2101
                $role,
2102
                $currentUser,
2103
                new SubtreeLimitation(
2104
                    array(
2105
                        'limitationValues' => array('/1/43/', '/1/2/'),
2106
                    )
2107
                )
2108
            );
2109
        } catch (Exception $e) {
2110
            $this->fail('Got exception at first valid attempt to assign role');
2111
        }
2112
2113
        // Re-Assign the "Anonymous" role to the current user
2114
        // This call will fail with an InvalidArgumentException, because limitation is already assigned
2115
        $roleService->assignRoleToUser(
2116
            $role,
2117
            $currentUser,
2118
            new SubtreeLimitation(
2119
                array(
2120
                    'limitationValues' => array('/1/43/'),
2121
                )
2122
            )
2123
        );
2124
        /* END: Use Case */
2125
    }
2126
2127
    /**
2128
     * Test for the unassignRoleFromUser() method.
2129
     *
2130
     * @see \eZ\Publish\API\Repository\RoleService::unassignRoleFromUser()
2131
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUser
2132
     */
2133 View Code Duplication
    public function testUnassignRoleFromUser()
2134
    {
2135
        $repository = $this->getRepository();
2136
        $roleService = $repository->getRoleService();
2137
2138
        /* BEGIN: Use Case */
2139
        $user = $this->createUserVersion1();
2140
2141
        // Load the existing "Member" role
2142
        $role = $roleService->loadRoleByIdentifier('Member');
2143
2144
        // Assign the "Member" role to the newly created user
2145
        $roleService->assignRoleToUser($role, $user);
2146
2147
        // Unassign user from role
2148
        $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...
2149
2150
        // The assignments array will not contain the new role<->user assignment
2151
        $roleAssignments = $roleService->getRoleAssignments($role);
2152
        /* END: Use Case */
2153
2154
        // Members + Editors + Partners
2155
        $this->assertEquals(3, count($roleAssignments));
2156
    }
2157
2158
    /**
2159
     * Test for the unassignRoleFromUser() method.
2160
     *
2161
     * @see \eZ\Publish\API\Repository\RoleService::unassignRoleFromUser()
2162
     * @expectedException \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException
2163
     */
2164 View Code Duplication
    public function testUnassignRoleFromUserThrowsInvalidArgumentException()
2165
    {
2166
        $repository = $this->getRepository();
2167
        $roleService = $repository->getRoleService();
2168
2169
        /* BEGIN: Use Case */
2170
        $user = $this->createUserVersion1();
2171
2172
        // Load the existing "Member" role
2173
        $role = $roleService->loadRoleByIdentifier('Member');
2174
2175
        // This call will fail with a "InvalidArgumentException", because the
2176
        // user does not have the "Member" role.
2177
        $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...
2178
        /* END: Use Case */
2179
    }
2180
2181
    /**
2182
     * Test for the getRoleAssignmentsForUser() method.
2183
     *
2184
     * @see \eZ\Publish\API\Repository\RoleService::getRoleAssignmentsForUser()
2185
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUser
2186
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRoleWithAddPolicy
2187
     */
2188 View Code Duplication
    public function testGetRoleAssignmentsForUserDirect()
2189
    {
2190
        $repository = $this->getRepository();
2191
        $roleService = $repository->getRoleService();
2192
2193
        /* BEGIN: Use Case */
2194
        $user = $this->createUserVersion1();
2195
2196
        // Instantiate a role create and add some policies
2197
        $roleCreate = $roleService->newRoleCreateStruct('Example Role');
2198
2199
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
2200
        // $roleCreate->mainLanguageCode = 'eng-US';
2201
2202
        $roleCreate->addPolicy(
2203
            $roleService->newPolicyCreateStruct('user', 'login')
2204
        );
2205
        $roleCreate->addPolicy(
2206
            $roleService->newPolicyCreateStruct('content', 'read')
2207
        );
2208
        $roleCreate->addPolicy(
2209
            $roleService->newPolicyCreateStruct('content', 'edit')
2210
        );
2211
2212
        // Create the new role instance
2213
        $roleDraft = $roleService->createRole($roleCreate);
2214
        $roleService->publishRoleDraft($roleDraft);
2215
        $role = $roleService->loadRole($roleDraft->id);
2216
2217
        // Assign role to new user
2218
        $roleService->assignRoleToUser($role, $user);
2219
2220
        // Load the currently assigned role
2221
        $roleAssignments = $roleService->getRoleAssignmentsForUser($user);
2222
        /* END: Use Case */
2223
2224
        $this->assertEquals(1, count($roleAssignments));
2225
        $this->assertInstanceOf(
2226
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\UserRoleAssignment',
2227
            reset($roleAssignments)
2228
        );
2229
    }
2230
2231
    /**
2232
     * Test for the getRoleAssignmentsForUser() method.
2233
     *
2234
     * @see \eZ\Publish\API\Repository\RoleService::getRoleAssignmentsForUser()
2235
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUser
2236
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRoleWithAddPolicy
2237
     */
2238
    public function testGetRoleAssignmentsForUserEmpty()
2239
    {
2240
        $repository = $this->getRepository();
2241
        $roleService = $repository->getRoleService();
2242
2243
        /* BEGIN: Use Case */
2244
        $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...
2245
2246
        // Load the currently assigned role
2247
        $roleAssignments = $roleService->getRoleAssignmentsForUser($adminUser);
2248
        /* END: Use Case */
2249
2250
        $this->assertEquals(0, count($roleAssignments));
2251
    }
2252
2253
    /**
2254
     * Test for the getRoleAssignmentsForUser() method.
2255
     *
2256
     * @see \eZ\Publish\API\Repository\RoleService::getRoleAssignmentsForUser()
2257
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUser
2258
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRoleWithAddPolicy
2259
     */
2260
    public function testGetRoleAssignmentsForUserInherited()
2261
    {
2262
        $repository = $this->getRepository();
2263
        $roleService = $repository->getRoleService();
2264
2265
        /* BEGIN: Use Case */
2266
        $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...
2267
2268
        // Load the currently assigned role + inherited role assignments
2269
        $roleAssignments = $roleService->getRoleAssignmentsForUser($adminUser, true);
2270
        /* END: Use Case */
2271
2272
        $this->assertEquals(1, count($roleAssignments));
2273
        $this->assertInstanceOf(
2274
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\UserGroupRoleAssignment',
2275
            reset($roleAssignments)
2276
        );
2277
    }
2278
2279
    /**
2280
     * Test for the assignRoleToUserGroup() method.
2281
     *
2282
     * @see \eZ\Publish\API\Repository\RoleService::assignRoleToUserGroup()
2283
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testGetRoleAssignments
2284
     */
2285 View Code Duplication
    public function testAssignRoleToUserGroup()
2286
    {
2287
        $repository = $this->getRepository();
2288
        $roleService = $repository->getRoleService();
2289
2290
        /* BEGIN: Use Case */
2291
        $userGroup = $this->createUserGroupVersion1();
2292
2293
        // Load the existing "Administrator" role
2294
        $role = $roleService->loadRoleByIdentifier('Administrator');
2295
2296
        // Assign the "Administrator" role to the newly created user group
2297
        $roleService->assignRoleToUserGroup($role, $userGroup);
2298
2299
        // The assignments array will contain the new role<->group assignment
2300
        $roleAssignments = $roleService->getRoleAssignments($role);
2301
        /* END: Use Case */
2302
2303
        // Administrator + Example Group
2304
        $this->assertEquals(2, count($roleAssignments));
2305
    }
2306
2307
    /**
2308
     * Test for the assignRoleToUserGroup() method.
2309
     *
2310
     * @see \eZ\Publish\API\Repository\RoleService::assignRoleToUserGroup($role, $userGroup, $roleLimitation)
2311
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUserGroup
2312
     */
2313 View Code Duplication
    public function testAssignRoleToUserGroupWithRoleLimitation()
2314
    {
2315
        $repository = $this->getRepository();
2316
        $roleService = $repository->getRoleService();
2317
2318
        /* BEGIN: Use Case */
2319
        $userGroup = $this->createUserGroupVersion1();
2320
2321
        // Load the existing "Anonymous" role
2322
        $role = $roleService->loadRoleByIdentifier('Anonymous');
2323
2324
        // Assign the "Anonymous" role to the newly created user group
2325
        $roleService->assignRoleToUserGroup(
2326
            $role,
2327
            $userGroup,
2328
            new SubtreeLimitation(
2329
                array(
2330
                    'limitationValues' => array('/1/43/'),
2331
                )
2332
            )
2333
        );
2334
2335
        // The assignments array will contain the new role<->group assignment
2336
        $roleAssignments = $roleService->getRoleAssignments($role);
2337
        /* END: Use Case */
2338
2339
        // Members + Partners + Anonymous + Example Group
2340
        $this->assertEquals(4, count($roleAssignments));
2341
2342
        // Get the role limitation
2343
        $roleLimitation = null;
2344
        foreach ($roleAssignments as $roleAssignment) {
2345
            $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...
2346
            if ($roleLimitation) {
2347
                break;
2348
            }
2349
        }
2350
2351
        $this->assertEquals(
2352
            new SubtreeLimitation(
2353
                array(
2354
                    'limitationValues' => array('/1/43/'),
2355
                )
2356
            ),
2357
            $roleLimitation
2358
        );
2359
2360
        // Test again to see values being merged
2361
        $roleService->assignRoleToUserGroup(
2362
            $role,
2363
            $userGroup,
2364
            new SubtreeLimitation(
2365
                array(
2366
                    'limitationValues' => array('/1/43/', '/1/2/'),
2367
                )
2368
            )
2369
        );
2370
2371
        // The assignments array will contain the new role<->user assignment
2372
        $roleAssignments = $roleService->getRoleAssignments($role);
2373
2374
        // Members + Partners + Anonymous + Example User
2375
        $this->assertEquals(5, count($roleAssignments));
2376
2377
        // Get the role limitation
2378
        $roleLimitations = [];
2379
        foreach ($roleAssignments as $roleAssignment) {
2380
            $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...
2381
            if ($roleLimitation) {
2382
                $this->assertInstanceOf(
2383
                    '\\eZ\\Publish\\API\\Repository\\Values\\User\\UserGroupRoleAssignment',
2384
                    $roleAssignment
2385
                );
2386
                $roleLimitations[] = $roleLimitation;
2387
            }
2388
        }
2389
        array_multisort($roleLimitations);
2390
2391
        $this->assertEquals(
2392
            [
2393
                new SubtreeLimitation(
2394
                    array(
2395
                        'limitationValues' => array('/1/2/'),
2396
                    )
2397
                ),
2398
                new SubtreeLimitation(
2399
                    array(
2400
                        'limitationValues' => array('/1/43/'),
2401
                    )
2402
                ),
2403
            ],
2404
            $roleLimitations
2405
        );
2406
    }
2407
2408
    /**
2409
     * Test for the assignRoleToUserGroup() method.
2410
     *
2411
     * @see \eZ\Publish\API\Repository\RoleService::assignRoleToUserGroup($role, $userGroup, $roleLimitation)
2412
     * @expectedException \eZ\Publish\API\Repository\Exceptions\LimitationValidationException
2413
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleByIdentifier
2414
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUserGroup
2415
     */
2416
    public function testAssignRoleToUserGroupWithRoleLimitationThrowsLimitationValidationException()
2417
    {
2418
        $repository = $this->getRepository();
2419
2420
        $mainGroupId = $this->generateId('group', 4);
2421
        /* BEGIN: Use Case */
2422
        // $mainGroupId is the ID of the main "Users" group
2423
2424
        $userService = $repository->getUserService();
2425
        $roleService = $repository->getRoleService();
2426
2427
        $userGroup = $userService->loadUserGroup($mainGroupId);
2428
2429
        // Load the existing "Anonymous" role
2430
        $role = $roleService->loadRoleByIdentifier('Anonymous');
2431
2432
        // Assign the "Anonymous" role to the newly created user group
2433
        // This call will fail with an LimitationValidationException, because subtree "/lorem/ipsum/42/"
2434
        // does not exists
2435
        $roleService->assignRoleToUserGroup(
2436
            $role,
2437
            $userGroup,
2438
            new SubtreeLimitation(
2439
                array(
2440
                    'limitationValues' => array('/lorem/ipsum/42/'),
2441
                )
2442
            )
2443
        );
2444
        /* END: Use Case */
2445
    }
2446
2447
    /**
2448
     * Test for the assignRoleToUserGroup() method.
2449
     *
2450
     * Makes sure assigning role several times throws.
2451
     *
2452
     * @see \eZ\Publish\API\Repository\RoleService::assignRoleToUserGroup($role, $userGroup, $roleLimitation)
2453
     * @expectedException \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException
2454
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleByIdentifier
2455
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUserGroup
2456
     */
2457
    public function testAssignRoleToUserGroupThrowsInvalidArgumentException()
2458
    {
2459
        $repository = $this->getRepository();
2460
2461
        $mainGroupId = $this->generateId('group', 4);
2462
        /* BEGIN: Use Case */
2463
        // $mainGroupId is the ID of the main "Users" group
2464
2465
        $userService = $repository->getUserService();
2466
        $roleService = $repository->getRoleService();
2467
2468
        $userGroup = $userService->loadUserGroup($mainGroupId);
2469
2470
        // Load the existing "Anonymous" role
2471
        $role = $roleService->loadRoleByIdentifier('Anonymous');
2472
2473
        // Assign the "Anonymous" role to the newly created user group
2474
        try {
2475
            $roleService->assignRoleToUserGroup(
2476
                $role,
2477
                $userGroup
2478
            );
2479
        } catch (Exception $e) {
2480
            $this->fail('Got exception at first valid attempt to assign role');
2481
        }
2482
2483
        // Re-Assign the "Anonymous" role to the newly created user group
2484
        // This call will fail with an InvalidArgumentException, because role is already assigned
2485
        $roleService->assignRoleToUserGroup(
2486
            $role,
2487
            $userGroup
2488
        );
2489
        /* END: Use Case */
2490
    }
2491
2492
    /**
2493
     * Test for the assignRoleToUserGroup() method.
2494
     *
2495
     * Makes sure assigning role several times with same limitations throws.
2496
     *
2497
     * @see \eZ\Publish\API\Repository\RoleService::assignRoleToUserGroup($role, $userGroup, $roleLimitation)
2498
     * @expectedException \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException
2499
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleByIdentifier
2500
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUserGroup
2501
     */
2502
    public function testAssignRoleToUserGroupWithRoleLimitationThrowsInvalidArgumentException()
2503
    {
2504
        $repository = $this->getRepository();
2505
2506
        $mainGroupId = $this->generateId('group', 4);
2507
        /* BEGIN: Use Case */
2508
        // $mainGroupId is the ID of the main "Users" group
2509
2510
        $userService = $repository->getUserService();
2511
        $roleService = $repository->getRoleService();
2512
2513
        $userGroup = $userService->loadUserGroup($mainGroupId);
2514
2515
        // Load the existing "Anonymous" role
2516
        $role = $roleService->loadRoleByIdentifier('Anonymous');
2517
2518
        // Assign the "Anonymous" role to the newly created user group
2519
        try {
2520
            $roleService->assignRoleToUserGroup(
2521
                $role,
2522
                $userGroup,
2523
                new SubtreeLimitation(
2524
                    array(
2525
                        'limitationValues' => array('/1/43/', '/1/2/'),
2526
                    )
2527
                )
2528
            );
2529
        } catch (Exception $e) {
2530
            $this->fail('Got exception at first valid attempt to assign role');
2531
        }
2532
2533
        // Re-Assign the "Anonymous" role to the newly created user group
2534
        // This call will fail with an InvalidArgumentException, because limitation is already assigned
2535
        $roleService->assignRoleToUserGroup(
2536
            $role,
2537
            $userGroup,
2538
            new SubtreeLimitation(
2539
                array(
2540
                    'limitationValues' => array('/1/43/'),
2541
                )
2542
            )
2543
        );
2544
        /* END: Use Case */
2545
    }
2546
2547
    /**
2548
     * Test for the unassignRoleFromUserGroup() method.
2549
     *
2550
     * @see \eZ\Publish\API\Repository\RoleService::unassignRoleFromUserGroup()
2551
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUserGroup
2552
     */
2553 View Code Duplication
    public function testUnassignRoleFromUserGroup()
2554
    {
2555
        $repository = $this->getRepository();
2556
        $roleService = $repository->getRoleService();
2557
2558
        /* BEGIN: Use Case */
2559
        $userGroup = $this->createUserGroupVersion1();
2560
2561
        // Load the existing "Member" role
2562
        $role = $roleService->loadRoleByIdentifier('Member');
2563
2564
        // Assign the "Member" role to the newly created user group
2565
        $roleService->assignRoleToUserGroup($role, $userGroup);
2566
2567
        // Unassign group from role
2568
        $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...
2569
2570
        // The assignments array will not contain the new role<->group assignment
2571
        $roleAssignments = $roleService->getRoleAssignments($role);
2572
        /* END: Use Case */
2573
2574
        // Members + Editors + Partners
2575
        $this->assertEquals(3, count($roleAssignments));
2576
    }
2577
2578
    /**
2579
     * Test for the unassignRoleFromUserGroup() method.
2580
     *
2581
     * @see \eZ\Publish\API\Repository\RoleService::unassignRoleFromUserGroup()
2582
     * @expectedException \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException
2583
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testUnassignRoleFromUserGroup
2584
     */
2585 View Code Duplication
    public function testUnassignRoleFromUserGroupThrowsInvalidArgumentException()
2586
    {
2587
        $repository = $this->getRepository();
2588
        $roleService = $repository->getRoleService();
2589
2590
        /* BEGIN: Use Case */
2591
        $userGroup = $this->createUserGroupVersion1();
2592
2593
        // Load the existing "Member" role
2594
        $role = $roleService->loadRoleByIdentifier('Member');
2595
2596
        // This call will fail with a "InvalidArgumentException", because the
2597
        // user group does not have the "Member" role.
2598
        $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...
2599
        /* END: Use Case */
2600
    }
2601
2602
    /**
2603
     * Test unassigning role by assignment.
2604
     *
2605
     * @covers \eZ\Publish\API\Repository\RoleService::removeRoleAssignment
2606
     */
2607
    public function testUnassignRoleByAssignment()
2608
    {
2609
        $repository = $this->getRepository();
2610
        $roleService = $repository->getRoleService();
2611
2612
        $role = $roleService->loadRole(2);
2613
        $user = $repository->getUserService()->loadUser(14);
2614
2615
        $originalAssignmentCount = count($roleService->getRoleAssignmentsForUser($user));
2616
2617
        $roleService->assignRoleToUser($role, $user);
2618
        $newAssignmentCount = count($roleService->getRoleAssignmentsForUser($user));
2619
        self::assertEquals($originalAssignmentCount + 1, $newAssignmentCount);
2620
2621
        $assignments = $roleService->getRoleAssignmentsForUser($user);
2622
        $roleService->removeRoleAssignment($assignments[0]);
2623
        $finalAssignmentCount = count($roleService->getRoleAssignmentsForUser($user));
2624
        self::assertEquals($newAssignmentCount - 1, $finalAssignmentCount);
2625
    }
2626
2627
    /**
2628
     * Test unassigning role by assignment.
2629
     *
2630
     * But on current admin user so he lacks access to read roles.
2631
     *
2632
     * @covers \eZ\Publish\API\Repository\RoleService::removeRoleAssignment
2633
     * @expectedException \eZ\Publish\API\Repository\Exceptions\UnauthorizedException
2634
     */
2635 View Code Duplication
    public function testUnassignRoleByAssignmentThrowsUnauthorizedException()
2636
    {
2637
        $repository = $this->getRepository();
2638
        $roleService = $repository->getRoleService();
2639
2640
        try {
2641
            $adminUserGroup = $repository->getUserService()->loadUserGroup(12);
2642
            $assignments = $roleService->getRoleAssignmentsForUserGroup($adminUserGroup);
2643
            $roleService->removeRoleAssignment($assignments[0]);
2644
        } catch (Exception $e) {
2645
            self::fail(
2646
                'Unexpected exception: ' . $e->getMessage() . " \n[" . $e->getFile() . ' (' . $e->getLine() . ')]'
2647
            );
2648
        }
2649
2650
        $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...
2651
    }
2652
2653
    /**
2654
     * Test unassigning role by non-existing assignment.
2655
     *
2656
     * @covers \eZ\Publish\API\Repository\RoleService::removeRoleAssignment
2657
     * @expectedException \eZ\Publish\API\Repository\Exceptions\NotFoundException
2658
     */
2659 View Code Duplication
    public function testUnassignRoleByAssignmentThrowsNotFoundException()
2660
    {
2661
        $repository = $this->getRepository();
2662
        $roleService = $repository->getRoleService();
2663
2664
        try {
2665
            $editorsUserGroup = $repository->getUserService()->loadUserGroup(13);
2666
            $assignments = $roleService->getRoleAssignmentsForUserGroup($editorsUserGroup);
2667
            $roleService->removeRoleAssignment($assignments[0]);
2668
        } catch (Exception $e) {
2669
            self::fail(
2670
                'Unexpected exception: ' . $e->getMessage() . " \n[" . $e->getFile() . ' (' . $e->getLine() . ')]'
2671
            );
2672
        }
2673
2674
        $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...
2675
    }
2676
2677
    /**
2678
     * Test for the getRoleAssignmentsForUserGroup() method.
2679
     *
2680
     * @see \eZ\Publish\API\Repository\RoleService::getRoleAssignmentsForUserGroup()
2681
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUserGroup
2682
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRoleWithAddPolicy
2683
     */
2684 View Code Duplication
    public function testGetRoleAssignmentsForUserGroup()
2685
    {
2686
        $repository = $this->getRepository();
2687
        $roleService = $repository->getRoleService();
2688
2689
        /* BEGIN: Use Case */
2690
        $userGroup = $this->createUserGroupVersion1();
2691
2692
        // Instantiate a role create and add some policies
2693
        $roleCreate = $roleService->newRoleCreateStruct('Example Role');
2694
2695
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
2696
        // $roleCreate->mainLanguageCode = 'eng-US';
2697
2698
        $roleCreate->addPolicy(
2699
            $roleService->newPolicyCreateStruct('user', 'login')
2700
        );
2701
        $roleCreate->addPolicy(
2702
            $roleService->newPolicyCreateStruct('content', 'read')
2703
        );
2704
        $roleCreate->addPolicy(
2705
            $roleService->newPolicyCreateStruct('content', 'edit')
2706
        );
2707
2708
        // Create the new role instance
2709
        $roleDraft = $roleService->createRole($roleCreate);
2710
        $roleService->publishRoleDraft($roleDraft);
2711
        $role = $roleService->loadRole($roleDraft->id);
2712
2713
        // Assign role to new user group
2714
        $roleService->assignRoleToUserGroup($role, $userGroup);
2715
2716
        // Load the currently assigned role
2717
        $roleAssignments = $roleService->getRoleAssignmentsForUserGroup($userGroup);
2718
        /* END: Use Case */
2719
2720
        $this->assertEquals(1, count($roleAssignments));
2721
        $this->assertInstanceOf(
2722
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\UserGroupRoleAssignment',
2723
            reset($roleAssignments)
2724
        );
2725
    }
2726
2727
    /**
2728
     * Test for the loadPoliciesByUserId() method.
2729
     *
2730
     * @see \eZ\Publish\API\Repository\RoleService::loadPoliciesByUserId()
2731
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUser
2732
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUserGroup
2733
     */
2734
    public function testLoadPoliciesByUserId()
2735
    {
2736
        $repository = $this->getRepository();
2737
2738
        $anonUserId = $this->generateId('user', 10);
2739
        /* BEGIN: Use Case */
2740
        // $anonUserId is the ID of the "Anonymous" user.
2741
2742
        $userService = $repository->getUserService();
2743
        $roleService = $repository->getRoleService();
2744
2745
        // Load "Anonymous" user
2746
        $user = $userService->loadUser($anonUserId);
2747
2748
        // Instantiate a role create and add some policies
2749
        $roleCreate = $roleService->newRoleCreateStruct('User Role');
2750
2751
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
2752
        // $roleCreate->mainLanguageCode = 'eng-US';
2753
2754
        $roleCreate->addPolicy(
2755
            $roleService->newPolicyCreateStruct('notification', 'use')
2756
        );
2757
        $roleCreate->addPolicy(
2758
            $roleService->newPolicyCreateStruct('user', 'password')
2759
        );
2760
        $roleCreate->addPolicy(
2761
            $roleService->newPolicyCreateStruct('user', 'selfedit')
2762
        );
2763
2764
        // Create the new role instance
2765
        $roleDraft = $roleService->createRole($roleCreate);
2766
        $roleService->publishRoleDraft($roleDraft);
2767
        $role = $roleService->loadRole($roleDraft->id);
2768
2769
        // Assign role to anon user
2770
        $roleService->assignRoleToUser($role, $user);
2771
2772
        // Load the currently assigned role
2773
        $policies = array();
2774
        foreach ($roleService->loadPoliciesByUserId($user->id) as $policy) {
2775
            $policies[] = array($policy->roleId, $policy->module, $policy->function);
2776
        }
2777
        /* END: Use Case */
2778
        array_multisort($policies);
2779
2780
        $this->assertEquals(
2781
            array(
2782
                array(1, 'content', 'pdf'),
2783
                array(1, 'content', 'read'),
2784
                array(1, 'content', 'read'),
2785
                array(1, 'rss', 'feed'),
2786
                array(1, 'user', 'login'),
2787
                array(1, 'user', 'login'),
2788
                array(1, 'user', 'login'),
2789
                array(1, 'user', 'login'),
2790
                array($role->id, 'notification', 'use'),
2791
                array($role->id, 'user', 'password'),
2792
                array($role->id, 'user', 'selfedit'),
2793
            ),
2794
            $policies
2795
        );
2796
    }
2797
2798
    /**
2799
     * Test for the loadPoliciesByUserId() method.
2800
     *
2801
     * @see \eZ\Publish\API\Repository\RoleService::loadPoliciesByUserId()
2802
     * @expectedException \eZ\Publish\API\Repository\Exceptions\NotFoundException
2803
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadPoliciesByUserId
2804
     */
2805
    public function testLoadPoliciesByUserIdThrowsNotFoundException()
2806
    {
2807
        $repository = $this->getRepository();
2808
2809
        $nonExistingUserId = $this->generateId('user', self::DB_INT_MAX);
2810
        /* BEGIN: Use Case */
2811
        $roleService = $repository->getRoleService();
2812
2813
        // This call will fail with a "NotFoundException", because hopefully no
2814
        // user with an ID equal to self::DB_INT_MAX exists.
2815
        $roleService->loadPoliciesByUserId($nonExistingUserId);
2816
        /* END: Use Case */
2817
    }
2818
2819
    /**
2820
     * Test for the publishRoleDraft() method.
2821
     *
2822
     * @see \eZ\Publish\API\Repository\RoleService::publishRoleDraft()
2823
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRoleDraft
2824
     */
2825 View Code Duplication
    public function testPublishRoleDraft()
2826
    {
2827
        $repository = $this->getRepository();
2828
2829
        /* BEGIN: Use Case */
2830
        $roleService = $repository->getRoleService();
2831
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
2832
2833
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
2834
        // $roleCreate->mainLanguageCode = 'eng-US';
2835
2836
        $roleDraft = $roleService->createRole($roleCreate);
2837
2838
        $roleDraft = $roleService->addPolicyByRoleDraft(
2839
            $roleDraft,
2840
            $roleService->newPolicyCreateStruct('content', 'delete')
2841
        );
2842
        $roleDraft = $roleService->addPolicyByRoleDraft(
2843
            $roleDraft,
2844
            $roleService->newPolicyCreateStruct('content', 'create')
2845
        );
2846
2847
        $roleService->publishRoleDraft($roleDraft);
2848
        /* END: Use Case */
2849
2850
        $this->assertInstanceOf(
2851
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\Role',
2852
            $roleService->loadRoleByIdentifier($roleCreate->identifier)
2853
        );
2854
    }
2855
2856
    /**
2857
     * Test for the publishRoleDraft() method.
2858
     *
2859
     * @see \eZ\Publish\API\Repository\RoleService::publishRoleDraft()
2860
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRoleDraft
2861
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicyByRoleDraft
2862
     */
2863 View Code Duplication
    public function testPublishRoleDraftAddPolicies()
2864
    {
2865
        $repository = $this->getRepository();
2866
2867
        /* BEGIN: Use Case */
2868
        $roleService = $repository->getRoleService();
2869
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
2870
2871
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
2872
        // $roleCreate->mainLanguageCode = 'eng-US';
2873
2874
        $roleDraft = $roleService->createRole($roleCreate);
2875
2876
        $roleDraft = $roleService->addPolicyByRoleDraft(
2877
            $roleDraft,
2878
            $roleService->newPolicyCreateStruct('content', 'delete')
2879
        );
2880
        $roleDraft = $roleService->addPolicyByRoleDraft(
2881
            $roleDraft,
2882
            $roleService->newPolicyCreateStruct('content', 'create')
2883
        );
2884
2885
        $roleService->publishRoleDraft($roleDraft);
2886
        $role = $roleService->loadRoleByIdentifier($roleCreate->identifier);
2887
        /* END: Use Case */
2888
2889
        $actual = array();
2890
        foreach ($role->getPolicies() as $policy) {
2891
            $actual[] = array(
2892
                'module' => $policy->module,
2893
                'function' => $policy->function,
2894
            );
2895
        }
2896
        usort(
2897
            $actual,
2898
            function ($p1, $p2) {
2899
                return strcasecmp($p1['function'], $p2['function']);
2900
            }
2901
        );
2902
2903
        $this->assertEquals(
2904
            array(
2905
                array(
2906
                    'module' => 'content',
2907
                    'function' => 'create',
2908
                ),
2909
                array(
2910
                    'module' => 'content',
2911
                    'function' => 'delete',
2912
                ),
2913
            ),
2914
            $actual
2915
        );
2916
    }
2917
2918
    /**
2919
     * Create a user group fixture in a variable named <b>$userGroup</b>,.
2920
     *
2921
     * @return \eZ\Publish\API\Repository\Values\User\UserGroup
2922
     */
2923
    private function createUserGroupVersion1()
2924
    {
2925
        $repository = $this->getRepository();
2926
2927
        $mainGroupId = $this->generateId('group', 4);
2928
        /* BEGIN: Inline */
2929
        // $mainGroupId is the ID of the main "Users" group
2930
2931
        $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...
2932
        $userService = $repository->getUserService();
2933
2934
        // Load main group
2935
        $parentUserGroup = $userService->loadUserGroup($mainGroupId);
2936
2937
        // Instantiate a new create struct
2938
        $userGroupCreate = $userService->newUserGroupCreateStruct('eng-US');
2939
        $userGroupCreate->setField('name', 'Example Group');
2940
2941
        // Create the new user group
2942
        $userGroup = $userService->createUserGroup(
2943
            $userGroupCreate,
2944
            $parentUserGroup
2945
        );
2946
        /* END: Inline */
2947
2948
        return $userGroup;
2949
    }
2950
}
2951