Completed
Push — master ( 44e556...6dea28 )
by
unknown
30:10 queued 11:42
created

testAddPolicyByRoleDraftUpdatesRole()   B

Complexity

Conditions 4
Paths 3

Size

Total Lines 32
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

foreach ($a as $b) {
}

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


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

// $b is now guaranteed to be defined here.
Loading history...
730
    }
731
732
    /**
733
     * Test for the loadRoles() method.
734
     *
735
     * @see \eZ\Publish\API\Repository\RoleService::loadRoles()
736
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoles
737
     */
738
    public function testLoadRolesReturnsExpectedSetOfDefaultRoles()
739
    {
740
        $repository = $this->getRepository();
741
742
        /* BEGIN: Use Case */
743
        $roleService = $repository->getRoleService();
744
745
        $roles = $roleService->loadRoles();
746
747
        $roleNames = array();
748
        foreach ($roles as $role) {
749
            $roleNames[] = $role->identifier;
750
        }
751
        /* END: Use Case */
752
753
        sort($roleNames);
754
755
        $this->assertEquals(
756
            array(
757
                'Administrator',
758
                'Anonymous',
759
                'Editor',
760
                'Member',
761
                'Partner',
762
            ),
763
            $roleNames
764
        );
765
    }
766
767
    /**
768
     * Test for the newRoleUpdateStruct() method.
769
     *
770
     * @see \eZ\Publish\API\Repository\RoleService::newRoleUpdateStruct()
771
     */
772
    public function testNewRoleUpdateStruct()
773
    {
774
        $repository = $this->getRepository();
775
776
        /* BEGIN: Use Case */
777
        $roleService = $repository->getRoleService();
778
        $roleUpdate = $roleService->newRoleUpdateStruct('newRole');
779
        /* END: Use Case */
780
781
        $this->assertInstanceOf('\\eZ\\Publish\\API\\Repository\\Values\\User\\RoleUpdateStruct', $roleUpdate);
782
    }
783
784
    /**
785
     * Test for the updateRole() method.
786
     *
787
     * @see \eZ\Publish\API\Repository\RoleService::updateRole()
788
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewRoleUpdateStruct
789
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleByIdentifier
790
     */
791
    public function testUpdateRole()
792
    {
793
        $repository = $this->getRepository();
794
795
        /* BEGIN: Use Case */
796
        $roleService = $repository->getRoleService();
797
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
798
799
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
800
        // $roleCreate->mainLanguageCode = 'eng-US';
801
802
        $roleDraft = $roleService->createRole($roleCreate);
803
        $roleService->publishRoleDraft($roleDraft);
804
        $role = $roleService->loadRole($roleDraft->id);
805
806
        $roleUpdate = $roleService->newRoleUpdateStruct();
807
        $roleUpdate->identifier = 'updatedRole';
808
809
        $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...
810
        /* END: Use Case */
811
812
        // Now verify that our change was saved
813
        $role = $roleService->loadRoleByIdentifier('updatedRole');
814
815
        $this->assertEquals($role->id, $updatedRole->id);
816
    }
817
818
    /**
819
     * Test for the updateRoleDraft() method.
820
     *
821
     * @see \eZ\Publish\API\Repository\RoleService::updateRoleDraft()
822
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewRoleUpdateStruct
823
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleDraft
824
     */
825 View Code Duplication
    public function testUpdateRoleDraft()
826
    {
827
        $repository = $this->getRepository();
828
829
        /* BEGIN: Use Case */
830
        $roleService = $repository->getRoleService();
831
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
832
833
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
834
        // $roleCreate->mainLanguageCode = 'eng-US';
835
836
        $roleDraft = $roleService->createRole($roleCreate);
837
838
        $roleUpdate = $roleService->newRoleUpdateStruct();
839
        $roleUpdate->identifier = 'updatedRole';
840
841
        $updatedRole = $roleService->updateRoleDraft($roleDraft, $roleUpdate);
842
        /* END: Use Case */
843
844
        // Now verify that our change was saved
845
        $role = $roleService->loadRoleDraft($updatedRole->id);
846
847
        $this->assertEquals($role->identifier, 'updatedRole');
848
    }
849
850
    /**
851
     * Test for the updateRole() method.
852
     *
853
     * @see \eZ\Publish\API\Repository\RoleService::updateRole()
854
     * @expectedException \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException
855
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testUpdateRole
856
     */
857 View Code Duplication
    public function testUpdateRoleThrowsInvalidArgumentException()
858
    {
859
        $repository = $this->getRepository();
860
861
        /* BEGIN: Use Case */
862
        $roleService = $repository->getRoleService();
863
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
864
865
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
866
        // $roleCreate->mainLanguageCode = 'eng-US';
867
868
        $roleDraft = $roleService->createRole($roleCreate);
869
        $roleService->publishRoleDraft($roleDraft);
870
        $role = $roleService->loadRole($roleDraft->id);
871
872
        $roleUpdate = $roleService->newRoleUpdateStruct();
873
        $roleUpdate->identifier = 'Editor';
874
875
        // This call will fail with an InvalidArgumentException, because Editor is a predefined role
876
        $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...
877
        /* END: Use Case */
878
    }
879
880
    /**
881
     * Test for the updateRoleDraft() method.
882
     *
883
     * @see \eZ\Publish\API\Repository\RoleService::updateRoleDraft()
884
     * @expectedException \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException
885
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testUpdateRoleDraft
886
     */
887
    public function testUpdateRoleDraftThrowsInvalidArgumentException()
888
    {
889
        $repository = $this->getRepository();
890
891
        /* BEGIN: Use Case */
892
        $roleService = $repository->getRoleService();
893
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
894
895
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
896
        // $roleCreate->mainLanguageCode = 'eng-US';
897
898
        $roleDraft = $roleService->createRole($roleCreate);
899
900
        $roleUpdate = $roleService->newRoleUpdateStruct();
901
        $roleUpdate->identifier = 'Editor';
902
903
        // This call will fail with an InvalidArgumentException, because Editor is a predefined role
904
        $roleService->updateRoleDraft($roleDraft, $roleUpdate);
905
        /* END: Use Case */
906
    }
907
908
    /**
909
     * Test for the deleteRole() method.
910
     *
911
     * @see \eZ\Publish\API\Repository\RoleService::deleteRole()
912
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRole
913
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoles
914
     */
915 View Code Duplication
    public function testDeleteRole()
916
    {
917
        $repository = $this->getRepository();
918
919
        /* BEGIN: Use Case */
920
        $roleService = $repository->getRoleService();
921
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
922
923
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
924
        // $roleCreate->mainLanguageCode = 'eng-US';
925
926
        $roleDraft = $roleService->createRole($roleCreate);
927
        $roleService->publishRoleDraft($roleDraft);
928
        $role = $roleService->loadRole($roleDraft->id);
929
930
        $roleService->deleteRole($role);
931
        /* END: Use Case */
932
933
        $this->assertEquals(5, count($roleService->loadRoles()));
934
    }
935
936
    /**
937
     * Test for the deleteRoleDraft() method.
938
     *
939
     * @see \eZ\Publish\API\Repository\RoleService::deleteRoleDraft()
940
     * @expectedException \eZ\Publish\API\Repository\Exceptions\NotFoundException
941
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleDraft
942
     */
943
    public function testDeleteRoleDraft()
944
    {
945
        $repository = $this->getRepository();
946
947
        /* BEGIN: Use Case */
948
        $roleService = $repository->getRoleService();
949
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
950
951
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
952
        // $roleCreate->mainLanguageCode = 'eng-US';
953
954
        $roleDraft = $roleService->createRole($roleCreate);
955
        $roleID = $roleDraft->id;
956
        $roleService->deleteRoleDraft($roleDraft);
957
958
        // This call will fail with a NotFoundException, because the draft no longer exists
959
        $roleService->loadRoleDraft($roleID);
960
        /* END: Use Case */
961
    }
962
963
    /**
964
     * Test for the newPolicyCreateStruct() method.
965
     *
966
     * @see \eZ\Publish\API\Repository\RoleService::newPolicyCreateStruct()
967
     */
968
    public function testNewPolicyCreateStruct()
969
    {
970
        $repository = $this->getRepository();
971
972
        /* BEGIN: Use Case */
973
        $roleService = $repository->getRoleService();
974
        $policyCreate = $roleService->newPolicyCreateStruct('content', 'create');
975
        /* END: Use Case */
976
977
        $this->assertInstanceOf('\\eZ\\Publish\\API\\Repository\\Values\\User\\PolicyCreateStruct', $policyCreate);
978
    }
979
980
    /**
981
     * Test for the newPolicyCreateStruct() method.
982
     *
983
     * @see \eZ\Publish\API\Repository\RoleService::newPolicyCreateStruct()
984
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewPolicyCreateStruct
985
     */
986
    public function testNewPolicyCreateStructSetsStructProperties()
987
    {
988
        $repository = $this->getRepository();
989
990
        /* BEGIN: Use Case */
991
        $roleService = $repository->getRoleService();
992
        $policyCreate = $roleService->newPolicyCreateStruct('content', 'create');
993
        /* END: Use Case */
994
995
        $this->assertEquals(
996
            array('content', 'create'),
997
            array($policyCreate->module, $policyCreate->function)
998
        );
999
    }
1000
1001
    /**
1002
     * Test for the addPolicy() method.
1003
     *
1004
     * @see \eZ\Publish\API\Repository\RoleService::addPolicy()
1005
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleByIdentifier
1006
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewPolicyCreateStruct
1007
     */
1008 View Code Duplication
    public function testAddPolicy()
1009
    {
1010
        $repository = $this->getRepository();
1011
1012
        /* BEGIN: Use Case */
1013
        $roleService = $repository->getRoleService();
1014
1015
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
1016
1017
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1018
        // $roleCreate->mainLanguageCode = 'eng-US';
1019
1020
        $roleDraft = $roleService->createRole($roleCreate);
1021
        $roleService->publishRoleDraft($roleDraft);
1022
        $role = $roleService->loadRole($roleDraft->id);
1023
1024
        $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...
1025
            $role,
1026
            $roleService->newPolicyCreateStruct('content', 'delete')
1027
        );
