Completed
Push — ezp-30882-thumbnail ( aacd67...c2bd81 )
by
unknown
19:25 queued 36s
created

testUpdatePolicyByRoleDraftNoLimitation()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 53

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
nc 3
nop 0
dl 0
loc 53
rs 9.0254
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
        $roleDraft = $roleService->createRoleDraft($role);
1264
        // Search for the new policy instance
1265
        $policy = null;
1266
        /** @var \eZ\Publish\API\Repository\Values\User\PolicyDraft $policy */
1267
        foreach ($roleDraft->getPolicies() as $policy) {
1268
            if ($policy->module === 'foo' && $policy->function === 'bar') {
1269
                break;
1270
            }
1271
        }
1272
1273
        // Create an update struct
1274
        $policyUpdate = $roleService->newPolicyUpdateStruct();
1275
1276
        // Update the the policy
1277
        $policy = $roleService->updatePolicyByRoleDraft(
1278
            $roleDraft,
1279
            $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...
1280
            $policyUpdate
1281
        );
1282
        $roleService->publishRoleDraft($roleDraft);
1283
1284
        /* END: Use Case */
1285
1286
        $this->assertInstanceOf(
1287
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\Policy',
1288
            $policy
1289
        );
1290
1291
        self::assertEquals([], $policy->getLimitations());
1292
    }
1293
1294
    /**
1295
     * @return array
1296
     *
1297
     * @see \eZ\Publish\API\Repository\RoleService::updatePolicyByRoleDraft()
1298
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicyByRoleDraft
1299
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewPolicyUpdateStruct
1300
     */
1301
    public function testUpdatePolicyByRoleDraft()
1302
    {
1303
        $repository = $this->getRepository();
1304
1305
        /* BEGIN: Use Case */
1306
        $roleService = $repository->getRoleService();
1307
1308
        // Instantiate new policy create
1309
        $policyCreate = $roleService->newPolicyCreateStruct('content', 'translate');
1310
1311
        // Add some limitations for the new policy
1312
        $policyCreate->addLimitation(
1313
            new LanguageLimitation(
1314
                [
1315
                    'limitationValues' => ['eng-US', 'eng-GB'],
1316
                ]
1317
            )
1318
        );
1319
1320
        // Instantiate a role create and add the policy create
1321
        $roleCreate = $roleService->newRoleCreateStruct('myRole');
1322
1323
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1324
        // $roleCreate->mainLanguageCode = 'eng-US';
1325
1326
        $roleCreate->addPolicy($policyCreate);
1327
1328
        // Create a new role instance.
1329
        $roleDraft = $roleService->createRole($roleCreate);
1330
        $roleService->publishRoleDraft($roleDraft);
1331
        $role = $roleService->loadRole($roleDraft->id);
1332
1333
        $roleDraft = $roleService->createRoleDraft($role);
1334
        // Search for the new policy instance
1335
        $policy = null;
1336
        /** @var \eZ\Publish\API\Repository\Values\User\PolicyDraft $policy */
1337
        foreach ($roleDraft->getPolicies() as $policy) {
1338
            if ($policy->module === 'content' && $policy->function === 'translate') {
1339
                break;
1340
            }
1341
        }
1342
1343
        // Create an update struct and set a modified limitation
1344
        $policyUpdate = $roleService->newPolicyUpdateStruct();
1345
        $policyUpdate->addLimitation(
1346
            new ContentTypeLimitation(
1347
                [
1348
                    'limitationValues' => [29, 30],
1349
                ]
1350
            )
1351
        );
1352
1353
        // Update the the policy
1354
        $policy = $roleService->updatePolicyByRoleDraft(
1355
            $roleDraft,
1356
            $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...
1357
            $policyUpdate
1358
        );
1359
        $roleService->publishRoleDraft($roleDraft);
1360
1361
        /* END: Use Case */
1362
1363
        $this->assertInstanceOf(
1364
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\Policy',
1365
            $policy
1366
        );
1367
1368
        return [$roleService->loadRole($role->id), $policy];
1369
    }
1370
1371
    /**
1372
     * @param array $roleAndPolicy
1373
     *
1374
     * @see \eZ\Publish\API\Repository\RoleService::testUpdatePolicyByRoleDraft()
1375
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testUpdatePolicyByRoleDraft
1376
     */
1377
    public function testUpdatePolicyUpdatesLimitations($roleAndPolicy)
1378
    {
1379
        list($role, $policy) = $roleAndPolicy;
1380
1381
        $this->assertEquals(
1382
            [
1383
                new ContentTypeLimitation(
1384
                    [
1385
                        'limitationValues' => [29, 30],
1386
                    ]
1387
                ),
1388
            ],
1389
            $policy->getLimitations()
1390
        );
1391
1392
        return $role;
1393
    }
1394
1395
    /**
1396
     * Test for the updatePolicy() method.
1397
     *
1398
     * @param \eZ\Publish\API\Repository\Values\User\Role $role
1399
     *
1400
     * @see \eZ\Publish\API\Repository\RoleService::updatePolicyByRoleDraft()
1401
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testUpdatePolicyUpdatesLimitations
1402
     */
1403
    public function testUpdatePolicyUpdatesRole($role)
1404
    {
1405
        $limitations = [];
1406
        foreach ($role->getPolicies() as $policy) {
1407
            foreach ($policy->getLimitations() as $limitation) {
1408
                $limitations[] = $limitation;
1409
            }
1410
        }
1411
1412
        $this->assertCount(1, $limitations);
1413
        $this->assertInstanceOf(
1414
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\Limitation',
1415
            $limitations[0]
1416
        );
1417
1418
        $expectedData = [
1419
            'limitationValues' => [29, 30],
1420
        ];
1421
        $this->assertPropertiesCorrectUnsorted(
1422
            $expectedData,
1423
            $limitations[0]
1424
        );
1425
    }
1426
1427
    /**
1428
     * Test for the updatePolicy() method.
1429
     *
1430
     * @see \eZ\Publish\API\Repository\RoleService::updatePolicyByRoleDraft()
1431
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicyByRoleDraft
1432
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewPolicyCreateStruct
1433
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewPolicyUpdateStruct
1434
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewRoleCreateStruct
1435
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRole
1436
     */
1437
    public function testUpdatePolicyByRoleDraftThrowsLimitationValidationException()
