Completed
Push — readme ( 4da83f...7adc69 )
by
unknown
28:00 queued 04:49
created

testAssignRoleToUserWithRoleLimitation()   B

Complexity

Conditions 5
Paths 9

Size

Total Lines 98

Duplication

Lines 98
Ratio 100 %

Importance

Changes 0
Metric Value
cc 5
nc 9
nop 0
dl 98
loc 98
rs 7.7325
c 0
b 0
f 0

How to fix   Long Method   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
3
/**
4
 * File containing the RoleServiceTest class.
5
 *
6
 * @copyright Copyright (C) eZ Systems AS. All rights reserved.
7
 * @license For full copyright and license information view LICENSE file distributed with this source code.
8
 */
9
namespace eZ\Publish\API\Repository\Tests;
10
11
use eZ\Publish\API\Repository\Values\User\Limitation;
12
use eZ\Publish\API\Repository\Values\User\Limitation\ContentTypeLimitation;
13
use eZ\Publish\API\Repository\Values\User\Limitation\LanguageLimitation;
14
use eZ\Publish\API\Repository\Values\User\Limitation\SubtreeLimitation;
15
use eZ\Publish\API\Repository\Values\User\Policy;
16
use eZ\Publish\API\Repository\Values\User\Role;
17
use eZ\Publish\API\Repository\Exceptions\NotFoundException;
18
use Exception;
19
20
/**
21
 * Test case for operations in the RoleService using in memory storage.
22
 *
23
 * The following IDs from the default eZ community edition database are used in
24
 * this test:
25
 *
26
 * <ul>
27
 *   <li>
28
 *     ContentType
29
 *     <ul>
30
 *       <li><strong>28</strong>: File</li>
31
 *       <li><strong>29</strong>: Flash</li>
32
 *       <li><strong>30</strong>: Image</li>
33
 *     </ul>
34
 *   </li>
35
 * <ul>
36
 *
37
 * @see eZ\Publish\API\Repository\RoleService
38
 * @group role
39
 */
