Completed
Push — ezp-30928-as_a_developer_i_wan... ( 0570c5 )
by
unknown
13:48
created

RoleServiceTest::testUpdatePolicyByRoleDraft()   B

Complexity

Conditions 4
Paths 3

Size

Total Lines 69

Duplication

Lines 0
Ratio 0 %

Importance

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