Completed
Push — ezp29559_uncomment_sleeping_ro... ( 4b5351...c00b69 )
by
unknown
28:12 queued 05:48
created

testGetRoleAssignmentsContainExpectedLimitation()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 1
dl 0
loc 7
rs 10
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\ContentTypeLimitation;
12
use eZ\Publish\API\Repository\Values\User\Limitation\LanguageLimitation;
13
use eZ\Publish\API\Repository\Values\User\Limitation\SubtreeLimitation;
14
use eZ\Publish\API\Repository\Exceptions\NotFoundException;
15
use Exception;
16
17
/**
18
 * Test case for operations in the RoleService using in memory storage.
19
 *
20
 * The following IDs from the default eZ community edition database are used in
21
 * this test:
22
 *
23
 * <ul>
24
 *   <li>
25
 *     ContentType
26
 *     <ul>
27
 *       <li><strong>28</strong>: File</li>
28
 *       <li><strong>29</strong>: Flash</li>
29
 *       <li><strong>30</strong>: Image</li>
30
 *     </ul>
31
 *   </li>
32
 * <ul>
33
 *
34
 * @see eZ\Publish\API\Repository\RoleService
35
 * @group role
36
 */
37
class RoleServiceTest extends BaseTest
38
{
39
    /**
40
     * Test for the newRoleCreateStruct() method.
41
     *
42
     * @see \eZ\Publish\API\Repository\RoleService::newRoleCreateStruct()
43
     */
44
    public function testNewRoleCreateStruct()
45
    {
46
        $repository = $this->getRepository();
47
48
        $roleService = $repository->getRoleService();
49
        $roleCreate = $roleService->newRoleCreateStruct('roleName');
50
51
        $this->assertInstanceOf('\\eZ\\Publish\\API\\Repository\\Values\\User\\RoleCreateStruct', $roleCreate);
52
    }
53
54
    /**
55
     * Test for the newRoleCreateStruct() method.
56
     *
57
     * @see \eZ\Publish\API\Repository\RoleService::newRoleCreateStruct()
58
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewRoleCreateStruct
59
     */
60
    public function testNewRoleCreateStructSetsNamePropertyOnStruct()
61
    {
62
        $repository = $this->getRepository();
63
64
        /* BEGIN: Use Case */
65
66
        $roleService = $repository->getRoleService();
67
        $roleCreate = $roleService->newRoleCreateStruct('roleName');
68
69
        /* END: Use Case */
70
71
        $this->assertEquals('roleName', $roleCreate->identifier);
72
    }
73
74
    /**
75
     * Test for the createRole() method.
76
     *
77
     * @see \eZ\Publish\API\Repository\RoleService::createRole()
78
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewRoleCreateStruct
79
     */
80
    public function testCreateRole()
81
    {
82
        $repository = $this->getRepository();
83
84
        /* BEGIN: Use Case */
85
86
        $roleService = $repository->getRoleService();
87
        $roleCreate = $roleService->newRoleCreateStruct('roleName');
88
89
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
90
        // $roleCreate->mainLanguageCode = 'eng-US';
91
92
        $role = $roleService->createRole($roleCreate);
93
94
        /* END: Use Case */
95
96
        $this->assertInstanceOf(
97
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\RoleDraft',
98
            $role
99
        );
100
101
        return [
102
            'createStruct' => $roleCreate,
103
            'role' => $role,
104
        ];
105
    }
106
107
    /**
108
     * Test for the createRole() method.
109
     *
110
     * @see \eZ\Publish\API\Repository\RoleService::createRole()
111
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRole
112
     */
113
    public function testRoleCreateStructValues(array $data)
114
    {
115
        $createStruct = $data['createStruct'];
116
        $role = $data['role'];
117
118
        $this->assertEquals(
119
            [
120
                'identifier' => $createStruct->identifier,
121
                'policies' => $createStruct->policies,
122
            ],
123
            [
124
                'identifier' => $role->identifier,
125
                'policies' => $role->policies,
126
            ]
127
        );
128
        $this->assertNotNull($role->id);
129
130
        return $data;
131
    }
132
133
    /**
134
     * Test for the createRole() method.
135
     *
136
     * @see \eZ\Publish\API\Repository\RoleService::createRole()
137
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewRoleCreateStruct
138
     */
139
    public function testCreateRoleWithPolicy()
140
    {
141
        $repository = $this->getRepository();
142
143
        /* BEGIN: Use Case */
144
145
        $roleService = $repository->getRoleService();
146
        $roleCreate = $roleService->newRoleCreateStruct('roleName');
147
148
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
149
        // $roleCreate->mainLanguageCode = 'eng-US';
150
151
        // Create new subtree limitation
152
        $limitation = new SubtreeLimitation(
153
            array(
154
                'limitationValues' => array('/1/2/'),
155
            )
156
        );
157
158
        // Create policy create struct and add limitation to it
159
        $policyCreate = $roleService->newPolicyCreateStruct('content', 'read');
160
        $policyCreate->addLimitation($limitation);
161
162
        // Add policy create struct to role create struct
163
        $roleCreate->addPolicy($policyCreate);
164
165
        $role = $roleService->createRole($roleCreate);
166
167
        /* END: Use Case */
168
169
        $this->assertInstanceOf(
170
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\RoleDraft',
171
            $role
172
        );
173
174
        return [
175
            'createStruct' => $roleCreate,
176
            'role' => $role,
177
        ];
178
    }
179
180
    /**
181
     * Test for the createRole() method.
182
     *
183
     * @see \eZ\Publish\API\Repository\RoleService::createRole()
184
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRoleWithPolicy
185
     */
186
    public function testRoleCreateStructValuesWithPolicy(array $data)
187
    {
188
        $createStruct = $data['createStruct'];
189
        $role = $data['role'];
190
191
        $this->assertEquals(
192
            [
193
                'identifier' => $createStruct->identifier,
194
                'policy_module' => $createStruct->policies[0]->module,
195
                'policy_function' => $createStruct->policies[0]->function,
196
                'policy_limitation' => array_values($createStruct->policies[0]->limitations),
197
            ],
198
            [
199
                'identifier' => $role->identifier,
200
                'policy_module' => $role->policies[0]->module,
201
                'policy_function' => $role->policies[0]->function,
202
                'policy_limitation' => array_values($role->policies[0]->limitations),
203
            ]
204
        );
205
        $this->assertNotNull($role->id);
206
207
        return $data;
208
    }
209
210
    /**
211
     * Test for the createRoleDraft() method.
212
     *
213
     * @see \eZ\Publish\API\Repository\RoleService::createRoleDraft()
214
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewRoleCreateStruct
215
     */
216 View Code Duplication
    public function testCreateRoleDraft()
217
    {
218
        $repository = $this->getRepository();
219
220
        /* BEGIN: Use Case */
221
222
        $roleService = $repository->getRoleService();
223
        $roleCreate = $roleService->newRoleCreateStruct('roleName');
224
225
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
226
        // $roleCreate->mainLanguageCode = 'eng-US';
227
228
        $roleDraft = $roleService->createRole($roleCreate);
229
        $roleService->addPolicyByRoleDraft(
230
            $roleDraft,
231
            $roleService->newPolicyCreateStruct('content', 'read')
232
        );
233
        $roleService->publishRoleDraft($roleDraft);
234
        $role = $roleService->loadRole($roleDraft->id);
235
        $newRoleDraft = $roleService->createRoleDraft($role);
236
237
        /* END: Use Case */
238
239
        $this->assertInstanceOf(
240
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\RoleDraft',
241
            $newRoleDraft
242
        );
243
    }
244
245
    /**
246
     * Test for the createRole() method.
247
     *
248
     * @see \eZ\Publish\API\Repository\RoleService::createRole()
249
     * @expectedException \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException
250
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRole
251
     */
252
    public function testCreateRoleThrowsInvalidArgumentException()
253
    {
254
        $repository = $this->getRepository();
255
256
        /* BEGIN: Use Case */
257
258
        $roleService = $repository->getRoleService();
259
        $roleCreate = $roleService->newRoleCreateStruct('Editor');
260
261
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
262
        // $roleCreate->mainLanguageCode = 'eng-US';
263
264
        // This call will fail with an InvalidArgumentException, because Editor exists
265
        $roleService->createRole($roleCreate);
266
267
        /* END: Use Case */
268
    }
269
270
    /**
271
     * Test for the createRoleDraft() method.
272
     *
273
     * @see \eZ\Publish\API\Repository\RoleService::createRoleDraft()
274
     * @expectedException \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException
275
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRoleDraft
276
     */
277 View Code Duplication
    public function testCreateRoleDraftThrowsInvalidArgumentException()
278
    {
279
        $repository = $this->getRepository();
280
281
        /* BEGIN: Use Case */
282
283
        $roleService = $repository->getRoleService();
284
        $roleCreate = $roleService->newRoleCreateStruct('Editor');
285
286
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
287
        // $roleCreate->mainLanguageCode = 'eng-US';
288
289
        $roleDraft = $roleService->createRole($roleCreate);
290
        $roleService->addPolicyByRoleDraft(
291
            $roleDraft,
292
            $roleService->newPolicyCreateStruct('content', 'read')
293
        );
294
        $roleService->publishRoleDraft($roleDraft);
295
        $role = $roleService->loadRole($roleDraft->id);
296
        $roleService->createRoleDraft($role); // First role draft
297
298
        // This call will fail with an InvalidArgumentException, because there is already a draft
299
        $roleService->createRoleDraft($role);
300
301
        /* END: Use Case */
302
    }
303
304
    /**
305
     * Test for the createRole() method.
306
     *
307
     * @see \eZ\Publish\API\Repository\RoleService::createRole()
308
     * @expectedException \eZ\Publish\API\Repository\Exceptions\LimitationValidationException
309
     */
310 View Code Duplication
    public function testCreateRoleThrowsLimitationValidationException()
311
    {
312
        $repository = $this->getRepository();
313
314
        /* BEGIN: Use Case */
315
        $roleService = $repository->getRoleService();
316
317
        // Create new role create struct
318
        $roleCreate = $roleService->newRoleCreateStruct('Lumberjack');
319
320
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
321
        // $roleCreate->mainLanguageCode = 'eng-US';
322
323
        // Create new subtree limitation
324
        $limitation = new SubtreeLimitation(
325
            array(
326
                'limitationValues' => array('/mountain/forest/tree/42/'),
327
            )
328
        );
329
330
        // Create policy create struct and add limitation to it
331
        $policyCreate = $roleService->newPolicyCreateStruct('content', 'remove');
332
        $policyCreate->addLimitation($limitation);
333
334
        // Add policy create struct to role create struct
335
        $roleCreate->addPolicy($policyCreate);
336
337
        // This call will fail with an LimitationValidationException, because subtree
338
        // "/mountain/forest/tree/42/" does not exist
339
        $roleService->createRole($roleCreate);
340
        /* END: Use Case */
341
    }
342
343
    /**
344
     * Test for the createRole() method.
345
     *
346
     * @see \eZ\Publish\API\Repository\RoleService::createRole()
347
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewRoleCreateStruct
348
     */
349
    public function testCreateRoleInTransactionWithRollback()
350
    {
351
        $repository = $this->getRepository();
352
353
        /* BEGIN: Use Case */
354
355
        $roleService = $repository->getRoleService();
356
357
        $repository->beginTransaction();
358
359
        $roleCreate = $roleService->newRoleCreateStruct('roleName');
360
361
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
362
        // $roleCreate->mainLanguageCode = 'eng-US';
363
364
        $createdRoleId = $roleService->createRole($roleCreate)->id;
365
366
        $repository->rollback();
367
368
        try {
369
            // This call will fail with a "NotFoundException"
370
            $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...
371
        } catch (NotFoundException $e) {
372
            return;
373
        }
374
        /* END: Use Case */
375
376
        $this->fail('Role object still exists after rollback.');
377
    }
378
379
    /**
380
     * Test for the createRoleDraft() method.
381
     *
382
     * @see \eZ\Publish\API\Repository\RoleService::createRoleDraft()
383
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewRoleCreateStruct
384
     */
385
    public function testCreateRoleDraftInTransactionWithRollback()
386
    {
387
        $repository = $this->getRepository();
388
389
        /* BEGIN: Use Case */
390
391
        $roleService = $repository->getRoleService();
392
393
        $repository->beginTransaction();
394
395
        $roleCreate = $roleService->newRoleCreateStruct('roleName');
396
397
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
398
        // $roleCreate->mainLanguageCode = 'eng-US';
399
400
        $createdRoleId = $roleService->createRole($roleCreate)->id;
401
402
        $repository->rollback();
403
404
        try {
405
            // This call will fail with a "NotFoundException"
406
            $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...
407
        } catch (NotFoundException $e) {
408
            return;
409
        }
410
        /* END: Use Case */
411
412
        $this->fail('Role draft object still exists after rollback.');
413
    }
414
415
    /**
416
     * Test for the loadRole() method.
417
     *
418
     * @see \eZ\Publish\API\Repository\RoleService::loadRole()
419
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRole
420
     */
421
    public function testLoadRole()
422
    {
423
        $repository = $this->getRepository();
424
425
        /* BEGIN: Use Case */
426
427
        $roleService = $repository->getRoleService();
428
        $roleCreate = $roleService->newRoleCreateStruct('roleName');
429
430
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
431
        // $roleCreate->mainLanguageCode = 'eng-US';
432
433
        $roleDraft = $roleService->createRole($roleCreate);
434
        $roleService->addPolicyByRoleDraft(
435
            $roleDraft,
436
            $roleService->newPolicyCreateStruct('content', 'read')
437
        );
438
        $roleService->publishRoleDraft($roleDraft);
439
440
        // Load the newly created role by its ID
441
        $role = $roleService->loadRole($roleDraft->id);
442
443
        /* END: Use Case */
444
445
        $this->assertEquals('roleName', $role->identifier);
446
    }
447
448
    /**
449
     * Test for the loadRoleDraft() method.
450
     *
451
     * @see \eZ\Publish\API\Repository\RoleService::loadRoleDraft()
452
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRoleDraft
453
     */
454
    public function testLoadRoleDraft()
455
    {
456
        $repository = $this->getRepository();
457
458
        /* BEGIN: Use Case */
459
460
        $roleService = $repository->getRoleService();
461
        $roleCreate = $roleService->newRoleCreateStruct('roleName');
462
463
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
464
        // $roleCreate->mainLanguageCode = 'eng-US';
465
466
        $roleDraft = $roleService->createRole($roleCreate);
467
468
        // Load the newly created role by its ID
469
        $role = $roleService->loadRoleDraft($roleDraft->id);
470
471
        /* END: Use Case */
472
473
        $this->assertEquals('roleName', $role->identifier);
474
    }
475
476
    public function testLoadRoleDraftByRoleId()
477
    {
478
        $repository = $this->getRepository();
479
480
        /* BEGIN: Use Case */
481
482
        $roleService = $repository->getRoleService();
483
        $roleCreate = $roleService->newRoleCreateStruct('roleName');
484
485
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
486
        // $roleCreate->mainLanguageCode = 'eng-US';
487
488
        $role = $roleService->createRole($roleCreate);
489
        $roleService->addPolicyByRoleDraft(
490
            $role,
491
            $roleService->newPolicyCreateStruct('content', 'read')
492
        );
493
        $roleService->publishRoleDraft($role);
494
495
        // Now create a new draft based on the role
496
        $newDraft = $roleService->createRoleDraft($role);
497
        $loadedRoleDraft = $roleService->loadRoleDraftByRoleId($role->id);
498
499
        /* END: Use Case */
500
501
        self::assertEquals('roleName', $role->identifier);
502
        self::assertInstanceOf('eZ\Publish\API\Repository\Values\User\RoleDraft', $loadedRoleDraft);
503
        self::assertEquals($newDraft, $loadedRoleDraft);
504
    }
505
506
    /**
507
     * Test for the loadRole() method.
508
     *
509
     * @see \eZ\Publish\API\Repository\RoleService::loadRole()
510
     * @expectedException \eZ\Publish\API\Repository\Exceptions\NotFoundException
511
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRole
512
     */
513 View Code Duplication
    public function testLoadRoleThrowsNotFoundException()
514
    {
515
        $repository = $this->getRepository();
516
517
        $nonExistingRoleId = $this->generateId('role', self::DB_INT_MAX);
518
        /* BEGIN: Use Case */
519
520
        $roleService = $repository->getRoleService();
521
522
        // This call will fail with a NotFoundException, because no such role exists.
523
        $roleService->loadRole($nonExistingRoleId);
524
525
        /* END: Use Case */
526
    }
527
528
    /**
529
     * Test for the loadRoleDraft() method.
530
     *
531
     * @see \eZ\Publish\API\Repository\RoleService::loadRoleDraft()
532
     * @expectedException \eZ\Publish\API\Repository\Exceptions\NotFoundException
533
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleDraft
534
     */
535 View Code Duplication
    public function testLoadRoleDraftThrowsNotFoundException()
536
    {
537
        $repository = $this->getRepository();
538
539
        $nonExistingRoleId = $this->generateId('role', self::DB_INT_MAX);
540
        /* BEGIN: Use Case */
541
542
        $roleService = $repository->getRoleService();
543
544
        // This call will fail with a NotFoundException, because no such role exists.
545
        $roleService->loadRoleDraft($nonExistingRoleId);
546
547
        /* END: Use Case */
548
    }
549
550
    /**
551
     * @expectedException \eZ\Publish\API\Repository\Exceptions\NotFoundException
552
     */
553 View Code Duplication
    public function testLoadRoleDraftByRoleIdThrowsNotFoundException()
554
    {
555
        $repository = $this->getRepository();
556
557
        $nonExistingRoleId = $this->generateId('role', self::DB_INT_MAX);
558
        /* BEGIN: Use Case */
559
560
        $roleService = $repository->getRoleService();
561
562
        // This call will fail with a NotFoundException, because no such role exists.
563
        $roleService->loadRoleDraftByRoleId($nonExistingRoleId);
564
565
        /* END: Use Case */
566
    }
567
568
    /**
569
     * Test for the loadRoleByIdentifier() method.
570
     *
571
     * @see \eZ\Publish\API\Repository\RoleService::loadRoleByIdentifier()
572
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRole
573
     */
574
    public function testLoadRoleByIdentifier()
575
    {
576
        $repository = $this->getRepository();
577
578
        /* BEGIN: Use Case */
579
580
        $roleService = $repository->getRoleService();
581
        $roleCreate = $roleService->newRoleCreateStruct('roleName');
582
583
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
584
        // $roleCreate->mainLanguageCode = 'eng-US';
585
586
        $roleDraft = $roleService->createRole($roleCreate);
587
        $roleService->addPolicyByRoleDraft(
588
            $roleDraft,
589
            $roleService->newPolicyCreateStruct('content', 'read')
590
        );
591
        $roleService->publishRoleDraft($roleDraft);
592
593
        // Load the newly created role by its identifier
594
        $role = $roleService->loadRoleByIdentifier('roleName');
595
596
        /* END: Use Case */
597
598
        $this->assertEquals('roleName', $role->identifier);
599
    }
600
601
    /**
602
     * Test for the loadRoleByIdentifier() method.
603
     *
604
     * @see \eZ\Publish\API\Repository\RoleService::loadRoleByIdentifier()
605
     * @expectedException \eZ\Publish\API\Repository\Exceptions\NotFoundException
606
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleByIdentifier
607
     */
608
    public function testLoadRoleByIdentifierThrowsNotFoundException()
609
    {
610
        $repository = $this->getRepository();
611
612
        /* BEGIN: Use Case */
613
614
        $roleService = $repository->getRoleService();
615
616
        // This call will fail with a NotFoundException, because no such role exists.
617
        $roleService->loadRoleByIdentifier('MissingRole');
618
619
        /* END: Use Case */
620
    }
621
622
    /**
623
     * Test for the loadRoles() method.
624
     *
625
     * @see \eZ\Publish\API\Repository\RoleService::loadRoles()
626
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRole
627
     */
628
    public function testLoadRoles()
629
    {
630
        $repository = $this->getRepository();
631
632
        /* BEGIN: Use Case */
633
634
        // First create a custom role
635
        $roleService = $repository->getRoleService();
636
        $roleCreate = $roleService->newRoleCreateStruct('roleName');
637
638
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
639
        // $roleCreate->mainLanguageCode = 'eng-US';
640
641
        $roleDraft = $roleService->createRole($roleCreate);
642
        $roleService->addPolicyByRoleDraft(
643
            $roleDraft,
644
            $roleService->newPolicyCreateStruct('content', 'read')
645
        );
646
        $roleService->publishRoleDraft($roleDraft);
647
648
        // Now load all available roles
649
        $roles = $roleService->loadRoles();
650
651
        foreach ($roles as $role) {
652
            if ($role->identifier === 'roleName') {
653
                break;
654
            }
655
        }
656
657
        /* END: Use Case */
658
659
        $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 651. 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...
660
    }
661
662
    /**
663
     * Test for the loadRoles() method.
664
     *
665
     * @see \eZ\Publish\API\Repository\RoleService::loadRoles()
666
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoles
667
     */
668
    public function testLoadRolesReturnsExpectedSetOfDefaultRoles()
669
    {
670
        $repository = $this->getRepository();
671
672
        /* BEGIN: Use Case */
673
        $roleService = $repository->getRoleService();
674
675
        $roles = $roleService->loadRoles();
676
677
        $roleNames = array();
678
        foreach ($roles as $role) {
679
            $roleNames[] = $role->identifier;
680
        }
681
        /* END: Use Case */
682
683
        sort($roleNames);
684
685
        $this->assertEquals(
686
            array(
687
                'Administrator',
688
                'Anonymous',
689
                'Editor',
690
                'Member',
691
                'Partner',
692
            ),
693
            $roleNames
694
        );
695
    }
696
697
    /**
698
     * Test for the newRoleUpdateStruct() method.
699
     *
700
     * @see \eZ\Publish\API\Repository\RoleService::newRoleUpdateStruct()
701
     */
702
    public function testNewRoleUpdateStruct()
703
    {
704
        $repository = $this->getRepository();
705
706
        /* BEGIN: Use Case */
707
        $roleService = $repository->getRoleService();
708
        $roleUpdate = $roleService->newRoleUpdateStruct('newRole');
709
        /* END: Use Case */
710
711
        $this->assertInstanceOf('\\eZ\\Publish\\API\\Repository\\Values\\User\\RoleUpdateStruct', $roleUpdate);
712
    }
713
714
    /**
715
     * Test for the updateRole() method.
716
     *
717
     * @see \eZ\Publish\API\Repository\RoleService::updateRole()
718
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewRoleUpdateStruct
719
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleByIdentifier
720
     */
721
    public function testUpdateRole()
722
    {
723
        $repository = $this->getRepository();
724
725
        /* BEGIN: Use Case */
726
        $roleService = $repository->getRoleService();
727
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
728
729
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
730
        // $roleCreate->mainLanguageCode = 'eng-US';
731
732
        $roleDraft = $roleService->createRole($roleCreate);
733
        $roleService->addPolicyByRoleDraft(
734
            $roleDraft,
735
            $roleService->newPolicyCreateStruct('content', 'read')
736
        );
737
        $roleService->publishRoleDraft($roleDraft);
738
        $role = $roleService->loadRole($roleDraft->id);
739
740
        $roleUpdate = $roleService->newRoleUpdateStruct();
741
        $roleUpdate->identifier = 'updatedRole';
742
743
        $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...
744
        /* END: Use Case */
745
746
        // Now verify that our change was saved
747
        $role = $roleService->loadRoleByIdentifier('updatedRole');
748
749
        $this->assertEquals($role->id, $updatedRole->id);
750
    }
751
752
    /**
753
     * Test for the updateRoleDraft() method.
754
     *
755
     * @see \eZ\Publish\API\Repository\RoleService::updateRoleDraft()
756
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewRoleUpdateStruct
757
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleDraft
758
     */
759
    public function testUpdateRoleDraft()
760
    {
761
        $repository = $this->getRepository();
762
763
        /* BEGIN: Use Case */
764
        $roleService = $repository->getRoleService();
765
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
766
767
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
768
        // $roleCreate->mainLanguageCode = 'eng-US';
769
770
        $roleDraft = $roleService->createRole($roleCreate);
771
772
        $roleUpdate = $roleService->newRoleUpdateStruct();
773
        $roleUpdate->identifier = 'updatedRole';
774
775
        $updatedRole = $roleService->updateRoleDraft($roleDraft, $roleUpdate);
776
        /* END: Use Case */
777
778
        // Now verify that our change was saved
779
        $role = $roleService->loadRoleDraft($updatedRole->id);
780
781
        $this->assertEquals($role->identifier, 'updatedRole');
782
    }
783
784
    /**
785
     * Test for the updateRole() method.
786
     *
787
     * @see \eZ\Publish\API\Repository\RoleService::updateRole()
788
     * @expectedException \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException
789
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testUpdateRole
790
     */
791 View Code Duplication
    public function testUpdateRoleThrowsInvalidArgumentException()
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->addPolicyByRoleDraft(
804
            $roleDraft,
805
            $roleService->newPolicyCreateStruct('content', 'read')
806
        );
807
        $roleService->publishRoleDraft($roleDraft);
808
        $role = $roleService->loadRole($roleDraft->id);
809
810
        $roleUpdate = $roleService->newRoleUpdateStruct();
811
        $roleUpdate->identifier = 'Editor';
812
813
        // This call will fail with an InvalidArgumentException, because Editor is a predefined role
814
        $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...
815
        /* END: Use Case */
816
    }