40
class RoleServiceTest extends BaseTest
41
{
42
    /**
43
     * Test for the newRoleCreateStruct() method.
44
     *
45
     * @see \eZ\Publish\API\Repository\RoleService::newRoleCreateStruct()
46
     */
47
    public function testNewRoleCreateStruct()
48
    {
49
        $repository = $this->getRepository();
50
51
        $roleService = $repository->getRoleService();
52
        $roleCreate = $roleService->newRoleCreateStruct('roleName');
53
54
        $this->assertInstanceOf('\\eZ\\Publish\\API\\Repository\\Values\\User\\RoleCreateStruct', $roleCreate);
55
    }
56
57
    /**
58
     * Test for the newRoleCreateStruct() method.
59
     *
60
     * @see \eZ\Publish\API\Repository\RoleService::newRoleCreateStruct()
61
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewRoleCreateStruct
62
     */
63
    public function testNewRoleCreateStructSetsNamePropertyOnStruct()
64
    {
65
        $repository = $this->getRepository();
66
67
        /* BEGIN: Use Case */
68
69
        $roleService = $repository->getRoleService();
70
        $roleCreate = $roleService->newRoleCreateStruct('roleName');
71
72
        /* END: Use Case */
73
74
        $this->assertEquals('roleName', $roleCreate->identifier);
75
    }
76
77
    /**
78
     * Test for the createRole() method.
79
     *
80
     * @see \eZ\Publish\API\Repository\RoleService::createRole()
81
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewRoleCreateStruct
82
     */
83
    public function testCreateRole()
84
    {
85
        $repository = $this->getRepository();
86
87
        /* BEGIN: Use Case */
88
89
        $roleService = $repository->getRoleService();
90
        $roleCreate = $roleService->newRoleCreateStruct('roleName');
91
92
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
93
        // $roleCreate->mainLanguageCode = 'eng-US';
94
95
        $role = $roleService->createRole($roleCreate);
96
97
        /* END: Use Case */
98
99
        $this->assertInstanceOf(
100
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\RoleDraft',
101
            $role
102
        );
103
104
        return [
105
            'createStruct' => $roleCreate,
106
            'role' => $role,
107
        ];
108
    }
109
110
    /**
111
     * Test for the createRole() method.
112
     *
113
     * @see \eZ\Publish\API\Repository\RoleService::createRole()
114
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRole
115
     */
116
    public function testRoleCreateStructValues(array $data)
117
    {
118
        $createStruct = $data['createStruct'];
119
        $role = $data['role'];
120
121
        $this->assertEquals(
122
            [
123
                'identifier' => $createStruct->identifier,
124
                'policies' => $createStruct->policies,
125
            ],
126
            [
127
                'identifier' => $role->identifier,
128
                'policies' => $role->policies,
129
            ]
130
        );
131
        $this->assertNotNull($role->id);
132
133
        return $data;
134
    }
135
136
    /**
137
     * Test for the createRole() method.
138
     *
139
     * @see \eZ\Publish\API\Repository\RoleService::createRole()
140
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewRoleCreateStruct
141
     */
142
    public function testCreateRoleWithPolicy()
143
    {
144
        $repository = $this->getRepository();
145
146
        /* BEGIN: Use Case */
147
148
        $roleService = $repository->getRoleService();
149
        $roleCreate = $roleService->newRoleCreateStruct('roleName');
150
151
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
152
        // $roleCreate->mainLanguageCode = 'eng-US';
153
154
        // Create new subtree limitation
155
        $limitation = new SubtreeLimitation(
156
            [
157
                'limitationValues' => ['/1/2/'],
158
            ]
159
        );
160
161
        // Create policy create struct and add limitation to it
162
        $policyCreate = $roleService->newPolicyCreateStruct('content', 'read');
163
        $policyCreate->addLimitation($limitation);
164
165
        // Add policy create struct to role create struct
166
        $roleCreate->addPolicy($policyCreate);
167
168
        $role = $roleService->createRole($roleCreate);
169
170
        /* END: Use Case */
171
172
        $this->assertInstanceOf(
173
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\RoleDraft',
174
            $role
175
        );
176
177
        return [
178
            'createStruct' => $roleCreate,
179
            'role' => $role,
180
        ];
181
    }
182
183
    /**
184
     * Test for the createRole() method.
185
     *
186
     * @see \eZ\Publish\API\Repository\RoleService::createRole()
187
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRoleWithPolicy
188
     */
189
    public function testRoleCreateStructValuesWithPolicy(array $data)
190
    {
191
        $createStruct = $data['createStruct'];
192
        $role = $data['role'];
193
194
        $this->assertEquals(
195
            [
196
                'identifier' => $createStruct->identifier,
197
                'policy_module' => $createStruct->policies[0]->module,
198
                'policy_function' => $createStruct->policies[0]->function,
199
                'policy_limitation' => array_values($createStruct->policies[0]->limitations),
200
            ],
201
            [
202
                'identifier' => $role->identifier,
203
                'policy_module' => $role->policies[0]->module,
204
                'policy_function' => $role->policies[0]->function,
205
                'policy_limitation' => array_values($role->policies[0]->limitations),
206
            ]
207
        );
208
        $this->assertNotNull($role->id);
209
210
        return $data;
211
    }
212
213
    /**
214
     * Test creating a role with multiple policies.
215
     *
216
     * @covers \eZ\Publish\API\Repository\RoleService::createRole
217
     */
218
    public function testCreateRoleWithMultiplePolicies()
219
    {
220
        $repository = $this->getRepository();
221
        $roleService = $repository->getRoleService();
222
223
        $limitation1 = new Limitation\ContentTypeLimitation();
224
        $limitation1->limitationValues = ['1', '3', '13'];
225
226
        $limitation2 = new Limitation\SectionLimitation();
227
        $limitation2->limitationValues = ['2', '3'];
228
229
        $limitation3 = new Limitation\OwnerLimitation();
230
        $limitation3->limitationValues = ['1', '2'];
231
232
        $limitation4 = new Limitation\UserGroupLimitation();
233
        $limitation4->limitationValues = ['1'];
234
235
        $policyCreateStruct1 = $roleService->newPolicyCreateStruct('content', 'read');
236
        $policyCreateStruct1->addLimitation($limitation1);
237
        $policyCreateStruct1->addLimitation($limitation2);
238
239
        $policyCreateStruct2 = $roleService->newPolicyCreateStruct('content', 'edit');
240
        $policyCreateStruct2->addLimitation($limitation3);
241
        $policyCreateStruct2->addLimitation($limitation4);
242
243
        $roleCreateStruct = $roleService->newRoleCreateStruct('ultimate_permissions');
244
        $roleCreateStruct->addPolicy($policyCreateStruct1);
245
        $roleCreateStruct->addPolicy($policyCreateStruct2);
246
247
        $createdRole = $roleService->createRole($roleCreateStruct);
248
249
        self::assertInstanceOf(Role::class, $createdRole);
250
        self::assertGreaterThan(0, $createdRole->id);
251
252
        $this->assertPropertiesCorrect(
253
            [
254
                'identifier' => $roleCreateStruct->identifier,
255
            ],
256
            $createdRole
257
        );
258
259
        self::assertCount(2, $createdRole->getPolicies());
260
261
        foreach ($createdRole->getPolicies() as $policy) {
262
            self::assertInstanceOf(Policy::class, $policy);
263
            self::assertGreaterThan(0, $policy->id);
264
            self::assertEquals($createdRole->id, $policy->roleId);
265
266
            self::assertCount(2, $policy->getLimitations());
267
268
            foreach ($policy->getLimitations() as $limitation) {
269
                self::assertInstanceOf(Limitation::class, $limitation);
270
271
                if ($policy->module == 'content' && $policy->function == 'read') {
272 View Code Duplication
                    switch ($limitation->getIdentifier()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
273
                        case Limitation::CONTENTTYPE:
274
                            self::assertEquals($limitation1->limitationValues, $limitation->limitationValues);
275
                            break;
276
277
                        case Limitation::SECTION:
278
                            self::assertEquals($limitation2->limitationValues, $limitation->limitationValues);
279
                            break;
280
281
                        default:
282
                            self::fail('Created role contains limitations not defined with create struct');
283
                    }
284
                } elseif ($policy->module == 'content' && $policy->function == 'edit') {
285 View Code Duplication
                    switch ($limitation->getIdentifier()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
286
                        case Limitation::OWNER:
287
                            self::assertEquals($limitation3->limitationValues, $limitation->limitationValues);
288
                            break;
289
290
                        case Limitation::USERGROUP:
291
                            self::assertEquals($limitation4->limitationValues, $limitation->limitationValues);
292
                            break;
293
294
                        default:
295
                            self::fail('Created role contains limitations not defined with create struct');
296
                    }
297
                } else {
298
                    self::fail('Created role contains policy not defined with create struct');
299
                }
300
            }
301
        }
302
    }
303
304
    /**
305
     * Test for the createRoleDraft() method.
306
     *
307
     * @see \eZ\Publish\API\Repository\RoleService::createRoleDraft()
308
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewRoleCreateStruct
309
     */
310 View Code Duplication
    public function testCreateRoleDraft()
311
    {
312
        $repository = $this->getRepository();
313
314
        /* BEGIN: Use Case */
315
316
        $roleService = $repository->getRoleService();
317
        $roleCreate = $roleService->newRoleCreateStruct('roleName');
318
319
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
320
        // $roleCreate->mainLanguageCode = 'eng-US';
321
322
        $roleDraft = $roleService->createRole($roleCreate);
323
        $roleService->publishRoleDraft($roleDraft);
324
        $role = $roleService->loadRole($roleDraft->id);
325
        $newRoleDraft = $roleService->createRoleDraft($role);
326
327
        /* END: Use Case */
328
329
        $this->assertInstanceOf(
330
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\RoleDraft',
331
            $newRoleDraft
332
        );
333
    }
334
335
    /**
336
     * Test for the createRole() method.
337
     *
338
     * @see \eZ\Publish\API\Repository\RoleService::createRole()
339
     * @expectedException \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException
340
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRole
341
     */
342
    public function testCreateRoleThrowsInvalidArgumentException()
343
    {
344
        $repository = $this->getRepository();
345
346
        /* BEGIN: Use Case */
347
348
        $roleService = $repository->getRoleService();
349
        $roleCreate = $roleService->newRoleCreateStruct('Editor');
350
351
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
352
        // $roleCreate->mainLanguageCode = 'eng-US';
353
354
        // This call will fail with an InvalidArgumentException, because Editor exists
355
        $roleService->createRole($roleCreate);
356
357
        /* END: Use Case */
358
    }
359
360
    /**
361
     * Test for the createRoleDraft() method.
362
     *
363
     * @see \eZ\Publish\API\Repository\RoleService::createRoleDraft()
364
     * @expectedException \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException
365
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRoleDraft
366
     */
367
    public function testCreateRoleDraftThrowsInvalidArgumentException()
368
    {
369
        $repository = $this->getRepository();
370
371
        /* BEGIN: Use Case */
372
373
        $roleService = $repository->getRoleService();
374
        $roleCreate = $roleService->newRoleCreateStruct('Editor');
375
376
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
377
        // $roleCreate->mainLanguageCode = 'eng-US';
378
379
        $roleDraft = $roleService->createRole($roleCreate);
380
        $roleService->publishRoleDraft($roleDraft);
381
        $role = $roleService->loadRole($roleDraft->id);
382
        $roleService->createRoleDraft($role); // First role draft
383
384
        // This call will fail with an InvalidArgumentException, because there is already a draft
385
        $roleService->createRoleDraft($role);
386
387
        /* END: Use Case */
388
    }
389
390
    /**
391
     * Test for the createRole() method.
392
     *
393
     * @see \eZ\Publish\API\Repository\RoleService::createRole()
394
     * @expectedException \eZ\Publish\API\Repository\Exceptions\LimitationValidationException
395
     */
396 View Code Duplication
    public function testCreateRoleThrowsLimitationValidationException()
397
    {
398
        $repository = $this->getRepository();
399
400
        /* BEGIN: Use Case */
401
        $roleService = $repository->getRoleService();
402
403
        // Create new role create struct
404
        $roleCreate = $roleService->newRoleCreateStruct('Lumberjack');
405
406
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
407
        // $roleCreate->mainLanguageCode = 'eng-US';
408
409
        // Create new subtree limitation
410
        $limitation = new SubtreeLimitation(
411
            [
412
                'limitationValues' => ['/mountain/forest/tree/42/'],
413
            ]
414
        );
415
416
        // Create policy create struct and add limitation to it
417
        $policyCreate = $roleService->newPolicyCreateStruct('content', 'remove');
418
        $policyCreate->addLimitation($limitation);
419
420
        // Add policy create struct to role create struct
421
        $roleCreate->addPolicy($policyCreate);
422
423
        // This call will fail with an LimitationValidationException, because subtree
424
        // "/mountain/forest/tree/42/" does not exist
425
        $roleService->createRole($roleCreate);
426
        /* END: Use Case */
427
    }
428
429
    /**
430
     * Test for the createRole() method.
431
     *
432
     * @see \eZ\Publish\API\Repository\RoleService::createRole()
433
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewRoleCreateStruct
434
     */
435
    public function testCreateRoleInTransactionWithRollback()
436
    {
437
        $repository = $this->getRepository();
438
439
        /* BEGIN: Use Case */
440
441
        $roleService = $repository->getRoleService();
442
443
        $repository->beginTransaction();
444
445
        $roleCreate = $roleService->newRoleCreateStruct('roleName');
446
447
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
448
        // $roleCreate->mainLanguageCode = 'eng-US';
449
450
        $createdRoleId = $roleService->createRole($roleCreate)->id;
451
452
        $repository->rollback();
453
454
        try {
455
            // This call will fail with a "NotFoundException"
456
            $role = $roleService->loadRole($createdRoleId);
0 ignored issues
show
Unused Code introduced by
$role is not used, you could remove the assignment.

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

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

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

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

Loading history...
457
        } catch (NotFoundException $e) {
458
            return;
459
        }
460
        /* END: Use Case */
461
462
        $this->fail('Role object still exists after rollback.');
463
    }
464
465
    /**
466
     * Test for the createRoleDraft() method.
467
     *
468
     * @see \eZ\Publish\API\Repository\RoleService::createRoleDraft()
469
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewRoleCreateStruct
470
     */
471
    public function testCreateRoleDraftInTransactionWithRollback()
472
    {
473
        $repository = $this->getRepository();
474
475
        /* BEGIN: Use Case */
476
477
        $roleService = $repository->getRoleService();
478
479
        $repository->beginTransaction();
480
481
        $roleCreate = $roleService->newRoleCreateStruct('roleName');
482
483
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
484
        // $roleCreate->mainLanguageCode = 'eng-US';
485
486
        $createdRoleId = $roleService->createRole($roleCreate)->id;
487
488
        $repository->rollback();
489
490
        try {
491
            // This call will fail with a "NotFoundException"
492
            $role = $roleService->loadRoleDraft($createdRoleId);
0 ignored issues
show
Unused Code introduced by
$role is not used, you could remove the assignment.

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

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

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

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

Loading history...
493
        } catch (NotFoundException $e) {
494
            return;
495
        }
496
        /* END: Use Case */
497
498
        $this->fail('Role draft object still exists after rollback.');
499
    }
500
501
    /**
502
     * Test for the loadRole() method.
503
     *
504
     * @see \eZ\Publish\API\Repository\RoleService::loadRole()
505
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRole
506
     */
507
    public function testLoadRole()
508
    {
509
        $repository = $this->getRepository();
510
511
        /* BEGIN: Use Case */
512
513
        $roleService = $repository->getRoleService();
514
        $roleCreate = $roleService->newRoleCreateStruct('roleName');
515
516
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
517
        // $roleCreate->mainLanguageCode = 'eng-US';
518
519
        $roleDraft = $roleService->createRole($roleCreate);
520
        $roleService->publishRoleDraft($roleDraft);
521
522
        // Load the newly created role by its ID
523
        $role = $roleService->loadRole($roleDraft->id);
524
525
        /* END: Use Case */
526
527
        $this->assertEquals('roleName', $role->identifier);
528
    }
529
530
    /**
531
     * Test for the loadRoleDraft() method.
532
     *
533
     * @see \eZ\Publish\API\Repository\RoleService::loadRoleDraft()
534
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRoleDraft
535
     */
536 View Code Duplication
    public function testLoadRoleDraft()
537
    {
538
        $repository = $this->getRepository();
539
540
        /* BEGIN: Use Case */
541
542
        $roleService = $repository->getRoleService();
543
        $roleCreate = $roleService->newRoleCreateStruct('roleName');
544
545
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
546
        // $roleCreate->mainLanguageCode = 'eng-US';
547
548
        $roleDraft = $roleService->createRole($roleCreate);
549
550
        // Load the newly created role by its ID
551
        $role = $roleService->loadRoleDraft($roleDraft->id);
552
553
        /* END: Use Case */
554
555
        $this->assertEquals('roleName', $role->identifier);
556
    }
557
558
    public function testLoadRoleDraftByRoleId()
559
    {
560
        $repository = $this->getRepository();
561
562
        /* BEGIN: Use Case */
563
564
        $roleService = $repository->getRoleService();
565
        $roleCreate = $roleService->newRoleCreateStruct('roleName');
566
567
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
568
        // $roleCreate->mainLanguageCode = 'eng-US';
569
570
        $role = $roleService->createRole($roleCreate);
571
        $roleService->publishRoleDraft($role);
572
573
        // Now create a new draft based on the role
574
        $newDraft = $roleService->createRoleDraft($role);
575
        $loadedRoleDraft = $roleService->loadRoleDraftByRoleId($role->id);
576
577
        /* END: Use Case */
578
579
        self::assertEquals('roleName', $role->identifier);
580
        self::assertInstanceOf('eZ\Publish\API\Repository\Values\User\RoleDraft', $loadedRoleDraft);
581
        self::assertEquals($newDraft, $loadedRoleDraft);
582
    }
583
584
    /**
585
     * Test for the loadRole() method.
586
     *
587
     * @see \eZ\Publish\API\Repository\RoleService::loadRole()
588
     * @expectedException \eZ\Publish\API\Repository\Exceptions\NotFoundException
589
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRole
590
     */
591 View Code Duplication
    public function testLoadRoleThrowsNotFoundException()
592
    {
593
        $repository = $this->getRepository();
594
595
        $nonExistingRoleId = $this->generateId('role', self::DB_INT_MAX);
596
        /* BEGIN: Use Case */
597
598
        $roleService = $repository->getRoleService();
599
600
        // This call will fail with a NotFoundException, because no such role exists.
601
        $roleService->loadRole($nonExistingRoleId);
602
603
        /* END: Use Case */
604
    }
605
606
    /**
607
     * Test for the loadRoleDraft() method.
608
     *
609
     * @see \eZ\Publish\API\Repository\RoleService::loadRoleDraft()
610
     * @expectedException \eZ\Publish\API\Repository\Exceptions\NotFoundException
611
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleDraft
612
     */
613 View Code Duplication
    public function testLoadRoleDraftThrowsNotFoundException()
614
    {
615
        $repository = $this->getRepository();
616
617
        $nonExistingRoleId = $this->generateId('role', self::DB_INT_MAX);
618
        /* BEGIN: Use Case */
619
620
        $roleService = $repository->getRoleService();
621
622
        // This call will fail with a NotFoundException, because no such role exists.
623
        $roleService->loadRoleDraft($nonExistingRoleId);
624
625
        /* END: Use Case */
626
    }
627
628
    /**
629
     * @expectedException \eZ\Publish\API\Repository\Exceptions\NotFoundException
630
     */
631 View Code Duplication
    public function testLoadRoleDraftByRoleIdThrowsNotFoundException()
632
    {
633
        $repository = $this->getRepository();
634
635
        $nonExistingRoleId = $this->generateId('role', self::DB_INT_MAX);
636
        /* BEGIN: Use Case */
637
638
        $roleService = $repository->getRoleService();
639
640
        // This call will fail with a NotFoundException, because no such role exists.
641
        $roleService->loadRoleDraftByRoleId($nonExistingRoleId);
642
643
        /* END: Use Case */
644
    }
645
646
    /**
647
     * Test for the loadRoleByIdentifier() method.
648
     *
649
     * @see \eZ\Publish\API\Repository\RoleService::loadRoleByIdentifier()
650
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRole
651
     */
652 View Code Duplication
    public function testLoadRoleByIdentifier()
653
    {
654
        $repository = $this->getRepository();
655
656
        /* BEGIN: Use Case */
657
658
        $roleService = $repository->getRoleService();
659
        $roleCreate = $roleService->newRoleCreateStruct('roleName');
660
661
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
662
        // $roleCreate->mainLanguageCode = 'eng-US';
663
664
        $roleDraft = $roleService->createRole($roleCreate);
665
        $roleService->publishRoleDraft($roleDraft);
666
667
        // Load the newly created role by its identifier
668
        $role = $roleService->loadRoleByIdentifier('roleName');
669
670
        /* END: Use Case */
671
672
        $this->assertEquals('roleName', $role->identifier);
673
    }
674
675
    /**
676
     * Test for the loadRoleByIdentifier() method.
677
     *
678
     * @see \eZ\Publish\API\Repository\RoleService::loadRoleByIdentifier()
679
     * @expectedException \eZ\Publish\API\Repository\Exceptions\NotFoundException
680
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleByIdentifier
681
     */
682
    public function testLoadRoleByIdentifierThrowsNotFoundException()
683
    {
684
        $repository = $this->getRepository();
685
686
        /* BEGIN: Use Case */
687
688
        $roleService = $repository->getRoleService();
689
690
        // This call will fail with a NotFoundException, because no such role exists.
691
        $roleService->loadRoleByIdentifier('MissingRole');
692
693
        /* END: Use Case */
694
    }
695
696
    /**
697
     * Test for the loadRoles() method.
698
     *
699
     * @see \eZ\Publish\API\Repository\RoleService::loadRoles()
700
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRole
701
     */
702
    public function testLoadRoles()
703
    {
704
        $repository = $this->getRepository();
705
706
        /* BEGIN: Use Case */
707
708
        // First create a custom role
709
        $roleService = $repository->getRoleService();
710
        $roleCreate = $roleService->newRoleCreateStruct('roleName');
711
712
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
713
        // $roleCreate->mainLanguageCode = 'eng-US';
714
715
        $roleDraft = $roleService->createRole($roleCreate);
716
        $roleService->publishRoleDraft($roleDraft);
717
718
        // Now load all available roles
719
        $roles = $roleService->loadRoles();
720
721
        foreach ($roles as $role) {
722
            if ($role->identifier === 'roleName') {
723
                break;
724
            }
725
        }
726
727
        /* END: Use Case */
728
729
        $this->assertEquals('roleName', $role->identifier);
0 ignored issues
show
Bug introduced by
The variable $role seems to be defined by a foreach iteration on line 721. Are you sure the iterator is never empty, otherwise this variable is not defined?

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

foreach ($a as $b) {
}

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


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

// $b is now guaranteed to be defined here.
Loading history...
730
    }
731
732
    /**
733
     * Test for the loadRoles() method.
734
     *
735
     * @see \eZ\Publish\API\Repository\RoleService::loadRoles()
736
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoles
737
     */
738
    public function testLoadRolesReturnsExpectedSetOfDefaultRoles()
739
    {
740
        $repository = $this->getRepository();
741
742
        /* BEGIN: Use Case */
743
        $roleService = $repository->getRoleService();
744
745
        $roles = $roleService->loadRoles();
746
747
        $roleNames = [];
748
        foreach ($roles as $role) {
749
            $roleNames[] = $role->identifier;
750
        }
751
        /* END: Use Case */
752
753
        sort($roleNames);
754
755
        $this->assertEquals(
756
            [
757
                'Administrator',
758
                'Anonymous',
759
                'Editor',
760
                'Member',
761
                'Partner',
762
            ],
763
            $roleNames
764
        );
765
    }
766
767
    /**
768
     * Test for the newRoleUpdateStruct() method.
769
     *
770
     * @see \eZ\Publish\API\Repository\RoleService::newRoleUpdateStruct()
771
     */
772
    public function testNewRoleUpdateStruct()
773
    {
774
        $repository = $this->getRepository();
775
776
        /* BEGIN: Use Case */
777
        $roleService = $repository->getRoleService();
778
        $roleUpdate = $roleService->newRoleUpdateStruct('newRole');
779
        /* END: Use Case */
780
781
        $this->assertInstanceOf('\\eZ\\Publish\\API\\Repository\\Values\\User\\RoleUpdateStruct', $roleUpdate);
782
    }
783
784
    /**
785
     * Test for the updateRole() method.
786
     *
787
     * @see \eZ\Publish\API\Repository\RoleService::updateRole()
788
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewRoleUpdateStruct
789
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleByIdentifier
790
     */
791
    public function testUpdateRole()
792
    {
793
        $repository = $this->getRepository();
794
795
        /* BEGIN: Use Case */
796
        $roleService = $repository->getRoleService();
797
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
798
799
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
800
        // $roleCreate->mainLanguageCode = 'eng-US';
801
802
        $roleDraft = $roleService->createRole($roleCreate);
803
        $roleService->publishRoleDraft($roleDraft);
804
        $role = $roleService->loadRole($roleDraft->id);
805
806
        $roleUpdate = $roleService->newRoleUpdateStruct();
807
        $roleUpdate->identifier = 'updatedRole';
808
809
        $updatedRole = $roleService->updateRole($role, $roleUpdate);
0 ignored issues
show
Deprecated Code introduced by
The method eZ\Publish\API\Repositor...leService::updateRole() has been deprecated with message: since 6.0, use {@see updateRoleDraft}

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

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

Loading history...
810
        /* END: Use Case */
811
812
        // Now verify that our change was saved
813
        $role = $roleService->loadRoleByIdentifier('updatedRole');
814
815
        $this->assertEquals($role->id, $updatedRole->id);
816
    }
817
818
    /**
819
     * Test for the updateRoleDraft() method.
820
     *
821
     * @see \eZ\Publish\API\Repository\RoleService::updateRoleDraft()
822
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewRoleUpdateStruct
823
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleDraft
824
     */
825
    public function testUpdateRoleDraft()
826
    {
827
        $repository = $this->getRepository();
828
829
        /* BEGIN: Use Case */
830
        $roleService = $repository->getRoleService();
831
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
832
833
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
834
        // $roleCreate->mainLanguageCode = 'eng-US';
835
836
        $roleDraft = $roleService->createRole($roleCreate);
837
838
        $roleUpdate = $roleService->newRoleUpdateStruct();
839
        $roleUpdate->identifier = 'updatedRole';
840
841
        $updatedRole = $roleService->updateRoleDraft($roleDraft, $roleUpdate);
842
        /* END: Use Case */
843
844
        // Now verify that our change was saved
845
        $role = $roleService->loadRoleDraft($updatedRole->id);
846
847
        $this->assertEquals($role->identifier, 'updatedRole');
848
    }
849
850
    /**
851
     * Test for the updateRole() method.
852
     *
853
     * @see \eZ\Publish\API\Repository\RoleService::updateRole()
854
     * @expectedException \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException
855
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testUpdateRole
856
     */
857 View Code Duplication
    public function testUpdateRoleThrowsInvalidArgumentException()
858
    {
859
        $repository = $this->getRepository();
860
861
        /* BEGIN: Use Case */
862
        $roleService = $repository->getRoleService();
863
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
864
865
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
866
        // $roleCreate->mainLanguageCode = 'eng-US';
867
868
        $roleDraft = $roleService->createRole($roleCreate);
869
        $roleService->publishRoleDraft($roleDraft);
870
        $role = $roleService->loadRole($roleDraft->id);
871
872
        $roleUpdate = $roleService->newRoleUpdateStruct();
873
        $roleUpdate->identifier = 'Editor';
874
875
        // This call will fail with an InvalidArgumentException, because Editor is a predefined role
876
        $roleService->updateRole($role, $roleUpdate);
0 ignored issues
show
Deprecated Code introduced by
The method eZ\Publish\API\Repositor...leService::updateRole() has been deprecated with message: since 6.0, use {@see updateRoleDraft}

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

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

Loading history...
877
        /* END: Use Case */
878
    }
879
880
    /**
881
     * Test for the updateRoleDraft() method.
882
     *
883
     * @see \eZ\Publish\API\Repository\RoleService::updateRoleDraft()
884
     * @expectedException \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException
885
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testUpdateRoleDraft
886
     */
887
    public function testUpdateRoleDraftThrowsInvalidArgumentException()
888
    {
889
        $repository = $this->getRepository();
890
891
        /* BEGIN: Use Case */
892
        $roleService = $repository->getRoleService();
893
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
894
895
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
896
        // $roleCreate->mainLanguageCode = 'eng-US';
897
898
        $roleDraft = $roleService->createRole($roleCreate);
899
900
        $roleUpdate = $roleService->newRoleUpdateStruct();
901
        $roleUpdate->identifier = 'Editor';
902
903
        // This call will fail with an InvalidArgumentException, because Editor is a predefined role
904
        $roleService->updateRoleDraft($roleDraft, $roleUpdate);
905
        /* END: Use Case */
906
    }
907
908
    /**
909
     * Test for the deleteRole() method.
910
     *
911
     * @see \eZ\Publish\API\Repository\RoleService::deleteRole()
912
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRole
913
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoles
914
     */
915 View Code Duplication
    public function testDeleteRole()
916
    {
917
        $repository = $this->getRepository();
918
919
        /* BEGIN: Use Case */
920
        $roleService = $repository->getRoleService();
921
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
922
923
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
924
        // $roleCreate->mainLanguageCode = 'eng-US';
925
926
        $roleDraft = $roleService->createRole($roleCreate);
927
        $roleService->publishRoleDraft($roleDraft);
928
        $role = $roleService->loadRole($roleDraft->id);
929
930
        $roleService->deleteRole($role);
931
        /* END: Use Case */
932
933
        $this->assertEquals(5, count($roleService->loadRoles()));
934
    }
935
936
    /**
937
     * Test for the deleteRoleDraft() method.
938
     *
939
     * @see \eZ\Publish\API\Repository\RoleService::deleteRoleDraft()
940
     * @expectedException \eZ\Publish\API\Repository\Exceptions\NotFoundException
941
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleDraft
942
     */
943 View Code Duplication
    public function testDeleteRoleDraft()
944
    {
945
        $repository = $this->getRepository();
946
947
        /* BEGIN: Use Case */
948
        $roleService = $repository->getRoleService();
949
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
950
951
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
952
        // $roleCreate->mainLanguageCode = 'eng-US';
953
954
        $roleDraft = $roleService->createRole($roleCreate);
955
        $roleID = $roleDraft->id;
956
        $roleService->deleteRoleDraft($roleDraft);
957
958
        // This call will fail with a NotFoundException, because the draft no longer exists
959
        $roleService->loadRoleDraft($roleID);
960
        /* END: Use Case */
961
    }
962
963
    /**
964
     * Test for the newPolicyCreateStruct() method.
965
     *
966
     * @see \eZ\Publish\API\Repository\RoleService::newPolicyCreateStruct()
967
     */
968
    public function testNewPolicyCreateStruct()
969
    {
970
        $repository = $this->getRepository();
971
972
        /* BEGIN: Use Case */
973
        $roleService = $repository->getRoleService();
974
        $policyCreate = $roleService->newPolicyCreateStruct('content', 'create');
975
        /* END: Use Case */
976
977
        $this->assertInstanceOf('\\eZ\\Publish\\API\\Repository\\Values\\User\\PolicyCreateStruct', $policyCreate);
978
    }
979
980
    /**
981
     * Test for the newPolicyCreateStruct() method.
982
     *
983
     * @see \eZ\Publish\API\Repository\RoleService::newPolicyCreateStruct()
984
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewPolicyCreateStruct
985
     */
986
    public function testNewPolicyCreateStructSetsStructProperties()
987
    {
988
        $repository = $this->getRepository();
989
990
        /* BEGIN: Use Case */
991
        $roleService = $repository->getRoleService();
992
        $policyCreate = $roleService->newPolicyCreateStruct('content', 'create');
993
        /* END: Use Case */
994
995
        $this->assertEquals(
996
            ['content', 'create'],
997
            [$policyCreate->module, $policyCreate->function]
998
        );
999
    }
1000
1001
    /**
1002
     * Test for the addPolicy() method.
1003
     *
1004
     * @see \eZ\Publish\API\Repository\RoleService::addPolicy()
1005
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleByIdentifier
1006
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewPolicyCreateStruct
1007
     */
1008 View Code Duplication
    public function testAddPolicy()
1009
    {
1010
        $repository = $this->getRepository();
1011
1012
        /* BEGIN: Use Case */
1013
        $roleService = $repository->getRoleService();
1014
1015
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
1016
1017
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1018
        // $roleCreate->mainLanguageCode = 'eng-US';
1019
1020
        $roleDraft = $roleService->createRole($roleCreate);
1021
        $roleService->publishRoleDraft($roleDraft);
1022
        $role = $roleService->loadRole($roleDraft->id);
1023
1024
        $role = $roleService->addPolicy(
0 ignored issues
show
Deprecated Code introduced by
The method eZ\Publish\API\Repository\RoleService::addPolicy() has been deprecated with message: since 6.0, use {@see addPolicyByRoleDraft}

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

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

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

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

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

Loading history...
1029
            $role,
1030
            $roleService->newPolicyCreateStruct('content', 'create')
1031
        );
1032
        /* END: Use Case */
1033
1034
        $actual = [];
1035
        foreach ($role->getPolicies() as $policy) {
1036
            $actual[] = [
1037
                'module' => $policy->module,
1038
                'function' => $policy->function,
1039
            ];
1040
        }
1041
        usort(
1042
            $actual,
1043
            function ($p1, $p2) {
1044
                return strcasecmp($p1['function'], $p2['function']);
1045
            }
1046
        );
1047
1048
        $this->assertEquals(
1049
            [
1050
                [
1051
                    'module' => 'content',
1052
                    'function' => 'create',
1053
                ],
1054
                [
1055
                    'module' => 'content',
1056
                    'function' => 'delete',
1057
                ],
1058
            ],
1059
            $actual
1060
        );
1061
    }
1062
1063
    /**
1064
     * Test for the addPolicyByRoleDraft() method.
1065
     *
1066
     * @see \eZ\Publish\API\Repository\RoleService::addPolicyByRoleDraft()
1067
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRoleDraft
1068
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewPolicyCreateStruct
1069
     */
1070
    public function testAddPolicyByRoleDraft()
1071
    {
1072
        $repository = $this->getRepository();
1073
1074
        /* BEGIN: Use Case */
1075
        $roleService = $repository->getRoleService();
1076
1077
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
1078
1079
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1080
        // $roleCreate->mainLanguageCode = 'eng-US';
1081
1082
        $roleDraft = $roleService->createRole($roleCreate);
1083
1084
        $roleDraft = $roleService->addPolicyByRoleDraft(
1085
            $roleDraft,
1086
            $roleService->newPolicyCreateStruct('content', 'delete')
1087
        );
1088
        $roleDraft = $roleService->addPolicyByRoleDraft(
1089
            $roleDraft,
1090
            $roleService->newPolicyCreateStruct('content', 'create')
1091
        );
1092
        /* END: Use Case */
1093
1094
        $actual = [];
1095 View Code Duplication
        foreach ($roleDraft->getPolicies() as $policy) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
1096
            $actual[] = [
1097
                'module' => $policy->module,
1098
                'function' => $policy->function,
1099
            ];
1100
        }
1101
        usort(
1102
            $actual,
1103
            function ($p1, $p2) {
1104
                return strcasecmp($p1['function'], $p2['function']);
1105
            }
1106
        );
1107
1108
        $this->assertEquals(
1109
            [
1110
                [
1111
                    'module' => 'content',
1112
                    'function' => 'create',
1113
                ],
1114
                [
1115
                    'module' => 'content',
1116
                    'function' => 'delete',
1117
                ],
1118
            ],
1119
            $actual
1120
        );
1121
    }