1438
    {
1439
        $this->expectException(\eZ\Publish\API\Repository\Exceptions\LimitationValidationException::class);
1440
1441
        $repository = $this->getRepository();
1442
1443
        /* BEGIN: Use Case */
1444
        $roleService = $repository->getRoleService();
1445
1446
        // Instantiate new policy create
1447
        $policyCreate = $roleService->newPolicyCreateStruct('content', 'remove');
1448
1449
        // Add some limitations for the new policy
1450
        $policyCreate->addLimitation(
1451
            new SubtreeLimitation(
1452
                [
1453
                    'limitationValues' => ['/1/2/'],
1454
                ]
1455
            )
1456
        );
1457
1458
        // Instantiate a role create and add the policy create
1459
        $roleCreate = $roleService->newRoleCreateStruct('myRole');
1460
1461
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1462
        // $roleCreate->mainLanguageCode = 'eng-US';
1463
1464
        $roleCreate->addPolicy($policyCreate);
1465
1466
        // Create a new role instance.
1467
        $roleDraft = $roleService->createRole($roleCreate);
1468
        $roleService->publishRoleDraft($roleDraft);
1469
        $role = $roleService->loadRole($roleDraft->id);
1470
        $roleDraft = $roleService->createRoleDraft($role);
1471
        // Search for the new policy instance
1472
        $policy = null;
1473
        /** @var \eZ\Publish\API\Repository\Values\User\PolicyDraft $policy */
1474
        foreach ($roleDraft->getPolicies() as $policy) {
1475
            if ($policy->module === 'content' && $policy->function === 'remove') {
1476
                break;
1477
            }
1478
        }
1479
1480
        // Create an update struct and set a modified limitation
1481
        $policyUpdate = $roleService->newPolicyUpdateStruct();
1482
        $policyUpdate->addLimitation(
1483
            new SubtreeLimitation(
1484
                [
1485
                    'limitationValues' => ['/mountain/forest/tree/42/'],
1486
                ]
1487
            )
1488
        );
1489
1490
        // This call will fail with an LimitationValidationException, because subtree
1491
        // "/mountain/forest/tree/42/" does not exist
1492
        $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...
1493
            $roleDraft,
1494
            $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...
1495
            $policyUpdate
1496
        );
1497
        /* END: Use Case */
1498
    }
1499
1500
    /**
1501
     * Test for the removePolicyByRoleDraft() method.
1502
     *
1503
     * @see \eZ\Publish\API\Repository\RoleService::removePolicyByRoleDraft()
1504
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicyByRoleDraft
1505
     */
1506 View Code Duplication
    public function testRemovePolicyByRoleDraft()
1507
    {
1508
        $repository = $this->getRepository();
1509
1510
        /* BEGIN: Use Case */
1511
        $roleService = $repository->getRoleService();
1512
1513
        // Instantiate a new role create
1514
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
1515
1516
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1517
        // $roleCreate->mainLanguageCode = 'eng-US';
1518
1519
        // Create a new role with two policies
1520
        $roleDraft = $roleService->createRole($roleCreate);
1521
        $roleService->addPolicyByRoleDraft(
1522
            $roleDraft,
1523
            $roleService->newPolicyCreateStruct('content', 'create')
1524
        );
1525
        $roleService->addPolicyByRoleDraft(
1526
            $roleDraft,
1527
            $roleService->newPolicyCreateStruct('content', 'delete')
1528
        );
1529
1530
        // Delete all policies from the new role
1531
        foreach ($roleDraft->getPolicies() as $policy) {
1532
            $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...
1533
        }
1534
        /* END: Use Case */
1535
1536
        $this->assertSame([], $roleDraft->getPolicies());
1537
    }
1538
1539
    /**
1540
     * Test for the addPolicyByRoleDraft() method.
1541
     *
1542
     * @see \eZ\Publish\API\Repository\RoleService::addPolicyByRoleDraft()
1543
     */
1544
    public function testAddPolicyWithRoleAssignment()
1545
    {
1546
        $repository = $this->getRepository();
1547
1548
        /* BEGIN: Use Case */
1549
        $roleService = $repository->getRoleService();
1550
        $userService = $repository->getUserService();
1551
1552
        /* Create new user group */
1553
        $mainGroupId = $this->generateId('group', 4);
1554
        $parentUserGroup = $userService->loadUserGroup($mainGroupId);
1555
        $userGroupCreate = $userService->newUserGroupCreateStruct('eng-US');
1556
        $userGroupCreate->setField('name', 'newUserGroup');
1557
        $userGroup = $userService->createUserGroup($userGroupCreate, $parentUserGroup);
1558
1559
        /* Create Role */
1560
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
1561
        $roleDraft = $roleService->createRole($roleCreate);
1562
        $roleService->publishRoleDraft($roleDraft);
1563
1564
        $role = $roleService->loadRole($roleDraft->id);
1565
        $roleService->assignRoleToUserGroup($role, $userGroup);
1566
1567
        $roleAssignmentsBeforeNewPolicy = $roleService->getRoleAssignments($role)[0];
1568
1569
        /* Add new policy to existing role */
1570
        $roleUpdateDraft = $roleService->createRoleDraft($role);
1571
        $roleUpdateDraft = $roleService->addPolicyByRoleDraft(
1572
            $roleUpdateDraft,
1573
            $roleService->newPolicyCreateStruct('content', 'create')
1574
        );
1575
        $roleService->publishRoleDraft($roleUpdateDraft);
1576
1577
        $roleAfterUpdate = $roleService->loadRole($role->id);
1578
        $roleAssignmentsAfterNewPolicy = $roleService->getRoleAssignments($roleAfterUpdate)[0];
1579
        /* END: Use Case */
1580
1581
        $this->assertNotEquals($roleAssignmentsBeforeNewPolicy->id, $roleAssignmentsAfterNewPolicy->id);
1582
    }
1583
1584
    /**
1585
     * Test loading user/group role assignments.
1586
     *
1587
     * @return \eZ\Publish\API\Repository\Values\User\UserGroupRoleAssignment
1588
     *
1589
     * @covers \eZ\Publish\API\Repository\RoleService::loadRoleAssignment
1590
     */
1591
    public function testLoadRoleAssignment()
1592
    {
1593
        $repository = $this->getRepository();
1594
1595
        /* BEGIN: Use Case */
1596
        $roleService = $repository->getRoleService();
1597
        $user = $repository->getUserService()->loadUser(14);
1598
1599
        // Check inital empty assigments (also warms up potential cache to validate it is correct below)
1600
        $this->assertCount(0, $roleService->getRoleAssignmentsForUser($user));
1601
1602
        // Assignment to user group
1603
        $groupRoleAssignment = $roleService->loadRoleAssignment(25);
1604
1605
        // Assignment to user
1606
        $role = $roleService->loadRole(2);
1607
        $roleService->assignRoleToUser($role, $user);
1608
        $userRoleAssignments = $roleService->getRoleAssignmentsForUser($user);
1609
1610
        $userRoleAssignment = $roleService->loadRoleAssignment($userRoleAssignments[0]->id);
1611
        /* END: Use Case */
1612
1613
        $this->assertInstanceOf(
1614
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\UserGroupRoleAssignment',
1615
            $groupRoleAssignment
1616
        );
1617
1618
        $this->assertEquals(
1619
            [
1620
                12,
1621
                2,
1622
                25,
1623
            ],
1624
            [
1625
                $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...
1626
                $groupRoleAssignment->role->id,
1627
                $groupRoleAssignment->id,
1628
            ]
1629
        );
1630
1631
        self::assertInstanceOf('\\eZ\\Publish\\API\\Repository\\Values\\User\\UserRoleAssignment', $userRoleAssignment);
1632
        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...
1633
1634
        return $groupRoleAssignment;
1635
    }
1636
1637
    /**
1638
     * Test for the getRoleAssignments() method.
1639
     *
1640
     * @return \eZ\Publish\API\Repository\Values\User\RoleAssignment[]
1641
     *
1642
     * @see \eZ\Publish\API\Repository\RoleService::getRoleAssignments()
1643
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleByIdentifier
1644
     */