817
818
    /**
819
     * Test for the updateRoleDraft() method.
820
     *
821
     * @see \eZ\Publish\API\Repository\RoleService::updateRoleDraft()
822
     * @expectedException \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException
823
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testUpdateRoleDraft
824
     */
825
    public function testUpdateRoleDraftThrowsInvalidArgumentException()
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 = 'Editor';
840
841
        // This call will fail with an InvalidArgumentException, because Editor is a predefined role
842
        $roleService->updateRoleDraft($roleDraft, $roleUpdate);
843
        /* END: Use Case */
844
    }
845
846
    /**
847
     * Test for the deleteRole() method.
848
     *
849
     * @see \eZ\Publish\API\Repository\RoleService::deleteRole()
850
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRole
851
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoles
852
     */
853 View Code Duplication
    public function testDeleteRole()
854
    {
855
        $repository = $this->getRepository();
856
857
        /* BEGIN: Use Case */
858
        $roleService = $repository->getRoleService();
859
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
860
861
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
862
        // $roleCreate->mainLanguageCode = 'eng-US';
863
864
        $roleDraft = $roleService->createRole($roleCreate);
865
        $roleService->addPolicyByRoleDraft(
866
            $roleDraft,
867
            $roleService->newPolicyCreateStruct('content', 'read')
868
        );
869
        $roleService->publishRoleDraft($roleDraft);
870
        $role = $roleService->loadRole($roleDraft->id);
871
872
        $roleService->deleteRole($role);
873
        /* END: Use Case */
874
875
        $this->assertEquals(5, count($roleService->loadRoles()));
876
    }