1122
1123
    /**
1124
     * Test for the addPolicy() method.
1125
     *
1126
     * @return array [\eZ\Publish\API\Repository\Values\User\Role, \eZ\Publish\API\Repository\Values\User\Policy]
1127
     *
1128
     * @see \eZ\Publish\API\Repository\RoleService::addPolicy()
1129
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicy
1130
     */
1131
    public function testAddPolicyUpdatesRole()
1132
    {
1133
        $repository = $this->getRepository();
1134
1135
        /* BEGIN: Use Case */
1136
        $roleService = $repository->getRoleService();
1137
1138
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
1139
1140
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1141
        // $roleCreate->mainLanguageCode = 'eng-US';
1142
1143
        $roleDraft = $roleService->createRole($roleCreate);
1144
        $roleService->publishRoleDraft($roleDraft);
1145
        $role = $roleService->loadRole($roleDraft->id);
1146
1147
        $policyCreate = $roleService->newPolicyCreateStruct('content', 'create');
1148
        $role = $roleService->addPolicy($role, $policyCreate);
0 ignored issues
show
Deprecated Code introduced by
The method eZ\Publish\API\Repository\RoleService::addPolicy() has been deprecated with message: since 6.0, use {@see addPolicyByRoleDraft}

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

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

Loading history...
1149
1150
        $policy = null;
1151
        foreach ($role->getPolicies() as $policy) {
1152
            if ($policy->module === 'content' && $policy->function === 'create') {
1153
                break;
1154
            }
1155
        }
1156
        /* END: Use Case */
1157
1158
        $this->assertInstanceOf(
1159
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\Policy',
1160
            $policy
1161
        );
1162
1163
        return [$role, $policy];
1164
    }
