Completed
Push — assert-equals-canonicalize ( 968a1f...79e195 )
by
unknown
29:44 queued 09:39
created

testCreateRoleDraftWithAddPolicy()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 50

Duplication

Lines 3
Ratio 6 %

Importance

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

foreach ($a as $b) {
}

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


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

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

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

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

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

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

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

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

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

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

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

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

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

Loading history...
1027
            $role,
1028
            $roleService->newPolicyCreateStruct('content', 'create')
1029
        );
1030
        /* END: Use Case */
1031
1032
        $actual = [];
1033
        foreach ($role->getPolicies() as $policy) {
1034
            $actual[] = [
1035
                'module' => $policy->module,
1036
                'function' => $policy->function,
1037
            ];
1038
        }
1039
        usort(
1040
            $actual,
1041
            function ($p1, $p2) {
1042
                return strcasecmp($p1['function'], $p2['function']);
1043
            }
1044
        );
1045
1046
        $this->assertEquals(
1047
            [
1048
                [
1049
                    'module' => 'content',
1050
                    'function' => 'create',
1051
                ],
1052
                [
1053
                    'module' => 'content',
1054
                    'function' => 'delete',
1055
                ],
1056
            ],
1057
            $actual
1058
        );
1059
    }
1060
1061
    /**
1062
     * Test for the addPolicyByRoleDraft() method.
1063
     *
1064
     * @see \eZ\Publish\API\Repository\RoleService::addPolicyByRoleDraft()
1065
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRoleDraft
1066
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewPolicyCreateStruct
1067
     */
1068
    public function testAddPolicyByRoleDraft()
1069
    {
1070
        $repository = $this->getRepository();
1071
1072
        /* BEGIN: Use Case */
1073
        $roleService = $repository->getRoleService();
1074
1075
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
1076
1077
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1078
        // $roleCreate->mainLanguageCode = 'eng-US';
1079
1080
        $roleDraft = $roleService->createRole($roleCreate);
1081
1082
        $roleDraft = $roleService->addPolicyByRoleDraft(
1083
            $roleDraft,
1084
            $roleService->newPolicyCreateStruct('content', 'delete')
1085
        );
1086
        $roleDraft = $roleService->addPolicyByRoleDraft(
1087
            $roleDraft,
1088
            $roleService->newPolicyCreateStruct('content', 'create')
1089
        );
1090
        /* END: Use Case */
1091
1092
        $actual = [];
1093 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...
1094
            $actual[] = [
1095
                'module' => $policy->module,
1096
                'function' => $policy->function,
1097
            ];
1098
        }
1099
        usort(
1100
            $actual,
1101
            function ($p1, $p2) {
1102
                return strcasecmp($p1['function'], $p2['function']);
1103
            }
1104
        );
1105
1106
        $this->assertEquals(
1107
            [
1108
                [
1109
                    'module' => 'content',
1110
                    'function' => 'create',
1111
                ],
1112
                [
1113
                    'module' => 'content',
1114
                    'function' => 'delete',
1115
                ],
1116
            ],
1117
            $actual
1118
        );
1119
    }
1120
1121
    /**
1122
     * Test for the addPolicy() method.
1123
     *
1124
     * @return array [\eZ\Publish\API\Repository\Values\User\Role, \eZ\Publish\API\Repository\Values\User\Policy]
1125
     *
1126
     * @see \eZ\Publish\API\Repository\RoleService::addPolicy()
1127
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicy
1128
     */
1129
    public function testAddPolicyUpdatesRole()
1130
    {
1131
        $repository = $this->getRepository();
1132
1133
        /* BEGIN: Use Case */
1134
        $roleService = $repository->getRoleService();
1135
1136
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
1137
1138
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1139
        // $roleCreate->mainLanguageCode = 'eng-US';
1140
1141
        $roleDraft = $roleService->createRole($roleCreate);
1142
        $roleService->publishRoleDraft($roleDraft);
1143
        $role = $roleService->loadRole($roleDraft->id);
1144
1145
        $policyCreate = $roleService->newPolicyCreateStruct('content', 'create');
1146
        $role = $roleService->addPolicy($role, $policyCreate);
0 ignored issues
show
Deprecated Code introduced by
The method eZ\Publish\API\Repository\RoleService::addPolicy() has been deprecated with message: since 6.0, use {@see addPolicyByRoleDraft}

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

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

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

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

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

Loading history...
1279
        /* END: Use Case */
1280
    }
1281
1282
    /**
1283
     * Test for the addPolicyByRoleDraft() method.
1284
     *
1285
     * @see \eZ\Publish\API\Repository\RoleService::addPolicyByRoleDraft()
1286
     * @expectedException \eZ\Publish\API\Repository\Exceptions\LimitationValidationException
1287
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewPolicyCreateStruct
1288
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRoleDraft
1289
     */
1290 View Code Duplication
    public function testAddPolicyByRoleDraftThrowsLimitationValidationException()
1291
    {
1292
        $repository = $this->getRepository();
1293
1294
        /* BEGIN: Use Case */
1295
        $roleService = $repository->getRoleService();
1296
1297
        $roleCreate = $roleService->newRoleCreateStruct('Lumberjack');
1298
1299
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1300
        // $roleCreate->mainLanguageCode = 'eng-US';
1301
1302
        $roleDraft = $roleService->createRole($roleCreate);
1303
1304
        // Create new subtree limitation
1305
        $limitation = new SubtreeLimitation(
1306
            [
1307
                'limitationValues' => ['/mountain/forest/tree/42/'],
1308
            ]
1309
        );
1310
1311
        // Create policy create struct and add limitation to it
1312
        $policyCreateStruct = $roleService->newPolicyCreateStruct('content', 'remove');
1313
        $policyCreateStruct->addLimitation($limitation);
1314
1315
        // This call will fail with an LimitationValidationException, because subtree
1316
        // "/mountain/forest/tree/42/" does not exist
1317
        $roleService->addPolicyByRoleDraft($roleDraft, $policyCreateStruct);
1318
        /* END: Use Case */
1319
    }
1320
1321
    /**
1322
     * Test for the createRole() method.
1323
     *
1324
     * @see \eZ\Publish\API\Repository\RoleService::createRole()
1325
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicyUpdatesRole
1326
     */
1327
    public function testCreateRoleWithAddPolicy()
1328
    {
1329
        $repository = $this->getRepository();
1330
1331
        /* BEGIN: Use Case */
1332
        $roleService = $repository->getRoleService();
1333
1334
        // Instantiate a new create struct
1335
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
1336
1337
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1338
        // $roleCreate->mainLanguageCode = 'eng-US';
1339
1340
        // Add some role policies
1341
        $roleCreate->addPolicy(
1342
            $roleService->newPolicyCreateStruct(
1343
                'content',
1344
                'read'
1345
            )
1346
        );
1347
        $roleCreate->addPolicy(
1348
            $roleService->newPolicyCreateStruct(
1349
                'content',
1350
                'translate'
1351
            )
1352
        );
1353
1354
        // Create new role instance
1355
        $roleDraft = $roleService->createRole($roleCreate);
1356
        $roleService->publishRoleDraft($roleDraft);
1357
        $role = $roleService->loadRole($roleDraft->id);
1358
1359
        $policies = [];
1360 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...
1361
            $policies[] = ['module' => $policy->module, 'function' => $policy->function];
1362
        }
1363
        /* END: Use Case */
1364
        array_multisort($policies);