877
878
    /**
879
     * Test for the deleteRoleDraft() method.
880
     *
881
     * @see \eZ\Publish\API\Repository\RoleService::deleteRoleDraft()
882
     * @expectedException \eZ\Publish\API\Repository\Exceptions\NotFoundException
883
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleDraft
884
     */
885
    public function testDeleteRoleDraft()
886
    {
887
        $repository = $this->getRepository();
888
889
        /* BEGIN: Use Case */
890
        $roleService = $repository->getRoleService();
891
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
892
893
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
894
        // $roleCreate->mainLanguageCode = 'eng-US';
895
896
        $roleDraft = $roleService->createRole($roleCreate);
897
        $roleID = $roleDraft->id;
898
        $roleService->deleteRoleDraft($roleDraft);
899
900
        // This call will fail with a NotFoundException, because the draft no longer exists
901
        $roleService->loadRoleDraft($roleID);
902
        /* END: Use Case */
903
    }
904
905
    /**
906
     * Test for the newPolicyCreateStruct() method.
907
     *
908
     * @see \eZ\Publish\API\Repository\RoleService::newPolicyCreateStruct()
909
     */
910
    public function testNewPolicyCreateStruct()
911
    {
912
        $repository = $this->getRepository();
913
914
        /* BEGIN: Use Case */
915
        $roleService = $repository->getRoleService();
916
        $policyCreate = $roleService->newPolicyCreateStruct('content', 'create');
917
        /* END: Use Case */
918
919
        $this->assertInstanceOf('\\eZ\\Publish\\API\\Repository\\Values\\User\\PolicyCreateStruct', $policyCreate);
920
    }
921
922
    /**
923
     * Test for the newPolicyCreateStruct() method.
924
     *
925
     * @see \eZ\Publish\API\Repository\RoleService::newPolicyCreateStruct()
926
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewPolicyCreateStruct
927
     */
928
    public function testNewPolicyCreateStructSetsStructProperties()
929
    {
930
        $repository = $this->getRepository();
931
932
        /* BEGIN: Use Case */
933
        $roleService = $repository->getRoleService();
934
        $policyCreate = $roleService->newPolicyCreateStruct('content', 'create');
935
        /* END: Use Case */
936
937
        $this->assertEquals(
938
            array('content', 'create'),
939
            array($policyCreate->module, $policyCreate->function)
940
        );
941
    }
942
943
    /**
944
     * Test for the addPolicy() method.
945
     *
946
     * @see \eZ\Publish\API\Repository\RoleService::addPolicy()
947
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleByIdentifier
948
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewPolicyCreateStruct
949
     */
950 View Code Duplication
    public function testAddPolicy()
951
    {
952
        $repository = $this->getRepository();
953
954
        /* BEGIN: Use Case */
955
        $roleService = $repository->getRoleService();
956
957
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
958
959
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
960
        // $roleCreate->mainLanguageCode = 'eng-US';
961
962
        $roleDraft = $roleService->createRole($roleCreate);
963
        $roleService->addPolicyByRoleDraft(
964
            $roleDraft,
965
            $roleService->newPolicyCreateStruct('content', 'delete')
966
        );
967
        $roleService->publishRoleDraft($roleDraft);
968
        $role = $roleService->loadRole($roleDraft->id);
969
970
        $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...
971
            $role,
972
            $roleService->newPolicyCreateStruct('content', 'create')
973
        );
974
        /* END: Use Case */
975
976
        $actual = array();
977
        foreach ($role->getPolicies() as $policy) {
978
            $actual[] = array(
979
                'module' => $policy->module,
980
                'function' => $policy->function,
981
            );
982
        }
983
        usort(
984
            $actual,
985
            function ($p1, $p2) {
986
                return strcasecmp($p1['function'], $p2['function']);
987
            }
988
        );
989
990
        $this->assertEquals(
991
            array(
992
                array(
993
                    'module' => 'content',
994
                    'function' => 'create',
995
                ),
996
                array(
997
                    'module' => 'content',
998
                    'function' => 'delete',
999
                ),
1000
            ),
1001
            $actual
1002
        );
1003
    }
1004
1005
    /**
1006
     * Test for the addPolicyByRoleDraft() method.
1007
     *
1008
     * @see \eZ\Publish\API\Repository\RoleService::addPolicyByRoleDraft()
1009
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRoleDraft
1010
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewPolicyCreateStruct
1011
     */
1012
    public function testAddPolicyByRoleDraft()
1013
    {
1014
        $repository = $this->getRepository();
1015
1016
        /* BEGIN: Use Case */
1017
        $roleService = $repository->getRoleService();
1018
1019
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
1020
1021
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1022
        // $roleCreate->mainLanguageCode = 'eng-US';
1023
1024
        $roleDraft = $roleService->createRole($roleCreate);
1025
1026
        $roleDraft = $roleService->addPolicyByRoleDraft(
1027
            $roleDraft,
1028
            $roleService->newPolicyCreateStruct('content', 'delete')
1029
        );
1030
        $roleDraft = $roleService->addPolicyByRoleDraft(
1031
            $roleDraft,
1032
            $roleService->newPolicyCreateStruct('content', 'create')
1033
        );
1034
        /* END: Use Case */
1035
1036
        $actual = array();
1037 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...
1038
            $actual[] = array(
1039
                'module' => $policy->module,
1040
                'function' => $policy->function,
1041
            );
1042
        }
1043
        usort(
1044
            $actual,
1045
            function ($p1, $p2) {
1046
                return strcasecmp($p1['function'], $p2['function']);
1047
            }
1048
        );
1049
1050
        $this->assertEquals(
1051
            array(
1052
                array(
1053
                    'module' => 'content',
1054
                    'function' => 'create',
1055
                ),
1056
                array(
1057
                    'module' => 'content',
1058
                    'function' => 'delete',
1059
                ),
1060
            ),
1061
            $actual
1062
        );
1063
    }
1064
1065
    /**
1066
     * Test for the addPolicy() method.
1067
     *
1068
     * @return array [\eZ\Publish\API\Repository\Values\User\Role, \eZ\Publish\API\Repository\Values\User\Policy]
1069
     *
1070
     * @see \eZ\Publish\API\Repository\RoleService::addPolicy()
1071
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicy
1072
     */
1073
    public function testAddPolicyUpdatesRole()
1074
    {
1075
        $repository = $this->getRepository();
1076
1077
        /* BEGIN: Use Case */
1078
        $roleService = $repository->getRoleService();
1079
1080
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
1081
1082
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1083
        // $roleCreate->mainLanguageCode = 'eng-US';
1084
1085
        $roleDraft = $roleService->createRole($roleCreate);
1086
        $roleService->addPolicyByRoleDraft(
1087
            $roleDraft,
1088
            $roleService->newPolicyCreateStruct('content', 'read')
1089
        );
1090
        $roleService->publishRoleDraft($roleDraft);
1091
        $role = $roleService->loadRole($roleDraft->id);
1092
1093
        $policyCreate = $roleService->newPolicyCreateStruct('content', 'create');
1094
        $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...
1095
1096
        $policy = null;
1097
        foreach ($role->getPolicies() as $policy) {
1098
            if ($policy->module === 'content' && $policy->function === 'create') {
1099
                break;
1100
            }
1101
        }
1102
        /* END: Use Case */
1103
1104
        $this->assertInstanceOf(
1105
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\Policy',
1106
            $policy
1107
        );
1108
1109
        return array($role, $policy);
1110
    }
1111
1112
    /**
1113
     * Test for the addPolicyByRoleDraft() method.
1114
     *
1115
     * @return array [\eZ\Publish\API\Repository\Values\User\RoleDraft, \eZ\Publish\API\Repository\Values\User\Policy]
1116
     *
1117
     * @see \eZ\Publish\API\Repository\RoleService::addPolicyByRoleDraft()
1118
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicyByRoleDraft
1119
     */
1120
    public function testAddPolicyByRoleDraftUpdatesRole()
1121
    {
1122
        $repository = $this->getRepository();
1123
1124
        /* BEGIN: Use Case */
1125
        $roleService = $repository->getRoleService();
1126
1127
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
1128
1129
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1130
        // $roleCreate->mainLanguageCode = 'eng-US';
1131
1132
        $roleDraft = $roleService->createRole($roleCreate);
1133
1134
        $policyCreate = $roleService->newPolicyCreateStruct('content', 'create');
1135
        $roleDraft = $roleService->addPolicyByRoleDraft($roleDraft, $policyCreate);
1136
1137
        $policy = null;
1138
        foreach ($roleDraft->getPolicies() as $policy) {
1139
            if ($policy->module === 'content' && $policy->function === 'create') {
1140
                break;
1141
            }
1142
        }
1143
        /* END: Use Case */
1144
1145
        $this->assertInstanceOf(
1146
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\Policy',
1147
            $policy
1148
        );
1149
1150
        return array($roleDraft, $policy);
1151
    }
1152
1153
    /**
1154
     * Test for the addPolicy() method.
1155
     *
1156
     * @param array $roleAndPolicy
1157
     *
1158
     * @see \eZ\Publish\API\Repository\RoleService::addPolicy()
1159
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicyUpdatesRole
1160
     */
1161 View Code Duplication
    public function testAddPolicySetsPolicyProperties($roleAndPolicy)
1162
    {
1163
        list($role, $policy) = $roleAndPolicy;
1164
1165
        $this->assertEquals(
1166
            array($role->id, 'content', 'create'),
1167
            array($policy->roleId, $policy->module, $policy->function)
1168
        );
1169
    }
1170
1171
    /**
1172
     * Test for the addPolicyByRoleDraft() method.
1173
     *
1174
     * @param array $roleAndPolicy
1175
     *
1176
     * @see \eZ\Publish\API\Repository\RoleService::addPolicyByRoleDraft()
1177
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicyByRoleDraftUpdatesRole
1178
     */
1179 View Code Duplication
    public function testAddPolicyByRoleDraftSetsPolicyProperties($roleAndPolicy)
1180
    {
1181
        list($role, $policy) = $roleAndPolicy;
1182
1183
        $this->assertEquals(
1184
            array($role->id, 'content', 'create'),
1185
            array($policy->roleId, $policy->module, $policy->function)
1186
        );
1187
    }
1188
1189
    /**
1190
     * Test for the publishRoleDraft() method.
1191
     *
1192
     * @expectedException \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException
1193
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRole
1194
     */
1195 View Code Duplication
    public function testPublishEmptyRoleThrowsInvalidArgumentException()
1196
    {
1197
        $repository = $this->getRepository();
1198
1199
        /* BEGIN: Use Case */
1200
        $roleService = $repository->getRoleService();
1201
1202
        $roleCreate = $roleService->newRoleCreateStruct('Lumberjack');
1203
1204
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1205
        // $roleCreate->mainLanguageCode = 'eng-US';
1206
1207
        $roleDraft = $roleService->createRole($roleCreate);
1208
        // This call will fail with an InvalidArgumentException, because the role has no policies
1209
        $roleService->publishRoleDraft($roleDraft);
1210
        /* END: Use Case */
1211
    }