1028
        $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...
1029
            $role,
1030
            $roleService->newPolicyCreateStruct('content', 'create')
1031
        );
1032
        /* END: Use Case */
1033
1034
        $actual = array();
1035
        foreach ($role->getPolicies() as $policy) {
1036
            $actual[] = array(
1037
                'module' => $policy->module,
1038
                'function' => $policy->function,
1039
            );
1040
        }
1041
        usort(
1042
            $actual,
1043
            function ($p1, $p2) {
1044
                return strcasecmp($p1['function'], $p2['function']);
1045
            }
1046
        );
1047
1048
        $this->assertEquals(
1049
            array(
1050
                array(
1051
                    'module' => 'content',
1052
                    'function' => 'create',
1053
                ),
1054
                array(
1055
                    'module' => 'content',
1056
                    'function' => 'delete',
1057
                ),
1058
            ),
1059
            $actual
1060
        );
1061
    }
1062
1063
    /**
1064
     * Test for the addPolicyByRoleDraft() method.
1065
     *
1066
     * @see \eZ\Publish\API\Repository\RoleService::addPolicyByRoleDraft()
1067
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRoleDraft
1068
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewPolicyCreateStruct
1069
     */
1070
    public function testAddPolicyByRoleDraft()
1071
    {
1072
        $repository = $this->getRepository();
1073
1074
        /* BEGIN: Use Case */
1075
        $roleService = $repository->getRoleService();
1076
1077
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
1078
1079
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1080
        // $roleCreate->mainLanguageCode = 'eng-US';
1081
1082
        $roleDraft = $roleService->createRole($roleCreate);
1083
1084
        $roleDraft = $roleService->addPolicyByRoleDraft(
1085
            $roleDraft,
1086
            $roleService->newPolicyCreateStruct('content', 'delete')
1087
        );
1088
        $roleDraft = $roleService->addPolicyByRoleDraft(
1089
            $roleDraft,
1090
            $roleService->newPolicyCreateStruct('content', 'create')
1091
        );
1092
        /* END: Use Case */
1093
1094
        $actual = array();
1095 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...
1096
            $actual[] = array(
1097
                'module' => $policy->module,
1098
                'function' => $policy->function,
1099
            );
1100
        }
1101
        usort(
1102
            $actual,
1103
            function ($p1, $p2) {
1104
                return strcasecmp($p1['function'], $p2['function']);
1105
            }
1106
        );
1107
1108
        $this->assertEquals(
1109
            array(
1110
                array(
1111
                    'module' => 'content',
1112
                    'function' => 'create',
1113
                ),
1114
                array(
1115
                    'module' => 'content',
1116
                    'function' => 'delete',
1117
                ),
1118
            ),
1119
            $actual
1120
        );
1121
    }
1122
1123
    /**
1124
     * Test for the addPolicy() method.
1125
     *
1126
     * @return array [\eZ\Publish\API\Repository\Values\User\Role, \eZ\Publish\API\Repository\Values\User\Policy]
1127
     *
1128
     * @see \eZ\Publish\API\Repository\RoleService::addPolicy()
1129
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicy
1130
     */
1131
    public function testAddPolicyUpdatesRole()
1132
    {
1133
        $repository = $this->getRepository();
1134
1135
        /* BEGIN: Use Case */
1136
        $roleService = $repository->getRoleService();
1137
1138
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
1139
1140
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1141
        // $roleCreate->mainLanguageCode = 'eng-US';
1142
1143
        $roleDraft = $roleService->createRole($roleCreate);
1144
        $roleService->publishRoleDraft($roleDraft);
1145
        $role = $roleService->loadRole($roleDraft->id);
1146
1147
        $policyCreate = $roleService->newPolicyCreateStruct('content', 'create');
1148
        $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...
1149
1150
        $policy = null;
1151
        foreach ($role->getPolicies() as $policy) {
1152
            if ($policy->module === 'content' && $policy->function === 'create') {
1153
                break;
1154
            }
1155
        }
1156
        /* END: Use Case */
1157
1158
        $this->assertInstanceOf(
1159
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\Policy',
1160
            $policy
1161
        );
1162
1163
        return array($role, $policy);
1164
    }
1165
1166
    /**
1167
     * Test for the addPolicyByRoleDraft() method.
1168
     *
1169
     * @return array [\eZ\Publish\API\Repository\Values\User\RoleDraft, \eZ\Publish\API\Repository\Values\User\Policy]
1170
     *
1171
     * @see \eZ\Publish\API\Repository\RoleService::addPolicyByRoleDraft()
1172
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicyByRoleDraft
1173
     */
1174
    public function testAddPolicyByRoleDraftUpdatesRole()
1175
    {
1176
        $repository = $this->getRepository();
1177
1178
        /* BEGIN: Use Case */
1179
        $roleService = $repository->getRoleService();
1180
1181
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
1182
1183
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1184
        // $roleCreate->mainLanguageCode = 'eng-US';
1185
1186
        $roleDraft = $roleService->createRole($roleCreate);
1187
1188
        $policyCreate = $roleService->newPolicyCreateStruct('content', 'create');
1189
        $roleDraft = $roleService->addPolicyByRoleDraft($roleDraft, $policyCreate);
1190
1191
        $policy = null;
1192
        foreach ($roleDraft->getPolicies() as $policy) {
1193
            if ($policy->module === 'content' && $policy->function === 'create') {
1194
                break;
1195
            }
1196
        }
1197
        /* END: Use Case */
1198
1199
        $this->assertInstanceOf(
1200
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\Policy',
1201
            $policy
1202
        );
1203
1204
        return array($roleDraft, $policy);
1205
    }
1206
1207
    /**
1208
     * Test for the addPolicy() method.
1209
     *
1210
     * @param array $roleAndPolicy
1211
     *
1212
     * @see \eZ\Publish\API\Repository\RoleService::addPolicy()
1213
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicyUpdatesRole
1214
     */
1215 View Code Duplication
    public function testAddPolicySetsPolicyProperties($roleAndPolicy)
1216
    {
1217
        list($role, $policy) = $roleAndPolicy;
1218
1219
        $this->assertEquals(
1220
            array($role->id, 'content', 'create'),
1221
            array($policy->roleId, $policy->module, $policy->function)
1222
        );
1223
    }
1224
1225
    /**
1226
     * Test for the addPolicyByRoleDraft() method.
1227
     *
1228
     * @param array $roleAndPolicy
1229
     *
1230
     * @see \eZ\Publish\API\Repository\RoleService::addPolicyByRoleDraft()
1231
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicyByRoleDraftUpdatesRole
1232
     */
1233 View Code Duplication
    public function testAddPolicyByRoleDraftSetsPolicyProperties($roleAndPolicy)
1234
    {
1235
        list($role, $policy) = $roleAndPolicy;
1236
1237
        $this->assertEquals(
1238
            array($role->id, 'content', 'create'),
1239
            array($policy->roleId, $policy->module, $policy->function)
1240
        );
1241
    }
1242
1243
    /**
1244
     * Test for the addPolicy() method.
1245
     *
1246
     * @see \eZ\Publish\API\Repository\RoleService::addPolicy()
1247
     * @expectedException \eZ\Publish\API\Repository\Exceptions\LimitationValidationException
1248
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewPolicyCreateStruct
1249
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRole
1250
     */
1251
    public function testAddPolicyThrowsLimitationValidationException()
1252
    {
1253
        $repository = $this->getRepository();
1254
1255
        /* BEGIN: Use Case */
1256
        $roleService = $repository->getRoleService();
1257
1258
        $roleCreate = $roleService->newRoleCreateStruct('Lumberjack');
1259
1260
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1261
        // $roleCreate->mainLanguageCode = 'eng-US';
1262
1263
        $roleDraft = $roleService->createRole($roleCreate);
1264
        $roleService->publishRoleDraft($roleDraft);
1265
        $role = $roleService->loadRole($roleDraft->id);
1266
1267
        // Create new subtree limitation
1268
        $limitation = new SubtreeLimitation(
1269
            array(
1270
                'limitationValues' => array('/mountain/forest/tree/42/'),
1271
            )
1272
        );
1273
1274
        // Create policy create struct and add limitation to it
1275
        $policyCreateStruct = $roleService->newPolicyCreateStruct('content', 'remove');
1276
        $policyCreateStruct->addLimitation($limitation);
1277
1278
        // This call will fail with an LimitationValidationException, because subtree
1279
        // "/mountain/forest/tree/42/" does not exist
1280
        $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...
1281
        /* END: Use Case */
1282
    }
1283
1284
    /**
1285
     * Test for the addPolicyByRoleDraft() method.
1286
     *
1287
     * @see \eZ\Publish\API\Repository\RoleService::addPolicyByRoleDraft()
1288
     * @expectedException \eZ\Publish\API\Repository\Exceptions\LimitationValidationException
1289
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewPolicyCreateStruct
1290
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRoleDraft
1291
     */
1292 View Code Duplication
    public function testAddPolicyByRoleDraftThrowsLimitationValidationException()
1293
    {
1294
        $repository = $this->getRepository();
1295
1296
        /* BEGIN: Use Case */
1297
        $roleService = $repository->getRoleService();
1298
1299
        $roleCreate = $roleService->newRoleCreateStruct('Lumberjack');
1300
1301
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1302
        // $roleCreate->mainLanguageCode = 'eng-US';
1303
1304
        $roleDraft = $roleService->createRole($roleCreate);
1305
1306
        // Create new subtree limitation
1307
        $limitation = new SubtreeLimitation(
1308
            array(
1309
                'limitationValues' => array('/mountain/forest/tree/42/'),
1310
            )
1311
        );
1312
1313
        // Create policy create struct and add limitation to it
1314
        $policyCreateStruct = $roleService->newPolicyCreateStruct('content', 'remove');
1315
        $policyCreateStruct->addLimitation($limitation);
1316
1317
        // This call will fail with an LimitationValidationException, because subtree
1318
        // "/mountain/forest/tree/42/" does not exist
1319
        $roleService->addPolicyByRoleDraft($roleDraft, $policyCreateStruct);
1320
        /* END: Use Case */
1321
    }