1365
1366
        $this->assertEquals(
1367
            [
1368
                [
1369
                    'module' => 'content',
1370
                    'function' => 'read',
1371
                ],
1372
                [
1373
                    'module' => 'content',
1374
                    'function' => 'translate',
1375
                ],
1376
            ],
1377
            $policies
1378
        );
1379
    }
1380
1381
    /**
1382
     * Test for the createRoleDraft() method.
1383
     *
1384
     * @see \eZ\Publish\API\Repository\RoleService::createRoleDraft()
1385
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicyByRoleDraftUpdatesRole
1386
     */
1387
    public function testCreateRoleDraftWithAddPolicy()
1388
    {
1389
        $repository = $this->getRepository();
1390
1391
        /* BEGIN: Use Case */
1392
        $roleService = $repository->getRoleService();
1393
1394
        // Instantiate a new create struct
1395
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
1396
1397
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1398
        // $roleCreate->mainLanguageCode = 'eng-US';
1399
1400
        // Add some role policies
1401
        $roleCreate->addPolicy(
1402
            $roleService->newPolicyCreateStruct(
1403
                'content',
1404
                'read'
1405
            )
1406
        );
1407
        $roleCreate->addPolicy(
1408
            $roleService->newPolicyCreateStruct(
1409
                'content',
1410
                'translate'
1411
            )
1412
        );
1413
1414
        // Create new role instance
1415
        $roleDraft = $roleService->createRole($roleCreate);
1416
1417
        $policies = [];
1418 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...
1419
            $policies[] = ['module' => $policy->module, 'function' => $policy->function];
1420
        }
1421
        /* END: Use Case */
1422
1423
        $this->assertEquals(
1424
            [
1425
                [
1426
                    'module' => 'content',
1427
                    'function' => 'read',
1428
                ],
1429
                [
1430
                    'module' => 'content',
1431
                    'function' => 'translate',
1432
                ],
1433
            ],
1434
            $policies
1435
        );
1436
    }
1437
1438
    /**
1439
     * Test for the newPolicyUpdateStruct() method.
1440
     *
1441
     * @see \eZ\Publish\API\Repository\RoleService::newPolicyUpdateStruct()
1442
     */
1443
    public function testNewPolicyUpdateStruct()
1444
    {
1445
        $repository = $this->getRepository();
1446
1447
        /* BEGIN: Use Case */
1448
        $roleService = $repository->getRoleService();
1449
        $policyUpdate = $roleService->newPolicyUpdateStruct();
1450
        /* END: Use Case */
1451
1452
        $this->assertInstanceOf(
1453
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\PolicyUpdateStruct',
1454
            $policyUpdate
1455
        );
1456
    }
1457
1458
    public function testUpdatePolicyNoLimitation()
1459
    {
1460
        $repository = $this->getRepository();
1461
1462
        /* BEGIN: Use Case */
1463
        $roleService = $repository->getRoleService();
1464
1465
        // Instantiate new policy create
1466
        $policyCreate = $roleService->newPolicyCreateStruct('foo', 'bar');
1467
1468
        // Instantiate a role create and add the policy create
1469
        $roleCreate = $roleService->newRoleCreateStruct('myRole');
1470
1471
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1472
        // $roleCreate->mainLanguageCode = 'eng-US';
1473
1474
        $roleCreate->addPolicy($policyCreate);
1475
1476
        // Create a new role instance.
1477
        $roleDraft = $roleService->createRole($roleCreate);
1478
        $roleService->publishRoleDraft($roleDraft);
1479
        $role = $roleService->loadRole($roleDraft->id);
1480
1481
        // Search for the new policy instance
1482
        $policy = null;
1483
        foreach ($role->getPolicies() as $policy) {
1484
            if ($policy->module === 'foo' && $policy->function === 'bar') {
1485
                break;
1486
            }
1487
        }
1488
1489
        // Create an update struct
1490
        $policyUpdate = $roleService->newPolicyUpdateStruct();
1491
1492
        // Update the the policy
1493
        $policy = $roleService->updatePolicy($policy, $policyUpdate);
0 ignored issues
show
Bug introduced by
It seems like $policy can be null; however, updatePolicy() does not accept null, maybe add an additional type check?

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

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

function doesNotAcceptNull(stdClass $x) { }

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

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

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

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

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

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

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

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

function doesNotAcceptNull(stdClass $x) { }

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

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

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

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

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

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

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

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

function doesNotAcceptNull(stdClass $x) { }

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

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

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
Unused Code introduced by
$policy is not used, you could remove the assignment.

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

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

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

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

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

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

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

Loading history...
1697
        /* END: Use Case */
1698
    }
1699
1700
    /**
1701
     * Test for the removePolicyByRoleDraft() method.
1702
     *
1703
     * @see \eZ\Publish\API\Repository\RoleService::removePolicyByRoleDraft()
1704
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicyByRoleDraft
1705
     */
1706 View Code Duplication
    public function testRemovePolicyByRoleDraft()
1707
    {
1708
        $repository = $this->getRepository();
1709
1710
        /* BEGIN: Use Case */
1711
        $roleService = $repository->getRoleService();
1712
1713
        // Instantiate a new role create
1714
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
1715
1716
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1717
        // $roleCreate->mainLanguageCode = 'eng-US';
1718
1719
        // Create a new role with two policies
1720
        $roleDraft = $roleService->createRole($roleCreate);
1721
        $roleService->addPolicyByRoleDraft(
1722
            $roleDraft,
1723
            $roleService->newPolicyCreateStruct('content', 'create')
1724
        );
1725
        $roleService->addPolicyByRoleDraft(
1726
            $roleDraft,
1727
            $roleService->newPolicyCreateStruct('content', 'delete')
1728
        );
1729
1730
        // Delete all policies from the new role
1731
        foreach ($roleDraft->getPolicies() as $policy) {
1732
            $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...
1733
        }
1734
        /* END: Use Case */
1735
1736
        $this->assertSame([], $roleDraft->getPolicies());
1737
    }
1738
1739
    /**
1740
     * Test for the deletePolicy() method.
1741
     *
1742
     * @see \eZ\Publish\API\Repository\RoleService::deletePolicy()
1743
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRole
1744
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicy
1745
     */
1746
    public function testDeletePolicy()
1747
    {
1748
        $repository = $this->getRepository();
1749
1750
        /* BEGIN: Use Case */
1751
        $roleService = $repository->getRoleService();
1752
1753
        // Instantiate a new role create
1754
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
1755
1756
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1757
        // $roleCreate->mainLanguageCode = 'eng-US';
1758
1759
        // Create a new role with two policies
1760
        $roleDraft = $roleService->createRole($roleCreate);
1761
        $roleService->addPolicyByRoleDraft(
1762
            $roleDraft,
1763
            $roleService->newPolicyCreateStruct('content', 'create')
1764
        );
1765
        $roleService->addPolicyByRoleDraft(
1766
            $roleDraft,
1767
            $roleService->newPolicyCreateStruct('content', 'delete')
1768
        );
1769
        $roleService->publishRoleDraft($roleDraft);
1770
        $role = $roleService->loadRole($roleDraft->id);
1771
1772
        // Delete all policies from the new role
1773
        foreach ($role->getPolicies() as $policy) {
1774
            $roleService->deletePolicy($policy);
0 ignored issues
show
Deprecated Code introduced by
The method eZ\Publish\API\Repositor...Service::deletePolicy() has been deprecated with message: since 6.0, use {@link removePolicyByRoleDraft()} instead.

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

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

Loading history...
1775
        }
1776
        /* END: Use Case */
1777
1778
        $role = $roleService->loadRole($role->id);
1779
        $this->assertSame([], $role->getPolicies());
1780
    }