1212
1213
    /**
1214
     * Test for the addPolicy() method.
1215
     *
1216
     * @see \eZ\Publish\API\Repository\RoleService::addPolicy()
1217
     * @expectedException \eZ\Publish\API\Repository\Exceptions\LimitationValidationException
1218
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewPolicyCreateStruct
1219
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRole
1220
     */
1221
    public function testAddPolicyThrowsLimitationValidationException()
1222
    {
1223
        $repository = $this->getRepository();
1224
1225
        /* BEGIN: Use Case */
1226
        $roleService = $repository->getRoleService();
1227
1228
        $roleCreate = $roleService->newRoleCreateStruct('Lumberjack');
1229
1230
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1231
        // $roleCreate->mainLanguageCode = 'eng-US';
1232
1233
        $roleDraft = $roleService->createRole($roleCreate);
1234
        $roleService->addPolicyByRoleDraft(
1235
            $roleDraft,
1236
            $roleService->newPolicyCreateStruct('content', 'create')
1237
        );
1238
1239
        $roleService->publishRoleDraft($roleDraft);
1240
        $role = $roleService->loadRole($roleDraft->id);
1241
1242
        // Create new subtree limitation
1243
        $limitation = new SubtreeLimitation(
1244
            array(
1245
                'limitationValues' => array('/mountain/forest/tree/42/'),
1246
            )
1247
        );
1248
1249
        // Create policy create struct and add limitation to it
1250
        $policyCreateStruct = $roleService->newPolicyCreateStruct('content', 'remove');
1251
        $policyCreateStruct->addLimitation($limitation);
1252
1253
        // This call will fail with an LimitationValidationException, because subtree
1254
        // "/mountain/forest/tree/42/" does not exist
1255
        $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...
1256
        /* END: Use Case */
1257
    }
1258
1259
    /**
1260
     * Test for the addPolicyByRoleDraft() method.
1261
     *
1262
     * @see \eZ\Publish\API\Repository\RoleService::addPolicyByRoleDraft()
1263
     * @expectedException \eZ\Publish\API\Repository\Exceptions\LimitationValidationException
1264
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewPolicyCreateStruct
1265
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRoleDraft
1266
     */
1267 View Code Duplication
    public function testAddPolicyByRoleDraftThrowsLimitationValidationException()
1268
    {
1269
        $repository = $this->getRepository();
1270
1271
        /* BEGIN: Use Case */
1272
        $roleService = $repository->getRoleService();
1273
1274
        $roleCreate = $roleService->newRoleCreateStruct('Lumberjack');
1275
1276
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1277
        // $roleCreate->mainLanguageCode = 'eng-US';
1278
1279
        $roleDraft = $roleService->createRole($roleCreate);
1280
1281
        // Create new subtree limitation
1282
        $limitation = new SubtreeLimitation(
1283
            array(
1284
                'limitationValues' => array('/mountain/forest/tree/42/'),
1285
            )
1286
        );
1287
1288
        // Create policy create struct and add limitation to it
1289
        $policyCreateStruct = $roleService->newPolicyCreateStruct('content', 'remove');
1290
        $policyCreateStruct->addLimitation($limitation);
1291
1292
        // This call will fail with an LimitationValidationException, because subtree
1293
        // "/mountain/forest/tree/42/" does not exist
1294
        $roleService->addPolicyByRoleDraft($roleDraft, $policyCreateStruct);
1295
        /* END: Use Case */
1296
    }
1297
1298
    /**
1299
     * Test for the createRole() method.
1300
     *
1301
     * @see \eZ\Publish\API\Repository\RoleService::createRole()
1302
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicyUpdatesRole
1303
     */
1304
    public function testCreateRoleWithAddPolicy()
1305
    {
1306
        $repository = $this->getRepository();
1307
1308
        /* BEGIN: Use Case */
1309
        $roleService = $repository->getRoleService();
1310
1311
        // Instantiate a new create struct
1312
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
1313
1314
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1315
        // $roleCreate->mainLanguageCode = 'eng-US';
1316
1317
        // Add some role policies
1318
        $roleCreate->addPolicy(
1319
            $roleService->newPolicyCreateStruct(
1320
                'content',
1321
                'read'
1322
            )
1323
        );
1324
        $roleCreate->addPolicy(
1325
            $roleService->newPolicyCreateStruct(
1326
                'content',
1327
                'translate'
1328
            )
1329
        );
1330
1331
        // Create new role instance
1332
        $roleDraft = $roleService->createRole($roleCreate);
1333
        $roleService->publishRoleDraft($roleDraft);
1334
        $role = $roleService->loadRole($roleDraft->id);
1335
1336
        $policies = array();
1337 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...
1338
            $policies[] = array('module' => $policy->module, 'function' => $policy->function);
1339
        }
1340
        /* END: Use Case */
1341
        array_multisort($policies);
1342
1343
        $this->assertEquals(
1344
            array(
1345
                array(
1346
                    'module' => 'content',
1347
                    'function' => 'read',
1348
                ),
1349
                array(
1350
                    'module' => 'content',
1351
                    'function' => 'translate',
1352
                ),
1353
            ),
1354
            $policies
1355
        );
1356
    }
1357
1358
    /**
1359
     * Test for the createRoleDraft() method.
1360
     *
1361
     * @see \eZ\Publish\API\Repository\RoleService::createRoleDraft()
1362
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicyByRoleDraftUpdatesRole
1363
     */
1364
    public function testCreateRoleDraftWithAddPolicy()
1365
    {
1366
        $repository = $this->getRepository();
1367
1368
        /* BEGIN: Use Case */
1369
        $roleService = $repository->getRoleService();
1370
1371
        // Instantiate a new create struct
1372
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
1373
1374
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1375
        // $roleCreate->mainLanguageCode = 'eng-US';
1376
1377
        // Add some role policies
1378
        $roleCreate->addPolicy(
1379
            $roleService->newPolicyCreateStruct(
1380
                'content',
1381
                'read'
1382
            )
1383
        );
1384
        $roleCreate->addPolicy(
1385
            $roleService->newPolicyCreateStruct(
1386
                'content',
1387
                'translate'
1388
            )
1389
        );
1390
1391
        // Create new role instance
1392
        $roleDraft = $roleService->createRole($roleCreate);
1393
1394
        $policies = array();
1395 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...
1396
            $policies[] = array('module' => $policy->module, 'function' => $policy->function);
1397
        }
1398
        /* END: Use Case */
1399
1400
        $this->assertEquals(
1401
            array(
1402
                array(
1403
                    'module' => 'content',
1404
                    'function' => 'read',
1405
                ),
1406
                array(
1407
                    'module' => 'content',
1408
                    'function' => 'translate',
1409
                ),
1410
            ),
1411
            $policies
1412
        );
1413
    }
1414
1415
    /**
1416
     * Test for the newPolicyUpdateStruct() method.
1417
     *
1418
     * @see \eZ\Publish\API\Repository\RoleService::newPolicyUpdateStruct()
1419
     */
1420
    public function testNewPolicyUpdateStruct()
1421
    {
1422
        $repository = $this->getRepository();
1423
1424
        /* BEGIN: Use Case */
1425
        $roleService = $repository->getRoleService();
1426
        $policyUpdate = $roleService->newPolicyUpdateStruct();
1427
        /* END: Use Case */
1428
1429
        $this->assertInstanceOf(
1430
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\PolicyUpdateStruct',
1431
            $policyUpdate
1432
        );
1433
    }
1434
1435
    public function testUpdatePolicyNoLimitation()
1436
    {
1437
        $repository = $this->getRepository();
1438
1439
        /* BEGIN: Use Case */
1440
        $roleService = $repository->getRoleService();
1441
1442
        // Instantiate new policy create
1443
        $policyCreate = $roleService->newPolicyCreateStruct('foo', 'bar');
1444
1445
        // Instantiate a role create and add the policy create
1446
        $roleCreate = $roleService->newRoleCreateStruct('myRole');
1447
1448
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1449
        // $roleCreate->mainLanguageCode = 'eng-US';
1450
1451
        $roleCreate->addPolicy($policyCreate);
1452
1453
        // Create a new role instance.
1454
        $roleDraft = $roleService->createRole($roleCreate);
1455
        $roleService->publishRoleDraft($roleDraft);
1456
        $role = $roleService->loadRole($roleDraft->id);
1457
1458
        // Search for the new policy instance
1459
        $policy = null;
1460
        foreach ($role->getPolicies() as $policy) {
1461
            if ($policy->module === 'foo' && $policy->function === 'bar') {
1462
                break;
1463
            }
1464
        }
1465
1466
        // Create an update struct
1467
        $policyUpdate = $roleService->newPolicyUpdateStruct();
1468
1469
        // Update the the policy
1470
        $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...
1471
        /* END: Use Case */
1472
1473
        $this->assertInstanceOf(
1474
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\Policy',
1475
            $policy
1476
        );
1477
1478
        self::assertEquals(array(), $policy->getLimitations());
1479
    }
1480
1481
    /**
1482
     * Test for the updatePolicy() method.
1483
     *
1484
     * @return array
1485
     *
1486
     * @see \eZ\Publish\API\Repository\RoleService::updatePolicy()
1487
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicy
1488
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewPolicyUpdateStruct
1489
     */
1490
    public function testUpdatePolicy()
1491
    {
1492
        $repository = $this->getRepository();
1493
1494
        /* BEGIN: Use Case */
1495
        $roleService = $repository->getRoleService();
1496
1497
        // Instantiate new policy create
1498
        $policyCreate = $roleService->newPolicyCreateStruct('content', 'translate');
1499
1500
        // Add some limitations for the new policy
1501
        $policyCreate->addLimitation(
1502
            new LanguageLimitation(
1503
                array(
1504
                    'limitationValues' => array('eng-US', 'eng-GB'),
1505
                )
1506
            )
1507
        );
1508
1509
        // Instantiate a role create and add the policy create
1510
        $roleCreate = $roleService->newRoleCreateStruct('myRole');
1511
1512
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1513
        // $roleCreate->mainLanguageCode = 'eng-US';
1514
1515
        $roleCreate->addPolicy($policyCreate);
1516
1517
        // Create a new role instance.
1518
        $roleDraft = $roleService->createRole($roleCreate);
1519
        $roleService->publishRoleDraft($roleDraft);
1520
        $role = $roleService->loadRole($roleDraft->id);
1521
1522
        // Search for the new policy instance
1523
        $policy = null;
1524
        foreach ($role->getPolicies() as $policy) {
1525
            if ($policy->module === 'content' && $policy->function === 'translate') {
1526
                break;
1527
            }
1528
        }
1529
1530
        // Create an update struct and set a modified limitation
1531
        $policyUpdate = $roleService->newPolicyUpdateStruct();
1532
        $policyUpdate->addLimitation(
1533
            new ContentTypeLimitation(
1534
                array(
1535
                    'limitationValues' => array(29, 30),
1536
                )
1537
            )
1538
        );
1539
1540
        // Update the the policy
1541
        $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...
1542
        /* END: Use Case */
1543
1544
        $this->assertInstanceOf(
1545
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\Policy',
1546
            $policy
1547
        );
1548
1549
        return array($roleService->loadRole($role->id), $policy);
1550
    }
1551
1552
    /**
1553
     * Test for the updatePolicy() method.
1554
     *
1555
     * @param array $roleAndPolicy
1556
     *
1557
     * @see \eZ\Publish\API\Repository\RoleService::updatePolicy()
1558
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testUpdatePolicy
1559
     */
1560
    public function testUpdatePolicyUpdatesLimitations($roleAndPolicy)
1561
    {
1562
        list($role, $policy) = $roleAndPolicy;
1563
1564
        $this->assertEquals(
1565
            array(
1566
                new ContentTypeLimitation(
1567
                    array(
1568
                        'limitationValues' => array(29, 30),
1569
                    )
1570
                ),
1571
            ),
1572
            $policy->getLimitations()
1573
        );
1574
1575
        return $role;
1576
    }
1577
1578
    /**
1579
     * Test for the updatePolicy() method.
1580
     *
1581
     * @param \eZ\Publish\API\Repository\Values\User\Role $role
1582
     *
1583
     * @see \eZ\Publish\API\Repository\RoleService::updatePolicy()
1584
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testUpdatePolicyUpdatesLimitations
1585
     */
1586
    public function testUpdatePolicyUpdatesRole($role)
1587
    {
1588
        $limitations = array();
1589
        foreach ($role->getPolicies() as $policy) {
1590
            foreach ($policy->getLimitations() as $limitation) {
1591
                $limitations[] = $limitation;
1592
            }
1593
        }
1594
1595
        $this->assertCount(1, $limitations);
1596
        $this->assertInstanceOf(
1597
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\Limitation',
1598
            $limitations[0]
1599
        );
1600
1601
        $expectedData = array(
1602
            'limitationValues' => array(29, 30),
1603
        );
1604
        $this->assertPropertiesCorrectUnsorted(
1605
            $expectedData,
1606
            $limitations[0]
1607
        );
1608
    }