1322
1323
    /**
1324
     * Test for the createRole() method.
1325
     *
1326
     * @see \eZ\Publish\API\Repository\RoleService::createRole()
1327
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicyUpdatesRole
1328
     */
1329
    public function testCreateRoleWithAddPolicy()
1330
    {
1331
        $repository = $this->getRepository();
1332
1333
        /* BEGIN: Use Case */
1334
        $roleService = $repository->getRoleService();
1335
1336
        // Instantiate a new create struct
1337
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
1338
1339
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1340
        // $roleCreate->mainLanguageCode = 'eng-US';
1341
1342
        // Add some role policies
1343
        $roleCreate->addPolicy(
1344
            $roleService->newPolicyCreateStruct(
1345
                'content',
1346
                'read'
1347
            )
1348
        );
1349
        $roleCreate->addPolicy(
1350
            $roleService->newPolicyCreateStruct(
1351
                'content',
1352
                'translate'
1353
            )
1354
        );
1355
1356
        // Create new role instance
1357
        $roleDraft = $roleService->createRole($roleCreate);
1358
        $roleService->publishRoleDraft($roleDraft);
1359
        $role = $roleService->loadRole($roleDraft->id);
1360
1361
        $policies = array();
1362 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...
1363
            $policies[] = array('module' => $policy->module, 'function' => $policy->function);
1364
        }
1365
        /* END: Use Case */
1366
        array_multisort($policies);
1367
1368
        $this->assertEquals(
1369
            array(
1370
                array(
1371
                    'module' => 'content',
1372
                    'function' => 'read',
1373
                ),
1374
                array(
1375
                    'module' => 'content',
1376
                    'function' => 'translate',
1377
                ),
1378
            ),
1379
            $policies
1380
        );
1381
    }
1382
1383
    /**
1384
     * Test for the createRoleDraft() method.
1385
     *
1386
     * @see \eZ\Publish\API\Repository\RoleService::createRoleDraft()
1387
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicyByRoleDraftUpdatesRole
1388
     */
1389
    public function testCreateRoleDraftWithAddPolicy()
1390
    {
1391
        $repository = $this->getRepository();
1392
1393
        /* BEGIN: Use Case */
1394
        $roleService = $repository->getRoleService();
1395
1396
        // Instantiate a new create struct
1397
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
1398
1399
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1400
        // $roleCreate->mainLanguageCode = 'eng-US';
1401
1402
        // Add some role policies
1403
        $roleCreate->addPolicy(
1404
            $roleService->newPolicyCreateStruct(
1405
                'content',
1406
                'read'
1407
            )
1408
        );
1409
        $roleCreate->addPolicy(
1410
            $roleService->newPolicyCreateStruct(
1411
                'content',
1412
                'translate'
1413
            )
1414
        );
1415
1416
        // Create new role instance
1417
        $roleDraft = $roleService->createRole($roleCreate);
1418
1419
        $policies = array();
1420 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...
1421
            $policies[] = array('module' => $policy->module, 'function' => $policy->function);
1422
        }
1423
        /* END: Use Case */
1424
1425
        $this->assertEquals(
1426
            array(
1427
                array(
1428
                    'module' => 'content',
1429
                    'function' => 'read',
1430
                ),
1431
                array(
1432
                    'module' => 'content',
1433
                    'function' => 'translate',
1434
                ),
1435
            ),
1436
            $policies
1437
        );
1438
    }
1439
1440
    /**
1441
     * Test for the newPolicyUpdateStruct() method.
1442
     *
1443
     * @see \eZ\Publish\API\Repository\RoleService::newPolicyUpdateStruct()
1444
     */
1445
    public function testNewPolicyUpdateStruct()
1446
    {
1447
        $repository = $this->getRepository();
1448
1449
        /* BEGIN: Use Case */
1450
        $roleService = $repository->getRoleService();
1451
        $policyUpdate = $roleService->newPolicyUpdateStruct();
1452
        /* END: Use Case */
1453
1454
        $this->assertInstanceOf(
1455
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\PolicyUpdateStruct',
1456
            $policyUpdate
1457
        );
1458
    }
1459
1460
    public function testUpdatePolicyNoLimitation()
1461
    {
1462
        $repository = $this->getRepository();
1463
1464
        /* BEGIN: Use Case */
1465
        $roleService = $repository->getRoleService();
1466
1467
        // Instantiate new policy create
1468
        $policyCreate = $roleService->newPolicyCreateStruct('foo', 'bar');
1469
1470
        // Instantiate a role create and add the policy create
1471
        $roleCreate = $roleService->newRoleCreateStruct('myRole');
1472
1473
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1474
        // $roleCreate->mainLanguageCode = 'eng-US';
1475
1476
        $roleCreate->addPolicy($policyCreate);
1477
1478
        // Create a new role instance.
1479
        $roleDraft = $roleService->createRole($roleCreate);
1480
        $roleService->publishRoleDraft($roleDraft);
1481
        $role = $roleService->loadRole($roleDraft->id);
1482
1483
        // Search for the new policy instance
1484
        $policy = null;
1485
        foreach ($role->getPolicies() as $policy) {
1486
            if ($policy->module === 'foo' && $policy->function === 'bar') {
1487
                break;
1488
            }
1489
        }
1490
1491
        // Create an update struct
1492
        $policyUpdate = $roleService->newPolicyUpdateStruct();
1493
1494
        // Update the the policy
1495
        $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...
1496
        /* END: Use Case */
1497
1498
        $this->assertInstanceOf(
1499
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\Policy',
1500
            $policy
1501
        );
1502
1503
        self::assertEquals(array(), $policy->getLimitations());
1504
    }
1505
1506
    /**
1507
     * Test for the updatePolicy() method.
1508
     *
1509
     * @return array
1510
     *
1511
     * @see \eZ\Publish\API\Repository\RoleService::updatePolicy()
1512
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicy
1513
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewPolicyUpdateStruct
1514
     */
1515
    public function testUpdatePolicy()
1516
    {
1517
        $repository = $this->getRepository();
1518
1519
        /* BEGIN: Use Case */
1520
        $roleService = $repository->getRoleService();
1521
1522
        // Instantiate new policy create
1523
        $policyCreate = $roleService->newPolicyCreateStruct('content', 'translate');
1524
1525
        // Add some limitations for the new policy
1526
        $policyCreate->addLimitation(
1527
            new LanguageLimitation(
1528
                array(
1529
                    'limitationValues' => array('eng-US', 'eng-GB'),
1530
                )
1531
            )
1532
        );
1533
1534
        // Instantiate a role create and add the policy create
1535
        $roleCreate = $roleService->newRoleCreateStruct('myRole');
1536
1537
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1538
        // $roleCreate->mainLanguageCode = 'eng-US';
1539
1540
        $roleCreate->addPolicy($policyCreate);
1541
1542
        // Create a new role instance.
1543
        $roleDraft = $roleService->createRole($roleCreate);
1544
        $roleService->publishRoleDraft($roleDraft);
1545
        $role = $roleService->loadRole($roleDraft->id);
1546
1547
        // Search for the new policy instance
1548
        $policy = null;
1549
        foreach ($role->getPolicies() as $policy) {
1550
            if ($policy->module === 'content' && $policy->function === 'translate') {
1551
                break;
1552
            }
1553
        }
1554
1555
        // Create an update struct and set a modified limitation
1556
        $policyUpdate = $roleService->newPolicyUpdateStruct();
1557
        $policyUpdate->addLimitation(
1558
            new ContentTypeLimitation(
1559
                array(
1560
                    'limitationValues' => array(29, 30),
1561
                )
1562
            )
1563
        );
1564
1565
        // Update the the policy
1566
        $policy = $roleService->updatePolicy($policy, $policyUpdate);
0 ignored issues
show
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...
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...
1567
        /* END: Use Case */
1568
1569
        $this->assertInstanceOf(
1570
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\Policy',
1571
            $policy
1572
        );
1573
1574
        return array($roleService->loadRole($role->id), $policy);
1575
    }
1576
1577
    /**
1578
     * Test for the updatePolicy() method.
1579
     *
1580
     * @param array $roleAndPolicy
1581
     *
1582
     * @see \eZ\Publish\API\Repository\RoleService::updatePolicy()
1583
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testUpdatePolicy
1584
     */
1585
    public function testUpdatePolicyUpdatesLimitations($roleAndPolicy)
1586
    {
1587
        list($role, $policy) = $roleAndPolicy;
1588
1589
        $this->assertEquals(
1590
            array(
1591
                new ContentTypeLimitation(
1592
                    array(
1593
                        'limitationValues' => array(29, 30),
1594
                    )
1595
                ),
1596
            ),
1597
            $policy->getLimitations()
1598
        );
1599
1600
        return $role;
1601
    }
1602
1603
    /**
1604
     * Test for the updatePolicy() method.
1605
     *
1606
     * @param \eZ\Publish\API\Repository\Values\User\Role $role
1607
     *
1608
     * @see \eZ\Publish\API\Repository\RoleService::updatePolicy()
1609
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testUpdatePolicyUpdatesLimitations
1610
     */
1611
    public function testUpdatePolicyUpdatesRole($role)
1612
    {
1613
        $limitations = array();
1614
        foreach ($role->getPolicies() as $policy) {
1615
            foreach ($policy->getLimitations() as $limitation) {
1616
                $limitations[] = $limitation;
1617
            }
1618
        }
1619
1620
        $this->assertCount(1, $limitations);
1621
        $this->assertInstanceOf(
1622
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\Limitation',
1623
            $limitations[0]
1624
        );
1625
1626
        $expectedData = array(
1627
            'limitationValues' => array(29, 30),
1628
        );
1629
        $this->assertPropertiesCorrectUnsorted(
1630
            $expectedData,
1631
            $limitations[0]
1632
        );
1633
    }
