Completed
Push — EZP-31383-roles-copying ( d0932a...19a821 )
by
unknown
12:30
created

RoleServiceTest::providerForCopyRoleTests()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 39

Duplication

Lines 0
Ratio 0 %

Importance

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

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
2675
    }
2676
2677
    /**
2678
     * Test unassigning role by non-existing assignment.
2679
     *
2680
     * @covers \eZ\Publish\API\Repository\RoleService::removeRoleAssignment
2681
     */
2682 View Code Duplication
    public function testUnassignRoleByAssignmentThrowsNotFoundException()
2683
    {
2684
        $this->expectException(\eZ\Publish\API\Repository\Exceptions\NotFoundException::class);
2685
2686
        $repository = $this->getRepository();
2687
        $roleService = $repository->getRoleService();
2688
2689
        try {
2690
            $editorsUserGroup = $repository->getUserService()->loadUserGroup(13);
2691
            $assignments = $roleService->getRoleAssignmentsForUserGroup($editorsUserGroup);
2692
            $roleService->removeRoleAssignment($assignments[0]);
2693
        } catch (Exception $e) {
2694
            self::fail(
2695
                'Unexpected exception: ' . $e->getMessage() . " \n[" . $e->getFile() . ' (' . $e->getLine() . ')]'
2696
            );
2697
        }
2698
2699
        $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...
2700
    }
2701
2702
    /**
2703
     * Test for the getRoleAssignmentsForUserGroup() method.
2704
     *
2705
     * @see \eZ\Publish\API\Repository\RoleService::getRoleAssignmentsForUserGroup()
2706
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUserGroup
2707
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRoleWithAddPolicy
2708
     */
2709
    public function testGetRoleAssignmentsForUserGroup()
2710
    {
2711
        $repository = $this->getRepository();
2712
        $roleService = $repository->getRoleService();
2713
2714
        /* BEGIN: Use Case */
2715
        $userGroup = $this->createUserGroupVersion1();
2716
2717
        // Instantiate a role create and add some policies
2718
        $roleCreate = $roleService->newRoleCreateStruct('Example Role');
2719
2720
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
2721
        // $roleCreate->mainLanguageCode = 'eng-US';
2722
2723
        $roleCreate->addPolicy(
2724
            $roleService->newPolicyCreateStruct('user', 'login')
2725
        );
2726
        $roleCreate->addPolicy(
2727
            $roleService->newPolicyCreateStruct('content', 'read')
2728
        );
2729
        $roleCreate->addPolicy(
2730
            $roleService->newPolicyCreateStruct('content', 'edit')
2731
        );
2732
2733
        // Create the new role instance
2734
        $roleDraft = $roleService->createRole($roleCreate);
2735
        $roleService->publishRoleDraft($roleDraft);
2736
        $role = $roleService->loadRole($roleDraft->id);
2737
2738
        // Assign role to new user group
2739
        $roleService->assignRoleToUserGroup($role, $userGroup);
2740
2741
        // Load the currently assigned role
2742
        $roleAssignments = $roleService->getRoleAssignmentsForUserGroup($userGroup);
2743
        /* END: Use Case */
2744
2745
        $this->assertCount(1, $roleAssignments);
2746
        $this->assertInstanceOf(
2747
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\UserGroupRoleAssignment',
2748
            reset($roleAssignments)
2749
        );
2750
    }
2751
2752
    /**
2753
     * Test for the getRoleAssignmentsForUser() method.
2754
     *
2755
     * @see \eZ\Publish\API\Repository\RoleService::getRoleAssignmentsForUser()
2756
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUser
2757
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUserGroup
2758
     */
2759
    public function testLoadPoliciesByUserId()
2760
    {
2761
        $repository = $this->getRepository();
2762
2763
        $anonUserId = $this->generateId('user', 10);
2764
        /* BEGIN: Use Case */
2765
        // $anonUserId is the ID of the "Anonymous" user.
2766
2767
        $userService = $repository->getUserService();
2768
        $roleService = $repository->getRoleService();
2769
2770
        // Load "Anonymous" user
2771
        $user = $userService->loadUser($anonUserId);
2772
2773
        // Instantiate a role create and add some policies
2774
        $roleCreate = $roleService->newRoleCreateStruct('User Role');
2775
2776
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
2777
        // $roleCreate->mainLanguageCode = 'eng-US';
2778
2779
        $roleCreate->addPolicy(
2780
            $roleService->newPolicyCreateStruct('notification', 'use')
2781
        );
2782
        $roleCreate->addPolicy(
2783
            $roleService->newPolicyCreateStruct('user', 'password')
2784
        );
2785
        $roleCreate->addPolicy(
2786
            $roleService->newPolicyCreateStruct('user', 'selfedit')
2787
        );
2788
2789
        // Create the new role instance
2790
        $roleDraft = $roleService->createRole($roleCreate);
2791
        $roleService->publishRoleDraft($roleDraft);
2792
        $role = $roleService->loadRole($roleDraft->id);
2793
2794
        // Assign role to anon user
2795
        $roleService->assignRoleToUser($role, $user);
2796
        $roleAssignments = $roleService->getRoleAssignmentsForUser($user, true);
2797
2798
        $policies = [];
2799
        foreach ($roleAssignments as $roleAssignment) {
2800
            $policies[] = $roleAssignment->getRole()->getPolicies();
2801
        }
2802
        $policies = array_merge(...$policies);
2803
2804
        $simplePolicyList = [];
2805
        foreach ($policies as $simplePolicy) {
2806
            $simplePolicyList[] = [$simplePolicy->roleId, $simplePolicy->module, $simplePolicy->function];
2807
        }
2808
        /* END: Use Case */
2809
        array_multisort($simplePolicyList);
2810
2811
        $this->assertEquals(
2812
            [
2813
                [1, 'content', 'pdf'],
2814
                [1, 'content', 'read'],
2815
                [1, 'content', 'read'],
2816
                [1, 'rss', 'feed'],
2817
                [1, 'user', 'login'],
2818
                [1, 'user', 'login'],
2819
                [1, 'user', 'login'],
2820
                [1, 'user', 'login'],
2821
                [$role->id, 'notification', 'use'],
2822
                [$role->id, 'user', 'password'],
2823
                [$role->id, 'user', 'selfedit'],
2824
            ],
2825
            $simplePolicyList
2826
        );
2827
    }