1609
1610
    /**
1611
     * Test for the updatePolicy() method.
1612
     *
1613
     * @see \eZ\Publish\API\Repository\RoleService::updatePolicy()
1614
     * @expectedException \eZ\Publish\API\Repository\Exceptions\LimitationValidationException
1615
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicy
1616
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewPolicyCreateStruct
1617
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewPolicyUpdateStruct
1618
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewRoleCreateStruct
1619
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRole
1620
     */
1621
    public function testUpdatePolicyThrowsLimitationValidationException()
1622
    {
1623
        $repository = $this->getRepository();
1624
1625
        /* BEGIN: Use Case */
1626
        $roleService = $repository->getRoleService();
1627
1628
        // Instantiate new policy create
1629
        $policyCreate = $roleService->newPolicyCreateStruct('content', 'remove');
1630
1631
        // Add some limitations for the new policy
1632
        $policyCreate->addLimitation(
1633
            new SubtreeLimitation(
1634
                array(
1635
                    'limitationValues' => array('/1/2/'),
1636
                )
1637
            )
1638
        );
1639
1640
        // Instantiate a role create and add the policy create
1641
        $roleCreate = $roleService->newRoleCreateStruct('myRole');
1642
1643
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1644
        // $roleCreate->mainLanguageCode = 'eng-US';
1645
1646
        $roleCreate->addPolicy($policyCreate);
1647
1648
        // Create a new role instance.
1649
        $roleDraft = $roleService->createRole($roleCreate);
1650
        $roleService->publishRoleDraft($roleDraft);
1651
        $role = $roleService->loadRole($roleDraft->id);
1652
1653
        // Search for the new policy instance
1654
        $policy = null;
1655
        foreach ($role->getPolicies() as $policy) {
1656
            if ($policy->module === 'content' && $policy->function === 'remove') {
1657
                break;
1658
            }
1659
        }
1660
1661
        // Create an update struct and set a modified limitation
1662
        $policyUpdate = $roleService->newPolicyUpdateStruct();
1663
        $policyUpdate->addLimitation(
1664
            new SubtreeLimitation(
1665
                array(
1666
                    'limitationValues' => array('/mountain/forest/tree/42/'),
1667
                )
1668
            )
1669
        );
1670
1671
        // This call will fail with an LimitationValidationException, because subtree
1672
        // "/mountain/forest/tree/42/" does not exist
1673
        $policy = $roleService->updatePolicy($policy, $policyUpdate);
0 ignored issues
show
Bug introduced by
It seems like $policy can be null; however, updatePolicy() does not accept null, maybe add an additional type check?

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

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

function doesNotAcceptNull(stdClass $x) { }

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

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

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

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

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

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

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

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

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

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

Loading history...
1674
        /* END: Use Case */
1675
    }
1676
1677
    /**
1678
     * Test for the removePolicy() method.
1679
     *
1680
     * @see \eZ\Publish\API\Repository\RoleService::removePolicy()
1681
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicy
1682
     */
1683 View Code Duplication
    public function testRemovePolicy()
1684
    {
1685
        $repository = $this->getRepository();
1686
1687
        /* BEGIN: Use Case */
1688
        $roleService = $repository->getRoleService();
1689
1690
        // Instantiate a new role create
1691
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
1692
1693
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1694
        // $roleCreate->mainLanguageCode = 'eng-US';
1695
1696
        // Create a new role with two policies
1697
        $roleDraft = $roleService->createRole($roleCreate);
1698
        $roleService->addPolicyByRoleDraft(
1699
            $roleDraft,
1700
            $roleService->newPolicyCreateStruct('content', 'create')
1701
        );
1702
        $roleService->addPolicyByRoleDraft(
1703
            $roleDraft,
1704
            $roleService->newPolicyCreateStruct('content', 'delete')
1705
        );
1706
        $roleService->publishRoleDraft($roleDraft);
1707
        $role = $roleService->loadRole($roleDraft->id);
1708
1709
        // Delete all policies from the new role
1710
        foreach ($role->getPolicies() as $policy) {
1711
            $role = $roleService->removePolicy($role, $policy);
0 ignored issues
show
Deprecated Code introduced by
The method eZ\Publish\API\Repositor...Service::removePolicy() has been deprecated with message: since 5.3, 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...
1712
        }
1713
        /* END: Use Case */
1714
1715
        $this->assertSame(array(), $role->getPolicies());
1716
    }
1717
1718
    /**
1719
     * Test for the removePolicyByRoleDraft() method.
1720
     *
1721
     * @see \eZ\Publish\API\Repository\RoleService::removePolicyByRoleDraft()
1722
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicyByRoleDraft
1723
     */
1724 View Code Duplication
    public function testRemovePolicyByRoleDraft()
1725
    {
1726
        $repository = $this->getRepository();
1727
1728
        /* BEGIN: Use Case */
1729
        $roleService = $repository->getRoleService();
1730
1731
        // Instantiate a new role create
1732
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
1733
1734
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1735
        // $roleCreate->mainLanguageCode = 'eng-US';
1736
1737
        // Create a new role with two policies
1738
        $roleDraft = $roleService->createRole($roleCreate);
1739
        $roleService->addPolicyByRoleDraft(
1740
            $roleDraft,
1741
            $roleService->newPolicyCreateStruct('content', 'create')
1742
        );
1743
        $roleService->addPolicyByRoleDraft(
1744
            $roleDraft,
1745
            $roleService->newPolicyCreateStruct('content', 'delete')
1746
        );
1747
1748
        // Delete all policies from the new role
1749
        foreach ($roleDraft->getPolicies() as $policy) {
1750
            $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...
1751
        }
1752
        /* END: Use Case */
1753
1754
        $this->assertSame(array(), $roleDraft->getPolicies());
1755
    }
1756
1757
    /**
1758
     * Test for the deletePolicy() method.
1759
     *
1760
     * @see \eZ\Publish\API\Repository\RoleService::deletePolicy()
1761
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRole
1762
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicy
1763
     */
1764 View Code Duplication
    public function testDeletePolicy()
1765
    {
1766
        $repository = $this->getRepository();
1767
1768
        /* BEGIN: Use Case */
1769
        $roleService = $repository->getRoleService();
1770
1771
        // Instantiate a new role create
1772
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
1773
1774
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1775
        // $roleCreate->mainLanguageCode = 'eng-US';
1776
1777
        // Create a new role with two policies
1778
        $roleDraft = $roleService->createRole($roleCreate);
1779
        $roleService->addPolicyByRoleDraft(
1780
            $roleDraft,
1781
            $roleService->newPolicyCreateStruct('content', 'create')
1782
        );
1783
        $roleService->addPolicyByRoleDraft(
1784
            $roleDraft,
1785
            $roleService->newPolicyCreateStruct('content', 'delete')
1786
        );
1787
        $roleService->publishRoleDraft($roleDraft);
1788
        $role = $roleService->loadRole($roleDraft->id);
1789
1790
        // Delete all policies from the new role
1791
        foreach ($role->getPolicies() as $policy) {
1792
            $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...
1793
        }
1794
        /* END: Use Case */
1795
1796
        $role = $roleService->loadRole($role->id);
1797
        $this->assertSame(array(), $role->getPolicies());
1798
    }
1799
1800
    /**
1801
     * Test loading user/group role assignments.
1802
     *
1803
     * @return \eZ\Publish\API\Repository\Values\User\UserGroupRoleAssignment
1804
     *
1805
     * @covers \eZ\Publish\API\Repository\RoleService::loadRoleAssignment
1806
     */
1807
    public function testLoadRoleAssignment()
1808
    {
1809
        $repository = $this->getRepository();
1810
1811
        /* BEGIN: Use Case */
1812
        $roleService = $repository->getRoleService();
1813
1814
        // Assignment to user group
1815
        $groupRoleAssignment = $roleService->loadRoleAssignment(25);
1816
1817
        // Assignment to user
1818
        $role = $roleService->loadRole(2);
1819
        $user = $repository->getUserService()->loadUser(14);
1820
        $roleService->assignRoleToUser($role, $user);
1821
        $userRoleAssignments = $roleService->getRoleAssignmentsForUser($user);
1822
1823
        $userRoleAssignment = $roleService->loadRoleAssignment($userRoleAssignments[0]->id);
1824
        /* END: Use Case */
1825
1826
        $this->assertInstanceOf(
1827
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\UserGroupRoleAssignment',
1828
            $groupRoleAssignment
1829
        );
1830
1831
        $this->assertEquals(
1832
            [
1833
                12,
1834
                2,
1835
                25,
1836
            ],
1837
            [
1838
                $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...
1839
                $groupRoleAssignment->role->id,
1840
                $groupRoleAssignment->id,
1841
            ]
1842
        );
1843
1844
        self::assertInstanceOf('\\eZ\\Publish\\API\\Repository\\Values\\User\\UserRoleAssignment', $userRoleAssignment);
1845
        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...
1846
1847
        return $groupRoleAssignment;
1848
    }
1849
1850
    /**
1851
     * Test for the getRoleAssignments() method.
1852
     *
1853
     * @return \eZ\Publish\API\Repository\Values\User\RoleAssignment[]
1854
     *
1855
     * @see \eZ\Publish\API\Repository\RoleService::getRoleAssignments()
1856
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleByIdentifier
1857
     */
1858
    public function testGetRoleAssignments()
1859
    {
1860
        $repository = $this->getRepository();
1861
1862
        /* BEGIN: Use Case */
1863
        $roleService = $repository->getRoleService();
1864
1865
        // Load the editor role
1866
        $role = $roleService->loadRoleByIdentifier('Editor');
1867
1868
        // Load all assigned users and user groups
1869
        $roleAssignments = $roleService->getRoleAssignments($role);
1870
1871
        /* END: Use Case */
1872
1873
        $this->assertEquals(2, count($roleAssignments));
1874
        $this->assertInstanceOf(
1875
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\UserGroupRoleAssignment',
1876
            $roleAssignments[0]
1877
        );
1878
        $this->assertInstanceOf(
1879
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\UserGroupRoleAssignment',
1880
            $roleAssignments[1]
1881
        );
1882
1883
        return $roleAssignments;
1884
    }
1885
1886
    /**
1887
     * Test for the getRoleAssignments() method.
1888
     *
1889
     * @param \eZ\Publish\API\Repository\Values\User\RoleAssignment[] $roleAssignments
1890
     *
1891
     * @see \eZ\Publish\API\Repository\RoleService::getRoleAssignments()
1892
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testGetRoleAssignments
1893
     */
1894
    public function testGetRoleAssignmentsContainExpectedLimitation(array $roleAssignments)
1895
    {
1896
        $this->assertEquals(
1897
            'Subtree',
1898
            reset($roleAssignments)->limitation->getIdentifier()
1899
        );
1900
    }
1901
1902
    /**
1903
     * Test for the assignRoleToUser() method.
1904
     *
1905
     * @see \eZ\Publish\API\Repository\RoleService::assignRoleToUser()
1906
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testGetRoleAssignments
1907
     */
1908 View Code Duplication
    public function testAssignRoleToUser()
1909
    {
1910
        $repository = $this->getRepository();
1911
        $roleService = $repository->getRoleService();
1912
1913
        /* BEGIN: Use Case */
1914
        $user = $this->createUserVersion1();
1915
1916
        // Load the existing "Administrator" role
1917
        $role = $roleService->loadRoleByIdentifier('Administrator');
1918
1919
        // Assign the "Administrator" role to the newly created user
1920
        $roleService->assignRoleToUser($role, $user);
1921
1922
        // The assignments array will contain the new role<->user assignment
1923
        $roleAssignments = $roleService->getRoleAssignments($role);
1924
        /* END: Use Case */
1925
1926
        // Administrator + Example User
1927
        $this->assertEquals(2, count($roleAssignments));
1928
    }
1929
1930
    /**
1931
     * Test for the assignRoleToUser() method.
1932
     *
1933
     * @see \eZ\Publish\API\Repository\RoleService::assignRoleToUser($role, $user, $roleLimitation)
1934
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUser
1935
     */
1936 View Code Duplication
    public function testAssignRoleToUserWithRoleLimitation()