1634
1635
    /**
1636
     * Test for the updatePolicy() method.
1637
     *
1638
     * @see \eZ\Publish\API\Repository\RoleService::updatePolicy()
1639
     * @expectedException \eZ\Publish\API\Repository\Exceptions\LimitationValidationException
1640
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicy
1641
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewPolicyCreateStruct
1642
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewPolicyUpdateStruct
1643
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewRoleCreateStruct
1644
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRole
1645
     */
1646
    public function testUpdatePolicyThrowsLimitationValidationException()
1647
    {
1648
        $repository = $this->getRepository();
1649
1650
        /* BEGIN: Use Case */
1651
        $roleService = $repository->getRoleService();
1652
1653
        // Instantiate new policy create
1654
        $policyCreate = $roleService->newPolicyCreateStruct('content', 'remove');
1655
1656
        // Add some limitations for the new policy
1657
        $policyCreate->addLimitation(
1658
            new SubtreeLimitation(
1659
                array(
1660
                    'limitationValues' => array('/1/2/'),
1661
                )
1662
            )
1663
        );
1664
1665
        // Instantiate a role create and add the policy create
1666
        $roleCreate = $roleService->newRoleCreateStruct('myRole');
1667
1668
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1669
        // $roleCreate->mainLanguageCode = 'eng-US';
1670
1671
        $roleCreate->addPolicy($policyCreate);
1672
1673
        // Create a new role instance.
1674
        $roleDraft = $roleService->createRole($roleCreate);
1675
        $roleService->publishRoleDraft($roleDraft);
1676
        $role = $roleService->loadRole($roleDraft->id);
1677
1678
        // Search for the new policy instance
1679
        $policy = null;
1680
        foreach ($role->getPolicies() as $policy) {
1681
            if ($policy->module === 'content' && $policy->function === 'remove') {
1682
                break;
1683
            }
1684
        }
1685
1686
        // Create an update struct and set a modified limitation
1687
        $policyUpdate = $roleService->newPolicyUpdateStruct();
1688
        $policyUpdate->addLimitation(
1689
            new SubtreeLimitation(
1690
                array(
1691
                    'limitationValues' => array('/mountain/forest/tree/42/'),
1692
                )
1693
            )
1694
        );
1695
1696
        // This call will fail with an LimitationValidationException, because subtree
1697
        // "/mountain/forest/tree/42/" does not exist
1698
        $policy = $roleService->updatePolicy($policy, $policyUpdate);
0 ignored issues
show
Unused Code introduced by
$policy is not used, you could remove the assignment.

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

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

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

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

Loading history...
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...
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...
1699
        /* END: Use Case */
1700
    }
1701
1702
    /**
1703
     * Test for the removePolicyByRoleDraft() method.
1704
     *
1705
     * @see \eZ\Publish\API\Repository\RoleService::removePolicyByRoleDraft()
1706
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicyByRoleDraft
1707
     */
1708 View Code Duplication
    public function testRemovePolicyByRoleDraft()
1709
    {
1710
        $repository = $this->getRepository();
1711
1712
        /* BEGIN: Use Case */
1713
        $roleService = $repository->getRoleService();
1714
1715
        // Instantiate a new role create
1716
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
1717
1718
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1719
        // $roleCreate->mainLanguageCode = 'eng-US';
1720
1721
        // Create a new role with two policies
1722
        $roleDraft = $roleService->createRole($roleCreate);
1723
        $roleService->addPolicyByRoleDraft(
1724
            $roleDraft,
1725
            $roleService->newPolicyCreateStruct('content', 'create')
1726
        );
1727
        $roleService->addPolicyByRoleDraft(
1728
            $roleDraft,
1729
            $roleService->newPolicyCreateStruct('content', 'delete')
1730
        );
1731
1732
        // Delete all policies from the new role
1733
        foreach ($roleDraft->getPolicies() as $policy) {
1734
            $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...
1735
        }
1736
        /* END: Use Case */
1737
1738
        $this->assertSame(array(), $roleDraft->getPolicies());
1739
    }
1740
1741
    /**
1742
     * Test for the deletePolicy() method.
1743
     *
1744
     * @see \eZ\Publish\API\Repository\RoleService::deletePolicy()
1745
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRole
1746
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicy
1747
     */
1748
    public function testDeletePolicy()
1749
    {
1750
        $repository = $this->getRepository();
1751
1752
        /* BEGIN: Use Case */
1753
        $roleService = $repository->getRoleService();
1754
1755
        // Instantiate a new role create
1756
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
1757
1758
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1759
        // $roleCreate->mainLanguageCode = 'eng-US';
1760
1761
        // Create a new role with two policies
1762
        $roleDraft = $roleService->createRole($roleCreate);
1763
        $roleService->addPolicyByRoleDraft(
1764
            $roleDraft,
1765
            $roleService->newPolicyCreateStruct('content', 'create')
1766
        );
1767
        $roleService->addPolicyByRoleDraft(
1768
            $roleDraft,
1769
            $roleService->newPolicyCreateStruct('content', 'delete')
1770
        );
1771
        $roleService->publishRoleDraft($roleDraft);
1772
        $role = $roleService->loadRole($roleDraft->id);
1773
1774
        // Delete all policies from the new role
1775
        foreach ($role->getPolicies() as $policy) {
1776
            $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...
1777
        }
1778
        /* END: Use Case */
1779
1780
        $role = $roleService->loadRole($role->id);
1781
        $this->assertSame(array(), $role->getPolicies());
1782
    }
1783
1784
    /**
1785
     * Test loading user/group role assignments.
1786
     *
1787
     * @return \eZ\Publish\API\Repository\Values\User\UserGroupRoleAssignment
1788
     *
1789
     * @covers \eZ\Publish\API\Repository\RoleService::loadRoleAssignment
1790
     */
1791
    public function testLoadRoleAssignment()
1792
    {
1793
        $repository = $this->getRepository();
1794
1795
        /* BEGIN: Use Case */
1796
        $roleService = $repository->getRoleService();
1797
1798
        // Assignment to user group
1799
        $groupRoleAssignment = $roleService->loadRoleAssignment(25);
1800
1801
        // Assignment to user
1802
        $role = $roleService->loadRole(2);
1803
        $user = $repository->getUserService()->loadUser(14);
1804
        $roleService->assignRoleToUser($role, $user);
1805
        $userRoleAssignments = $roleService->getRoleAssignmentsForUser($user);
1806
1807
        $userRoleAssignment = $roleService->loadRoleAssignment($userRoleAssignments[0]->id);
1808
        /* END: Use Case */
1809
1810
        $this->assertInstanceOf(
1811
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\UserGroupRoleAssignment',
1812
            $groupRoleAssignment
1813
        );
1814
1815
        $this->assertEquals(
1816
            [
1817
                12,
1818
                2,
1819
                25,
1820
            ],
1821
            [
1822
                $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...
1823
                $groupRoleAssignment->role->id,
1824
                $groupRoleAssignment->id,
1825
            ]
1826
        );
1827
1828
        self::assertInstanceOf('\\eZ\\Publish\\API\\Repository\\Values\\User\\UserRoleAssignment', $userRoleAssignment);
1829
        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...
1830
1831
        return $groupRoleAssignment;
1832
    }
1833
1834
    /**
1835
     * Test for the getRoleAssignments() method.
1836
     *
1837
     * @return \eZ\Publish\API\Repository\Values\User\RoleAssignment[]
1838
     *
1839
     * @see \eZ\Publish\API\Repository\RoleService::getRoleAssignments()
1840
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleByIdentifier
1841
     */
1842
    public function testGetRoleAssignments()
1843
    {
1844
        $repository = $this->getRepository();
1845
1846
        /* BEGIN: Use Case */
1847
        $roleService = $repository->getRoleService();
1848
1849
        // Load the editor role
1850
        $role = $roleService->loadRoleByIdentifier('Editor');
1851
1852
        // Load all assigned users and user groups
1853
        $roleAssignments = $roleService->getRoleAssignments($role);
1854
1855
        /* END: Use Case */
1856
1857
        $this->assertEquals(2, count($roleAssignments));
1858
        $this->assertInstanceOf(
1859
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\UserGroupRoleAssignment',
1860
            $roleAssignments[0]
1861
        );
1862
        $this->assertInstanceOf(
1863
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\UserGroupRoleAssignment',
1864
            $roleAssignments[1]
1865
        );
1866
1867
        return $roleAssignments;
1868
    }
1869
1870
    /**
1871
     * Test for the getRoleAssignments() method.
1872
     *
1873
     * @param \eZ\Publish\API\Repository\Values\User\RoleAssignment[] $roleAssignments
1874
     *
1875
     * @see \eZ\Publish\API\Repository\RoleService::getRoleAssignments()
1876
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testGetRoleAssignments
1877
     */
1878
    public function testGetRoleAssignmentsContainExpectedLimitation(array $roleAssignments)
1879
    {
1880
        $this->assertEquals(
1881
            'Subtree',
1882
            reset($roleAssignments)->limitation->getIdentifier()
1883
        );
1884
    }
1885
1886
    /**
1887
     * Test for the assignRoleToUser() method.
1888
     *
1889
     * @see \eZ\Publish\API\Repository\RoleService::assignRoleToUser()
1890
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testGetRoleAssignments
1891
     */
1892 View Code Duplication
    public function testAssignRoleToUser()
1893
    {
1894
        $repository = $this->getRepository();
1895
        $roleService = $repository->getRoleService();
1896
1897
        /* BEGIN: Use Case */
1898
        $user = $this->createUserVersion1();
1899
1900
        // Load the existing "Administrator" role
1901
        $role = $roleService->loadRoleByIdentifier('Administrator');
1902
1903
        // Assign the "Administrator" role to the newly created user
1904
        $roleService->assignRoleToUser($role, $user);
1905
1906
        // The assignments array will contain the new role<->user assignment
1907
        $roleAssignments = $roleService->getRoleAssignments($role);
1908
        /* END: Use Case */
1909
1910
        // Administrator + Example User
1911
        $this->assertEquals(2, count($roleAssignments));
1912
    }