1645
    public function testGetRoleAssignments()
1646
    {
1647
        $repository = $this->getRepository();
1648
1649
        /* BEGIN: Use Case */
1650
        $roleService = $repository->getRoleService();
1651
1652
        // Load the editor role
1653
        $role = $roleService->loadRoleByIdentifier('Editor');
1654
1655
        // Load all assigned users and user groups
1656
        $roleAssignments = $roleService->getRoleAssignments($role);
1657
1658
        /* END: Use Case */
1659
1660
        $this->assertCount(2, $roleAssignments);
1661
        $this->assertInstanceOf(
1662
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\UserGroupRoleAssignment',
1663
            $roleAssignments[0]
1664
        );
1665
        $this->assertInstanceOf(
1666
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\UserGroupRoleAssignment',
1667
            $roleAssignments[1]
1668
        );
1669
1670
        return $roleAssignments;
1671
    }
1672
1673
    /**
1674
     * Test for the getRoleAssignments() method.
1675
     *
1676
     * @param \eZ\Publish\API\Repository\Values\User\RoleAssignment[] $roleAssignments
1677
     *
1678
     * @see \eZ\Publish\API\Repository\RoleService::getRoleAssignments()
1679
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testGetRoleAssignments
1680
     */
1681
    public function testGetRoleAssignmentsContainExpectedLimitation(array $roleAssignments)
1682
    {
1683
        $this->assertEquals(
1684
            'Subtree',
1685
            reset($roleAssignments)->limitation->getIdentifier()
1686
        );
1687
    }
1688
1689
    /**
1690
     * Test for the assignRoleToUser() method.
1691
     *
1692
     * @see \eZ\Publish\API\Repository\RoleService::assignRoleToUser()
1693
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testGetRoleAssignments
1694
     */
1695 View Code Duplication
    public function testAssignRoleToUser()
1696
    {
1697
        $repository = $this->getRepository();
1698
        $roleService = $repository->getRoleService();
1699
1700
        /* BEGIN: Use Case */
1701
        $user = $this->createUserVersion1();
1702
1703
        // Load the existing "Administrator" role
1704
        $role = $roleService->loadRoleByIdentifier('Administrator');
1705
1706
        // Assign the "Administrator" role to the newly created user
1707
        $roleService->assignRoleToUser($role, $user);
1708
1709
        // The assignments array will contain the new role<->user assignment
1710
        $roleAssignments = $roleService->getRoleAssignments($role);
1711
        /* END: Use Case */
1712
1713
        // Administrator + Example User
1714
        $this->assertCount(2, $roleAssignments);
1715
    }
1716
1717
    /**
1718
     * Test for the assignRoleToUser() method.
1719
     *
1720
     * @see \eZ\Publish\API\Repository\RoleService::assignRoleToUser($role, $user, $roleLimitation)
1721
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUser
1722
     */
1723 View Code Duplication
    public function testAssignRoleToUserWithRoleLimitation()
1724
    {
1725
        $repository = $this->getRepository();
1726
        $roleService = $repository->getRoleService();
1727
1728
        /* BEGIN: Use Case */
1729
        $user = $this->createUserVersion1();
1730
1731
        // Load the existing "Anonymous" role
1732
        $role = $roleService->loadRoleByIdentifier('Anonymous');
1733
1734
        // Assign the "Anonymous" role to the newly created user
1735
        $roleService->assignRoleToUser(
1736
            $role,
1737
            $user,
1738
            new SubtreeLimitation(
1739
                [
1740
                    'limitationValues' => ['/1/43/'],
1741
                ]
1742
            )
1743
        );
1744
1745
        // The assignments array will contain the new role<->user assignment
1746
        $roleAssignments = $roleService->getRoleAssignments($role);
1747
        /* END: Use Case */
1748
1749
        // Members + Partners + Anonymous + Example User
1750
        $this->assertCount(4, $roleAssignments);
1751
1752
        // Get the role limitation
1753
        $roleLimitation = null;
1754
        foreach ($roleAssignments as $roleAssignment) {
1755
            $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...
1756
            if ($roleLimitation) {
1757
                $this->assertInstanceOf(
1758
                    '\\eZ\\Publish\\API\\Repository\\Values\\User\\UserRoleAssignment',
1759
                    $roleAssignment
1760
                );
1761
                break;
1762
            }
1763
        }
1764
1765
        $this->assertEquals(
1766
            new SubtreeLimitation(
1767
                [
1768
                    'limitationValues' => ['/1/43/'],
1769
                ]
1770
            ),
1771
            $roleLimitation
1772
        );
1773
1774
        // Test again to see values being merged
1775
        $roleService->assignRoleToUser(
1776
            $role,
1777
            $user,
1778
            new SubtreeLimitation(
1779
                [
1780
                    'limitationValues' => ['/1/43/', '/1/2/'],
1781
                ]
1782
            )
1783
        );
1784
1785
        // The assignments array will contain the new role<->user assignment
1786
        $roleAssignments = $roleService->getRoleAssignments($role);
1787
1788
        // Members + Partners + Anonymous + Example User
1789
        $this->assertCount(5, $roleAssignments);
1790
1791
        // Get the role limitation
1792
        $roleLimitations = [];
1793
        foreach ($roleAssignments as $roleAssignment) {
1794
            $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...
1795
            if ($roleLimitation) {
1796
                $this->assertInstanceOf(
1797
                    '\\eZ\\Publish\\API\\Repository\\Values\\User\\UserRoleAssignment',
1798
                    $roleAssignment
1799
                );
1800
                $roleLimitations[] = $roleLimitation;
1801
            }
1802
        }
1803
        array_multisort($roleLimitations);
1804
1805
        $this->assertEquals(
1806
            [
1807
                new SubtreeLimitation(
1808
                    [
1809
                        'limitationValues' => ['/1/2/'],
1810
                    ]
1811
                ),
1812
                new SubtreeLimitation(
1813
                    [
1814
                        'limitationValues' => ['/1/43/'],
1815
                    ]
1816
                ),
1817
            ],
1818
            $roleLimitations
1819
        );
1820
    }
1821
1822
    /**
1823
     * Test for the assignRoleToUser() method.
1824
     *
1825
     * @see \eZ\Publish\API\Repository\RoleService::assignRoleToUser($role, $user, $roleLimitation)
1826
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUser
1827
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleByIdentifier
1828
     */
1829
    public function testAssignRoleToUserWithRoleLimitationThrowsLimitationValidationException()
1830
    {
1831
        $this->expectException(\eZ\Publish\API\Repository\Exceptions\LimitationValidationException::class);
1832
1833
        $repository = $this->getRepository();
1834
1835
        /* BEGIN: Use Case */
1836
        $roleService = $repository->getRoleService();
1837
1838
        // Load the existing "Anonymous" role
1839
        $role = $roleService->loadRoleByIdentifier('Anonymous');
1840
1841
        // Get current user
1842
        $permissionResolver = $this->getRepository()->getPermissionResolver();
1843
        $userService = $repository->getUserService();
1844
        $currentUser = $userService->loadUser($permissionResolver->getCurrentUserReference()->getUserId());
1845
1846
        // Assign the "Anonymous" role to the current user
1847
        // This call will fail with an LimitationValidationException, because subtree "/lorem/ipsum/42/"
1848
        // does not exists
1849
        $roleService->assignRoleToUser(
1850
            $role,
1851
            $currentUser,
1852
            new SubtreeLimitation(
1853
                [
1854
                    'limitationValues' => ['/lorem/ipsum/42/'],
1855
                ]
1856
            )
1857
        );
1858
        /* END: Use Case */
1859
    }