1937
    {
1938
        $repository = $this->getRepository();
1939
        $roleService = $repository->getRoleService();
1940
1941
        /* BEGIN: Use Case */
1942
        $user = $this->createUserVersion1();
1943
1944
        // Load the existing "Anonymous" role
1945
        $role = $roleService->loadRoleByIdentifier('Anonymous');
1946
1947
        // Assign the "Anonymous" role to the newly created user
1948
        $roleService->assignRoleToUser(
1949
            $role,
1950
            $user,
1951
            new SubtreeLimitation(
1952
                array(
1953
                    'limitationValues' => array('/1/43/'),
1954
                )
1955
            )
1956
        );
1957
1958
        // The assignments array will contain the new role<->user assignment
1959
        $roleAssignments = $roleService->getRoleAssignments($role);
1960
        /* END: Use Case */
1961
1962
        // Members + Partners + Anonymous + Example User
1963
        $this->assertEquals(4, count($roleAssignments));
1964
1965
        // Get the role limitation
1966
        $roleLimitation = null;
1967
        foreach ($roleAssignments as $roleAssignment) {
1968
            $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...
1969
            if ($roleLimitation) {
1970
                $this->assertInstanceOf(
1971
                    '\\eZ\\Publish\\API\\Repository\\Values\\User\\UserRoleAssignment',
1972
                    $roleAssignment
1973
                );
1974
                break;
1975
            }
1976
        }
1977
1978
        $this->assertEquals(
1979
            new SubtreeLimitation(
1980
                array(
1981
                    'limitationValues' => array('/1/43/'),
1982
                )
1983
            ),
1984
            $roleLimitation
1985
        );
1986
1987
        // Test again to see values being merged
1988
        $roleService->assignRoleToUser(
1989
            $role,
1990
            $user,
1991
            new SubtreeLimitation(
1992
                array(
1993
                    'limitationValues' => array('/1/43/', '/1/2/'),
1994
                )
1995
            )
1996
        );
1997
1998
        // The assignments array will contain the new role<->user assignment
1999
        $roleAssignments = $roleService->getRoleAssignments($role);
2000
2001
        // Members + Partners + Anonymous + Example User
2002
        $this->assertEquals(5, count($roleAssignments));
2003
2004
        // Get the role limitation
2005
        $roleLimitations = [];
2006
        foreach ($roleAssignments as $roleAssignment) {
2007
            $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...
2008
            if ($roleLimitation) {
2009
                $this->assertInstanceOf(
2010
                    '\\eZ\\Publish\\API\\Repository\\Values\\User\\UserRoleAssignment',
2011
                    $roleAssignment
2012
                );
2013
                $roleLimitations[] = $roleLimitation;
2014
            }
2015
        }
2016
        array_multisort($roleLimitations);
2017
2018
        $this->assertEquals(
2019
            [
2020
                new SubtreeLimitation(
2021
                    array(
2022
                        'limitationValues' => array('/1/2/'),
2023
                    )
2024
                ),
2025
                new SubtreeLimitation(
2026
                    array(
2027
                        'limitationValues' => array('/1/43/'),
2028
                    )
2029
                ),
2030
            ],
2031
            $roleLimitations
2032
        );
2033
    }
2034
2035
    /**
2036
     * Test for the assignRoleToUser() method.
2037
     *
2038
     * @see \eZ\Publish\API\Repository\RoleService::assignRoleToUser($role, $user, $roleLimitation)
2039
     * @expectedException \eZ\Publish\API\Repository\Exceptions\LimitationValidationException
2040
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUser
2041
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleByIdentifier
2042
     */
2043
    public function testAssignRoleToUserWithRoleLimitationThrowsLimitationValidationException()
2044
    {
2045
        $repository = $this->getRepository();
2046
2047
        /* BEGIN: Use Case */
2048
        $roleService = $repository->getRoleService();
2049
2050
        // Load the existing "Anonymous" role
2051
        $role = $roleService->loadRoleByIdentifier('Anonymous');
2052
2053
        // Get current user
2054
        $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...
2055
2056
        // Assign the "Anonymous" role to the current user
2057
        // This call will fail with an LimitationValidationException, because subtree "/lorem/ipsum/42/"
2058
        // does not exists
2059
        $roleService->assignRoleToUser(
2060
            $role,
2061
            $currentUser,
2062
            new SubtreeLimitation(
2063
                array(
2064
                    'limitationValues' => array('/lorem/ipsum/42/'),
2065
                )
2066
            )
2067
        );
2068
        /* END: Use Case */
2069
    }
2070
2071
    /**
2072
     * Test for the assignRoleToUser() method.
2073
     *
2074
     * Makes sure assigning role several times throws.
2075
     *
2076
     * @see \eZ\Publish\API\Repository\RoleService::assignRoleToUser($role, $user, $roleLimitation)
2077
     * @expectedException \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException
2078
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUser
2079
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleByIdentifier
2080
     */
2081 View Code Duplication
    public function testAssignRoleToUserThrowsInvalidArgumentException()
2082
    {
2083
        $repository = $this->getRepository();
2084
2085
        /* BEGIN: Use Case */
2086
        $roleService = $repository->getRoleService();
2087
2088
        // Load the existing "Anonymous" role
2089
        $role = $roleService->loadRoleByIdentifier('Anonymous');
2090
2091
        // Get current user
2092
        $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...
2093
2094
        // Assign the "Anonymous" role to the current user
2095
        try {
2096
            $roleService->assignRoleToUser(
2097
                $role,
2098
                $currentUser
2099
            );
2100
        } catch (Exception $e) {
2101
            $this->fail('Got exception at first valid attempt to assign role');
2102
        }
2103
2104
        // Re-Assign the "Anonymous" role to the current user
2105
        // This call will fail with an InvalidArgumentException, because limitation is already assigned
2106
        $roleService->assignRoleToUser(
2107
            $role,
2108
            $currentUser
2109
        );
2110
        /* END: Use Case */
2111
    }
2112
2113
    /**
2114
     * Test for the assignRoleToUser() method.
2115
     *
2116
     * Makes sure assigning role several times with same limitations throws.
2117
     *
2118
     * @see \eZ\Publish\API\Repository\RoleService::assignRoleToUser($role, $user, $roleLimitation)
2119
     * @expectedException \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException
2120
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUser
2121
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleByIdentifier
2122
     */
2123
    public function testAssignRoleToUserWithRoleLimitationThrowsInvalidArgumentException()
2124
    {
2125
        $repository = $this->getRepository();
2126
2127
        /* BEGIN: Use Case */
2128
        $roleService = $repository->getRoleService();
2129
2130
        // Load the existing "Anonymous" role
2131
        $role = $roleService->loadRoleByIdentifier('Anonymous');
2132
2133
        // Get current user
2134
        $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...
2135
2136
        // Assign the "Anonymous" role to the current user
2137
        try {
2138
            $roleService->assignRoleToUser(
2139
                $role,
2140
                $currentUser,
2141
                new SubtreeLimitation(
2142
                    array(
2143
                        'limitationValues' => array('/1/43/', '/1/2/'),
2144
                    )
2145
                )
2146
            );
2147
        } catch (Exception $e) {
2148
            $this->fail('Got exception at first valid attempt to assign role');
2149
        }
2150
2151
        // Re-Assign the "Anonymous" role to the current user
2152
        // This call will fail with an InvalidArgumentException, because limitation is already assigned
2153
        $roleService->assignRoleToUser(
2154
            $role,
2155
            $currentUser,
2156
            new SubtreeLimitation(
2157
                array(
2158
                    'limitationValues' => array('/1/43/'),
2159
                )
2160
            )
2161
        );
2162
        /* END: Use Case */
2163
    }
2164
2165
    /**
2166
     * Test for the unassignRoleFromUser() method.
2167
     *
2168
     * @see \eZ\Publish\API\Repository\RoleService::unassignRoleFromUser()
2169
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUser
2170
     */
2171 View Code Duplication
    public function testUnassignRoleFromUser()
2172
    {
2173
        $repository = $this->getRepository();
2174
        $roleService = $repository->getRoleService();
2175
2176
        /* BEGIN: Use Case */
2177
        $user = $this->createUserVersion1();
2178
2179
        // Load the existing "Member" role
2180
        $role = $roleService->loadRoleByIdentifier('Member');
2181
2182
        // Assign the "Member" role to the newly created user
2183
        $roleService->assignRoleToUser($role, $user);
2184
2185
        // Unassign user from role
2186
        $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...
2187
2188
        // The assignments array will not contain the new role<->user assignment
2189
        $roleAssignments = $roleService->getRoleAssignments($role);
2190
        /* END: Use Case */
2191
2192
        // Members + Editors + Partners
2193
        $this->assertEquals(3, count($roleAssignments));
2194
    }
2195
2196
    /**
2197
     * Test for the unassignRoleFromUser() method.
2198
     *
2199
     * @see \eZ\Publish\API\Repository\RoleService::unassignRoleFromUser()
2200
     * @expectedException \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException
2201
     */
2202 View Code Duplication
    public function testUnassignRoleFromUserThrowsInvalidArgumentException()
2203
    {
2204
        $repository = $this->getRepository();
2205
        $roleService = $repository->getRoleService();
2206
2207
        /* BEGIN: Use Case */
2208
        $user = $this->createUserVersion1();
2209
2210
        // Load the existing "Member" role
2211
        $role = $roleService->loadRoleByIdentifier('Member');
2212
2213
        // This call will fail with a "InvalidArgumentException", because the
2214
        // user does not have the "Member" role.
2215
        $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...
2216
        /* END: Use Case */
2217
    }
2218
2219
    /**
2220
     * Test for the getRoleAssignmentsForUser() method.
2221
     *
2222
     * @see \eZ\Publish\API\Repository\RoleService::getRoleAssignmentsForUser()
2223
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUser
2224
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRoleWithAddPolicy
2225
     */
2226 View Code Duplication
    public function testGetRoleAssignmentsForUserDirect()
2227
    {
2228
        $repository = $this->getRepository();
2229
        $roleService = $repository->getRoleService();
2230
2231
        /* BEGIN: Use Case */
2232
        $user = $this->createUserVersion1();
2233
2234
        // Instantiate a role create and add some policies
2235
        $roleCreate = $roleService->newRoleCreateStruct('Example Role');
2236
2237
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
2238
        // $roleCreate->mainLanguageCode = 'eng-US';
2239
2240
        $roleCreate->addPolicy(
2241
            $roleService->newPolicyCreateStruct('user', 'login')
2242
        );
2243
        $roleCreate->addPolicy(
2244
            $roleService->newPolicyCreateStruct('content', 'read')
2245
        );
2246
        $roleCreate->addPolicy(
2247
            $roleService->newPolicyCreateStruct('content', 'edit')
2248
        );
2249
2250
        // Create the new role instance
2251
        $roleDraft = $roleService->createRole($roleCreate);
2252
        $roleService->publishRoleDraft($roleDraft);
2253
        $role = $roleService->loadRole($roleDraft->id);
2254
2255
        // Assign role to new user
2256
        $roleService->assignRoleToUser($role, $user);
2257
2258
        // Load the currently assigned role
2259
        $roleAssignments = $roleService->getRoleAssignmentsForUser($user);
2260
        /* END: Use Case */
2261
2262
        $this->assertEquals(1, count($roleAssignments));
2263
        $this->assertInstanceOf(
2264
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\UserRoleAssignment',
2265
            reset($roleAssignments)
2266
        );
2267
    }
2268
2269
    /**
2270
     * Test for the getRoleAssignmentsForUser() method.
2271
     *
2272
     * @see \eZ\Publish\API\Repository\RoleService::getRoleAssignmentsForUser()
2273
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUser
2274
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRoleWithAddPolicy
2275
     */
2276
    public function testGetRoleAssignmentsForUserEmpty()
2277
    {
2278
        $repository = $this->getRepository();
2279
        $roleService = $repository->getRoleService();
2280
2281
        /* BEGIN: Use Case */
2282
        $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...
2283
2284
        // Load the currently assigned role
2285
        $roleAssignments = $roleService->getRoleAssignmentsForUser($adminUser);
2286
        /* END: Use Case */
2287
2288
        $this->assertEquals(0, count($roleAssignments));
2289
    }
2290
2291
    /**
2292
     * Test for the getRoleAssignmentsForUser() method.
2293
     *
2294
     * @see \eZ\Publish\API\Repository\RoleService::getRoleAssignmentsForUser()
2295
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUser
2296
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRoleWithAddPolicy
2297
     */
2298
    public function testGetRoleAssignmentsForUserInherited()
2299
    {
2300
        $repository = $this->getRepository();
2301
        $roleService = $repository->getRoleService();
2302
2303
        /* BEGIN: Use Case */
2304
        $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...
2305
2306
        // Load the currently assigned role + inherited role assignments
2307
        $roleAssignments = $roleService->getRoleAssignmentsForUser($adminUser, true);
2308
        /* END: Use Case */
2309
2310
        $this->assertEquals(1, count($roleAssignments));
2311
        $this->assertInstanceOf(
2312
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\UserGroupRoleAssignment',
2313
            reset($roleAssignments)
2314
        );
2315
    }