1165
1166
    /**
1167
     * Test for the addPolicyByRoleDraft() method.
1168
     *
1169
     * @return array [\eZ\Publish\API\Repository\Values\User\RoleDraft, \eZ\Publish\API\Repository\Values\User\Policy]
1170
     *
1171
     * @see \eZ\Publish\API\Repository\RoleService::addPolicyByRoleDraft()
1172
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicyByRoleDraft
1173
     */
1174
    public function testAddPolicyByRoleDraftUpdatesRole()
1175
    {
1176
        $repository = $this->getRepository();
1177
1178
        /* BEGIN: Use Case */
1179
        $roleService = $repository->getRoleService();
1180
1181
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
1182
1183
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1184
        // $roleCreate->mainLanguageCode = 'eng-US';
1185
1186
        $roleDraft = $roleService->createRole($roleCreate);
1187
1188
        $policyCreate = $roleService->newPolicyCreateStruct('content', 'create');
1189
        $roleDraft = $roleService->addPolicyByRoleDraft($roleDraft, $policyCreate);
1190
1191
        $policy = null;
1192
        foreach ($roleDraft->getPolicies() as $policy) {
1193
            if ($policy->module === 'content' && $policy->function === 'create') {
1194
                break;
1195
            }
1196
        }
1197
        /* END: Use Case */
1198
1199
        $this->assertInstanceOf(
1200
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\Policy',
1201
            $policy
1202
        );
1203
1204
        return [$roleDraft, $policy];
1205
    }