1860
1861
    /**
1862
     * Test for the assignRoleToUser() method.
1863
     *
1864
     * Makes sure assigning role several times throws.
1865
     *
1866
     * @see \eZ\Publish\API\Repository\RoleService::assignRoleToUser($role, $user, $roleLimitation)
1867
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUser
1868
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleByIdentifier
1869
     */
1870
    public function testAssignRoleToUserThrowsInvalidArgumentException()
1871
    {
1872
        $this->expectException(\eZ\Publish\API\Repository\Exceptions\InvalidArgumentException::class);
1873
1874
        $repository = $this->getRepository();
1875
1876
        /* BEGIN: Use Case */
1877
        $roleService = $repository->getRoleService();
1878
1879
        // Load the existing "Anonymous" role
1880
        $role = $roleService->loadRoleByIdentifier('Anonymous');
1881
1882
        // Get current user
1883
        $permissionResolver = $this->getRepository()->getPermissionResolver();
1884
        $userService = $repository->getUserService();
1885
        $currentUser = $userService->loadUser($permissionResolver->getCurrentUserReference()->getUserId());
1886
1887
        // Assign the "Anonymous" role to the current user
1888
        try {
1889
            $roleService->assignRoleToUser(
1890
                $role,
1891
                $currentUser
1892
            );
1893
        } catch (Exception $e) {
1894
            $this->fail('Got exception at first valid attempt to assign role');
1895
        }
1896
1897
        // Re-Assign the "Anonymous" role to the current user
1898
        // This call will fail with an InvalidArgumentException, because limitation is already assigned
1899
        $roleService->assignRoleToUser(
1900
            $role,
1901
            $currentUser
1902
        );
1903
        /* END: Use Case */
1904
    }
1905
1906
    /**
1907
     * Test for the assignRoleToUser() method.
1908
     *
1909
     * Makes sure assigning role several times with same limitations throws.
1910
     *
1911
     * @see \eZ\Publish\API\Repository\RoleService::assignRoleToUser($role, $user, $roleLimitation)
1912
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUser
1913
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleByIdentifier
1914
     */
1915
    public function testAssignRoleToUserWithRoleLimitationThrowsInvalidArgumentException()
1916
    {
1917
        $this->expectException(\eZ\Publish\API\Repository\Exceptions\InvalidArgumentException::class);
1918
1919
        $repository = $this->getRepository();
1920
1921
        /* BEGIN: Use Case */
1922
        $roleService = $repository->getRoleService();
1923
1924
        // Load the existing "Anonymous" role
1925
        $role = $roleService->loadRoleByIdentifier('Anonymous');
1926
1927
        // Get current user
1928
        $permissionResolver = $this->getRepository()->getPermissionResolver();
1929
        $userService = $repository->getUserService();
1930
        $currentUser = $userService->loadUser($permissionResolver->getCurrentUserReference()->getUserId());
1931
1932
        // Assign the "Anonymous" role to the current user
1933
        try {
1934
            $roleService->assignRoleToUser(
1935
                $role,
1936
                $currentUser,
1937
                new SubtreeLimitation(
1938
                    [
1939
                        'limitationValues' => ['/1/43/', '/1/2/'],
1940
                    ]
1941
                )
1942
            );
1943
        } catch (Exception $e) {
1944
            $this->fail('Got exception at first valid attempt to assign role');
1945
        }
1946
1947
        // Re-Assign the "Anonymous" role to the current user
1948
        // This call will fail with an InvalidArgumentException, because limitation is already assigned
1949
        $roleService->assignRoleToUser(
1950
            $role,
1951
            $currentUser,
1952
            new SubtreeLimitation(
1953
                [
1954
                    'limitationValues' => ['/1/43/'],
1955
                ]
1956
            )
1957
        );
1958
        /* END: Use Case */
1959
    }
1960
1961
    /**
1962
     * Test for the removeRoleAssignment() method.
1963
     *
1964
     * @see \eZ\Publish\API\Repository\RoleService::removeRoleAssignment()
1965
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUser
1966
     */
1967 View Code Duplication
    public function testRemoveRoleAssignment()
1968
    {
1969
        $repository = $this->getRepository();
1970
        $roleService = $repository->getRoleService();
1971
1972
        /* BEGIN: Use Case */
1973
        $user = $this->createUserVersion1();
1974
1975
        // Load the existing "Member" role
1976
        $role = $roleService->loadRoleByIdentifier('Member');
1977
1978
        // Assign the "Member" role to the newly created user
1979
        $roleService->assignRoleToUser($role, $user);
1980
1981
        // Unassign user from role
1982
        $roleAssignments = $roleService->getRoleAssignmentsForUser($user);
1983
        foreach ($roleAssignments as $roleAssignment) {
1984
            if ($roleAssignment->role->id === $role->id) {
1985
                $roleService->removeRoleAssignment($roleAssignment);
1986
            }
1987
        }
1988
        // The assignments array will not contain the new role<->user assignment
1989
        $roleAssignments = $roleService->getRoleAssignments($role);
1990
        /* END: Use Case */
1991
1992
        // Members + Editors + Partners
1993
        $this->assertCount(3, $roleAssignments);
1994
    }
1995
1996
    /**
1997
     * Test for the getRoleAssignmentsForUser() method.
1998
     *
1999
     * @see \eZ\Publish\API\Repository\RoleService::getRoleAssignmentsForUser()
2000
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUser
2001
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRoleWithAddPolicy
2002
     */
2003
    public function testGetRoleAssignmentsForUserDirect()
2004
    {
2005
        $repository = $this->getRepository();
2006
        $roleService = $repository->getRoleService();
2007
2008
        /* BEGIN: Use Case */
2009
        $user = $this->createUserVersion1();
2010
2011
        // Instantiate a role create and add some policies
2012
        $roleCreate = $roleService->newRoleCreateStruct('Example Role');
2013
2014
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
2015
        // $roleCreate->mainLanguageCode = 'eng-US';
2016
2017
        $roleCreate->addPolicy(
2018
            $roleService->newPolicyCreateStruct('user', 'login')
2019
        );
2020
        $roleCreate->addPolicy(
2021
            $roleService->newPolicyCreateStruct('content', 'read')
2022
        );
2023
        $roleCreate->addPolicy(
2024
            $roleService->newPolicyCreateStruct('content', 'edit')
2025
        );
2026
2027
        // Create the new role instance
2028
        $roleDraft = $roleService->createRole($roleCreate);
2029
        $roleService->publishRoleDraft($roleDraft);
2030
        $role = $roleService->loadRole($roleDraft->id);
2031
2032
        // Check inital empty assigments (also warms up potential cache to validate it is correct below)
2033
        $this->assertCount(0, $roleService->getRoleAssignmentsForUser($user));
2034
        $this->assertCount(0, $roleService->getRoleAssignments($role));
2035
2036
        // Assign role to new user
2037
        $roleService->assignRoleToUser($role, $user);
2038
2039
        // Load the currently assigned role
2040
        $roleAssignments = $roleService->getRoleAssignmentsForUser($user);
2041
        /* END: Use Case */
2042
2043
        $this->assertCount(1, $roleAssignments);
2044
        $this->assertInstanceOf(
2045
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\UserRoleAssignment',
2046
            reset($roleAssignments)
2047
        );
2048
        $this->assertCount(1, $roleService->getRoleAssignments($role));
2049
    }