1781
1782
    /**
1783
     * Test for the addPolicyByRoleDraft() method.
1784
     *
1785
     * @see \eZ\Publish\API\Repository\RoleService::addPolicyByRoleDraft()
1786
     */
1787
    public function testAddPolicyWithRoleAssignment()
1788
    {
1789
        $repository = $this->getRepository();
1790
1791
        /* BEGIN: Use Case */
1792
        $roleService = $repository->getRoleService();
1793
        $userService = $repository->getUserService();
1794
1795
        /* Create new user group */
1796
        $mainGroupId = $this->generateId('group', 4);
1797
        $parentUserGroup = $userService->loadUserGroup($mainGroupId);
1798
        $userGroupCreate = $userService->newUserGroupCreateStruct('eng-US');
1799
        $userGroupCreate->setField('name', 'newUserGroup');
1800
        $userGroup = $userService->createUserGroup($userGroupCreate, $parentUserGroup);
1801
1802
        /* Create Role */
1803
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
1804
        $roleDraft = $roleService->createRole($roleCreate);
1805
        $roleService->publishRoleDraft($roleDraft);
1806
1807
        $role = $roleService->loadRole($roleDraft->id);
1808
        $roleService->assignRoleToUserGroup($role, $userGroup);
1809
1810
        $roleAssignmentsBeforeNewPolicy = $roleService->getRoleAssignments($role)[0];
1811
1812
        /* Add new policy to existing role */
1813
        $roleUpdateDraft = $roleService->createRoleDraft($role);
1814
        $roleUpdateDraft = $roleService->addPolicyByRoleDraft(
1815
            $roleUpdateDraft,
1816
            $roleService->newPolicyCreateStruct('content', 'create')
1817
        );
1818
        $roleService->publishRoleDraft($roleUpdateDraft);
1819
1820
        $roleAfterUpdate = $roleService->loadRole($role->id);
1821
        $roleAssignmentsAfterNewPolicy = $roleService->getRoleAssignments($roleAfterUpdate)[0];
1822
        /* END: Use Case */
1823
1824
        $this->assertNotEquals($roleAssignmentsBeforeNewPolicy->id, $roleAssignmentsAfterNewPolicy->id);
1825
    }
1826
1827
    /**
1828
     * Test loading user/group role assignments.
1829
     *
1830
     * @return \eZ\Publish\API\Repository\Values\User\UserGroupRoleAssignment
1831
     *
1832
     * @covers \eZ\Publish\API\Repository\RoleService::loadRoleAssignment
1833
     */
1834
    public function testLoadRoleAssignment()
1835
    {
1836
        $repository = $this->getRepository();
1837
1838
        /* BEGIN: Use Case */
1839
        $roleService = $repository->getRoleService();
1840
        $user = $repository->getUserService()->loadUser(14);
1841
1842
        // Check inital empty assigments (also warms up potential cache to validate it is correct below)
1843
        $this->assertCount(0, $roleService->getRoleAssignmentsForUser($user));
1844
1845
        // Assignment to user group
1846
        $groupRoleAssignment = $roleService->loadRoleAssignment(25);
1847
1848
        // Assignment to user
1849
        $role = $roleService->loadRole(2);
1850
        $roleService->assignRoleToUser($role, $user);
1851
        $userRoleAssignments = $roleService->getRoleAssignmentsForUser($user);
1852
1853
        $userRoleAssignment = $roleService->loadRoleAssignment($userRoleAssignments[0]->id);
1854
        /* END: Use Case */
1855
1856
        $this->assertInstanceOf(
1857
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\UserGroupRoleAssignment',
1858
            $groupRoleAssignment
1859
        );
1860
1861
        $this->assertEquals(
1862
            [
1863
                12,
1864
                2,
1865
                25,
1866
            ],
1867
            [
1868
                $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...
1869
                $groupRoleAssignment->role->id,
1870
                $groupRoleAssignment->id,
1871
            ]
1872
        );
1873
1874
        self::assertInstanceOf('\\eZ\\Publish\\API\\Repository\\Values\\User\\UserRoleAssignment', $userRoleAssignment);
1875
        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...
1876
1877
        return $groupRoleAssignment;
1878
    }
1879
1880
    /**
1881
     * Test for the getRoleAssignments() method.
1882
     *
1883
     * @return \eZ\Publish\API\Repository\Values\User\RoleAssignment[]
1884
     *
1885
     * @see \eZ\Publish\API\Repository\RoleService::getRoleAssignments()
1886
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleByIdentifier
1887
     */
1888
    public function testGetRoleAssignments()
1889
    {
1890
        $repository = $this->getRepository();
1891
1892
        /* BEGIN: Use Case */
1893
        $roleService = $repository->getRoleService();
1894
1895
        // Load the editor role
1896
        $role = $roleService->loadRoleByIdentifier('Editor');
1897
1898
        // Load all assigned users and user groups
1899
        $roleAssignments = $roleService->getRoleAssignments($role);
1900
1901
        /* END: Use Case */
1902
1903
        $this->assertEquals(2, count($roleAssignments));
1904
        $this->assertInstanceOf(
1905
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\UserGroupRoleAssignment',
1906
            $roleAssignments[0]
1907
        );
1908
        $this->assertInstanceOf(
1909
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\UserGroupRoleAssignment',
1910
            $roleAssignments[1]
1911
        );
1912
1913
        return $roleAssignments;
1914
    }
1915
1916
    /**
1917
     * Test for the getRoleAssignments() method.
1918
     *
1919
     * @param \eZ\Publish\API\Repository\Values\User\RoleAssignment[] $roleAssignments
1920
     *
1921
     * @see \eZ\Publish\API\Repository\RoleService::getRoleAssignments()
1922
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testGetRoleAssignments
1923
     */
1924
    public function testGetRoleAssignmentsContainExpectedLimitation(array $roleAssignments)
1925
    {
1926
        $this->assertEquals(
1927
            'Subtree',
1928
            reset($roleAssignments)->limitation->getIdentifier()
1929
        );
1930
    }
1931
1932
    /**
1933
     * Test for the assignRoleToUser() method.
1934
     *
1935
     * @see \eZ\Publish\API\Repository\RoleService::assignRoleToUser()
1936
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testGetRoleAssignments
1937
     */
1938
    public function testAssignRoleToUser()
1939
    {
1940
        $repository = $this->getRepository();
1941
        $roleService = $repository->getRoleService();
1942
1943
        /* BEGIN: Use Case */
1944
        $user = $this->createUserVersion1();
1945
1946
        // Load the existing "Administrator" role
1947
        $role = $roleService->loadRoleByIdentifier('Administrator');
1948
1949
        // Assign the "Administrator" role to the newly created user
1950
        $roleService->assignRoleToUser($role, $user);
1951
1952
        // The assignments array will contain the new role<->user assignment
1953
        $roleAssignments = $roleService->getRoleAssignments($role);
1954
        /* END: Use Case */
1955
1956
        // Administrator + Example User
1957
        $this->assertCount(2, $roleAssignments);
1958
    }
1959
1960
    /**
1961
     * Test for the assignRoleToUser() method.
1962
     *
1963
     * @see \eZ\Publish\API\Repository\RoleService::assignRoleToUser($role, $user, $roleLimitation)
1964
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUser
1965
     */
1966 View Code Duplication
    public function testAssignRoleToUserWithRoleLimitation()