1206
1207
    /**
1208
     * Test for the addPolicy() method.
1209
     *
1210
     * @param array $roleAndPolicy
1211
     *
1212
     * @see \eZ\Publish\API\Repository\RoleService::addPolicy()
1213
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicyUpdatesRole
1214
     */
1215 View Code Duplication
    public function testAddPolicySetsPolicyProperties($roleAndPolicy)
1216
    {
1217
        list($role, $policy) = $roleAndPolicy;
1218
1219
        $this->assertEquals(
1220
            [$role->id, 'content', 'create'],
1221
            [$policy->roleId, $policy->module, $policy->function]
1222
        );
1223
    }
1224
1225
    /**
1226
     * Test for the addPolicyByRoleDraft() method.
1227
     *
1228
     * @param array $roleAndPolicy
1229
     *
1230
     * @see \eZ\Publish\API\Repository\RoleService::addPolicyByRoleDraft()
1231
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicyByRoleDraftUpdatesRole
1232
     */
1233 View Code Duplication
    public function testAddPolicyByRoleDraftSetsPolicyProperties($roleAndPolicy)
1234
    {
1235
        list($role, $policy) = $roleAndPolicy;
1236
1237
        $this->assertEquals(
1238
            [$role->id, 'content', 'create'],
1239
            [$policy->roleId, $policy->module, $policy->function]
1240
        );
1241
    }