1913
1914
    /**
1915
     * Test for the assignRoleToUser() method.
1916
     *
1917
     * @see \eZ\Publish\API\Repository\RoleService::assignRoleToUser($role, $user, $roleLimitation)
1918
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUser
1919
     */
1920 View Code Duplication
    public function testAssignRoleToUserWithRoleLimitation()
1921
    {
1922
        $repository = $this->getRepository();
1923
        $roleService = $repository->getRoleService();
1924
1925
        /* BEGIN: Use Case */
1926
        $user = $this->createUserVersion1();
1927
1928
        // Load the existing "Anonymous" role
1929
        $role = $roleService->loadRoleByIdentifier('Anonymous');
1930
1931
        // Assign the "Anonymous" role to the newly created user
1932
        $roleService->assignRoleToUser(
1933
            $role,
1934
            $user,
1935
            new SubtreeLimitation(
1936
                array(
1937
                    'limitationValues' => array('/1/43/'),
1938
                )
1939
            )
1940
        );
1941
1942
        // The assignments array will contain the new role<->user assignment
1943
        $roleAssignments = $roleService->getRoleAssignments($role);
1944
        /* END: Use Case */
1945
1946
        // Members + Partners + Anonymous + Example User
1947
        $this->assertEquals(4, count($roleAssignments));
1948
1949
        // Get the role limitation
1950
        $roleLimitation = null;
1951
        foreach ($roleAssignments as $roleAssignment) {
1952
            $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...
1953
            if ($roleLimitation) {
1954
                $this->assertInstanceOf(
1955
                    '\\eZ\\Publish\\API\\Repository\\Values\\User\\UserRoleAssignment',
1956
                    $roleAssignment
1957
                );
1958
                break;
1959
            }
1960
        }
1961
1962
        $this->assertEquals(
1963
            new SubtreeLimitation(
1964
                array(
1965
                    'limitationValues' => array('/1/43/'),
1966
                )
1967
            ),
1968
            $roleLimitation
1969
        );
1970
1971
        // Test again to see values being merged
1972
        $roleService->assignRoleToUser(
1973
            $role,
1974
            $user,
1975
            new SubtreeLimitation(
1976
                array(
1977
                    'limitationValues' => array('/1/43/', '/1/2/'),
1978
                )
1979
            )
1980
        );
1981
1982
        // The assignments array will contain the new role<->user assignment
1983
        $roleAssignments = $roleService->getRoleAssignments($role);
1984
1985
        // Members + Partners + Anonymous + Example User
1986
        $this->assertEquals(5, count($roleAssignments));
1987
1988
        // Get the role limitation
1989
        $roleLimitations = [];
1990
        foreach ($roleAssignments as $roleAssignment) {
1991
            $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...
1992
            if ($roleLimitation) {
1993
                $this->assertInstanceOf(
1994
                    '\\eZ\\Publish\\API\\Repository\\Values\\User\\UserRoleAssignment',
1995
                    $roleAssignment
1996
                );
1997
                $roleLimitations[] = $roleLimitation;
1998
            }
1999
        }
2000
        array_multisort($roleLimitations);
2001
2002
        $this->assertEquals(
2003
            [
2004
                new SubtreeLimitation(
2005
                    array(
2006
                        'limitationValues' => array('/1/2/'),
2007
                    )
2008
                ),
2009
                new SubtreeLimitation(
2010
                    array(
2011
                        'limitationValues' => array('/1/43/'),
2012
                    )
2013
                ),
2014
            ],
2015
            $roleLimitations
2016
        );
2017
    }
2018
2019
    /**
2020
     * Test for the assignRoleToUser() method.
2021
     *
2022
     * @see \eZ\Publish\API\Repository\RoleService::assignRoleToUser($role, $user, $roleLimitation)
2023
     * @expectedException \eZ\Publish\API\Repository\Exceptions\LimitationValidationException
2024
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUser
2025
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleByIdentifier
2026
     */
2027
    public function testAssignRoleToUserWithRoleLimitationThrowsLimitationValidationException()
2028
    {
2029
        $repository = $this->getRepository();
2030
2031
        /* BEGIN: Use Case */
2032
        $roleService = $repository->getRoleService();
2033
2034
        // Load the existing "Anonymous" role
2035
        $role = $roleService->loadRoleByIdentifier('Anonymous');
2036
2037
        // Get current user
2038
        $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...
2039
2040
        // Assign the "Anonymous" role to the current user
2041
        // This call will fail with an LimitationValidationException, because subtree "/lorem/ipsum/42/"
2042
        // does not exists
2043
        $roleService->assignRoleToUser(
2044
            $role,
2045
            $currentUser,
2046
            new SubtreeLimitation(
2047
                array(
2048
                    'limitationValues' => array('/lorem/ipsum/42/'),
2049
                )
2050
            )
2051
        );
2052
        /* END: Use Case */
2053
    }
2054
2055
    /**
2056
     * Test for the assignRoleToUser() method.
2057
     *
2058
     * Makes sure assigning role several times throws.
2059
     *
2060
     * @see \eZ\Publish\API\Repository\RoleService::assignRoleToUser($role, $user, $roleLimitation)
2061
     * @expectedException \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException
2062
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUser
2063
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleByIdentifier
2064
     */
2065 View Code Duplication
    public function testAssignRoleToUserThrowsInvalidArgumentException()
2066
    {
2067
        $repository = $this->getRepository();
2068
2069
        /* BEGIN: Use Case */
2070
        $roleService = $repository->getRoleService();
2071
2072
        // Load the existing "Anonymous" role
2073
        $role = $roleService->loadRoleByIdentifier('Anonymous');
2074
2075
        // Get current user
2076
        $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...
2077
2078
        // Assign the "Anonymous" role to the current user
2079
        try {
2080
            $roleService->assignRoleToUser(
2081
                $role,
2082
                $currentUser
2083
            );
2084
        } catch (Exception $e) {
2085
            $this->fail('Got exception at first valid attempt to assign role');
2086
        }
2087
2088
        // Re-Assign the "Anonymous" role to the current user
2089
        // This call will fail with an InvalidArgumentException, because limitation is already assigned
2090
        $roleService->assignRoleToUser(
2091
            $role,
2092
            $currentUser
2093
        );
2094
        /* END: Use Case */
2095
    }
2096
2097
    /**
2098
     * Test for the assignRoleToUser() method.
2099
     *
2100
     * Makes sure assigning role several times with same limitations throws.
2101
     *
2102
     * @see \eZ\Publish\API\Repository\RoleService::assignRoleToUser($role, $user, $roleLimitation)
2103
     * @expectedException \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException
2104
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUser
2105
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleByIdentifier
2106
     */
2107
    public function testAssignRoleToUserWithRoleLimitationThrowsInvalidArgumentException()
2108
    {
2109
        $repository = $this->getRepository();
2110
2111
        /* BEGIN: Use Case */
2112
        $roleService = $repository->getRoleService();
2113
2114
        // Load the existing "Anonymous" role
2115
        $role = $roleService->loadRoleByIdentifier('Anonymous');
2116
2117
        // Get current user
2118
        $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...
2119
2120
        // Assign the "Anonymous" role to the current user
2121
        try {
2122
            $roleService->assignRoleToUser(
2123
                $role,
2124
                $currentUser,
2125
                new SubtreeLimitation(
2126
                    array(
2127
                        'limitationValues' => array('/1/43/', '/1/2/'),
2128
                    )
2129
                )
2130
            );
2131
        } catch (Exception $e) {
2132
            $this->fail('Got exception at first valid attempt to assign role');
2133
        }
2134
2135
        // Re-Assign the "Anonymous" role to the current user
2136
        // This call will fail with an InvalidArgumentException, because limitation is already assigned
2137
        $roleService->assignRoleToUser(
2138
            $role,
2139
            $currentUser,
2140
            new SubtreeLimitation(
2141
                array(
2142
                    'limitationValues' => array('/1/43/'),
2143
                )
2144
            )
2145
        );
2146
        /* END: Use Case */
2147
    }
2148
2149
    /**
2150
     * Test for the unassignRoleFromUser() method.
2151
     *
2152
     * @see \eZ\Publish\API\Repository\RoleService::unassignRoleFromUser()
2153
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUser
2154
     */
2155 View Code Duplication
    public function testUnassignRoleFromUser()
2156
    {
2157
        $repository = $this->getRepository();
2158
        $roleService = $repository->getRoleService();
2159
2160
        /* BEGIN: Use Case */
2161
        $user = $this->createUserVersion1();
2162
2163
        // Load the existing "Member" role
2164
        $role = $roleService->loadRoleByIdentifier('Member');
2165
2166
        // Assign the "Member" role to the newly created user
2167
        $roleService->assignRoleToUser($role, $user);
2168
2169
        // Unassign user from role
2170
        $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...
2171
2172
        // The assignments array will not contain the new role<->user assignment
2173
        $roleAssignments = $roleService->getRoleAssignments($role);
2174
        /* END: Use Case */
2175
2176
        // Members + Editors + Partners
2177
        $this->assertEquals(3, count($roleAssignments));
2178
    }
2179
2180
    /**
2181
     * Test for the unassignRoleFromUser() method.
2182
     *
2183
     * @see \eZ\Publish\API\Repository\RoleService::unassignRoleFromUser()
2184
     * @expectedException \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException
2185
     */
2186 View Code Duplication
    public function testUnassignRoleFromUserThrowsInvalidArgumentException()
2187
    {
2188
        $repository = $this->getRepository();
2189
        $roleService = $repository->getRoleService();
2190
2191
        /* BEGIN: Use Case */
2192
        $user = $this->createUserVersion1();
2193
2194
        // Load the existing "Member" role
2195
        $role = $roleService->loadRoleByIdentifier('Member');
2196
2197
        // This call will fail with a "InvalidArgumentException", because the
2198
        // user does not have the "Member" role.
2199
        $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...
2200
        /* END: Use Case */
2201
    }
