Completed
Push — EZP-31383 ( 83ce0c )
by
unknown
19:12
created

RoleServiceTest::testCopyRole()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 23

Duplication

Lines 23
Ratio 100 %

Importance

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