2828
2829
    /**
2830
     * Test for the publishRoleDraft() method.
2831
     *
2832
     * @see \eZ\Publish\API\Repository\RoleService::publishRoleDraft()
2833
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRoleDraft
2834
     */
2835 View Code Duplication
    public function testPublishRoleDraft()
2836
    {
2837
        $repository = $this->getRepository();
2838
2839
        /* BEGIN: Use Case */
2840
        $roleService = $repository->getRoleService();
2841
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
2842
2843
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
2844
        // $roleCreate->mainLanguageCode = 'eng-US';
2845
2846
        $roleDraft = $roleService->createRole($roleCreate);
2847
2848
        $roleDraft = $roleService->addPolicyByRoleDraft(
2849
            $roleDraft,
2850
            $roleService->newPolicyCreateStruct('content', 'delete')
2851
        );
2852
        $roleDraft = $roleService->addPolicyByRoleDraft(
2853
            $roleDraft,
2854
            $roleService->newPolicyCreateStruct('content', 'create')
2855
        );
2856
2857
        $roleService->publishRoleDraft($roleDraft);
2858
        /* END: Use Case */
2859
2860
        $this->assertInstanceOf(
2861
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\Role',
2862
            $roleService->loadRoleByIdentifier($roleCreate->identifier)
2863
        );
2864
    }
2865
2866
    /**
2867
     * Test for the publishRoleDraft() method.
2868
     *
2869
     * @see \eZ\Publish\API\Repository\RoleService::publishRoleDraft()
2870
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRoleDraft
2871
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicyByRoleDraft
2872
     */
2873
    public function testPublishRoleDraftAddPolicies()
2874
    {
2875
        $repository = $this->getRepository();
2876
2877
        /* BEGIN: Use Case */
2878
        $roleService = $repository->getRoleService();
2879
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
2880
2881
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
2882
        // $roleCreate->mainLanguageCode = 'eng-US';
2883
2884
        $roleDraft = $roleService->createRole($roleCreate);
2885
2886
        $roleDraft = $roleService->addPolicyByRoleDraft(
2887
            $roleDraft,
2888
            $roleService->newPolicyCreateStruct('content', 'delete')
2889
        );
2890
        $roleDraft = $roleService->addPolicyByRoleDraft(
2891
            $roleDraft,
2892
            $roleService->newPolicyCreateStruct('content', 'create')
2893
        );
2894
2895
        $roleService->publishRoleDraft($roleDraft);
2896
        $role = $roleService->loadRoleByIdentifier($roleCreate->identifier);
2897
        /* END: Use Case */
2898
2899
        $actual = [];
2900
        foreach ($role->getPolicies() as $policy) {
2901
            $actual[] = [
2902
                'module' => $policy->module,
2903
                'function' => $policy->function,
2904
            ];
2905
        }
2906
        usort(
2907
            $actual,
2908
            function ($p1, $p2) {
2909
                return strcasecmp($p1['function'], $p2['function']);
2910
            }
2911
        );
2912
2913
        $this->assertEquals(
2914
            [
2915
                [
2916
                    'module' => 'content',
2917
                    'function' => 'create',
2918
                ],
2919
                [
2920
                    'module' => 'content',
2921
                    'function' => 'delete',
2922
                ],
2923
            ],
2924
            $actual
2925
        );
2926
    }
2927
2928
    /**
2929
     * Create a user group fixture in a variable named <b>$userGroup</b>,.
2930
     *
2931
     * @return \eZ\Publish\API\Repository\Values\User\UserGroup
2932
     */
2933
    private function createUserGroupVersion1()
2934
    {
2935
        $repository = $this->getRepository();
2936
2937
        $mainGroupId = $this->generateId('group', 4);
2938
        /* BEGIN: Inline */
2939
        // $mainGroupId is the ID of the main "Users" group
2940
2941
        $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...
2942
        $userService = $repository->getUserService();
2943
2944
        // Load main group
2945
        $parentUserGroup = $userService->loadUserGroup($mainGroupId);
2946
2947
        // Instantiate a new create struct
2948
        $userGroupCreate = $userService->newUserGroupCreateStruct('eng-US');
2949
        $userGroupCreate->setField('name', 'Example Group');
2950
2951
        // Create the new user group
2952
        $userGroup = $userService->createUserGroup(
2953
            $userGroupCreate,
2954
            $parentUserGroup
2955
        );
2956
        /* END: Inline */
2957
2958
        return $userGroup;
2959
    }
2960
}
2961