2202
2203
    /**
2204
     * Test for the getRoleAssignmentsForUser() method.
2205
     *
2206
     * @see \eZ\Publish\API\Repository\RoleService::getRoleAssignmentsForUser()
2207
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUser
2208
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRoleWithAddPolicy
2209
     */
2210 View Code Duplication
    public function testGetRoleAssignmentsForUserDirect()
2211
    {
2212
        $repository = $this->getRepository();
2213
        $roleService = $repository->getRoleService();
2214
2215
        /* BEGIN: Use Case */
2216
        $user = $this->createUserVersion1();
2217
2218
        // Instantiate a role create and add some policies
2219
        $roleCreate = $roleService->newRoleCreateStruct('Example Role');
2220
2221
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
2222
        // $roleCreate->mainLanguageCode = 'eng-US';
2223
2224
        $roleCreate->addPolicy(
2225
            $roleService->newPolicyCreateStruct('user', 'login')
2226
        );
2227
        $roleCreate->addPolicy(
2228
            $roleService->newPolicyCreateStruct('content', 'read')
2229
        );
2230
        $roleCreate->addPolicy(
2231
            $roleService->newPolicyCreateStruct('content', 'edit')
2232
        );
2233
2234
        // Create the new role instance
2235
        $roleDraft = $roleService->createRole($roleCreate);
2236
        $roleService->publishRoleDraft($roleDraft);
2237
        $role = $roleService->loadRole($roleDraft->id);
2238
2239
        // Assign role to new user
2240
        $roleService->assignRoleToUser($role, $user);
2241
2242
        // Load the currently assigned role
2243
        $roleAssignments = $roleService->getRoleAssignmentsForUser($user);
2244
        /* END: Use Case */
2245
2246
        $this->assertEquals(1, count($roleAssignments));
2247
        $this->assertInstanceOf(
2248
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\UserRoleAssignment',
2249
            reset($roleAssignments)
2250
        );
2251
    }
2252
2253
    /**
2254
     * Test for the getRoleAssignmentsForUser() method.
2255
     *
2256
     * @see \eZ\Publish\API\Repository\RoleService::getRoleAssignmentsForUser()
2257
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUser
2258
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRoleWithAddPolicy
2259
     */
2260
    public function testGetRoleAssignmentsForUserEmpty()
2261
    {
2262
        $repository = $this->getRepository();
2263
        $roleService = $repository->getRoleService();
2264
2265
        /* BEGIN: Use Case */
2266
        $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...
2267
2268
        // Load the currently assigned role
2269
        $roleAssignments = $roleService->getRoleAssignmentsForUser($adminUser);
2270
        /* END: Use Case */
2271
2272
        $this->assertEquals(0, count($roleAssignments));
2273
    }
2274
2275
    /**
2276
     * Test for the getRoleAssignmentsForUser() method.
2277
     *
2278
     * @see \eZ\Publish\API\Repository\RoleService::getRoleAssignmentsForUser()
2279
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUser
2280
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRoleWithAddPolicy
2281
     */
2282
    public function testGetRoleAssignmentsForUserInherited()
2283
    {
2284
        $repository = $this->getRepository();
2285
        $roleService = $repository->getRoleService();
2286
2287
        /* BEGIN: Use Case */
2288
        $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...
2289
2290
        // Load the currently assigned role + inherited role assignments
2291
        $roleAssignments = $roleService->getRoleAssignmentsForUser($adminUser, true);
2292
        /* END: Use Case */
2293
2294
        $this->assertEquals(1, count($roleAssignments));
2295
        $this->assertInstanceOf(
2296
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\UserGroupRoleAssignment',
2297
            reset($roleAssignments)
2298
        );
2299
    }
2300
2301
    /**
2302
     * Test for the assignRoleToUserGroup() method.
2303
     *
2304
     * @see \eZ\Publish\API\Repository\RoleService::assignRoleToUserGroup()
2305
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testGetRoleAssignments
2306
     */
2307 View Code Duplication
    public function testAssignRoleToUserGroup()
2308
    {
2309
        $repository = $this->getRepository();
2310
        $roleService = $repository->getRoleService();
2311
2312
        /* BEGIN: Use Case */
2313
        $userGroup = $this->createUserGroupVersion1();
2314
2315
        // Load the existing "Administrator" role
2316
        $role = $roleService->loadRoleByIdentifier('Administrator');
2317
2318
        // Assign the "Administrator" role to the newly created user group
2319
        $roleService->assignRoleToUserGroup($role, $userGroup);
2320
2321
        // The assignments array will contain the new role<->group assignment
2322
        $roleAssignments = $roleService->getRoleAssignments($role);
2323
        /* END: Use Case */
2324
2325
        // Administrator + Example Group
2326
        $this->assertEquals(2, count($roleAssignments));
2327
    }
2328
2329
    /**
2330
     * Test for the assignRoleToUserGroup() method.
2331
     *
2332
     * Related issue: EZP-29113
2333
     *
2334
     * @covers \eZ\Publish\API\Repository\RoleService::assignRoleToUserGroup()
2335
     */
2336
    public function testAssignRoleToUserGroupAffectsRoleAssignmentsForUser()
2337
    {
2338
        $roleService = $this->getRepository()->getRoleService();
2339
2340
        /* BEGIN: Use Case */
2341
        $userGroup = $this->createUserGroupVersion1();
2342
        $user = $this->createUser('user', 'John', 'Doe', $userGroup);
2343
2344
        $initRoleAssignments = $roleService->getRoleAssignmentsForUser($user, true);
2345
2346
        // Load the existing "Administrator" role
2347
        $role = $roleService->loadRoleByIdentifier('Administrator');
2348
2349
        // Assign the "Administrator" role to the newly created user group
2350
        $roleService->assignRoleToUserGroup($role, $userGroup);
2351
2352
        $updatedRoleAssignments = $roleService->getRoleAssignmentsForUser($user, true);
2353
        /* END: Use Case */
2354
2355
        $this->assertEmpty($initRoleAssignments);
2356
        $this->assertEquals(1, count($updatedRoleAssignments));
2357
    }
2358
2359
    /**
2360
     * Test for the assignRoleToUserGroup() method.
2361
     *
2362
     * @see \eZ\Publish\API\Repository\RoleService::assignRoleToUserGroup($role, $userGroup, $roleLimitation)
2363
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUserGroup
2364
     */
2365 View Code Duplication
    public function testAssignRoleToUserGroupWithRoleLimitation()
2366
    {
2367
        $repository = $this->getRepository();
2368
        $roleService = $repository->getRoleService();
2369
2370
        /* BEGIN: Use Case */
2371
        $userGroup = $this->createUserGroupVersion1();
2372
2373
        // Load the existing "Anonymous" role
2374
        $role = $roleService->loadRoleByIdentifier('Anonymous');
2375
2376
        // Assign the "Anonymous" role to the newly created user group
2377
        $roleService->assignRoleToUserGroup(
2378
            $role,
2379
            $userGroup,
2380
            new SubtreeLimitation(
2381
                array(
2382
                    'limitationValues' => array('/1/43/'),
2383
                )
2384
            )
2385
        );
2386
2387
        // The assignments array will contain the new role<->group assignment
2388
        $roleAssignments = $roleService->getRoleAssignments($role);
2389
        /* END: Use Case */
2390
2391
        // Members + Partners + Anonymous + Example Group
2392
        $this->assertEquals(4, count($roleAssignments));
2393
2394
        // Get the role limitation
2395
        $roleLimitation = null;
2396
        foreach ($roleAssignments as $roleAssignment) {
2397
            $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...
2398
            if ($roleLimitation) {
2399
                break;
2400
            }
2401
        }
2402
2403
        $this->assertEquals(
2404
            new SubtreeLimitation(
2405
                array(
2406
                    'limitationValues' => array('/1/43/'),
2407
                )
2408
            ),
2409
            $roleLimitation
2410
        );
2411
2412
        // Test again to see values being merged
2413
        $roleService->assignRoleToUserGroup(
2414
            $role,
2415
            $userGroup,
2416
            new SubtreeLimitation(
2417
                array(
2418
                    'limitationValues' => array('/1/43/', '/1/2/'),
2419
                )
2420
            )
2421
        );
2422
2423
        // The assignments array will contain the new role<->user assignment
2424
        $roleAssignments = $roleService->getRoleAssignments($role);
2425
2426
        // Members + Partners + Anonymous + Example User
2427
        $this->assertEquals(5, count($roleAssignments));
2428
2429
        // Get the role limitation
2430
        $roleLimitations = [];
2431
        foreach ($roleAssignments as $roleAssignment) {
2432
            $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...
2433
            if ($roleLimitation) {
2434
                $this->assertInstanceOf(
2435
                    '\\eZ\\Publish\\API\\Repository\\Values\\User\\UserGroupRoleAssignment',
2436
                    $roleAssignment
2437
                );
2438
                $roleLimitations[] = $roleLimitation;
2439
            }
2440
        }
2441
        array_multisort($roleLimitations);
2442
2443
        $this->assertEquals(
2444
            [
2445
                new SubtreeLimitation(
2446
                    array(
2447
                        'limitationValues' => array('/1/2/'),
2448
                    )
2449
                ),
2450
                new SubtreeLimitation(
2451
                    array(
2452
                        'limitationValues' => array('/1/43/'),
2453
                    )
2454
                ),
2455
            ],
2456
            $roleLimitations
2457
        );
2458
    }
2459
2460
    /**
2461
     * Test for the assignRoleToUserGroup() method.
2462
     *
2463
     * @see \eZ\Publish\API\Repository\RoleService::assignRoleToUserGroup($role, $userGroup, $roleLimitation)
2464
     * @expectedException \eZ\Publish\API\Repository\Exceptions\LimitationValidationException
2465
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleByIdentifier
2466
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUserGroup
2467
     */
2468
    public function testAssignRoleToUserGroupWithRoleLimitationThrowsLimitationValidationException()