2050
2051
    /**
2052
     * Test for the getRoleAssignmentsForUser() method.
2053
     *
2054
     * @see \eZ\Publish\API\Repository\RoleService::getRoleAssignmentsForUser()
2055
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUser
2056
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRoleWithAddPolicy
2057
     */
2058 View Code Duplication
    public function testGetRoleAssignmentsForUserEmpty()
2059
    {
2060
        $repository = $this->getRepository();
2061
        $roleService = $repository->getRoleService();
2062
2063
        /* BEGIN: Use Case */
2064
        $permissionResolver = $this->getRepository()->getPermissionResolver();
2065
        $userService = $repository->getUserService();
2066
        $adminUser = $userService->loadUser($permissionResolver->getCurrentUserReference()->getUserId());
2067
2068
        // Load the currently assigned role
2069
        $roleAssignments = $roleService->getRoleAssignmentsForUser($adminUser);
2070
        /* END: Use Case */
2071
2072
        $this->assertCount(0, $roleAssignments);
2073
    }
2074
2075
    /**
2076
     * Test for the getRoleAssignmentsForUser() method.
2077
     *
2078
     * @see \eZ\Publish\API\Repository\RoleService::getRoleAssignmentsForUser()
2079
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUser
2080
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRoleWithAddPolicy
2081
     */
2082
    public function testGetRoleAssignmentsForUserInherited()
2083
    {
2084
        $repository = $this->getRepository();
2085
        $roleService = $repository->getRoleService();
2086
2087
        /* BEGIN: Use Case */
2088
        $permissionResolver = $this->getRepository()->getPermissionResolver();
2089
        $userService = $repository->getUserService();
2090
        $adminUser = $userService->loadUser($permissionResolver->getCurrentUserReference()->getUserId());
2091
2092
        // Load the currently assigned role + inherited role assignments
2093
        $roleAssignments = $roleService->getRoleAssignmentsForUser($adminUser, true);
2094
        /* END: Use Case */
2095
2096
        $this->assertCount(1, $roleAssignments);
2097
        $this->assertInstanceOf(
2098
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\UserGroupRoleAssignment',
2099
            reset($roleAssignments)
2100
        );
2101
    }
2102
2103
    /**
2104
     * Test for the assignRoleToUserGroup() method.
2105
     *
2106
     * @see \eZ\Publish\API\Repository\RoleService::assignRoleToUserGroup()
2107
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testGetRoleAssignments
2108
     */
2109 View Code Duplication
    public function testAssignRoleToUserGroup()
2110
    {
2111
        $repository = $this->getRepository();
2112
        $roleService = $repository->getRoleService();
2113
2114
        /* BEGIN: Use Case */
2115
        $userGroup = $this->createUserGroupVersion1();
2116
2117
        // Load the existing "Administrator" role
2118
        $role = $roleService->loadRoleByIdentifier('Administrator');
2119
2120
        // Assign the "Administrator" role to the newly created user group
2121
        $roleService->assignRoleToUserGroup($role, $userGroup);
2122
2123
        // The assignments array will contain the new role<->group assignment
2124
        $roleAssignments = $roleService->getRoleAssignments($role);
2125
        /* END: Use Case */
2126
2127
        // Administrator + Example Group
2128
        $this->assertCount(2, $roleAssignments);
2129
    }
2130
2131
    /**
2132
     * Test for the assignRoleToUserGroup() method.
2133
     *
2134
     * Related issue: EZP-29113
2135
     *
2136
     * @covers \eZ\Publish\API\Repository\RoleService::assignRoleToUserGroup()
2137
     */
2138
    public function testAssignRoleToUserGroupAffectsRoleAssignmentsForUser()
2139
    {
2140
        $roleService = $this->getRepository()->getRoleService();
2141
2142
        /* BEGIN: Use Case */
2143
        $userGroup = $this->createUserGroupVersion1();
2144
        $user = $this->createUser('user', 'John', 'Doe', $userGroup);
2145
2146
        $initRoleAssignments = $roleService->getRoleAssignmentsForUser($user, true);
2147
2148
        // Load the existing "Administrator" role
2149
        $role = $roleService->loadRoleByIdentifier('Administrator');
2150
2151
        // Assign the "Administrator" role to the newly created user group
2152
        $roleService->assignRoleToUserGroup($role, $userGroup);
2153
2154
        $updatedRoleAssignments = $roleService->getRoleAssignmentsForUser($user, true);
2155
        /* END: Use Case */
2156
2157
        $this->assertEmpty($initRoleAssignments);
2158
        $this->assertCount(1, $updatedRoleAssignments);
2159
    }
2160
2161
    /**
2162
     * Test for the assignRoleToUserGroup() method.
2163
     *
2164
     * @see \eZ\Publish\API\Repository\RoleService::assignRoleToUserGroup($role, $userGroup, $roleLimitation)
2165
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUserGroup
2166
     */
2167 View Code Duplication
    public function testAssignRoleToUserGroupWithRoleLimitation()