1242
1243
    /**
1244
     * Test for the addPolicy() method.
1245
     *
1246
     * @see \eZ\Publish\API\Repository\RoleService::addPolicy()
1247
     * @expectedException \eZ\Publish\API\Repository\Exceptions\LimitationValidationException
1248
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewPolicyCreateStruct
1249
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRole
1250
     */
1251
    public function testAddPolicyThrowsLimitationValidationException()
1252
    {
1253
        $repository = $this->getRepository();
1254
1255
        /* BEGIN: Use Case */
1256
        $roleService = $repository->getRoleService();
1257
1258
        $roleCreate = $roleService->newRoleCreateStruct('Lumberjack');
1259
1260
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1261
        // $roleCreate->mainLanguageCode = 'eng-US';
1262
1263
        $roleDraft = $roleService->createRole($roleCreate);
1264
        $roleService->publishRoleDraft($roleDraft);
1265
        $role = $roleService->loadRole($roleDraft->id);
1266
1267
        // Create new subtree limitation
1268
        $limitation = new SubtreeLimitation(
1269
            [
1270
                'limitationValues' => ['/mountain/forest/tree/42/'],
1271
            ]
1272
        );
1273
1274
        // Create policy create struct and add limitation to it
1275
        $policyCreateStruct = $roleService->newPolicyCreateStruct('content', 'remove');
1276
        $policyCreateStruct->addLimitation($limitation);
1277
1278
        // This call will fail with an LimitationValidationException, because subtree
1279
        // "/mountain/forest/tree/42/" does not exist
1280
        $roleService->addPolicy($role, $policyCreateStruct);
0 ignored issues
show
Deprecated Code introduced by
The method eZ\Publish\API\Repository\RoleService::addPolicy() has been deprecated with message: since 6.0, use {@see addPolicyByRoleDraft}

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

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

Loading history...
1281
        /* END: Use Case */
1282
    }
1283
1284
    /**
1285
     * Test for the addPolicyByRoleDraft() method.
1286
     *
1287
     * @see \eZ\Publish\API\Repository\RoleService::addPolicyByRoleDraft()
1288
     * @expectedException \eZ\Publish\API\Repository\Exceptions\LimitationValidationException
1289
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewPolicyCreateStruct
1290
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRoleDraft
1291
     */
1292 View Code Duplication
    public function testAddPolicyByRoleDraftThrowsLimitationValidationException()
1293
    {
1294
        $repository = $this->getRepository();
1295
1296
        /* BEGIN: Use Case */
1297
        $roleService = $repository->getRoleService();
1298
1299
        $roleCreate = $roleService->newRoleCreateStruct('Lumberjack');
1300
1301
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1302
        // $roleCreate->mainLanguageCode = 'eng-US';
1303
1304
        $roleDraft = $roleService->createRole($roleCreate);
1305
1306
        // Create new subtree limitation
1307
        $limitation = new SubtreeLimitation(
1308
            [
1309
                'limitationValues' => ['/mountain/forest/tree/42/'],
1310
            ]
1311
        );
1312
1313
        // Create policy create struct and add limitation to it
1314
        $policyCreateStruct = $roleService->newPolicyCreateStruct('content', 'remove');
1315
        $policyCreateStruct->addLimitation($limitation);
1316
1317
        // This call will fail with an LimitationValidationException, because subtree
1318
        // "/mountain/forest/tree/42/" does not exist
1319
        $roleService->addPolicyByRoleDraft($roleDraft, $policyCreateStruct);
1320
        /* END: Use Case */
1321
    }
1322
1323
    /**
1324
     * Test for the createRole() method.
1325
     *
1326
     * @see \eZ\Publish\API\Repository\RoleService::createRole()
1327
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicyUpdatesRole
1328
     */
1329
    public function testCreateRoleWithAddPolicy()
1330
    {
1331
        $repository = $this->getRepository();
1332
1333
        /* BEGIN: Use Case */
1334
        $roleService = $repository->getRoleService();
1335
1336
        // Instantiate a new create struct
1337
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
1338
1339
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1340
        // $roleCreate->mainLanguageCode = 'eng-US';
1341
1342
        // Add some role policies
1343
        $roleCreate->addPolicy(
1344
            $roleService->newPolicyCreateStruct(
1345
                'content',
1346
                'read'
1347
            )
1348
        );
1349
        $roleCreate->addPolicy(
1350
            $roleService->newPolicyCreateStruct(
1351
                'content',
1352
                'translate'
1353
            )
1354
        );
1355
1356
        // Create new role instance
1357
        $roleDraft = $roleService->createRole($roleCreate);
1358
        $roleService->publishRoleDraft($roleDraft);
1359
        $role = $roleService->loadRole($roleDraft->id);
1360
1361
        $policies = [];
1362 View Code Duplication
        foreach ($role->getPolicies() as $policy) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
1363
            $policies[] = ['module' => $policy->module, 'function' => $policy->function];
1364
        }