2316
2317
    /**
2318
     * Test for the assignRoleToUserGroup() method.
2319
     *
2320
     * @see \eZ\Publish\API\Repository\RoleService::assignRoleToUserGroup()
2321
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testGetRoleAssignments
2322
     */
2323 View Code Duplication
    public function testAssignRoleToUserGroup()
2324
    {
2325
        $repository = $this->getRepository();
2326
        $roleService = $repository->getRoleService();
2327
2328
        /* BEGIN: Use Case */
2329
        $userGroup = $this->createUserGroupVersion1();
2330
2331
        // Load the existing "Administrator" role
2332
        $role = $roleService->loadRoleByIdentifier('Administrator');
2333
2334
        // Assign the "Administrator" role to the newly created user group
2335
        $roleService->assignRoleToUserGroup($role, $userGroup);
2336
2337
        // The assignments array will contain the new role<->group assignment
2338
        $roleAssignments = $roleService->getRoleAssignments($role);
2339
        /* END: Use Case */
2340
2341
        // Administrator + Example Group
2342
        $this->assertEquals(2, count($roleAssignments));
2343
    }
2344
2345
    /**
2346
     * Test for the assignRoleToUserGroup() method.
2347
     *
2348
     * @see \eZ\Publish\API\Repository\RoleService::assignRoleToUserGroup($role, $userGroup, $roleLimitation)
2349
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUserGroup
2350
     */
2351 View Code Duplication
    public function testAssignRoleToUserGroupWithRoleLimitation()