2168
    {
2169
        $repository = $this->getRepository();
2170
        $roleService = $repository->getRoleService();
2171
2172
        /* BEGIN: Use Case */
2173
        $userGroup = $this->createUserGroupVersion1();
2174
2175
        // Load the existing "Anonymous" role
2176
        $role = $roleService->loadRoleByIdentifier('Anonymous');
2177
2178
        // Assign the "Anonymous" role to the newly created user group
2179
        $roleService->assignRoleToUserGroup(
2180
            $role,
2181
            $userGroup,
2182
            new SubtreeLimitation(
2183
                [
2184
                    'limitationValues' => ['/1/43/'],
2185
                ]
2186
            )
2187
        );
2188
2189
        // The assignments array will contain the new role<->group assignment
2190
        $roleAssignments = $roleService->getRoleAssignments($role);
2191
        /* END: Use Case */
2192
2193
        // Members + Partners + Anonymous + Example Group
2194
        $this->assertCount(4, $roleAssignments);
2195
2196
        // Get the role limitation
2197
        $roleLimitation = null;
2198
        foreach ($roleAssignments as $roleAssignment) {
2199
            $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...
2200
            if ($roleLimitation) {
2201
                break;
2202
            }
2203
        }
2204
2205
        $this->assertEquals(
2206
            new SubtreeLimitation(
2207
                [
2208
                    'limitationValues' => ['/1/43/'],
2209
                ]
2210
            ),
2211
            $roleLimitation
2212
        );
2213
2214
        // Test again to see values being merged
2215
        $roleService->assignRoleToUserGroup(
2216
            $role,
2217
            $userGroup,
2218
            new SubtreeLimitation(
2219
                [
2220
                    'limitationValues' => ['/1/43/', '/1/2/'],
2221
                ]
2222
            )
2223
        );
2224
2225
        // The assignments array will contain the new role<->user assignment
2226
        $roleAssignments = $roleService->getRoleAssignments($role);
2227
2228
        // Members + Partners + Anonymous + Example User
2229
        $this->assertCount(5, $roleAssignments);
2230
2231
        // Get the role limitation
2232
        $roleLimitations = [];
2233
        foreach ($roleAssignments as $roleAssignment) {
2234
            $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...
2235
            if ($roleLimitation) {
2236
                $this->assertInstanceOf(
2237
                    '\\eZ\\Publish\\API\\Repository\\Values\\User\\UserGroupRoleAssignment',
2238
                    $roleAssignment
2239
                );
2240
                $roleLimitations[] = $roleLimitation;
2241
            }
2242
        }
2243
        array_multisort($roleLimitations);
2244
2245
        $this->assertEquals(
2246
            [
2247
                new SubtreeLimitation(
2248
                    [
2249
                        'limitationValues' => ['/1/2/'],
2250
                    ]
2251
                ),
2252
                new SubtreeLimitation(
2253
                    [
2254
                        'limitationValues' => ['/1/43/'],
2255
                    ]
2256
                ),
2257
            ],
2258
            $roleLimitations
2259
        );
2260
    }
2261
2262
    /**
2263
     * Test for the assignRoleToUserGroup() method.
2264
     *
2265
     * @see \eZ\Publish\API\Repository\RoleService::assignRoleToUserGroup($role, $userGroup, $roleLimitation)
2266
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleByIdentifier
2267
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUserGroup
2268
     */
2269 View Code Duplication
    public function testAssignRoleToUserGroupWithRoleLimitationThrowsLimitationValidationException()
2270
    {
2271
        $this->expectException(\eZ\Publish\API\Repository\Exceptions\LimitationValidationException::class);
2272
2273
        $repository = $this->getRepository();
2274
2275
        $mainGroupId = $this->generateId('group', 4);
2276
        /* BEGIN: Use Case */
2277
        // $mainGroupId is the ID of the main "Users" group
2278
2279
        $userService = $repository->getUserService();
2280
        $roleService = $repository->getRoleService();
2281
2282
        $userGroup = $userService->loadUserGroup($mainGroupId);
2283
2284
        // Load the existing "Anonymous" role
2285
        $role = $roleService->loadRoleByIdentifier('Anonymous');
2286
2287
        // Assign the "Anonymous" role to the newly created user group
2288
        // This call will fail with an LimitationValidationException, because subtree "/lorem/ipsum/42/"
2289
        // does not exists
2290
        $roleService->assignRoleToUserGroup(
2291
            $role,
2292
            $userGroup,
2293
            new SubtreeLimitation(
2294
                [
2295
                    'limitationValues' => ['/lorem/ipsum/42/'],
2296
                ]
2297
            )
2298
        );
2299
        /* END: Use Case */
2300
    }
2301
2302
    /**
2303
     * Test for the assignRoleToUserGroup() method.
2304
     *
2305
     * Makes sure assigning role several times throws.
2306
     *
2307
     * @see \eZ\Publish\API\Repository\RoleService::assignRoleToUserGroup($role, $userGroup, $roleLimitation)
2308
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleByIdentifier
2309
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUserGroup
2310
     */
2311 View Code Duplication
    public function testAssignRoleToUserGroupThrowsInvalidArgumentException()
2312
    {
2313
        $this->expectException(\eZ\Publish\API\Repository\Exceptions\InvalidArgumentException::class);
2314
2315
        $repository = $this->getRepository();
2316
2317
        $mainGroupId = $this->generateId('group', 4);
2318
        /* BEGIN: Use Case */
2319
        // $mainGroupId is the ID of the main "Users" group
2320
2321
        $userService = $repository->getUserService();
2322
        $roleService = $repository->getRoleService();
2323
2324
        $userGroup = $userService->loadUserGroup($mainGroupId);
2325
2326
        // Load the existing "Anonymous" role
2327
        $role = $roleService->loadRoleByIdentifier('Anonymous');
2328
2329
        // Assign the "Anonymous" role to the newly created user group
2330
        try {
2331
            $roleService->assignRoleToUserGroup(
2332
                $role,
2333
                $userGroup
2334
            );
2335
        } catch (Exception $e) {
2336
            $this->fail('Got exception at first valid attempt to assign role');
2337
        }
2338
2339
        // Re-Assign the "Anonymous" role to the newly created user group
2340
        // This call will fail with an InvalidArgumentException, because role is already assigned
2341
        $roleService->assignRoleToUserGroup(
2342
            $role,
2343
            $userGroup
2344
        );
2345
        /* END: Use Case */
2346
    }
2347
2348
    /**
2349
     * Test for the assignRoleToUserGroup() method.
2350
     *
2351
     * Makes sure assigning role several times with same limitations throws.
2352
     *
2353
     * @see \eZ\Publish\API\Repository\RoleService::assignRoleToUserGroup($role, $userGroup, $roleLimitation)
2354
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleByIdentifier
2355
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUserGroup
2356
     */
2357
    public function testAssignRoleToUserGroupWithRoleLimitationThrowsInvalidArgumentException()
2358
    {
2359
        $this->expectException(\eZ\Publish\API\Repository\Exceptions\InvalidArgumentException::class);
2360
2361
        $repository = $this->getRepository();
2362
2363
        $mainGroupId = $this->generateId('group', 4);
2364
        /* BEGIN: Use Case */
2365
        // $mainGroupId is the ID of the main "Users" group
2366
2367
        $userService = $repository->getUserService();
2368
        $roleService = $repository->getRoleService();
2369
2370
        $userGroup = $userService->loadUserGroup($mainGroupId);
2371
2372
        // Load the existing "Anonymous" role
2373
        $role = $roleService->loadRoleByIdentifier('Anonymous');
2374
2375
        // Assign the "Anonymous" role to the newly created user group
2376
        try {
2377
            $roleService->assignRoleToUserGroup(
2378
                $role,
2379
                $userGroup,
2380
                new SubtreeLimitation(
2381
                    [
2382
                        'limitationValues' => ['/1/43/', '/1/2/'],
2383
                    ]
2384
                )
2385
            );
2386
        } catch (Exception $e) {
2387
            $this->fail('Got exception at first valid attempt to assign role');
2388
        }
2389
2390
        // Re-Assign the "Anonymous" role to the newly created user group
2391
        // This call will fail with an InvalidArgumentException, because limitation is already assigned
2392
        $roleService->assignRoleToUserGroup(
2393
            $role,
2394
            $userGroup,
2395
            new SubtreeLimitation(
2396
                [
2397
                    'limitationValues' => ['/1/43/'],
2398
                ]
2399
            )
2400
        );
2401
        /* END: Use Case */
2402
    }