1967
    {
1968
        $repository = $this->getRepository();
1969
        $roleService = $repository->getRoleService();
1970
1971
        /* BEGIN: Use Case */
1972
        $user = $this->createUserVersion1();
1973
1974
        // Load the existing "Anonymous" role
1975
        $role = $roleService->loadRoleByIdentifier('Anonymous');
1976
1977
        // Assign the "Anonymous" role to the newly created user
1978
        $roleService->assignRoleToUser(
1979
            $role,
1980
            $user,
1981
            new SubtreeLimitation(
1982
                [
1983
                    'limitationValues' => ['/1/43/'],
1984
                ]
1985
            )
1986
        );
1987
1988
        // The assignments array will contain the new role<->user assignment
1989
        $roleAssignments = $roleService->getRoleAssignments($role);
1990
        /* END: Use Case */
1991
1992
        // Members + Partners + Anonymous + Example User
1993
        $this->assertEquals(4, count($roleAssignments));
1994
1995
        // Get the role limitation
1996
        $roleLimitation = null;
1997
        foreach ($roleAssignments as $roleAssignment) {
1998
            $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...
1999
            if ($roleLimitation) {
2000
                $this->assertInstanceOf(
2001
                    '\\eZ\\Publish\\API\\Repository\\Values\\User\\UserRoleAssignment',
2002
                    $roleAssignment
2003
                );
2004
                break;
2005
            }
2006
        }
2007
2008
        $this->assertEquals(
2009
            new SubtreeLimitation(
2010
                [
2011
                    'limitationValues' => ['/1/43/'],
2012
                ]
2013
            ),
2014
            $roleLimitation
2015
        );
2016
2017
        // Test again to see values being merged
2018
        $roleService->assignRoleToUser(
2019
            $role,
2020
            $user,
2021
            new SubtreeLimitation(
2022
                [
2023
                    'limitationValues' => ['/1/43/', '/1/2/'],
2024
                ]
2025
            )
2026
        );
2027
2028
        // The assignments array will contain the new role<->user assignment
2029
        $roleAssignments = $roleService->getRoleAssignments($role);
2030
2031
        // Members + Partners + Anonymous + Example User
2032
        $this->assertEquals(5, count($roleAssignments));
2033
2034
        // Get the role limitation
2035
        $roleLimitations = [];
2036
        foreach ($roleAssignments as $roleAssignment) {
2037
            $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...
2038
            if ($roleLimitation) {
2039
                $this->assertInstanceOf(
2040
                    '\\eZ\\Publish\\API\\Repository\\Values\\User\\UserRoleAssignment',
2041
                    $roleAssignment
2042
                );
2043
                $roleLimitations[] = $roleLimitation;
2044
            }
2045
        }
2046
        array_multisort($roleLimitations);
2047
2048
        $this->assertEquals(
2049
            [
2050
                new SubtreeLimitation(
2051
                    [
2052
                        'limitationValues' => ['/1/2/'],
2053
                    ]
2054
                ),
2055
                new SubtreeLimitation(
2056
                    [
2057
                        'limitationValues' => ['/1/43/'],
2058
                    ]
2059
                ),
2060
            ],
2061
            $roleLimitations
2062
        );
2063
    }
2064
2065
    /**
2066
     * Test for the assignRoleToUser() method.
2067
     *
2068
     * @see \eZ\Publish\API\Repository\RoleService::assignRoleToUser($role, $user, $roleLimitation)
2069
     * @expectedException \eZ\Publish\API\Repository\Exceptions\LimitationValidationException
2070
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUser
2071
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleByIdentifier
2072
     */
2073
    public function testAssignRoleToUserWithRoleLimitationThrowsLimitationValidationException()
2074
    {
2075
        $repository = $this->getRepository();
2076
2077
        /* BEGIN: Use Case */
2078
        $roleService = $repository->getRoleService();
2079
2080
        // Load the existing "Anonymous" role
2081
        $role = $roleService->loadRoleByIdentifier('Anonymous');
2082
2083
        // Get current user
2084
        $currentUser = $repository->getCurrentUser();
0 ignored issues
show
Deprecated Code introduced by
The method eZ\Publish\API\Repositor...itory::getCurrentUser() has been deprecated with message: since 6.6, to be removed. Use PermissionResolver::getCurrentUserReference() instead. Get current user. Loads the full user object if not already loaded, if you only need to know user id use {@see getCurrentUserReference()}

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

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

Loading history...
2085
2086
        // Assign the "Anonymous" role to the current user
2087
        // This call will fail with an LimitationValidationException, because subtree "/lorem/ipsum/42/"
2088
        // does not exists
2089
        $roleService->assignRoleToUser(
2090
            $role,
2091
            $currentUser,
2092
            new SubtreeLimitation(
2093
                [
2094
                    'limitationValues' => ['/lorem/ipsum/42/'],
2095
                ]
2096
            )
2097
        );
2098
        /* END: Use Case */
2099
    }
2100
2101
    /**
2102
     * Test for the assignRoleToUser() method.
2103
     *
2104
     * Makes sure assigning role several times throws.
2105
     *
2106
     * @see \eZ\Publish\API\Repository\RoleService::assignRoleToUser($role, $user, $roleLimitation)
2107
     * @expectedException \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException
2108
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUser
2109
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleByIdentifier
2110
     */
2111
    public function testAssignRoleToUserThrowsInvalidArgumentException()
2112
    {
2113
        $repository = $this->getRepository();
2114
2115
        /* BEGIN: Use Case */
2116
        $roleService = $repository->getRoleService();
2117
2118
        // Load the existing "Anonymous" role
2119
        $role = $roleService->loadRoleByIdentifier('Anonymous');
2120
2121
        // Get current user
2122
        $currentUser = $repository->getCurrentUser();
0 ignored issues
show
Deprecated Code introduced by
The method eZ\Publish\API\Repositor...itory::getCurrentUser() has been deprecated with message: since 6.6, to be removed. Use PermissionResolver::getCurrentUserReference() instead. Get current user. Loads the full user object if not already loaded, if you only need to know user id use {@see getCurrentUserReference()}

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

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

Loading history...
2123
2124
        // Assign the "Anonymous" role to the current user
2125
        try {
2126
            $roleService->assignRoleToUser(
2127
                $role,
2128
                $currentUser
2129
            );
2130
        } catch (Exception $e) {
2131
            $this->fail('Got exception at first valid attempt to assign role');
2132
        }
2133
2134
        // Re-Assign the "Anonymous" role to the current user
2135
        // This call will fail with an InvalidArgumentException, because limitation is already assigned
2136
        $roleService->assignRoleToUser(
2137
            $role,
2138
            $currentUser
2139
        );
2140
        /* END: Use Case */
2141
    }
2142
2143
    /**
2144
     * Test for the assignRoleToUser() method.
2145
     *
2146
     * Makes sure assigning role several times with same limitations throws.
2147
     *
2148
     * @see \eZ\Publish\API\Repository\RoleService::assignRoleToUser($role, $user, $roleLimitation)
2149
     * @expectedException \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException
2150
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUser
2151
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleByIdentifier
2152
     */
2153
    public function testAssignRoleToUserWithRoleLimitationThrowsInvalidArgumentException()