1365
        /* END: Use Case */
1366
        array_multisort($policies);
1367
1368
        $this->assertEquals(
1369
            [
1370
                [
1371
                    'module' => 'content',
1372
                    'function' => 'read',
1373
                ],
1374
                [
1375
                    'module' => 'content',
1376
                    'function' => 'translate',
1377
                ],
1378
            ],
1379
            $policies
1380
        );
1381
    }
1382
1383
    /**
1384
     * Test for the createRoleDraft() method.
1385
     *
1386
     * @see \eZ\Publish\API\Repository\RoleService::createRoleDraft()
1387
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicyByRoleDraftUpdatesRole
1388
     */
1389
    public function testCreateRoleDraftWithAddPolicy()
1390
    {
1391
        $repository = $this->getRepository();
1392
1393
        /* BEGIN: Use Case */
1394
        $roleService = $repository->getRoleService();
1395
1396
        // Instantiate a new create struct
1397
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
1398
1399
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1400
        // $roleCreate->mainLanguageCode = 'eng-US';
1401
1402
        // Add some role policies
1403
        $roleCreate->addPolicy(
1404
            $roleService->newPolicyCreateStruct(
1405
                'content',
1406
                'read'
1407
            )
1408
        );
1409
        $roleCreate->addPolicy(
1410
            $roleService->newPolicyCreateStruct(
1411
                'content',
1412
                'translate'
1413
            )
1414
        );
1415
1416
        // Create new role instance
1417
        $roleDraft = $roleService->createRole($roleCreate);
1418
1419
        $policies = [];
1420 View Code Duplication
        foreach ($roleDraft->getPolicies() as $policy) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
1421
            $policies[] = ['module' => $policy->module, 'function' => $policy->function];
1422
        }
1423
        /* END: Use Case */
1424
1425
        $this->assertEquals(
1426
            [
1427
                [
1428
                    'module' => 'content',
1429
                    'function' => 'read',
1430
                ],
1431
                [
1432
                    'module' => 'content',
1433
                    'function' => 'translate',
1434
                ],
1435
            ],
1436
            $policies
1437
        );
1438
    }
1439
1440
    /**
1441
     * Test for the newPolicyUpdateStruct() method.
1442
     *
1443
     * @see \eZ\Publish\API\Repository\RoleService::newPolicyUpdateStruct()
1444
     */
1445
    public function testNewPolicyUpdateStruct()
1446
    {
1447
        $repository = $this->getRepository();
1448
1449
        /* BEGIN: Use Case */
1450
        $roleService = $repository->getRoleService();
1451
        $policyUpdate = $roleService->newPolicyUpdateStruct();
1452
        /* END: Use Case */
1453
1454
        $this->assertInstanceOf(
1455
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\PolicyUpdateStruct',
1456
            $policyUpdate
1457
        );
1458
    }
1459
1460
    public function testUpdatePolicyNoLimitation()
1461
    {
1462
        $repository = $this->getRepository();
1463
1464
        /* BEGIN: Use Case */
1465
        $roleService = $repository->getRoleService();
1466
1467
        // Instantiate new policy create
1468
        $policyCreate = $roleService->newPolicyCreateStruct('foo', 'bar');
1469
1470
        // Instantiate a role create and add the policy create
1471
        $roleCreate = $roleService->newRoleCreateStruct('myRole');
1472
1473
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1474
        // $roleCreate->mainLanguageCode = 'eng-US';
1475
1476
        $roleCreate->addPolicy($policyCreate);
1477
1478
        // Create a new role instance.
1479
        $roleDraft = $roleService->createRole($roleCreate);
1480
        $roleService->publishRoleDraft($roleDraft);
1481
        $role = $roleService->loadRole($roleDraft->id);
1482
1483
        // Search for the new policy instance
1484
        $policy = null;
1485
        foreach ($role->getPolicies() as $policy) {
1486
            if ($policy->module === 'foo' && $policy->function === 'bar') {
1487
                break;
1488
            }
1489
        }
1490
1491
        // Create an update struct
1492
        $policyUpdate = $roleService->newPolicyUpdateStruct();
1493
1494
        // Update the the policy
1495
        $policy = $roleService->updatePolicy($policy, $policyUpdate);
0 ignored issues
show
Bug introduced by
It seems like $policy can be null; however, updatePolicy() does not accept null, maybe add an additional type check?

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

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

function doesNotAcceptNull(stdClass $x) { }

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

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

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

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

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

Loading history...
1496
        /* END: Use Case */
1497
1498
        $this->assertInstanceOf(
1499
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\Policy',
1500
            $policy
1501
        );
1502
1503
        self::assertEquals([], $policy->getLimitations());
1504
    }
1505
1506
    /**
1507
     * Test for the updatePolicy() method.
1508
     *
1509
     * @return array
1510
     *
1511
     * @see \eZ\Publish\API\Repository\RoleService::updatePolicy()
1512
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicy
1513
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewPolicyUpdateStruct
1514
     */
1515
    public function testUpdatePolicy()
1516
    {
1517
        $repository = $this->getRepository();
1518
1519
        /* BEGIN: Use Case */
1520
        $roleService = $repository->getRoleService();
1521
1522
        // Instantiate new policy create
1523
        $policyCreate = $roleService->newPolicyCreateStruct('content', 'translate');
1524
1525
        // Add some limitations for the new policy
1526
        $policyCreate->addLimitation(
1527
            new LanguageLimitation(
1528
                [
1529
                    'limitationValues' => ['eng-US', 'eng-GB'],
1530
                ]
1531
            )
1532
        );
1533
1534
        // Instantiate a role create and add the policy create
1535
        $roleCreate = $roleService->newRoleCreateStruct('myRole');
1536
1537
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1538
        // $roleCreate->mainLanguageCode = 'eng-US';
1539
1540
        $roleCreate->addPolicy($policyCreate);
1541
1542
        // Create a new role instance.
1543
        $roleDraft = $roleService->createRole($roleCreate);
1544
        $roleService->publishRoleDraft($roleDraft);
1545
        $role = $roleService->loadRole($roleDraft->id);
1546
1547
        // Search for the new policy instance
1548
        $policy = null;
1549
        foreach ($role->getPolicies() as $policy) {
1550
            if ($policy->module === 'content' && $policy->function === 'translate') {
1551
                break;
1552
            }
1553
        }
1554
1555
        // Create an update struct and set a modified limitation
1556
        $policyUpdate = $roleService->newPolicyUpdateStruct();
1557
        $policyUpdate->addLimitation(
1558
            new ContentTypeLimitation(
1559
                [
1560
                    'limitationValues' => [29, 30],
1561
                ]
1562
            )
1563
        );
1564
1565
        // Update the the policy
1566
        $policy = $roleService->updatePolicy($policy, $policyUpdate);
0 ignored issues
show
Deprecated Code introduced by
The method eZ\Publish\API\Repositor...Service::updatePolicy() has been deprecated with message: since 6.0, use {@link updatePolicyByRoleDraft()} instead.

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

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

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

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

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

function doesNotAcceptNull(stdClass $x) { }

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

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

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
1567
        /* END: Use Case */
1568
1569
        $this->assertInstanceOf(
1570
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\Policy',
1571
            $policy
1572
        );
1573
1574
        return [$roleService->loadRole($role->id), $policy];
1575
    }