2403
2404
    /**
2405
     * Test for the removeRoleAssignment() method.
2406
     *
2407
     * @see \eZ\Publish\API\Repository\RoleService::removeRoleAssignment()
2408
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUserGroup
2409
     */
2410
    public function testRemoveRoleAssignmentFromUserGroup()
2411
    {
2412
        $repository = $this->getRepository();
2413
        $roleService = $repository->getRoleService();
2414
2415
        /* BEGIN: Use Case */
2416
        $userGroup = $this->createUserGroupVersion1();
2417
2418
        // Load the existing "Member" role
2419
        $role = $roleService->loadRoleByIdentifier('Member');
2420
2421
        // Assign the "Member" role to the newly created user group
2422
        $roleService->assignRoleToUserGroup($role, $userGroup);
2423
2424
        // Unassign group from role
2425
        $roleAssignments = $roleService->getRoleAssignmentsForUserGroup($userGroup);
2426
2427
        // This call will fail with an "UnauthorizedException"
2428
        foreach ($roleAssignments as $roleAssignment) {
2429
            if ($roleAssignment->role->id === $role->id) {
2430
                $roleService->removeRoleAssignment($roleAssignment);
2431
            }
2432
        }
2433
        // The assignments array will not contain the new role<->group assignment
2434
        $roleAssignments = $roleService->getRoleAssignments($role);
2435
        /* END: Use Case */
2436
2437
        // Members + Editors + Partners
2438
        $this->assertCount(3, $roleAssignments);
2439
    }
2440
2441
    /**
2442
     * Test unassigning role by assignment.
2443
     *
2444
     * @covers \eZ\Publish\API\Repository\RoleService::removeRoleAssignment
2445
     */
2446
    public function testUnassignRoleByAssignment()
2447
    {
2448
        $repository = $this->getRepository();
2449
        $roleService = $repository->getRoleService();
2450
2451
        $role = $roleService->loadRole(2);
2452
        $user = $repository->getUserService()->loadUser(14);
2453
2454
        $originalAssignmentCount = count($roleService->getRoleAssignmentsForUser($user));
2455
2456
        $roleService->assignRoleToUser($role, $user);
2457
        $newAssignmentCount = count($roleService->getRoleAssignmentsForUser($user));
2458
        self::assertEquals($originalAssignmentCount + 1, $newAssignmentCount);
2459
2460
        $assignments = $roleService->getRoleAssignmentsForUser($user);
2461
        $roleService->removeRoleAssignment($assignments[0]);
2462
        $finalAssignmentCount = count($roleService->getRoleAssignmentsForUser($user));
2463
        self::assertEquals($newAssignmentCount - 1, $finalAssignmentCount);
2464
    }
2465
2466
    /**
2467
     * Test unassigning role by assignment.
2468
     *
2469
     * But on current admin user so he lacks access to read roles.
2470
     *
2471
     * @covers \eZ\Publish\API\Repository\RoleService::removeRoleAssignment
2472
     */
2473 View Code Duplication
    public function testUnassignRoleByAssignmentThrowsUnauthorizedException()
2474
    {
2475
        $this->expectException(\eZ\Publish\API\Repository\Exceptions\UnauthorizedException::class);
2476
2477
        $repository = $this->getRepository();
2478
        $roleService = $repository->getRoleService();
2479
2480
        try {
2481
            $adminUserGroup = $repository->getUserService()->loadUserGroup(12);
2482
            $assignments = $roleService->getRoleAssignmentsForUserGroup($adminUserGroup);
2483
            $roleService->removeRoleAssignment($assignments[0]);
2484
        } catch (Exception $e) {
2485
            self::fail(
2486
                'Unexpected exception: ' . $e->getMessage() . " \n[" . $e->getFile() . ' (' . $e->getLine() . ')]'
2487
            );
2488
        }
2489
2490
        $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...
2491
    }
2492
2493
    /**
2494
     * Test unassigning role by non-existing assignment.
2495
     *
2496
     * @covers \eZ\Publish\API\Repository\RoleService::removeRoleAssignment
2497
     */
2498 View Code Duplication
    public function testUnassignRoleByAssignmentThrowsNotFoundException()
2499
    {
2500
        $this->expectException(\eZ\Publish\API\Repository\Exceptions\NotFoundException::class);
2501
2502
        $repository = $this->getRepository();
2503
        $roleService = $repository->getRoleService();
2504
2505
        try {
2506
            $editorsUserGroup = $repository->getUserService()->loadUserGroup(13);
2507
            $assignments = $roleService->getRoleAssignmentsForUserGroup($editorsUserGroup);
2508
            $roleService->removeRoleAssignment($assignments[0]);
2509
        } catch (Exception $e) {
2510
            self::fail(
2511
                'Unexpected exception: ' . $e->getMessage() . " \n[" . $e->getFile() . ' (' . $e->getLine() . ')]'
2512
            );
2513
        }
2514
2515
        $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...
2516
    }
2517
2518
    /**
2519
     * Test for the getRoleAssignmentsForUserGroup() method.
2520
     *
2521
     * @see \eZ\Publish\API\Repository\RoleService::getRoleAssignmentsForUserGroup()
2522
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUserGroup
2523
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRoleWithAddPolicy
2524
     */
2525
    public function testGetRoleAssignmentsForUserGroup()
2526
    {
2527
        $repository = $this->getRepository();
2528
        $roleService = $repository->getRoleService();
2529
2530
        /* BEGIN: Use Case */
2531
        $userGroup = $this->createUserGroupVersion1();
2532
2533
        // Instantiate a role create and add some policies
2534
        $roleCreate = $roleService->newRoleCreateStruct('Example Role');
2535
2536
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
2537
        // $roleCreate->mainLanguageCode = 'eng-US';
2538
2539
        $roleCreate->addPolicy(
2540
            $roleService->newPolicyCreateStruct('user', 'login')
2541
        );
2542
        $roleCreate->addPolicy(
2543
            $roleService->newPolicyCreateStruct('content', 'read')
2544
        );
2545
        $roleCreate->addPolicy(
2546
            $roleService->newPolicyCreateStruct('content', 'edit')
2547
        );
2548
2549
        // Create the new role instance
2550
        $roleDraft = $roleService->createRole($roleCreate);
2551
        $roleService->publishRoleDraft($roleDraft);
2552
        $role = $roleService->loadRole($roleDraft->id);
2553
2554
        // Assign role to new user group
2555
        $roleService->assignRoleToUserGroup($role, $userGroup);
2556
2557
        // Load the currently assigned role
2558
        $roleAssignments = $roleService->getRoleAssignmentsForUserGroup($userGroup);
2559
        /* END: Use Case */
2560
2561
        $this->assertCount(1, $roleAssignments);
2562
        $this->assertInstanceOf(
2563
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\UserGroupRoleAssignment',
2564
            reset($roleAssignments)
2565
        );
2566
    }
2567
2568
    /**
2569
     * Test for the getRoleAssignmentsForUser() method.
2570
     *
2571
     * @see \eZ\Publish\API\Repository\RoleService::getRoleAssignmentsForUser()
2572
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUser
2573
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUserGroup
2574
     */
2575
    public function testLoadPoliciesByUserId()