2469
    {
2470
        $repository = $this->getRepository();
2471
2472
        $mainGroupId = $this->generateId('group', 4);
2473
        /* BEGIN: Use Case */
2474
        // $mainGroupId is the ID of the main "Users" group
2475
2476
        $userService = $repository->getUserService();
2477
        $roleService = $repository->getRoleService();
2478
2479
        $userGroup = $userService->loadUserGroup($mainGroupId);
2480
2481
        // Load the existing "Anonymous" role
2482
        $role = $roleService->loadRoleByIdentifier('Anonymous');
2483
2484
        // Assign the "Anonymous" role to the newly created user group
2485
        // This call will fail with an LimitationValidationException, because subtree "/lorem/ipsum/42/"
2486
        // does not exists
2487
        $roleService->assignRoleToUserGroup(
2488
            $role,
2489
            $userGroup,
2490
            new SubtreeLimitation(
2491
                array(
2492
                    'limitationValues' => array('/lorem/ipsum/42/'),
2493
                )
2494
            )
2495
        );
2496
        /* END: Use Case */
2497
    }
2498
2499
    /**
2500
     * Test for the assignRoleToUserGroup() method.
2501
     *
2502
     * Makes sure assigning role several times throws.
2503
     *
2504
     * @see \eZ\Publish\API\Repository\RoleService::assignRoleToUserGroup($role, $userGroup, $roleLimitation)
2505
     * @expectedException \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException
2506
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleByIdentifier
2507
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUserGroup
2508
     */
2509
    public function testAssignRoleToUserGroupThrowsInvalidArgumentException()
2510
    {
2511
        $repository = $this->getRepository();
2512
2513
        $mainGroupId = $this->generateId('group', 4);
2514
        /* BEGIN: Use Case */
2515
        // $mainGroupId is the ID of the main "Users" group
2516
2517
        $userService = $repository->getUserService();
2518
        $roleService = $repository->getRoleService();
2519
2520
        $userGroup = $userService->loadUserGroup($mainGroupId);
2521
2522
        // Load the existing "Anonymous" role
2523
        $role = $roleService->loadRoleByIdentifier('Anonymous');
2524
2525
        // Assign the "Anonymous" role to the newly created user group
2526
        try {
2527
            $roleService->assignRoleToUserGroup(
2528
                $role,
2529
                $userGroup
2530
            );
2531
        } catch (Exception $e) {
2532
            $this->fail('Got exception at first valid attempt to assign role');
2533
        }
2534
2535
        // Re-Assign the "Anonymous" role to the newly created user group
2536
        // This call will fail with an InvalidArgumentException, because role is already assigned
2537
        $roleService->assignRoleToUserGroup(
2538
            $role,
2539
            $userGroup
2540
        );
2541
        /* END: Use Case */
2542
    }
2543
2544
    /**
2545
     * Test for the assignRoleToUserGroup() method.
2546
     *
2547
     * Makes sure assigning role several times with same limitations throws.
2548
     *
2549
     * @see \eZ\Publish\API\Repository\RoleService::assignRoleToUserGroup($role, $userGroup, $roleLimitation)
2550
     * @expectedException \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException
2551
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleByIdentifier
2552
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUserGroup
2553
     */
2554
    public function testAssignRoleToUserGroupWithRoleLimitationThrowsInvalidArgumentException()
2555
    {
2556
        $repository = $this->getRepository();
2557
2558
        $mainGroupId = $this->generateId('group', 4);
2559
        /* BEGIN: Use Case */
2560
        // $mainGroupId is the ID of the main "Users" group
2561
2562
        $userService = $repository->getUserService();
2563
        $roleService = $repository->getRoleService();
2564
2565
        $userGroup = $userService->loadUserGroup($mainGroupId);
2566
2567
        // Load the existing "Anonymous" role
2568
        $role = $roleService->loadRoleByIdentifier('Anonymous');
2569
2570
        // Assign the "Anonymous" role to the newly created user group
2571
        try {
2572
            $roleService->assignRoleToUserGroup(
2573
                $role,
2574
                $userGroup,
2575
                new SubtreeLimitation(
2576
                    array(
2577
                        'limitationValues' => array('/1/43/', '/1/2/'),
2578
                    )
2579
                )
2580
            );
2581
        } catch (Exception $e) {
2582
            $this->fail('Got exception at first valid attempt to assign role');
2583
        }
2584
2585
        // Re-Assign the "Anonymous" role to the newly created user group
2586
        // This call will fail with an InvalidArgumentException, because limitation is already assigned
2587
        $roleService->assignRoleToUserGroup(
2588
            $role,
2589
            $userGroup,
2590
            new SubtreeLimitation(
2591
                array(
2592
                    'limitationValues' => array('/1/43/'),
2593
                )
2594
            )
2595
        );
2596
        /* END: Use Case */
2597
    }
2598
2599
    /**
2600
     * Test for the unassignRoleFromUserGroup() method.
2601
     *
2602
     * @see \eZ\Publish\API\Repository\RoleService::unassignRoleFromUserGroup()
2603
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUserGroup
2604
     */
2605 View Code Duplication
    public function testUnassignRoleFromUserGroup()
2606
    {
2607
        $repository = $this->getRepository();
2608
        $roleService = $repository->getRoleService();
2609
2610
        /* BEGIN: Use Case */
2611
        $userGroup = $this->createUserGroupVersion1();
2612
2613
        // Load the existing "Member" role
2614
        $role = $roleService->loadRoleByIdentifier('Member');
2615
2616
        // Assign the "Member" role to the newly created user group
2617
        $roleService->assignRoleToUserGroup($role, $userGroup);
2618
2619
        // Unassign group from role
2620
        $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...
2621
2622
        // The assignments array will not contain the new role<->group assignment
2623
        $roleAssignments = $roleService->getRoleAssignments($role);
2624
        /* END: Use Case */
2625
2626
        // Members + Editors + Partners
2627
        $this->assertEquals(3, count($roleAssignments));
2628
    }
2629
2630
    /**
2631
     * Test for the unassignRoleFromUserGroup() method.
2632
     *
2633
     * @see \eZ\Publish\API\Repository\RoleService::unassignRoleFromUserGroup()
2634
     * @expectedException \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException
2635
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testUnassignRoleFromUserGroup
2636
     */
2637 View Code Duplication
    public function testUnassignRoleFromUserGroupThrowsInvalidArgumentException()
2638
    {
2639
        $repository = $this->getRepository();
2640
        $roleService = $repository->getRoleService();
2641
2642
        /* BEGIN: Use Case */
2643
        $userGroup = $this->createUserGroupVersion1();
2644
2645
        // Load the existing "Member" role
2646
        $role = $roleService->loadRoleByIdentifier('Member');
2647
2648
        // This call will fail with a "InvalidArgumentException", because the
2649
        // user group does not have the "Member" role.
2650
        $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...
2651
        /* END: Use Case */
2652
    }
2653
2654
    /**
2655
     * Test unassigning role by assignment.
2656
     *
2657
     * @covers \eZ\Publish\API\Repository\RoleService::removeRoleAssignment
2658
     */
2659
    public function testUnassignRoleByAssignment()
2660
    {
2661
        $repository = $this->getRepository();
2662
        $roleService = $repository->getRoleService();
2663
2664
        $role = $roleService->loadRole(2);
2665
        $user = $repository->getUserService()->loadUser(14);
2666
2667
        $originalAssignmentCount = count($roleService->getRoleAssignmentsForUser($user));
2668
2669
        $roleService->assignRoleToUser($role, $user);
2670
        $newAssignmentCount = count($roleService->getRoleAssignmentsForUser($user));
2671
        self::assertEquals($originalAssignmentCount + 1, $newAssignmentCount);
2672
2673
        $assignments = $roleService->getRoleAssignmentsForUser($user);
2674
        $roleService->removeRoleAssignment($assignments[0]);
2675
        $finalAssignmentCount = count($roleService->getRoleAssignmentsForUser($user));
2676
        self::assertEquals($newAssignmentCount - 1, $finalAssignmentCount);
2677
    }
2678
2679
    /**
2680
     * Test unassigning role by assignment.
2681
     *
2682
     * But on current admin user so he lacks access to read roles.
2683
     *
2684
     * @covers \eZ\Publish\API\Repository\RoleService::removeRoleAssignment
2685
     * @expectedException \eZ\Publish\API\Repository\Exceptions\UnauthorizedException
2686
     */
2687 View Code Duplication
    public function testUnassignRoleByAssignmentThrowsUnauthorizedException()
2688
    {
2689
        $repository = $this->getRepository();
2690
        $roleService = $repository->getRoleService();
2691
2692
        try {
2693
            $adminUserGroup = $repository->getUserService()->loadUserGroup(12);
2694
            $assignments = $roleService->getRoleAssignmentsForUserGroup($adminUserGroup);
2695
            $roleService->removeRoleAssignment($assignments[0]);
2696
        } catch (Exception $e) {
2697
            self::fail(
2698
                'Unexpected exception: ' . $e->getMessage() . " \n[" . $e->getFile() . ' (' . $e->getLine() . ')]'
2699
            );
2700
        }
2701
2702
        $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...
2703
    }
2704
2705
    /**
2706
     * Test unassigning role by non-existing assignment.
2707
     *
2708
     * @covers \eZ\Publish\API\Repository\RoleService::removeRoleAssignment
2709
     * @expectedException \eZ\Publish\API\Repository\Exceptions\NotFoundException
2710
     */
2711 View Code Duplication
    public function testUnassignRoleByAssignmentThrowsNotFoundException()
2712
    {
2713
        $repository = $this->getRepository();
2714
        $roleService = $repository->getRoleService();
2715
2716
        try {
2717
            $editorsUserGroup = $repository->getUserService()->loadUserGroup(13);
2718
            $assignments = $roleService->getRoleAssignmentsForUserGroup($editorsUserGroup);
2719
            $roleService->removeRoleAssignment($assignments[0]);
2720
        } catch (Exception $e) {
2721
            self::fail(
2722
                'Unexpected exception: ' . $e->getMessage() . " \n[" . $e->getFile() . ' (' . $e->getLine() . ')]'
2723
            );
2724
        }
2725
2726
        $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...
2727
    }