2352
    {
2353
        $repository = $this->getRepository();
2354
        $roleService = $repository->getRoleService();
2355
2356
        /* BEGIN: Use Case */
2357
        $userGroup = $this->createUserGroupVersion1();
2358
2359
        // Load the existing "Anonymous" role
2360
        $role = $roleService->loadRoleByIdentifier('Anonymous');
2361
2362
        // Assign the "Anonymous" role to the newly created user group
2363
        $roleService->assignRoleToUserGroup(
2364
            $role,
2365
            $userGroup,
2366
            new SubtreeLimitation(
2367
                array(
2368
                    'limitationValues' => array('/1/43/'),
2369
                )
2370
            )
2371
        );
2372
2373
        // The assignments array will contain the new role<->group assignment
2374
        $roleAssignments = $roleService->getRoleAssignments($role);
2375
        /* END: Use Case */
2376
2377
        // Members + Partners + Anonymous + Example Group
2378
        $this->assertEquals(4, count($roleAssignments));
2379
2380
        // Get the role limitation
2381
        $roleLimitation = null;
2382
        foreach ($roleAssignments as $roleAssignment) {
2383
            $roleLimitation = $roleAssignment->getRoleLimitation();
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $roleLimitation is correct as $roleAssignment->getRoleLimitation() (which targets eZ\Publish\API\Repositor...nt::getRoleLimitation()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
2384
            if ($roleLimitation) {
2385
                break;
2386
            }
2387
        }
2388
2389
        $this->assertEquals(
2390
            new SubtreeLimitation(
2391
                array(
2392
                    'limitationValues' => array('/1/43/'),
2393
                )
2394
            ),
2395
            $roleLimitation
2396
        );
2397
2398
        // Test again to see values being merged
2399
        $roleService->assignRoleToUserGroup(
2400
            $role,
2401
            $userGroup,
2402
            new SubtreeLimitation(
2403
                array(
2404
                    'limitationValues' => array('/1/43/', '/1/2/'),
2405
                )
2406
            )
2407
        );
2408
2409
        // The assignments array will contain the new role<->user assignment
2410
        $roleAssignments = $roleService->getRoleAssignments($role);
2411
2412
        // Members + Partners + Anonymous + Example User
2413
        $this->assertEquals(5, count($roleAssignments));
2414
2415
        // Get the role limitation
2416
        $roleLimitations = [];
2417
        foreach ($roleAssignments as $roleAssignment) {
2418
            $roleLimitation = $roleAssignment->getRoleLimitation();
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $roleLimitation is correct as $roleAssignment->getRoleLimitation() (which targets eZ\Publish\API\Repositor...nt::getRoleLimitation()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
2419
            if ($roleLimitation) {
2420
                $this->assertInstanceOf(
2421
                    '\\eZ\\Publish\\API\\Repository\\Values\\User\\UserGroupRoleAssignment',
2422
                    $roleAssignment
2423
                );
2424
                $roleLimitations[] = $roleLimitation;
2425
            }
2426
        }
2427
        array_multisort($roleLimitations);
2428
2429
        $this->assertEquals(
2430
            [
2431
                new SubtreeLimitation(
2432
                    array(
2433
                        'limitationValues' => array('/1/2/'),
2434
                    )
2435
                ),
2436
                new SubtreeLimitation(
2437
                    array(
2438
                        'limitationValues' => array('/1/43/'),
2439
                    )
2440
                ),
2441
            ],
2442
            $roleLimitations
2443
        );
2444
    }
2445
2446
    /**
2447
     * Test for the assignRoleToUserGroup() method.
2448
     *
2449
     * @see \eZ\Publish\API\Repository\RoleService::assignRoleToUserGroup($role, $userGroup, $roleLimitation)
2450
     * @expectedException \eZ\Publish\API\Repository\Exceptions\LimitationValidationException
2451
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleByIdentifier
2452
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUserGroup
2453
     */
2454
    public function testAssignRoleToUserGroupWithRoleLimitationThrowsLimitationValidationException()
2455
    {
2456
        $repository = $this->getRepository();
2457
2458
        $mainGroupId = $this->generateId('group', 4);
2459
        /* BEGIN: Use Case */
2460
        // $mainGroupId is the ID of the main "Users" group
2461
2462
        $userService = $repository->getUserService();
2463
        $roleService = $repository->getRoleService();
2464
2465
        $userGroup = $userService->loadUserGroup($mainGroupId);
2466
2467
        // Load the existing "Anonymous" role
2468
        $role = $roleService->loadRoleByIdentifier('Anonymous');
2469
2470
        // Assign the "Anonymous" role to the newly created user group
2471
        // This call will fail with an LimitationValidationException, because subtree "/lorem/ipsum/42/"
2472
        // does not exists
2473
        $roleService->assignRoleToUserGroup(
2474
            $role,
2475
            $userGroup,
2476
            new SubtreeLimitation(
2477
                array(
2478
                    'limitationValues' => array('/lorem/ipsum/42/'),
2479
                )
2480
            )
2481
        );
2482
        /* END: Use Case */
2483
    }
2484
2485
    /**
2486
     * Test for the assignRoleToUserGroup() method.
2487
     *
2488
     * Makes sure assigning role several times throws.
2489
     *
2490
     * @see \eZ\Publish\API\Repository\RoleService::assignRoleToUserGroup($role, $userGroup, $roleLimitation)
2491
     * @expectedException \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException
2492
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleByIdentifier
2493
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUserGroup
2494
     */
2495
    public function testAssignRoleToUserGroupThrowsInvalidArgumentException()
2496
    {
2497
        $repository = $this->getRepository();
2498
2499
        $mainGroupId = $this->generateId('group', 4);
2500
        /* BEGIN: Use Case */
2501
        // $mainGroupId is the ID of the main "Users" group
2502
2503
        $userService = $repository->getUserService();
2504
        $roleService = $repository->getRoleService();
2505
2506
        $userGroup = $userService->loadUserGroup($mainGroupId);
2507
2508
        // Load the existing "Anonymous" role
2509
        $role = $roleService->loadRoleByIdentifier('Anonymous');
2510
2511
        // Assign the "Anonymous" role to the newly created user group
2512
        try {
2513
            $roleService->assignRoleToUserGroup(
2514
                $role,
2515
                $userGroup
2516
            );
2517
        } catch (Exception $e) {
2518
            $this->fail('Got exception at first valid attempt to assign role');
2519
        }
2520
2521
        // Re-Assign the "Anonymous" role to the newly created user group
2522
        // This call will fail with an InvalidArgumentException, because role is already assigned
2523
        $roleService->assignRoleToUserGroup(
2524
            $role,
2525
            $userGroup
2526
        );
2527
        /* END: Use Case */
2528
    }
2529
2530
    /**
2531
     * Test for the assignRoleToUserGroup() method.
2532
     *
2533
     * Makes sure assigning role several times with same limitations throws.
2534
     *
2535
     * @see \eZ\Publish\API\Repository\RoleService::assignRoleToUserGroup($role, $userGroup, $roleLimitation)
2536
     * @expectedException \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException
2537
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleByIdentifier
2538
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUserGroup
2539
     */
2540
    public function testAssignRoleToUserGroupWithRoleLimitationThrowsInvalidArgumentException()
2541
    {
2542
        $repository = $this->getRepository();
2543
2544
        $mainGroupId = $this->generateId('group', 4);
2545
        /* BEGIN: Use Case */
2546
        // $mainGroupId is the ID of the main "Users" group
2547
2548
        $userService = $repository->getUserService();
2549
        $roleService = $repository->getRoleService();
2550
2551
        $userGroup = $userService->loadUserGroup($mainGroupId);
2552
2553
        // Load the existing "Anonymous" role
2554
        $role = $roleService->loadRoleByIdentifier('Anonymous');
2555
2556
        // Assign the "Anonymous" role to the newly created user group
2557
        try {
2558
            $roleService->assignRoleToUserGroup(
2559
                $role,
2560
                $userGroup,
2561
                new SubtreeLimitation(
2562
                    array(
2563
                        'limitationValues' => array('/1/43/', '/1/2/'),
2564
                    )
2565
                )
2566
            );
2567
        } catch (Exception $e) {
2568
            $this->fail('Got exception at first valid attempt to assign role');
2569
        }
2570
2571
        // Re-Assign the "Anonymous" role to the newly created user group
2572
        // This call will fail with an InvalidArgumentException, because limitation is already assigned
2573
        $roleService->assignRoleToUserGroup(
2574
            $role,
2575
            $userGroup,
2576
            new SubtreeLimitation(
2577
                array(
2578
                    'limitationValues' => array('/1/43/'),
2579
                )
2580
            )
2581
        );
2582
        /* END: Use Case */
2583
    }
2584
2585
    /**
2586
     * Test for the unassignRoleFromUserGroup() method.
2587
     *
2588
     * @see \eZ\Publish\API\Repository\RoleService::unassignRoleFromUserGroup()
2589
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUserGroup
2590
     */
2591 View Code Duplication
    public function testUnassignRoleFromUserGroup()
2592
    {
2593
        $repository = $this->getRepository();
2594
        $roleService = $repository->getRoleService();
2595
2596
        /* BEGIN: Use Case */
2597
        $userGroup = $this->createUserGroupVersion1();
2598
2599
        // Load the existing "Member" role
2600
        $role = $roleService->loadRoleByIdentifier('Member');
2601
2602
        // Assign the "Member" role to the newly created user group
2603
        $roleService->assignRoleToUserGroup($role, $userGroup);
2604
2605
        // Unassign group from role
2606
        $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...
2607
2608
        // The assignments array will not contain the new role<->group assignment
2609
        $roleAssignments = $roleService->getRoleAssignments($role);
2610
        /* END: Use Case */
2611
2612
        // Members + Editors + Partners
2613
        $this->assertEquals(3, count($roleAssignments));
2614
    }
2615
2616
    /**
2617
     * Test for the unassignRoleFromUserGroup() method.
2618
     *
2619
     * @see \eZ\Publish\API\Repository\RoleService::unassignRoleFromUserGroup()
2620
     * @expectedException \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException
2621
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testUnassignRoleFromUserGroup
2622
     */
2623 View Code Duplication
    public function testUnassignRoleFromUserGroupThrowsInvalidArgumentException()
2624
    {
2625
        $repository = $this->getRepository();
2626
        $roleService = $repository->getRoleService();
2627
2628
        /* BEGIN: Use Case */
2629
        $userGroup = $this->createUserGroupVersion1();
2630
2631
        // Load the existing "Member" role
2632
        $role = $roleService->loadRoleByIdentifier('Member');
2633
2634
        // This call will fail with a "InvalidArgumentException", because the
2635
        // user group does not have the "Member" role.
2636
        $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...
2637
        /* END: Use Case */
2638
    }
2639
2640
    /**
2641
     * Test unassigning role by assignment.
2642
     *
2643
     * @covers \eZ\Publish\API\Repository\RoleService::removeRoleAssignment
2644
     */
2645
    public function testUnassignRoleByAssignment()
2646
    {
2647
        $repository = $this->getRepository();
2648
        $roleService = $repository->getRoleService();
2649
2650
        $role = $roleService->loadRole(2);
2651
        $user = $repository->getUserService()->loadUser(14);
2652
2653
        $originalAssignmentCount = count($roleService->getRoleAssignmentsForUser($user));
2654
2655
        $roleService->assignRoleToUser($role, $user);
2656
        $newAssignmentCount = count($roleService->getRoleAssignmentsForUser($user));
2657
        self::assertEquals($originalAssignmentCount + 1, $newAssignmentCount);
2658
2659
        $assignments = $roleService->getRoleAssignmentsForUser($user);
2660
        $roleService->removeRoleAssignment($assignments[0]);
2661
        $finalAssignmentCount = count($roleService->getRoleAssignmentsForUser($user));
2662
        self::assertEquals($newAssignmentCount - 1, $finalAssignmentCount);
2663
    }
2664
2665
    /**
2666
     * Test unassigning role by assignment.
2667
     *
2668
     * But on current admin user so he lacks access to read roles.
2669
     *
2670
     * @covers \eZ\Publish\API\Repository\RoleService::removeRoleAssignment
2671
     * @expectedException \eZ\Publish\API\Repository\Exceptions\UnauthorizedException
2672
     */
2673 View Code Duplication
    public function testUnassignRoleByAssignmentThrowsUnauthorizedException()
2674
    {
2675
        $repository = $this->getRepository();
2676
        $roleService = $repository->getRoleService();
2677
2678
        try {
2679
            $adminUserGroup = $repository->getUserService()->loadUserGroup(12);
2680
            $assignments = $roleService->getRoleAssignmentsForUserGroup($adminUserGroup);
2681
            $roleService->removeRoleAssignment($assignments[0]);
2682
        } catch (Exception $e) {
2683
            self::fail(
2684
                'Unexpected exception: ' . $e->getMessage() . " \n[" . $e->getFile() . ' (' . $e->getLine() . ')]'
2685
            );
2686
        }
2687
2688
        $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...
2689
    }
2690
2691
    /**
2692
     * Test unassigning role by non-existing assignment.
2693
     *
2694
     * @covers \eZ\Publish\API\Repository\RoleService::removeRoleAssignment
2695
     * @expectedException \eZ\Publish\API\Repository\Exceptions\NotFoundException
2696
     */
2697 View Code Duplication
    public function testUnassignRoleByAssignmentThrowsNotFoundException()
2698
    {
2699
        $repository = $this->getRepository();
2700
        $roleService = $repository->getRoleService();
2701
2702
        try {
2703
            $editorsUserGroup = $repository->getUserService()->loadUserGroup(13);
2704
            $assignments = $roleService->getRoleAssignmentsForUserGroup($editorsUserGroup);
2705
            $roleService->removeRoleAssignment($assignments[0]);
2706
        } catch (Exception $e) {
2707
            self::fail(
2708
                'Unexpected exception: ' . $e->getMessage() . " \n[" . $e->getFile() . ' (' . $e->getLine() . ')]'
2709
            );
2710
        }
2711
2712
        $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...
2713
    }
2714
2715
    /**
2716
     * Test for the getRoleAssignmentsForUserGroup() method.
2717
     *
2718
     * @see \eZ\Publish\API\Repository\RoleService::getRoleAssignmentsForUserGroup()
2719
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUserGroup
2720
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRoleWithAddPolicy
2721
     */
2722 View Code Duplication
    public function testGetRoleAssignmentsForUserGroup()
2723
    {
2724
        $repository = $this->getRepository();
2725
        $roleService = $repository->getRoleService();
2726
2727
        /* BEGIN: Use Case */
2728
        $userGroup = $this->createUserGroupVersion1();
2729
2730
        // Instantiate a role create and add some policies
2731
        $roleCreate = $roleService->newRoleCreateStruct('Example Role');
2732
2733
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
2734
        // $roleCreate->mainLanguageCode = 'eng-US';
2735
2736
        $roleCreate->addPolicy(
2737
            $roleService->newPolicyCreateStruct('user', 'login')
2738
        );
2739
        $roleCreate->addPolicy(
2740
            $roleService->newPolicyCreateStruct('content', 'read')
2741
        );
2742
        $roleCreate->addPolicy(
2743
            $roleService->newPolicyCreateStruct('content', 'edit')
2744
        );
2745
2746
        // Create the new role instance
2747
        $roleDraft = $roleService->createRole($roleCreate);
2748
        $roleService->publishRoleDraft($roleDraft);
2749
        $role = $roleService->loadRole($roleDraft->id);
2750
2751
        // Assign role to new user group
2752
        $roleService->assignRoleToUserGroup($role, $userGroup);
2753
2754
        // Load the currently assigned role
2755
        $roleAssignments = $roleService->getRoleAssignmentsForUserGroup($userGroup);
2756
        /* END: Use Case */
2757
2758
        $this->assertEquals(1, count($roleAssignments));
2759
        $this->assertInstanceOf(
2760
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\UserGroupRoleAssignment',
2761
            reset($roleAssignments)
2762
        );
2763
    }
2764
2765
    /**
2766
     * Test for the loadPoliciesByUserId() method.
2767
     *
2768
     * @see \eZ\Publish\API\Repository\RoleService::loadPoliciesByUserId()
2769
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUser
2770
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUserGroup
2771
     */
2772
    public function testLoadPoliciesByUserId()
2773
    {
2774
        $repository = $this->getRepository();
2775
2776
        $anonUserId = $this->generateId('user', 10);
2777
        /* BEGIN: Use Case */
2778
        // $anonUserId is the ID of the "Anonymous" user.
2779
2780
        $userService = $repository->getUserService();
2781
        $roleService = $repository->getRoleService();
2782
2783
        // Load "Anonymous" user
2784
        $user = $userService->loadUser($anonUserId);
2785
2786
        // Instantiate a role create and add some policies
2787
        $roleCreate = $roleService->newRoleCreateStruct('User Role');
2788
2789
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
2790
        // $roleCreate->mainLanguageCode = 'eng-US';
2791
2792
        $roleCreate->addPolicy(
2793
            $roleService->newPolicyCreateStruct('notification', 'use')
2794
        );
2795
        $roleCreate->addPolicy(
2796
            $roleService->newPolicyCreateStruct('user', 'password')
2797
        );
2798
        $roleCreate->addPolicy(
2799
            $roleService->newPolicyCreateStruct('user', 'selfedit')
2800
        );
2801
2802
        // Create the new role instance
2803
        $roleDraft = $roleService->createRole($roleCreate);
2804
        $roleService->publishRoleDraft($roleDraft);
2805
        $role = $roleService->loadRole($roleDraft->id);
2806
2807
        // Assign role to anon user
2808
        $roleService->assignRoleToUser($role, $user);
2809
2810
        // Load the currently assigned role
2811
        $policies = array();
2812
        foreach ($roleService->loadPoliciesByUserId($user->id) as $policy) {
2813
            $policies[] = array($policy->roleId, $policy->module, $policy->function);
2814
        }
2815
        /* END: Use Case */
2816
        array_multisort($policies);
2817
2818
        $this->assertEquals(
2819
            array(
2820
                array(1, 'content', 'pdf'),
2821
                array(1, 'content', 'read'),
2822
                array(1, 'content', 'read'),
2823
                array(1, 'rss', 'feed'),
2824
                array(1, 'user', 'login'),
2825
                array(1, 'user', 'login'),
2826
                array(1, 'user', 'login'),
2827
                array(1, 'user', 'login'),
2828
                array($role->id, 'notification', 'use'),
2829
                array($role->id, 'user', 'password'),
2830
                array($role->id, 'user', 'selfedit'),
2831
            ),
2832
            $policies
2833
        );
2834
    }
2835
2836
    /**
2837
     * Test for the loadPoliciesByUserId() method.
2838
     *
2839
     * @see \eZ\Publish\API\Repository\RoleService::loadPoliciesByUserId()
2840
     * @expectedException \eZ\Publish\API\Repository\Exceptions\NotFoundException
2841
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadPoliciesByUserId
2842
     */
2843
    public function testLoadPoliciesByUserIdThrowsNotFoundException()
2844
    {
2845
        $repository = $this->getRepository();
2846
2847
        $nonExistingUserId = $this->generateId('user', self::DB_INT_MAX);
2848
        /* BEGIN: Use Case */
2849
        $roleService = $repository->getRoleService();
2850
2851
        // This call will fail with a "NotFoundException", because hopefully no
2852
        // user with an ID equal to self::DB_INT_MAX exists.
2853
        $roleService->loadPoliciesByUserId($nonExistingUserId);
2854
        /* END: Use Case */
2855
    }
2856
2857
    /**
2858
     * Test for the publishRoleDraft() method.
2859
     *
2860
     * @see \eZ\Publish\API\Repository\RoleService::publishRoleDraft()
2861
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRoleDraft
2862
     */
2863 View Code Duplication
    public function testPublishRoleDraft()
2864
    {
2865
        $repository = $this->getRepository();
2866
2867
        /* BEGIN: Use Case */
2868
        $roleService = $repository->getRoleService();
2869
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
2870
2871
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
2872
        // $roleCreate->mainLanguageCode = 'eng-US';
2873
2874
        $roleDraft = $roleService->createRole($roleCreate);
2875
2876
        $roleDraft = $roleService->addPolicyByRoleDraft(
2877
            $roleDraft,
2878
            $roleService->newPolicyCreateStruct('content', 'delete')
2879
        );
2880
        $roleDraft = $roleService->addPolicyByRoleDraft(
2881
            $roleDraft,
2882
            $roleService->newPolicyCreateStruct('content', 'create')
2883
        );
2884
2885
        $roleService->publishRoleDraft($roleDraft);
2886
        /* END: Use Case */
2887
2888
        $this->assertInstanceOf(
2889
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\Role',
2890
            $roleService->loadRoleByIdentifier($roleCreate->identifier)
2891
        );
2892
    }
2893
2894
    /**
2895
     * Test for the publishRoleDraft() method.
2896
     *
2897
     * @see \eZ\Publish\API\Repository\RoleService::publishRoleDraft()
2898
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRoleDraft
2899
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicyByRoleDraft
2900
     */
2901 View Code Duplication
    public function testPublishRoleDraftAddPolicies()
2902
    {
2903
        $repository = $this->getRepository();
2904
2905
        /* BEGIN: Use Case */
2906
        $roleService = $repository->getRoleService();
2907
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
2908
2909
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
2910
        // $roleCreate->mainLanguageCode = 'eng-US';
2911
2912
        $roleDraft = $roleService->createRole($roleCreate);
2913
2914
        $roleDraft = $roleService->addPolicyByRoleDraft(
2915
            $roleDraft,
2916
            $roleService->newPolicyCreateStruct('content', 'delete')
2917
        );
2918
        $roleDraft = $roleService->addPolicyByRoleDraft(
2919
            $roleDraft,
2920
            $roleService->newPolicyCreateStruct('content', 'create')
2921
        );
2922
2923
        $roleService->publishRoleDraft($roleDraft);
2924
        $role = $roleService->loadRoleByIdentifier($roleCreate->identifier);
2925
        /* END: Use Case */
2926
2927
        $actual = array();
2928
        foreach ($role->getPolicies() as $policy) {
2929
            $actual[] = array(
2930
                'module' => $policy->module,
2931
                'function' => $policy->function,
2932
            );
2933
        }
2934
        usort(
2935
            $actual,
2936
            function ($p1, $p2) {
2937
                return strcasecmp($p1['function'], $p2['function']);
2938
            }
2939
        );
2940
2941
        $this->assertEquals(
2942
            array(
2943
                array(
2944
                    'module' => 'content',
2945
                    'function' => 'create',
2946
                ),
2947
                array(
2948
                    'module' => 'content',
2949
                    'function' => 'delete',
2950
                ),
2951
            ),
2952
            $actual
2953
        );
2954
    }
2955
2956
    /**
2957
     * Create a user group fixture in a variable named <b>$userGroup</b>,.
2958
     *
2959
     * @return \eZ\Publish\API\Repository\Values\User\UserGroup
2960
     */
2961
    private function createUserGroupVersion1()
2962
    {
2963
        $repository = $this->getRepository();
2964
2965
        $mainGroupId = $this->generateId('group', 4);
2966
        /* BEGIN: Inline */
2967
        // $mainGroupId is the ID of the main "Users" group
2968
2969
        $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...
2970
        $userService = $repository->getUserService();
2971
2972
        // Load main group
2973
        $parentUserGroup = $userService->loadUserGroup($mainGroupId);
2974
2975
        // Instantiate a new create struct
2976
        $userGroupCreate = $userService->newUserGroupCreateStruct('eng-US');
2977
        $userGroupCreate->setField('name', 'Example Group');
2978
2979
        // Create the new user group
2980
        $userGroup = $userService->createUserGroup(
2981
            $userGroupCreate,
2982
            $parentUserGroup
2983
        );
2984
        /* END: Inline */
2985
2986
        return $userGroup;
2987
    }
2988
}
2989