2154
    {
2155
        $repository = $this->getRepository();
2156
2157
        /* BEGIN: Use Case */
2158
        $roleService = $repository->getRoleService();
2159
2160
        // Load the existing "Anonymous" role
2161
        $role = $roleService->loadRoleByIdentifier('Anonymous');
2162
2163
        // Get current user
2164
        $currentUser = $repository->getCurrentUser();
0 ignored issues
show
Deprecated Code introduced by
The method eZ\Publish\API\Repositor...itory::getCurrentUser() has been deprecated with message: since 6.6, to be removed. Use PermissionResolver::getCurrentUserReference() instead. Get current user. Loads the full user object if not already loaded, if you only need to know user id use {@see getCurrentUserReference()}

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

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

Loading history...
2165
2166
        // Assign the "Anonymous" role to the current user
2167
        try {
2168
            $roleService->assignRoleToUser(
2169
                $role,
2170
                $currentUser,
2171
                new SubtreeLimitation(
2172
                    [
2173
                        'limitationValues' => ['/1/43/', '/1/2/'],
2174
                    ]
2175
                )
2176
            );
2177
        } catch (Exception $e) {
2178
            $this->fail('Got exception at first valid attempt to assign role');
2179
        }
2180
2181
        // Re-Assign the "Anonymous" role to the current user
2182
        // This call will fail with an InvalidArgumentException, because limitation is already assigned
2183
        $roleService->assignRoleToUser(
2184
            $role,
2185
            $currentUser,
2186
            new SubtreeLimitation(
2187
                [
2188
                    'limitationValues' => ['/1/43/'],
2189
                ]
2190
            )
2191
        );
2192
        /* END: Use Case */
2193
    }
2194
2195
    /**
2196
     * Test for the unassignRoleFromUser() method.
2197
     *
2198
     * @see \eZ\Publish\API\Repository\RoleService::unassignRoleFromUser()
2199
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUser
2200
     */
2201 View Code Duplication
    public function testUnassignRoleFromUser()
2202
    {
2203
        $repository = $this->getRepository();
2204
        $roleService = $repository->getRoleService();
2205
2206
        /* BEGIN: Use Case */
2207
        $user = $this->createUserVersion1();
2208
2209
        // Load the existing "Member" role
2210
        $role = $roleService->loadRoleByIdentifier('Member');
2211
2212
        // Assign the "Member" role to the newly created user
2213
        $roleService->assignRoleToUser($role, $user);
2214
2215
        // Unassign user from role
2216
        $roleService->unassignRoleFromUser($role, $user);
0 ignored issues
show
Deprecated Code introduced by
The method eZ\Publish\API\Repositor...:unassignRoleFromUser() has been deprecated with message: since 6.0, use {@see removeRoleAssignment} instead.

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

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

Loading history...
2217
2218
        // The assignments array will not contain the new role<->user assignment
2219
        $roleAssignments = $roleService->getRoleAssignments($role);
2220
        /* END: Use Case */
2221
2222
        // Members + Editors + Partners
2223
        $this->assertEquals(3, count($roleAssignments));
2224
    }
2225
2226
    /**
2227
     * Test for the unassignRoleFromUser() method.
2228
     *
2229
     * @see \eZ\Publish\API\Repository\RoleService::unassignRoleFromUser()
2230
     * @expectedException \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException
2231
     */
2232 View Code Duplication
    public function testUnassignRoleFromUserThrowsInvalidArgumentException()
2233
    {
2234
        $repository = $this->getRepository();
2235
        $roleService = $repository->getRoleService();
2236
2237
        /* BEGIN: Use Case */
2238
        $user = $this->createUserVersion1();
2239
2240
        // Load the existing "Member" role
2241
        $role = $roleService->loadRoleByIdentifier('Member');
2242
2243
        // This call will fail with a "InvalidArgumentException", because the
2244
        // user does not have the "Member" role.
2245
        $roleService->unassignRoleFromUser($role, $user);
0 ignored issues
show
Deprecated Code introduced by
The method eZ\Publish\API\Repositor...:unassignRoleFromUser() has been deprecated with message: since 6.0, use {@see removeRoleAssignment} instead.

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

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

Loading history...
2246
        /* END: Use Case */
2247
    }
2248
2249
    /**
2250
     * Test for the getRoleAssignmentsForUser() method.
2251
     *
2252
     * @see \eZ\Publish\API\Repository\RoleService::getRoleAssignmentsForUser()
2253
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUser
2254
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRoleWithAddPolicy
2255
     */
2256
    public function testGetRoleAssignmentsForUserDirect()
2257
    {
2258
        $repository = $this->getRepository();
2259
        $roleService = $repository->getRoleService();
2260
2261
        /* BEGIN: Use Case */
2262
        $user = $this->createUserVersion1();
2263
2264
        // Instantiate a role create and add some policies
2265
        $roleCreate = $roleService->newRoleCreateStruct('Example Role');
2266
2267
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
2268
        // $roleCreate->mainLanguageCode = 'eng-US';
2269
2270
        $roleCreate->addPolicy(
2271
            $roleService->newPolicyCreateStruct('user', 'login')
2272
        );
2273
        $roleCreate->addPolicy(
2274
            $roleService->newPolicyCreateStruct('content', 'read')
2275
        );
2276
        $roleCreate->addPolicy(
2277
            $roleService->newPolicyCreateStruct('content', 'edit')
2278
        );
2279
2280
        // Create the new role instance
2281
        $roleDraft = $roleService->createRole($roleCreate);
2282
        $roleService->publishRoleDraft($roleDraft);
2283
        $role = $roleService->loadRole($roleDraft->id);
2284
2285
        // Check inital empty assigments (also warms up potential cache to validate it is correct below)
2286
        $this->assertCount(0, $roleService->getRoleAssignmentsForUser($user));
2287
        $this->assertCount(0, $roleService->getRoleAssignments($role));
2288
2289
        // Assign role to new user
2290
        $roleService->assignRoleToUser($role, $user);
2291
2292
        // Load the currently assigned role
2293
        $roleAssignments = $roleService->getRoleAssignmentsForUser($user);
2294
        /* END: Use Case */
2295
2296
        $this->assertCount(1, $roleAssignments);
2297
        $this->assertInstanceOf(
2298
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\UserRoleAssignment',
2299
            reset($roleAssignments)
2300
        );
2301
        $this->assertCount(1, $roleService->getRoleAssignments($role));
2302
    }
2303
2304
    /**
2305
     * Test for the getRoleAssignmentsForUser() method.
2306
     *
2307
     * @see \eZ\Publish\API\Repository\RoleService::getRoleAssignmentsForUser()
2308
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUser
2309
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRoleWithAddPolicy
2310
     */
2311
    public function testGetRoleAssignmentsForUserEmpty()
2312
    {
2313
        $repository = $this->getRepository();
2314
        $roleService = $repository->getRoleService();
2315
2316
        /* BEGIN: Use Case */
2317
        $adminUser = $repository->getCurrentUser();
0 ignored issues
show
Deprecated Code introduced by
The method eZ\Publish\API\Repositor...itory::getCurrentUser() has been deprecated with message: since 6.6, to be removed. Use PermissionResolver::getCurrentUserReference() instead. Get current user. Loads the full user object if not already loaded, if you only need to know user id use {@see getCurrentUserReference()}

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

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

Loading history...
2318
2319
        // Load the currently assigned role
2320
        $roleAssignments = $roleService->getRoleAssignmentsForUser($adminUser);
2321
        /* END: Use Case */
2322
2323
        $this->assertEquals(0, count($roleAssignments));
2324
    }
2325
2326
    /**
2327
     * Test for the getRoleAssignmentsForUser() method.
2328
     *
2329
     * @see \eZ\Publish\API\Repository\RoleService::getRoleAssignmentsForUser()
2330
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUser
2331
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRoleWithAddPolicy
2332
     */