1576
1577
    /**
1578
     * Test for the updatePolicy() method.
1579
     *
1580
     * @param array $roleAndPolicy
1581
     *
1582
     * @see \eZ\Publish\API\Repository\RoleService::updatePolicy()
1583
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testUpdatePolicy
1584
     */
1585
    public function testUpdatePolicyUpdatesLimitations($roleAndPolicy)
1586
    {
1587
        list($role, $policy) = $roleAndPolicy;
1588
1589
        $this->assertEquals(
1590
            [
1591
                new ContentTypeLimitation(
1592
                    [
1593
                        'limitationValues' => [29, 30],
1594
                    ]
1595
                ),
1596
            ],
1597
            $policy->getLimitations()
1598
        );
1599
1600
        return $role;
1601
    }
1602
1603
    /**
1604
     * Test for the updatePolicy() method.
1605
     *
1606
     * @param \eZ\Publish\API\Repository\Values\User\Role $role
1607
     *
1608
     * @see \eZ\Publish\API\Repository\RoleService::updatePolicy()
1609
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testUpdatePolicyUpdatesLimitations
1610
     */
1611
    public function testUpdatePolicyUpdatesRole($role)
1612
    {
1613
        $limitations = [];
1614
        foreach ($role->getPolicies() as $policy) {
1615
            foreach ($policy->getLimitations() as $limitation) {
1616
                $limitations[] = $limitation;
1617
            }
1618
        }
1619
1620
        $this->assertCount(1, $limitations);
1621
        $this->assertInstanceOf(
1622
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\Limitation',
1623
            $limitations[0]
1624
        );
1625
1626
        $expectedData = [
1627
            'limitationValues' => [29, 30],
1628
        ];
1629
        $this->assertPropertiesCorrectUnsorted(
1630
            $expectedData,
1631
            $limitations[0]
1632
        );
1633
    }
1634
1635
    /**
1636
     * Test for the updatePolicy() method.
1637
     *
1638
     * @see \eZ\Publish\API\Repository\RoleService::updatePolicy()
1639
     * @expectedException \eZ\Publish\API\Repository\Exceptions\LimitationValidationException
1640
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicy
1641
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewPolicyCreateStruct
1642
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewPolicyUpdateStruct
1643
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewRoleCreateStruct
1644
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRole
1645
     */
1646
    public function testUpdatePolicyThrowsLimitationValidationException()
1647
    {
1648
        $repository = $this->getRepository();
1649
1650
        /* BEGIN: Use Case */
1651
        $roleService = $repository->getRoleService();
1652
1653
        // Instantiate new policy create
1654
        $policyCreate = $roleService->newPolicyCreateStruct('content', 'remove');
1655
1656
        // Add some limitations for the new policy
1657
        $policyCreate->addLimitation(
1658
            new SubtreeLimitation(
1659
                [
1660
                    'limitationValues' => ['/1/2/'],
1661
                ]
1662
            )
1663
        );
1664
1665
        // Instantiate a role create and add the policy create
1666
        $roleCreate = $roleService->newRoleCreateStruct('myRole');
1667
1668
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1669
        // $roleCreate->mainLanguageCode = 'eng-US';
1670
1671
        $roleCreate->addPolicy($policyCreate);
1672
1673
        // Create a new role instance.
1674
        $roleDraft = $roleService->createRole($roleCreate);
1675
        $roleService->publishRoleDraft($roleDraft);
1676
        $role = $roleService->loadRole($roleDraft->id);
1677
1678
        // Search for the new policy instance
1679
        $policy = null;
1680
        foreach ($role->getPolicies() as $policy) {
1681
            if ($policy->module === 'content' && $policy->function === 'remove') {
1682
                break;
1683
            }
1684
        }
1685
1686
        // Create an update struct and set a modified limitation
1687
        $policyUpdate = $roleService->newPolicyUpdateStruct();
1688
        $policyUpdate->addLimitation(
1689
            new SubtreeLimitation(
1690
                [
1691
                    'limitationValues' => ['/mountain/forest/tree/42/'],
1692
                ]
1693
            )
1694
        );
1695
1696
        // This call will fail with an LimitationValidationException, because subtree
1697
        // "/mountain/forest/tree/42/" does not exist
1698
        $policy = $roleService->updatePolicy($policy, $policyUpdate);
0 ignored issues
show
Unused Code introduced by
$policy is not used, you could remove the assignment.

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

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

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

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

Loading history...
Deprecated Code introduced by
The method eZ\Publish\API\Repositor...Service::updatePolicy() has been deprecated with message: since 6.0, use {@link updatePolicyByRoleDraft()} instead.

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

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

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

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

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

function doesNotAcceptNull(stdClass $x) { }

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

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

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
1699
        /* END: Use Case */
1700
    }
1701
1702
    /**
1703
     * Test for the removePolicyByRoleDraft() method.
1704
     *
1705
     * @see \eZ\Publish\API\Repository\RoleService::removePolicyByRoleDraft()
1706
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicyByRoleDraft
1707
     */
1708 View Code Duplication
    public function testRemovePolicyByRoleDraft()
1709
    {
1710
        $repository = $this->getRepository();
1711
1712
        /* BEGIN: Use Case */
1713
        $roleService = $repository->getRoleService();
1714
1715
        // Instantiate a new role create
1716
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
1717
1718
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1719
        // $roleCreate->mainLanguageCode = 'eng-US';
1720
1721
        // Create a new role with two policies
1722
        $roleDraft = $roleService->createRole($roleCreate);
1723
        $roleService->addPolicyByRoleDraft(
1724
            $roleDraft,
1725
            $roleService->newPolicyCreateStruct('content', 'create')
1726
        );
1727
        $roleService->addPolicyByRoleDraft(
1728
            $roleDraft,
1729
            $roleService->newPolicyCreateStruct('content', 'delete')
1730
        );
1731
1732
        // Delete all policies from the new role
1733
        foreach ($roleDraft->getPolicies() as $policy) {
1734
            $roleDraft = $roleService->removePolicyByRoleDraft($roleDraft, $policy);
0 ignored issues
show
Compatibility introduced by
$policy of type object<eZ\Publish\API\Re...ory\Values\User\Policy> is not a sub-type of object<eZ\Publish\API\Re...alues\User\PolicyDraft>. It seems like you assume a child class of the class eZ\Publish\API\Repository\Values\User\Policy to be always present.

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

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

Loading history...
1735
        }
1736
        /* END: Use Case */
1737
1738
        $this->assertSame([], $roleDraft->getPolicies());
1739
    }
1740
1741
    /**
1742
     * Test for the deletePolicy() method.
1743
     *
1744
     * @see \eZ\Publish\API\Repository\RoleService::deletePolicy()
1745
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRole
1746
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicy
1747
     */
1748
    public function testDeletePolicy()
1749
    {
1750
        $repository = $this->getRepository();
1751
1752
        /* BEGIN: Use Case */
1753
        $roleService = $repository->getRoleService();
1754
1755
        // Instantiate a new role create
1756
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
1757
1758
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1759
        // $roleCreate->mainLanguageCode = 'eng-US';
1760
1761
        // Create a new role with two policies
1762
        $roleDraft = $roleService->createRole($roleCreate);
1763
        $roleService->addPolicyByRoleDraft(
1764
            $roleDraft,
1765
            $roleService->newPolicyCreateStruct('content', 'create')
1766
        );
1767
        $roleService->addPolicyByRoleDraft(
1768
            $roleDraft,
1769
            $roleService->newPolicyCreateStruct('content', 'delete')
1770
        );
1771
        $roleService->publishRoleDraft($roleDraft);
1772
        $role = $roleService->loadRole($roleDraft->id);
1773
1774
        // Delete all policies from the new role
1775
        foreach ($role->getPolicies() as $policy) {
1776
            $roleService->deletePolicy($policy);
0 ignored issues
show
Deprecated Code introduced by
The method eZ\Publish\API\Repositor...Service::deletePolicy() has been deprecated with message: since 6.0, use {@link removePolicyByRoleDraft()} instead.

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

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

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

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

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

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

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

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

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