2576
    {
2577
        $repository = $this->getRepository();
2578
2579
        $anonUserId = $this->generateId('user', 10);
2580
        /* BEGIN: Use Case */
2581
        // $anonUserId is the ID of the "Anonymous" user.
2582
2583
        $userService = $repository->getUserService();
2584
        $roleService = $repository->getRoleService();
2585
2586
        // Load "Anonymous" user
2587
        $user = $userService->loadUser($anonUserId);
2588
2589
        // Instantiate a role create and add some policies
2590
        $roleCreate = $roleService->newRoleCreateStruct('User Role');
2591
2592
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
2593
        // $roleCreate->mainLanguageCode = 'eng-US';
2594
2595
        $roleCreate->addPolicy(
2596
            $roleService->newPolicyCreateStruct('notification', 'use')
2597
        );
2598
        $roleCreate->addPolicy(
2599
            $roleService->newPolicyCreateStruct('user', 'password')
2600
        );
2601
        $roleCreate->addPolicy(
2602
            $roleService->newPolicyCreateStruct('user', 'selfedit')
2603
        );
2604
2605
        // Create the new role instance
2606
        $roleDraft = $roleService->createRole($roleCreate);
2607
        $roleService->publishRoleDraft($roleDraft);
2608
        $role = $roleService->loadRole($roleDraft->id);
2609
2610
        // Assign role to anon user
2611
        $roleService->assignRoleToUser($role, $user);
2612
        $roleAssignments = $roleService->getRoleAssignmentsForUser($user, true);
2613
2614
        $policies = [];
2615
        foreach ($roleAssignments as $roleAssignment) {
2616
            $policies[] = $roleAssignment->getRole()->getPolicies();
2617
        }
2618
        $policies = array_merge(...$policies);
2619
2620
        $simplePolicyList = [];
2621
        foreach ($policies as $simplePolicy) {
2622
            $simplePolicyList[] = [$simplePolicy->roleId, $simplePolicy->module, $simplePolicy->function];
2623
        }
2624
        /* END: Use Case */
2625
        array_multisort($simplePolicyList);
2626
2627
        $this->assertEquals(
2628
            [
2629
                [1, 'content', 'pdf'],
2630
                [1, 'content', 'read'],
2631
                [1, 'content', 'read'],
2632
                [1, 'rss', 'feed'],
2633
                [1, 'user', 'login'],
2634
                [1, 'user', 'login'],
2635
                [1, 'user', 'login'],
2636
                [1, 'user', 'login'],
2637
                [$role->id, 'notification', 'use'],
2638
                [$role->id, 'user', 'password'],
2639
                [$role->id, 'user', 'selfedit'],
2640
            ],
2641
            $simplePolicyList
2642
        );
2643
    }
2644
2645
    /**
2646
     * Test for the publishRoleDraft() method.
2647
     *
2648
     * @see \eZ\Publish\API\Repository\RoleService::publishRoleDraft()
2649
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRoleDraft
2650
     */
2651 View Code Duplication
    public function testPublishRoleDraft()
2652
    {
2653
        $repository = $this->getRepository();
2654
2655
        /* BEGIN: Use Case */
2656
        $roleService = $repository->getRoleService();
2657
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
2658
2659
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
2660
        // $roleCreate->mainLanguageCode = 'eng-US';
2661
2662
        $roleDraft = $roleService->createRole($roleCreate);
2663
2664
        $roleDraft = $roleService->addPolicyByRoleDraft(
2665
            $roleDraft,
2666
            $roleService->newPolicyCreateStruct('content', 'delete')
2667
        );
2668
        $roleDraft = $roleService->addPolicyByRoleDraft(
2669
            $roleDraft,
2670
            $roleService->newPolicyCreateStruct('content', 'create')
2671
        );
2672
2673
        $roleService->publishRoleDraft($roleDraft);
2674
        /* END: Use Case */
2675
2676
        $this->assertInstanceOf(
2677
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\Role',
2678
            $roleService->loadRoleByIdentifier($roleCreate->identifier)
2679
        );
2680
    }
2681
2682
    /**
2683
     * Test for the publishRoleDraft() method.
2684
     *
2685
     * @see \eZ\Publish\API\Repository\RoleService::publishRoleDraft()
2686
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRoleDraft
2687
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicyByRoleDraft
2688
     */
2689
    public function testPublishRoleDraftAddPolicies()
2690
    {
2691
        $repository = $this->getRepository();
2692
2693
        /* BEGIN: Use Case */
2694
        $roleService = $repository->getRoleService();
2695
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
2696
2697
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
2698
        // $roleCreate->mainLanguageCode = 'eng-US';
2699
2700
        $roleDraft = $roleService->createRole($roleCreate);
2701
2702
        $roleDraft = $roleService->addPolicyByRoleDraft(
2703
            $roleDraft,
2704
            $roleService->newPolicyCreateStruct('content', 'delete')
2705
        );
2706
        $roleDraft = $roleService->addPolicyByRoleDraft(
2707
            $roleDraft,
2708
            $roleService->newPolicyCreateStruct('content', 'create')
2709
        );
2710
2711
        $roleService->publishRoleDraft($roleDraft);
2712
        $role = $roleService->loadRoleByIdentifier($roleCreate->identifier);
2713
        /* END: Use Case */
2714
2715
        $actual = [];
2716
        foreach ($role->getPolicies() as $policy) {
2717
            $actual[] = [
2718
                'module' => $policy->module,
2719
                'function' => $policy->function,
2720
            ];
2721
        }
2722
        usort(
2723
            $actual,
2724
            function ($p1, $p2) {
2725
                return strcasecmp($p1['function'], $p2['function']);
2726
            }
2727
        );
2728
2729
        $this->assertEquals(
2730
            [
2731
                [
2732
                    'module' => 'content',
2733
                    'function' => 'create',
2734
                ],
2735
                [
2736
                    'module' => 'content',
2737
                    'function' => 'delete',
2738
                ],
2739
            ],
2740
            $actual
2741
        );
2742
    }
2743
2744
    /**
2745
     * Create a user group fixture in a variable named <b>$userGroup</b>,.
2746
     *
2747
     * @return \eZ\Publish\API\Repository\Values\User\UserGroup
2748
     */
2749
    private function createUserGroupVersion1()
2750
    {
2751
        $repository = $this->getRepository();
2752
2753
        $mainGroupId = $this->generateId('group', 4);
2754
        /* BEGIN: Inline */
2755
        // $mainGroupId is the ID of the main "Users" group
2756
2757
        $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...
2758
        $userService = $repository->getUserService();
2759
2760
        // Load main group
2761
        $parentUserGroup = $userService->loadUserGroup($mainGroupId);
2762
2763
        // Instantiate a new create struct
2764
        $userGroupCreate = $userService->newUserGroupCreateStruct('eng-US');
2765
        $userGroupCreate->setField('name', 'Example Group');
2766
2767
        // Create the new user group
2768
        $userGroup = $userService->createUserGroup(
2769
            $userGroupCreate,
2770
            $parentUserGroup
2771
        );
2772
        /* END: Inline */
2773
2774
        return $userGroup;
2775
    }
2776
}
2777