2333
    public function testGetRoleAssignmentsForUserInherited()
2334
    {
2335
        $repository = $this->getRepository();
2336
        $roleService = $repository->getRoleService();
2337
2338
        /* BEGIN: Use Case */
2339
        $adminUser = $repository->getCurrentUser();
0 ignored issues
show
Deprecated Code introduced by
The method eZ\Publish\API\Repositor...itory::getCurrentUser() has been deprecated with message: since 6.6, to be removed. Use PermissionResolver::getCurrentUserReference() instead. Get current user. Loads the full user object if not already loaded, if you only need to know user id use {@see getCurrentUserReference()}

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

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

Loading history...
2340
2341
        // Load the currently assigned role + inherited role assignments
2342
        $roleAssignments = $roleService->getRoleAssignmentsForUser($adminUser, true);
2343
        /* END: Use Case */
2344
2345
        $this->assertEquals(1, count($roleAssignments));
2346
        $this->assertInstanceOf(
2347
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\UserGroupRoleAssignment',
2348
            reset($roleAssignments)
2349
        );
2350
    }
2351
2352
    /**
2353
     * Test for the assignRoleToUserGroup() method.
2354
     *
2355
     * @see \eZ\Publish\API\Repository\RoleService::assignRoleToUserGroup()
2356
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testGetRoleAssignments
2357
     */
2358 View Code Duplication
    public function testAssignRoleToUserGroup()
2359
    {
2360
        $repository = $this->getRepository();
2361
        $roleService = $repository->getRoleService();
2362
2363
        /* BEGIN: Use Case */
2364
        $userGroup = $this->createUserGroupVersion1();
2365
2366
        // Load the existing "Administrator" role
2367
        $role = $roleService->loadRoleByIdentifier('Administrator');
2368
2369
        // Assign the "Administrator" role to the newly created user group
2370
        $roleService->assignRoleToUserGroup($role, $userGroup);
2371
2372
        // The assignments array will contain the new role<->group assignment
2373
        $roleAssignments = $roleService->getRoleAssignments($role);
2374
        /* END: Use Case */
2375
2376
        // Administrator + Example Group
2377
        $this->assertEquals(2, count($roleAssignments));
2378
    }
2379
2380
    /**
2381
     * Test for the assignRoleToUserGroup() method.
2382
     *
2383
     * Related issue: EZP-29113
2384
     *
2385
     * @covers \eZ\Publish\API\Repository\RoleService::assignRoleToUserGroup()
2386
     */
2387
    public function testAssignRoleToUserGroupAffectsRoleAssignmentsForUser()
2388
    {
2389
        $roleService = $this->getRepository()->getRoleService();
2390
2391
        /* BEGIN: Use Case */
2392
        $userGroup = $this->createUserGroupVersion1();
2393
        $user = $this->createUser('user', 'John', 'Doe', $userGroup);
2394
2395
        $initRoleAssignments = $roleService->getRoleAssignmentsForUser($user, true);
2396
2397
        // Load the existing "Administrator" role
2398
        $role = $roleService->loadRoleByIdentifier('Administrator');
2399
2400
        // Assign the "Administrator" role to the newly created user group
2401
        $roleService->assignRoleToUserGroup($role, $userGroup);
2402
2403
        $updatedRoleAssignments = $roleService->getRoleAssignmentsForUser($user, true);
2404
        /* END: Use Case */
2405
2406
        $this->assertEmpty($initRoleAssignments);
2407
        $this->assertEquals(1, count($updatedRoleAssignments));
2408
    }
2409
2410
    /**
2411
     * Test for the assignRoleToUserGroup() method.
2412
     *
2413
     * @see \eZ\Publish\API\Repository\RoleService::assignRoleToUserGroup($role, $userGroup, $roleLimitation)
2414
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUserGroup
2415
     */
2416 View Code Duplication
    public function testAssignRoleToUserGroupWithRoleLimitation()
2417
    {
2418
        $repository = $this->getRepository();
2419
        $roleService = $repository->getRoleService();
2420
2421
        /* BEGIN: Use Case */
2422
        $userGroup = $this->createUserGroupVersion1();
2423
2424
        // Load the existing "Anonymous" role
2425
        $role = $roleService->loadRoleByIdentifier('Anonymous');
2426
2427
        // Assign the "Anonymous" role to the newly created user group
2428
        $roleService->assignRoleToUserGroup(
2429
            $role,
2430
            $userGroup,
2431
            new SubtreeLimitation(
2432
                [
2433
                    'limitationValues' => ['/1/43/'],
2434
                ]
2435
            )
2436
        );
2437
2438
        // The assignments array will contain the new role<->group assignment
2439
        $roleAssignments = $roleService->getRoleAssignments($role);
2440
        /* END: Use Case */
2441
2442
        // Members + Partners + Anonymous + Example Group
2443
        $this->assertEquals(4, count($roleAssignments));
2444
2445
        // Get the role limitation
2446
        $roleLimitation = null;
2447
        foreach ($roleAssignments as $roleAssignment) {
2448
            $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...
2449
            if ($roleLimitation) {
2450
                break;
2451
            }
2452
        }
2453
2454
        $this->assertEquals(
2455
            new SubtreeLimitation(
2456
                [
2457
                    'limitationValues' => ['/1/43/'],
2458
                ]
2459
            ),
2460
            $roleLimitation
2461
        );
2462
2463
        // Test again to see values being merged
2464
        $roleService->assignRoleToUserGroup(
2465
            $role,
2466
            $userGroup,
2467
            new SubtreeLimitation(
2468
                [
2469
                    'limitationValues' => ['/1/43/', '/1/2/'],
2470
                ]
2471
            )
2472
        );
2473
2474
        // The assignments array will contain the new role<->user assignment
2475
        $roleAssignments = $roleService->getRoleAssignments($role);
2476
2477
        // Members + Partners + Anonymous + Example User
2478
        $this->assertEquals(5, count($roleAssignments));
2479
2480
        // Get the role limitation
2481
        $roleLimitations = [];
2482
        foreach ($roleAssignments as $roleAssignment) {
2483
            $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...
2484
            if ($roleLimitation) {
2485
                $this->assertInstanceOf(
2486
                    '\\eZ\\Publish\\API\\Repository\\Values\\User\\UserGroupRoleAssignment',
2487
                    $roleAssignment
2488
                );
2489
                $roleLimitations[] = $roleLimitation;
2490
            }
2491
        }
2492
        array_multisort($roleLimitations);
2493
2494
        $this->assertEquals(
2495
            [
2496
                new SubtreeLimitation(
2497
                    [
2498
                        'limitationValues' => ['/1/2/'],
2499
                    ]
2500
                ),
2501
                new SubtreeLimitation(
2502
                    [
2503
                        'limitationValues' => ['/1/43/'],
2504
                    ]
2505
                ),
2506
            ],
2507
            $roleLimitations
2508
        );
2509
    }
2510
2511
    /**
2512
     * Test for the assignRoleToUserGroup() method.
2513
     *
2514
     * @see \eZ\Publish\API\Repository\RoleService::assignRoleToUserGroup($role, $userGroup, $roleLimitation)
2515
     * @expectedException \eZ\Publish\API\Repository\Exceptions\LimitationValidationException
2516
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleByIdentifier
2517
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUserGroup
2518
     */
2519
    public function testAssignRoleToUserGroupWithRoleLimitationThrowsLimitationValidationException()