2728
2729
    /**
2730
     * Test for the getRoleAssignmentsForUserGroup() method.
2731
     *
2732
     * @see \eZ\Publish\API\Repository\RoleService::getRoleAssignmentsForUserGroup()
2733
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUserGroup
2734
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRoleWithAddPolicy
2735
     */
2736 View Code Duplication
    public function testGetRoleAssignmentsForUserGroup()
2737
    {
2738
        $repository = $this->getRepository();
2739
        $roleService = $repository->getRoleService();
2740
2741
        /* BEGIN: Use Case */
2742
        $userGroup = $this->createUserGroupVersion1();
2743
2744
        // Instantiate a role create and add some policies
2745
        $roleCreate = $roleService->newRoleCreateStruct('Example Role');
2746
2747
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
2748
        // $roleCreate->mainLanguageCode = 'eng-US';
2749
2750
        $roleCreate->addPolicy(
2751
            $roleService->newPolicyCreateStruct('user', 'login')
2752
        );
2753
        $roleCreate->addPolicy(
2754
            $roleService->newPolicyCreateStruct('content', 'read')
2755
        );
2756
        $roleCreate->addPolicy(
2757
            $roleService->newPolicyCreateStruct('content', 'edit')
2758
        );
2759
2760
        // Create the new role instance
2761
        $roleDraft = $roleService->createRole($roleCreate);
2762
        $roleService->publishRoleDraft($roleDraft);
2763
        $role = $roleService->loadRole($roleDraft->id);
2764
2765
        // Assign role to new user group
2766
        $roleService->assignRoleToUserGroup($role, $userGroup);
2767
2768
        // Load the currently assigned role
2769
        $roleAssignments = $roleService->getRoleAssignmentsForUserGroup($userGroup);
2770
        /* END: Use Case */
2771
2772
        $this->assertEquals(1, count($roleAssignments));
2773
        $this->assertInstanceOf(
2774
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\UserGroupRoleAssignment',
2775
            reset($roleAssignments)
2776
        );
2777
    }
2778
2779
    /**
2780
     * Test for the loadPoliciesByUserId() method.
2781
     *
2782
     * @see \eZ\Publish\API\Repository\RoleService::loadPoliciesByUserId()
2783
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUser
2784
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUserGroup
2785
     */
2786
    public function testLoadPoliciesByUserId()
2787
    {
2788
        $repository = $this->getRepository();
2789
2790
        $anonUserId = $this->generateId('user', 10);
2791
        /* BEGIN: Use Case */
2792
        // $anonUserId is the ID of the "Anonymous" user.
2793
2794
        $userService = $repository->getUserService();
2795
        $roleService = $repository->getRoleService();
2796
2797
        // Load "Anonymous" user
2798
        $user = $userService->loadUser($anonUserId);
2799
2800
        // Instantiate a role create and add some policies
2801
        $roleCreate = $roleService->newRoleCreateStruct('User Role');
2802
2803
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
2804
        // $roleCreate->mainLanguageCode = 'eng-US';
2805
2806
        $roleCreate->addPolicy(
2807
            $roleService->newPolicyCreateStruct('notification', 'use')
2808
        );
2809
        $roleCreate->addPolicy(
2810
            $roleService->newPolicyCreateStruct('user', 'password')
2811
        );
2812
        $roleCreate->addPolicy(
2813
            $roleService->newPolicyCreateStruct('user', 'selfedit')
2814
        );
2815
2816
        // Create the new role instance
2817
        $roleDraft = $roleService->createRole($roleCreate);
2818
        $roleService->publishRoleDraft($roleDraft);
2819
        $role = $roleService->loadRole($roleDraft->id);
2820
2821
        // Assign role to anon user
2822
        $roleService->assignRoleToUser($role, $user);
2823
2824
        // Load the currently assigned role
2825
        $policies = array();
2826
        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...
2827
            $policies[] = array($policy->roleId, $policy->module, $policy->function);
2828
        }
2829
        /* END: Use Case */
2830
        array_multisort($policies);
2831
2832
        $this->assertEquals(
2833
            array(
2834
                array(1, 'content', 'pdf'),
2835
                array(1, 'content', 'read'),
2836
                array(1, 'content', 'read'),
2837
                array(1, 'rss', 'feed'),
2838
                array(1, 'user', 'login'),
2839
                array(1, 'user', 'login'),
2840
                array(1, 'user', 'login'),
2841
                array(1, 'user', 'login'),
2842
                array($role->id, 'notification', 'use'),
2843
                array($role->id, 'user', 'password'),
2844
                array($role->id, 'user', 'selfedit'),
2845
            ),
2846
            $policies
2847
        );
2848
    }
2849
2850
    /**
2851
     * Test for the loadPoliciesByUserId() method.
2852
     *
2853
     * @see \eZ\Publish\API\Repository\RoleService::loadPoliciesByUserId()
2854
     * @expectedException \eZ\Publish\API\Repository\Exceptions\NotFoundException
2855
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadPoliciesByUserId
2856
     */
2857
    public function testLoadPoliciesByUserIdThrowsNotFoundException()
2858
    {
2859
        $repository = $this->getRepository();
2860
2861
        $nonExistingUserId = $this->generateId('user', self::DB_INT_MAX);
2862
        /* BEGIN: Use Case */
2863
        $roleService = $repository->getRoleService();
2864
2865
        // This call will fail with a "NotFoundException", because hopefully no
2866
        // user with an ID equal to self::DB_INT_MAX exists.
2867
        $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...
2868
        /* END: Use Case */
2869
    }
2870
2871
    /**
2872
     * Test for the publishRoleDraft() method.
2873
     *
2874
     * @see \eZ\Publish\API\Repository\RoleService::publishRoleDraft()
2875
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRoleDraft
2876
     */
2877 View Code Duplication
    public function testPublishRoleDraft()
2878
    {
2879
        $repository = $this->getRepository();
2880
2881
        /* BEGIN: Use Case */
2882
        $roleService = $repository->getRoleService();
2883
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
2884
2885
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
2886
        // $roleCreate->mainLanguageCode = 'eng-US';
2887
2888
        $roleDraft = $roleService->createRole($roleCreate);
2889
2890
        $roleDraft = $roleService->addPolicyByRoleDraft(
2891
            $roleDraft,
2892
            $roleService->newPolicyCreateStruct('content', 'delete')
2893
        );
2894
        $roleDraft = $roleService->addPolicyByRoleDraft(
2895
            $roleDraft,
2896
            $roleService->newPolicyCreateStruct('content', 'create')
2897
        );
2898
2899
        $roleService->publishRoleDraft($roleDraft);
2900
        /* END: Use Case */
2901
2902
        $this->assertInstanceOf(
2903
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\Role',
2904
            $roleService->loadRoleByIdentifier($roleCreate->identifier)
2905
        );
2906
    }
2907
2908
    /**
2909
     * Test for the publishRoleDraft() method.
2910
     *
2911
     * @see \eZ\Publish\API\Repository\RoleService::publishRoleDraft()
2912
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRoleDraft
2913
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicyByRoleDraft
2914
     */
2915 View Code Duplication
    public function testPublishRoleDraftAddPolicies()
2916
    {
2917
        $repository = $this->getRepository();
2918
2919
        /* BEGIN: Use Case */
2920
        $roleService = $repository->getRoleService();
2921
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
2922
2923
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
2924
        // $roleCreate->mainLanguageCode = 'eng-US';
2925
2926
        $roleDraft = $roleService->createRole($roleCreate);
2927
2928
        $roleDraft = $roleService->addPolicyByRoleDraft(
2929
            $roleDraft,
2930
            $roleService->newPolicyCreateStruct('content', 'delete')
2931
        );
2932
        $roleDraft = $roleService->addPolicyByRoleDraft(
2933
            $roleDraft,
2934
            $roleService->newPolicyCreateStruct('content', 'create')
2935
        );
2936
2937
        $roleService->publishRoleDraft($roleDraft);
2938
        $role = $roleService->loadRoleByIdentifier($roleCreate->identifier);
2939
        /* END: Use Case */
2940
2941
        $actual = array();
2942
        foreach ($role->getPolicies() as $policy) {
2943
            $actual[] = array(
2944
                'module' => $policy->module,
2945
                'function' => $policy->function,
2946
            );
2947
        }
2948
        usort(
2949
            $actual,
2950
            function ($p1, $p2) {
2951
                return strcasecmp($p1['function'], $p2['function']);
2952
            }
2953
        );
2954
2955
        $this->assertEquals(
2956
            array(
2957
                array(
2958
                    'module' => 'content',
2959
                    'function' => 'create',
2960
                ),
2961
                array(
2962
                    'module' => 'content',
2963
                    'function' => 'delete',
2964
                ),
2965
            ),
2966
            $actual
2967
        );
2968
    }
2969
2970
    /**
2971
     * Create a user group fixture in a variable named <b>$userGroup</b>,.
2972
     *
2973
     * @return \eZ\Publish\API\Repository\Values\User\UserGroup
2974
     */
2975
    private function createUserGroupVersion1()
2976
    {
2977
        $repository = $this->getRepository();
2978
2979
        $mainGroupId = $this->generateId('group', 4);
2980
        /* BEGIN: Inline */
2981
        // $mainGroupId is the ID of the main "Users" group
2982
2983
        $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...
2984
        $userService = $repository->getUserService();
2985
2986
        // Load main group
2987
        $parentUserGroup = $userService->loadUserGroup($mainGroupId);
2988
2989
        // Instantiate a new create struct
2990
        $userGroupCreate = $userService->newUserGroupCreateStruct('eng-US');
2991
        $userGroupCreate->setField('name', 'Example Group');
2992
2993
        // Create the new user group
2994
        $userGroup = $userService->createUserGroup(
2995
            $userGroupCreate,
2996
            $parentUserGroup
2997
        );
2998
        /* END: Inline */
2999
3000
        return $userGroup;
3001
    }
3002
}
3003