2520
    {
2521
        $repository = $this->getRepository();
2522
2523
        $mainGroupId = $this->generateId('group', 4);
2524
        /* BEGIN: Use Case */
2525
        // $mainGroupId is the ID of the main "Users" group
2526
2527
        $userService = $repository->getUserService();
2528
        $roleService = $repository->getRoleService();
2529
2530
        $userGroup = $userService->loadUserGroup($mainGroupId);
2531
2532
        // Load the existing "Anonymous" role
2533
        $role = $roleService->loadRoleByIdentifier('Anonymous');
2534
2535
        // Assign the "Anonymous" role to the newly created user group
2536
        // This call will fail with an LimitationValidationException, because subtree "/lorem/ipsum/42/"
2537
        // does not exists
2538
        $roleService->assignRoleToUserGroup(
2539
            $role,
2540
            $userGroup,
2541
            new SubtreeLimitation(
2542
                [
2543
                    'limitationValues' => ['/lorem/ipsum/42/'],
2544
                ]
2545
            )
2546
        );
2547
        /* END: Use Case */
2548
    }
2549
2550
    /**
2551
     * Test for the assignRoleToUserGroup() method.
2552
     *
2553
     * Makes sure assigning role several times throws.
2554
     *
2555
     * @see \eZ\Publish\API\Repository\RoleService::assignRoleToUserGroup($role, $userGroup, $roleLimitation)
2556
     * @expectedException \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException
2557
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleByIdentifier
2558
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUserGroup
2559
     */
2560
    public function testAssignRoleToUserGroupThrowsInvalidArgumentException()
2561
    {
2562
        $repository = $this->getRepository();
2563
2564
        $mainGroupId = $this->generateId('group', 4);
2565
        /* BEGIN: Use Case */
2566
        // $mainGroupId is the ID of the main "Users" group
2567
2568
        $userService = $repository->getUserService();
2569
        $roleService = $repository->getRoleService();
2570
2571
        $userGroup = $userService->loadUserGroup($mainGroupId);
2572
2573
        // Load the existing "Anonymous" role
2574
        $role = $roleService->loadRoleByIdentifier('Anonymous');
2575
2576
        // Assign the "Anonymous" role to the newly created user group
2577
        try {
2578
            $roleService->assignRoleToUserGroup(
2579
                $role,
2580
                $userGroup
2581
            );
2582
        } catch (Exception $e) {
2583
            $this->fail('Got exception at first valid attempt to assign role');
2584
        }
2585
2586
        // Re-Assign the "Anonymous" role to the newly created user group
2587
        // This call will fail with an InvalidArgumentException, because role is already assigned
2588
        $roleService->assignRoleToUserGroup(
2589
            $role,
2590
            $userGroup
2591
        );
2592
        /* END: Use Case */
2593
    }
2594
2595
    /**
2596
     * Test for the assignRoleToUserGroup() method.
2597
     *
2598
     * Makes sure assigning role several times with same limitations throws.
2599
     *
2600
     * @see \eZ\Publish\API\Repository\RoleService::assignRoleToUserGroup($role, $userGroup, $roleLimitation)
2601
     * @expectedException \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException
2602
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleByIdentifier
2603
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUserGroup
2604
     */
2605
    public function testAssignRoleToUserGroupWithRoleLimitationThrowsInvalidArgumentException()
2606
    {
2607
        $repository = $this->getRepository();
2608
2609
        $mainGroupId = $this->generateId('group', 4);
2610
        /* BEGIN: Use Case */
2611
        // $mainGroupId is the ID of the main "Users" group
2612
2613
        $userService = $repository->getUserService();
2614
        $roleService = $repository->getRoleService();
2615
2616
        $userGroup = $userService->loadUserGroup($mainGroupId);
2617
2618
        // Load the existing "Anonymous" role
2619
        $role = $roleService->loadRoleByIdentifier('Anonymous');
2620
2621
        // Assign the "Anonymous" role to the newly created user group
2622
        try {
2623
            $roleService->assignRoleToUserGroup(
2624
                $role,
2625
                $userGroup,
2626
                new SubtreeLimitation(
2627
                    [
2628
                        'limitationValues' => ['/1/43/', '/1/2/'],
2629
                    ]
2630
                )
2631
            );
2632
        } catch (Exception $e) {
2633
            $this->fail('Got exception at first valid attempt to assign role');
2634
        }
2635
2636
        // Re-Assign the "Anonymous" role to the newly created user group
2637
        // This call will fail with an InvalidArgumentException, because limitation is already assigned
2638
        $roleService->assignRoleToUserGroup(
2639
            $role,
2640
            $userGroup,
2641
            new SubtreeLimitation(
2642
                [
2643
                    'limitationValues' => ['/1/43/'],
2644
                ]
2645
            )
2646
        );
2647
        /* END: Use Case */
2648
    }
2649
2650
    /**
2651
     * Test for the unassignRoleFromUserGroup() method.
2652
     *
2653
     * @see \eZ\Publish\API\Repository\RoleService::unassignRoleFromUserGroup()
2654
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUserGroup
2655
     */
2656 View Code Duplication
    public function testUnassignRoleFromUserGroup()
2657
    {
2658
        $repository = $this->getRepository();
2659
        $roleService = $repository->getRoleService();
2660
2661
        /* BEGIN: Use Case */
2662
        $userGroup = $this->createUserGroupVersion1();
2663
2664
        // Load the existing "Member" role
2665
        $role = $roleService->loadRoleByIdentifier('Member');
2666
2667
        // Assign the "Member" role to the newly created user group
2668
        $roleService->assignRoleToUserGroup($role, $userGroup);
2669
2670
        // Unassign group from role
2671
        $roleService->unassignRoleFromUserGroup($role, $userGroup);
0 ignored issues
show
Deprecated Code introduced by
The method eZ\Publish\API\Repositor...signRoleFromUserGroup() has been deprecated with message: since 6.0, use {@see removeRoleAssignment} instead.

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

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

Loading history...
2672
2673
        // The assignments array will not contain the new role<->group assignment
2674
        $roleAssignments = $roleService->getRoleAssignments($role);
2675
        /* END: Use Case */
2676
2677
        // Members + Editors + Partners
2678
        $this->assertEquals(3, count($roleAssignments));
2679
    }
2680
2681
    /**
2682
     * Test for the unassignRoleFromUserGroup() method.
2683
     *
2684
     * @see \eZ\Publish\API\Repository\RoleService::unassignRoleFromUserGroup()
2685
     * @expectedException \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException
2686
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testUnassignRoleFromUserGroup
2687
     */
2688 View Code Duplication
    public function testUnassignRoleFromUserGroupThrowsInvalidArgumentException()
2689
    {
2690
        $repository = $this->getRepository();
2691
        $roleService = $repository->getRoleService();
2692
2693
        /* BEGIN: Use Case */
2694
        $userGroup = $this->createUserGroupVersion1();
2695
2696
        // Load the existing "Member" role
2697
        $role = $roleService->loadRoleByIdentifier('Member');
2698
2699
        // This call will fail with a "InvalidArgumentException", because the
2700
        // user group does not have the "Member" role.
2701
        $roleService->unassignRoleFromUserGroup($role, $userGroup);
0 ignored issues
show
Deprecated Code introduced by
The method eZ\Publish\API\Repositor...signRoleFromUserGroup() has been deprecated with message: since 6.0, use {@see removeRoleAssignment} instead.

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

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

Loading history...
2702
        /* END: Use Case */
2703
    }
2704
2705
    /**
2706
     * Test unassigning role by assignment.
2707
     *
2708
     * @covers \eZ\Publish\API\Repository\RoleService::removeRoleAssignment
2709
     */
2710
    public function testUnassignRoleByAssignment()
2711
    {
2712
        $repository = $this->getRepository();
2713
        $roleService = $repository->getRoleService();
2714
2715
        $role = $roleService->loadRole(2);
2716
        $user = $repository->getUserService()->loadUser(14);
2717
2718
        $originalAssignmentCount = count($roleService->getRoleAssignmentsForUser($user));
2719
2720
        $roleService->assignRoleToUser($role, $user);
2721
        $newAssignmentCount = count($roleService->getRoleAssignmentsForUser($user));
2722
        self::assertEquals($originalAssignmentCount + 1, $newAssignmentCount);
2723
2724
        $assignments = $roleService->getRoleAssignmentsForUser($user);
2725
        $roleService->removeRoleAssignment($assignments[0]);
2726
        $finalAssignmentCount = count($roleService->getRoleAssignmentsForUser($user));
2727
        self::assertEquals($newAssignmentCount - 1, $finalAssignmentCount);
2728
    }
2729
2730
    /**
2731
     * Test unassigning role by assignment.
2732
     *
2733
     * But on current admin user so he lacks access to read roles.
2734
     *
2735
     * @covers \eZ\Publish\API\Repository\RoleService::removeRoleAssignment
2736
     * @expectedException \eZ\Publish\API\Repository\Exceptions\UnauthorizedException
2737
     */
2738 View Code Duplication
    public function testUnassignRoleByAssignmentThrowsUnauthorizedException()
2739
    {
2740
        $repository = $this->getRepository();
2741
        $roleService = $repository->getRoleService();
2742
2743
        try {
2744
            $adminUserGroup = $repository->getUserService()->loadUserGroup(12);
2745
            $assignments = $roleService->getRoleAssignmentsForUserGroup($adminUserGroup);
2746
            $roleService->removeRoleAssignment($assignments[0]);
2747
        } catch (Exception $e) {
2748
            self::fail(
2749
                'Unexpected exception: ' . $e->getMessage() . " \n[" . $e->getFile() . ' (' . $e->getLine() . ')]'
2750
            );
2751
        }
2752
2753
        $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...
2754
    }
2755
2756
    /**
2757
     * Test unassigning role by non-existing assignment.
2758
     *
2759
     * @covers \eZ\Publish\API\Repository\RoleService::removeRoleAssignment
2760
     * @expectedException \eZ\Publish\API\Repository\Exceptions\NotFoundException
2761
     */
2762 View Code Duplication
    public function testUnassignRoleByAssignmentThrowsNotFoundException()
2763
    {
2764
        $repository = $this->getRepository();
2765
        $roleService = $repository->getRoleService();
2766
2767
        try {
2768
            $editorsUserGroup = $repository->getUserService()->loadUserGroup(13);
2769
            $assignments = $roleService->getRoleAssignmentsForUserGroup($editorsUserGroup);
2770
            $roleService->removeRoleAssignment($assignments[0]);
2771
        } catch (Exception $e) {
2772
            self::fail(
2773
                'Unexpected exception: ' . $e->getMessage() . " \n[" . $e->getFile() . ' (' . $e->getLine() . ')]'
2774
            );
2775
        }
2776
2777
        $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...
2778
    }
2779
2780
    /**
2781
     * Test for the getRoleAssignmentsForUserGroup() method.
2782
     *
2783
     * @see \eZ\Publish\API\Repository\RoleService::getRoleAssignmentsForUserGroup()
2784
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUserGroup
2785
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRoleWithAddPolicy
2786
     */
2787
    public function testGetRoleAssignmentsForUserGroup()
2788
    {
2789
        $repository = $this->getRepository();
2790
        $roleService = $repository->getRoleService();
2791
2792
        /* BEGIN: Use Case */
2793
        $userGroup = $this->createUserGroupVersion1();
2794
2795
        // Instantiate a role create and add some policies
2796
        $roleCreate = $roleService->newRoleCreateStruct('Example Role');
2797
2798
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
2799
        // $roleCreate->mainLanguageCode = 'eng-US';
2800
2801
        $roleCreate->addPolicy(
2802
            $roleService->newPolicyCreateStruct('user', 'login')
2803
        );
2804
        $roleCreate->addPolicy(
2805
            $roleService->newPolicyCreateStruct('content', 'read')
2806
        );
2807
        $roleCreate->addPolicy(
2808
            $roleService->newPolicyCreateStruct('content', 'edit')
2809
        );
2810
2811
        // Create the new role instance
2812
        $roleDraft = $roleService->createRole($roleCreate);
2813
        $roleService->publishRoleDraft($roleDraft);
2814
        $role = $roleService->loadRole($roleDraft->id);
2815
2816
        // Assign role to new user group
2817
        $roleService->assignRoleToUserGroup($role, $userGroup);
2818
2819
        // Load the currently assigned role
2820
        $roleAssignments = $roleService->getRoleAssignmentsForUserGroup($userGroup);
2821
        /* END: Use Case */
2822
2823
        $this->assertEquals(1, count($roleAssignments));
2824
        $this->assertInstanceOf(
2825
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\UserGroupRoleAssignment',
2826
            reset($roleAssignments)
2827
        );
2828
    }
2829
2830
    /**
2831
     * Test for the loadPoliciesByUserId() method.
2832
     *
2833
     * @see \eZ\Publish\API\Repository\RoleService::loadPoliciesByUserId()
2834
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUser
2835
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUserGroup
2836
     */
2837
    public function testLoadPoliciesByUserId()
2838
    {
2839
        $repository = $this->getRepository();
2840
2841
        $anonUserId = $this->generateId('user', 10);
2842
        /* BEGIN: Use Case */
2843
        // $anonUserId is the ID of the "Anonymous" user.
2844
2845
        $userService = $repository->getUserService();
2846
        $roleService = $repository->getRoleService();
2847
2848
        // Load "Anonymous" user
2849
        $user = $userService->loadUser($anonUserId);
2850
2851
        // Instantiate a role create and add some policies
2852
        $roleCreate = $roleService->newRoleCreateStruct('User Role');
2853
2854
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
2855
        // $roleCreate->mainLanguageCode = 'eng-US';
2856
2857
        $roleCreate->addPolicy(
2858
            $roleService->newPolicyCreateStruct('notification', 'use')
2859
        );
2860
        $roleCreate->addPolicy(
2861
            $roleService->newPolicyCreateStruct('user', 'password')
2862
        );
2863
        $roleCreate->addPolicy(
2864
            $roleService->newPolicyCreateStruct('user', 'selfedit')
2865
        );
2866
2867
        // Create the new role instance
2868
        $roleDraft = $roleService->createRole($roleCreate);
2869
        $roleService->publishRoleDraft($roleDraft);
2870
        $role = $roleService->loadRole($roleDraft->id);
2871
2872
        // Assign role to anon user
2873
        $roleService->assignRoleToUser($role, $user);
2874
2875
        // Load the currently assigned role
2876
        $policies = [];
2877
        foreach ($roleService->loadPoliciesByUserId($user->id) as $policy) {
0 ignored issues
show
Deprecated Code introduced by
The method eZ\Publish\API\Repositor...:loadPoliciesByUserId() has been deprecated with message: Since 6.8, not currently in use as permission system needs to know about role assignment limitations.

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

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

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

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

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

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