Completed
Push — ezp29559_uncomment_sleeping_ro... ( c331f0...4b5351 )
by
unknown
33:02 queued 11:08
created

testLoadRoleByIdentifierThrowsNotFoundException()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 0
dl 0
loc 13
rs 9.8333
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
    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', 'read')
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', 'delete')
973
        );
974
        $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...
975
            $role,
976
            $roleService->newPolicyCreateStruct('content', 'create')
977
        );
978
        /* END: Use Case */
979
980
        $actual = array();
981
        foreach ($role->getPolicies() as $policy) {
982
            $actual[] = array(
983
                'module' => $policy->module,
984
                'function' => $policy->function,
985
            );
986
        }
987
        usort(
988
            $actual,
989
            function ($p1, $p2) {
990
                return strcasecmp($p1['function'], $p2['function']);
991
            }
992
        );
993
994
        $this->assertEquals(
995
            array(
996
                array(
997
                    'module' => 'content',
998
                    'function' => 'create',
999
                ),
1000
                array(
1001
                    'module' => 'content',
1002
                    'function' => 'delete',
1003
                ),
1004
            ),
1005
            $actual
1006
        );
1007
    }
1008
1009
    /**
1010
     * Test for the addPolicyByRoleDraft() method.
1011
     *
1012
     * @see \eZ\Publish\API\Repository\RoleService::addPolicyByRoleDraft()
1013
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRoleDraft
1014
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewPolicyCreateStruct
1015
     */
1016
    public function testAddPolicyByRoleDraft()
1017
    {
1018
        $repository = $this->getRepository();
1019
1020
        /* BEGIN: Use Case */
1021
        $roleService = $repository->getRoleService();
1022
1023
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
1024
1025
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1026
        // $roleCreate->mainLanguageCode = 'eng-US';
1027
1028
        $roleDraft = $roleService->createRole($roleCreate);
1029
1030
        $roleDraft = $roleService->addPolicyByRoleDraft(
1031
            $roleDraft,
1032
            $roleService->newPolicyCreateStruct('content', 'delete')
1033
        );
1034
        $roleDraft = $roleService->addPolicyByRoleDraft(
1035
            $roleDraft,
1036
            $roleService->newPolicyCreateStruct('content', 'create')
1037
        );
1038
        /* END: Use Case */
1039
1040
        $actual = array();
1041 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...
1042
            $actual[] = array(
1043
                'module' => $policy->module,
1044
                'function' => $policy->function,
1045
            );
1046
        }
1047
        usort(
1048
            $actual,
1049
            function ($p1, $p2) {
1050
                return strcasecmp($p1['function'], $p2['function']);
1051
            }
1052
        );
1053
1054
        $this->assertEquals(
1055
            array(
1056
                array(
1057
                    'module' => 'content',
1058
                    'function' => 'create',
1059
                ),
1060
                array(
1061
                    'module' => 'content',
1062
                    'function' => 'delete',
1063
                ),
1064
            ),
1065
            $actual
1066
        );
1067
    }
1068
1069
    /**
1070
     * Test for the addPolicy() method.
1071
     *
1072
     * @return array [\eZ\Publish\API\Repository\Values\User\Role, \eZ\Publish\API\Repository\Values\User\Policy]
1073
     *
1074
     * @see \eZ\Publish\API\Repository\RoleService::addPolicy()
1075
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicy
1076
     */
1077
    public function testAddPolicyUpdatesRole()
1078
    {
1079
        $repository = $this->getRepository();
1080
1081
        /* BEGIN: Use Case */
1082
        $roleService = $repository->getRoleService();
1083
1084
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
1085
1086
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1087
        // $roleCreate->mainLanguageCode = 'eng-US';
1088
1089
        $roleDraft = $roleService->createRole($roleCreate);
1090
        $roleService->addPolicyByRoleDraft(
1091
            $roleDraft,
1092
            $roleService->newPolicyCreateStruct('content', 'read')
1093
        );
1094
        $roleService->publishRoleDraft($roleDraft);
1095
        $role = $roleService->loadRole($roleDraft->id);
1096
1097
        $policyCreate = $roleService->newPolicyCreateStruct('content', 'create');
1098
        $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...
1099
1100
        $policy = null;
1101
        foreach ($role->getPolicies() as $policy) {
1102
            if ($policy->module === 'content' && $policy->function === 'create') {
1103
                break;
1104
            }
1105
        }
1106
        /* END: Use Case */
1107
1108
        $this->assertInstanceOf(
1109
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\Policy',
1110
            $policy
1111
        );
1112
1113
        return array($role, $policy);
1114
    }
1115
1116
    /**
1117
     * Test for the addPolicyByRoleDraft() method.
1118
     *
1119
     * @return array [\eZ\Publish\API\Repository\Values\User\RoleDraft, \eZ\Publish\API\Repository\Values\User\Policy]
1120
     *
1121
     * @see \eZ\Publish\API\Repository\RoleService::addPolicyByRoleDraft()
1122
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicyByRoleDraft
1123
     */
1124
    public function testAddPolicyByRoleDraftUpdatesRole()
1125
    {
1126
        $repository = $this->getRepository();
1127
1128
        /* BEGIN: Use Case */
1129
        $roleService = $repository->getRoleService();
1130
1131
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
1132
1133
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1134
        // $roleCreate->mainLanguageCode = 'eng-US';
1135
1136
        $roleDraft = $roleService->createRole($roleCreate);
1137
1138
        $policyCreate = $roleService->newPolicyCreateStruct('content', 'create');
1139
        $roleDraft = $roleService->addPolicyByRoleDraft($roleDraft, $policyCreate);
1140
1141
        $policy = null;
1142
        foreach ($roleDraft->getPolicies() as $policy) {
1143
            if ($policy->module === 'content' && $policy->function === 'create') {
1144
                break;
1145
            }
1146
        }
1147
        /* END: Use Case */
1148
1149
        $this->assertInstanceOf(
1150
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\Policy',
1151
            $policy
1152
        );
1153
1154
        return array($roleDraft, $policy);
1155
    }
1156
1157
    /**
1158
     * Test for the addPolicy() method.
1159
     *
1160
     * @param array $roleAndPolicy
1161
     *
1162
     * @see \eZ\Publish\API\Repository\RoleService::addPolicy()
1163
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicyUpdatesRole
1164
     */
1165 View Code Duplication
    public function testAddPolicySetsPolicyProperties($roleAndPolicy)
1166
    {
1167
        list($role, $policy) = $roleAndPolicy;
1168
1169
        $this->assertEquals(
1170
            array($role->id, 'content', 'create'),
1171
            array($policy->roleId, $policy->module, $policy->function)
1172
        );
1173
    }
1174
1175
    /**
1176
     * Test for the addPolicyByRoleDraft() method.
1177
     *
1178
     * @param array $roleAndPolicy
1179
     *
1180
     * @see \eZ\Publish\API\Repository\RoleService::addPolicyByRoleDraft()
1181
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicyByRoleDraftUpdatesRole
1182
     */
1183 View Code Duplication
    public function testAddPolicyByRoleDraftSetsPolicyProperties($roleAndPolicy)
1184
    {
1185
        list($role, $policy) = $roleAndPolicy;
1186
1187
        $this->assertEquals(
1188
            array($role->id, 'content', 'create'),
1189
            array($policy->roleId, $policy->module, $policy->function)
1190
        );
1191
    }
1192
1193
    /**
1194
     * Test for the publishRoleDraft() method.
1195
     *
1196
     * @expectedException \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException
1197
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRole
1198
     */
1199 View Code Duplication
    public function testPublishEmptyRoleThrowsInvalidArgumentException()
1200
    {
1201
        $repository = $this->getRepository();
1202
1203
        /* BEGIN: Use Case */
1204
        $roleService = $repository->getRoleService();
1205
1206
        $roleCreate = $roleService->newRoleCreateStruct('Lumberjack');
1207
1208
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1209
        // $roleCreate->mainLanguageCode = 'eng-US';
1210
1211
        $roleDraft = $roleService->createRole($roleCreate);
1212
        // This call will fail with an InvalidArgumentException, because the role has no policies
1213
        $roleService->publishRoleDraft($roleDraft);
1214
        /* END: Use Case */
1215
    }
1216
1217
    /**
1218
     * Test for the addPolicy() method.
1219
     *
1220
     * @see \eZ\Publish\API\Repository\RoleService::addPolicy()
1221
     * @expectedException \eZ\Publish\API\Repository\Exceptions\LimitationValidationException
1222
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewPolicyCreateStruct
1223
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRole
1224
     */
1225
    public function testAddPolicyThrowsLimitationValidationException()
1226
    {
1227
        $repository = $this->getRepository();
1228
1229
        /* BEGIN: Use Case */
1230
        $roleService = $repository->getRoleService();
1231
1232
        $roleCreate = $roleService->newRoleCreateStruct('Lumberjack');
1233
1234
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1235
        // $roleCreate->mainLanguageCode = 'eng-US';
1236
1237
        $roleDraft = $roleService->createRole($roleCreate);
1238
        $roleService->addPolicyByRoleDraft(
1239
            $roleDraft,
1240
            $roleService->newPolicyCreateStruct('content', 'create')
1241
        );
1242
1243
        $roleService->publishRoleDraft($roleDraft);
1244
        $role = $roleService->loadRole($roleDraft->id);
1245
1246
        // Create new subtree limitation
1247
        $limitation = new SubtreeLimitation(
1248
            array(
1249
                'limitationValues' => array('/mountain/forest/tree/42/'),
1250
            )
1251
        );
1252
1253
        // Create policy create struct and add limitation to it
1254
        $policyCreateStruct = $roleService->newPolicyCreateStruct('content', 'remove');
1255
        $policyCreateStruct->addLimitation($limitation);
1256
1257
        // This call will fail with an LimitationValidationException, because subtree
1258
        // "/mountain/forest/tree/42/" does not exist
1259
        $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...
1260
        /* END: Use Case */
1261
    }
1262
1263
    /**
1264
     * Test for the addPolicyByRoleDraft() method.
1265
     *
1266
     * @see \eZ\Publish\API\Repository\RoleService::addPolicyByRoleDraft()
1267
     * @expectedException \eZ\Publish\API\Repository\Exceptions\LimitationValidationException
1268
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewPolicyCreateStruct
1269
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRoleDraft
1270
     */
1271 View Code Duplication
    public function testAddPolicyByRoleDraftThrowsLimitationValidationException()
1272
    {
1273
        $repository = $this->getRepository();
1274
1275
        /* BEGIN: Use Case */
1276
        $roleService = $repository->getRoleService();
1277
1278
        $roleCreate = $roleService->newRoleCreateStruct('Lumberjack');
1279
1280
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1281
        // $roleCreate->mainLanguageCode = 'eng-US';
1282
1283
        $roleDraft = $roleService->createRole($roleCreate);
1284
1285
        // Create new subtree limitation
1286
        $limitation = new SubtreeLimitation(
1287
            array(
1288
                'limitationValues' => array('/mountain/forest/tree/42/'),
1289
            )
1290
        );
1291
1292
        // Create policy create struct and add limitation to it
1293
        $policyCreateStruct = $roleService->newPolicyCreateStruct('content', 'remove');
1294
        $policyCreateStruct->addLimitation($limitation);
1295
1296
        // This call will fail with an LimitationValidationException, because subtree
1297
        // "/mountain/forest/tree/42/" does not exist
1298
        $roleService->addPolicyByRoleDraft($roleDraft, $policyCreateStruct);
1299
        /* END: Use Case */
1300
    }
1301
1302
    /**
1303
     * Test for the createRole() method.
1304
     *
1305
     * @see \eZ\Publish\API\Repository\RoleService::createRole()
1306
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicyUpdatesRole
1307
     */
1308
    public function testCreateRoleWithAddPolicy()
1309
    {
1310
        $repository = $this->getRepository();
1311
1312
        /* BEGIN: Use Case */
1313
        $roleService = $repository->getRoleService();
1314
1315
        // Instantiate a new create struct
1316
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
1317
1318
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1319
        // $roleCreate->mainLanguageCode = 'eng-US';
1320
1321
        // Add some role policies
1322
        $roleCreate->addPolicy(
1323
            $roleService->newPolicyCreateStruct(
1324
                'content',
1325
                'read'
1326
            )
1327
        );
1328
        $roleCreate->addPolicy(
1329
            $roleService->newPolicyCreateStruct(
1330
                'content',
1331
                'translate'
1332
            )
1333
        );
1334
1335
        // Create new role instance
1336
        $roleDraft = $roleService->createRole($roleCreate);
1337
        $roleService->publishRoleDraft($roleDraft);
1338
        $role = $roleService->loadRole($roleDraft->id);
1339
1340
        $policies = array();
1341 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...
1342
            $policies[] = array('module' => $policy->module, 'function' => $policy->function);
1343
        }
1344
        /* END: Use Case */
1345
        array_multisort($policies);
1346
1347
        $this->assertEquals(
1348
            array(
1349
                array(
1350
                    'module' => 'content',
1351
                    'function' => 'read',
1352
                ),
1353
                array(
1354
                    'module' => 'content',
1355
                    'function' => 'translate',
1356
                ),
1357
            ),
1358
            $policies
1359
        );
1360
    }
1361
1362
    /**
1363
     * Test for the createRoleDraft() method.
1364
     *
1365
     * @see \eZ\Publish\API\Repository\RoleService::createRoleDraft()
1366
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicyByRoleDraftUpdatesRole
1367
     */
1368
    public function testCreateRoleDraftWithAddPolicy()
1369
    {
1370
        $repository = $this->getRepository();
1371
1372
        /* BEGIN: Use Case */
1373
        $roleService = $repository->getRoleService();
1374
1375
        // Instantiate a new create struct
1376
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
1377
1378
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1379
        // $roleCreate->mainLanguageCode = 'eng-US';
1380
1381
        // Add some role policies
1382
        $roleCreate->addPolicy(
1383
            $roleService->newPolicyCreateStruct(
1384
                'content',
1385
                'read'
1386
            )
1387
        );
1388
        $roleCreate->addPolicy(
1389
            $roleService->newPolicyCreateStruct(
1390
                'content',
1391
                'translate'
1392
            )
1393
        );
1394
1395
        // Create new role instance
1396
        $roleDraft = $roleService->createRole($roleCreate);
1397
1398
        $policies = array();
1399 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...
1400
            $policies[] = array('module' => $policy->module, 'function' => $policy->function);
1401
        }
1402
        /* END: Use Case */
1403
1404
        $this->assertEquals(
1405
            array(
1406
                array(
1407
                    'module' => 'content',
1408
                    'function' => 'read',
1409
                ),
1410
                array(
1411
                    'module' => 'content',
1412
                    'function' => 'translate',
1413
                ),
1414
            ),
1415
            $policies
1416
        );
1417
    }
1418
1419
    /**
1420
     * Test for the newPolicyUpdateStruct() method.
1421
     *
1422
     * @see \eZ\Publish\API\Repository\RoleService::newPolicyUpdateStruct()
1423
     */
1424
    public function testNewPolicyUpdateStruct()
1425
    {
1426
        $repository = $this->getRepository();
1427
1428
        /* BEGIN: Use Case */
1429
        $roleService = $repository->getRoleService();
1430
        $policyUpdate = $roleService->newPolicyUpdateStruct();
1431
        /* END: Use Case */
1432
1433
        $this->assertInstanceOf(
1434
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\PolicyUpdateStruct',
1435
            $policyUpdate
1436
        );
1437
    }
1438
1439
    public function testUpdatePolicyNoLimitation()
1440
    {
1441
        $repository = $this->getRepository();
1442
1443
        /* BEGIN: Use Case */
1444
        $roleService = $repository->getRoleService();
1445
1446
        // Instantiate new policy create
1447
        $policyCreate = $roleService->newPolicyCreateStruct('foo', 'bar');
1448
1449
        // Instantiate a role create and add the policy create
1450
        $roleCreate = $roleService->newRoleCreateStruct('myRole');
1451
1452
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1453
        // $roleCreate->mainLanguageCode = 'eng-US';
1454
1455
        $roleCreate->addPolicy($policyCreate);
1456
1457
        // Create a new role instance.
1458
        $roleDraft = $roleService->createRole($roleCreate);
1459
        $roleService->publishRoleDraft($roleDraft);
1460
        $role = $roleService->loadRole($roleDraft->id);
1461
1462
        // Search for the new policy instance
1463
        $policy = null;
1464
        foreach ($role->getPolicies() as $policy) {
1465
            if ($policy->module === 'foo' && $policy->function === 'bar') {
1466
                break;
1467
            }
1468
        }
1469
1470
        // Create an update struct
1471
        $policyUpdate = $roleService->newPolicyUpdateStruct();
1472
1473
        // Update the the policy
1474
        $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...
1475
        /* END: Use Case */
1476
1477
        $this->assertInstanceOf(
1478
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\Policy',
1479
            $policy
1480
        );
1481
1482
        self::assertEquals(array(), $policy->getLimitations());
1483
    }
1484
1485
    /**
1486
     * Test for the updatePolicy() method.
1487
     *
1488
     * @return array
1489
     *
1490
     * @see \eZ\Publish\API\Repository\RoleService::updatePolicy()
1491
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicy
1492
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewPolicyUpdateStruct
1493
     */
1494
    public function testUpdatePolicy()
1495
    {
1496
        $repository = $this->getRepository();
1497
1498
        /* BEGIN: Use Case */
1499
        $roleService = $repository->getRoleService();
1500
1501
        // Instantiate new policy create
1502
        $policyCreate = $roleService->newPolicyCreateStruct('content', 'translate');
1503
1504
        // Add some limitations for the new policy
1505
        $policyCreate->addLimitation(
1506
            new LanguageLimitation(
1507
                array(
1508
                    'limitationValues' => array('eng-US', 'eng-GB'),
1509
                )
1510
            )
1511
        );
1512
1513
        // Instantiate a role create and add the policy create
1514
        $roleCreate = $roleService->newRoleCreateStruct('myRole');
1515
1516
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1517
        // $roleCreate->mainLanguageCode = 'eng-US';
1518
1519
        $roleCreate->addPolicy($policyCreate);
1520
1521
        // Create a new role instance.
1522
        $roleDraft = $roleService->createRole($roleCreate);
1523
        $roleService->publishRoleDraft($roleDraft);
1524
        $role = $roleService->loadRole($roleDraft->id);
1525
1526
        // Search for the new policy instance
1527
        $policy = null;
1528
        foreach ($role->getPolicies() as $policy) {
1529
            if ($policy->module === 'content' && $policy->function === 'translate') {
1530
                break;
1531
            }
1532
        }
1533
1534
        // Create an update struct and set a modified limitation
1535
        $policyUpdate = $roleService->newPolicyUpdateStruct();
1536
        $policyUpdate->addLimitation(
1537
            new ContentTypeLimitation(
1538
                array(
1539
                    'limitationValues' => array(29, 30),
1540
                )
1541
            )
1542
        );
1543
1544
        // Update the the policy
1545
        $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...
1546
        /* END: Use Case */
1547
1548
        $this->assertInstanceOf(
1549
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\Policy',
1550
            $policy
1551
        );
1552
1553
        return array($roleService->loadRole($role->id), $policy);
1554
    }
1555
1556
    /**
1557
     * Test for the updatePolicy() method.
1558
     *
1559
     * @param array $roleAndPolicy
1560
     *
1561
     * @see \eZ\Publish\API\Repository\RoleService::updatePolicy()
1562
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testUpdatePolicy
1563
     */
1564
    public function testUpdatePolicyUpdatesLimitations($roleAndPolicy)
1565
    {
1566
        list($role, $policy) = $roleAndPolicy;
1567
1568
        $this->assertEquals(
1569
            array(
1570
                new ContentTypeLimitation(
1571
                    array(
1572
                        'limitationValues' => array(29, 30),
1573
                    )
1574
                ),
1575
            ),
1576
            $policy->getLimitations()
1577
        );
1578
1579
        return $role;
1580
    }
1581
1582
    /**
1583
     * Test for the updatePolicy() method.
1584
     *
1585
     * @param \eZ\Publish\API\Repository\Values\User\Role $role
1586
     *
1587
     * @see \eZ\Publish\API\Repository\RoleService::updatePolicy()
1588
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testUpdatePolicyUpdatesLimitations
1589
     */
1590
    public function testUpdatePolicyUpdatesRole($role)
1591
    {
1592
        $limitations = array();
1593
        foreach ($role->getPolicies() as $policy) {
1594
            foreach ($policy->getLimitations() as $limitation) {
1595
                $limitations[] = $limitation;
1596
            }
1597
        }
1598
1599
        $this->assertCount(1, $limitations);
1600
        $this->assertInstanceOf(
1601
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\Limitation',
1602
            $limitations[0]
1603
        );
1604
1605
        $expectedData = array(
1606
            'limitationValues' => array(29, 30),
1607
        );
1608
        $this->assertPropertiesCorrectUnsorted(
1609
            $expectedData,
1610
            $limitations[0]
1611
        );
1612
    }
1613
1614
    /**
1615
     * Test for the updatePolicy() method.
1616
     *
1617
     * @see \eZ\Publish\API\Repository\RoleService::updatePolicy()
1618
     * @expectedException \eZ\Publish\API\Repository\Exceptions\LimitationValidationException
1619
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicy
1620
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewPolicyCreateStruct
1621
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewPolicyUpdateStruct
1622
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testNewRoleCreateStruct
1623
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRole
1624
     */
1625
    public function testUpdatePolicyThrowsLimitationValidationException()
1626
    {
1627
        $repository = $this->getRepository();
1628
1629
        /* BEGIN: Use Case */
1630
        $roleService = $repository->getRoleService();
1631
1632
        // Instantiate new policy create
1633
        $policyCreate = $roleService->newPolicyCreateStruct('content', 'remove');
1634
1635
        // Add some limitations for the new policy
1636
        $policyCreate->addLimitation(
1637
            new SubtreeLimitation(
1638
                array(
1639
                    'limitationValues' => array('/1/2/'),
1640
                )
1641
            )
1642
        );
1643
1644
        // Instantiate a role create and add the policy create
1645
        $roleCreate = $roleService->newRoleCreateStruct('myRole');
1646
1647
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1648
        // $roleCreate->mainLanguageCode = 'eng-US';
1649
1650
        $roleCreate->addPolicy($policyCreate);
1651
1652
        // Create a new role instance.
1653
        $roleDraft = $roleService->createRole($roleCreate);
1654
        $roleService->publishRoleDraft($roleDraft);
1655
        $role = $roleService->loadRole($roleDraft->id);
1656
1657
        // Search for the new policy instance
1658
        $policy = null;
1659
        foreach ($role->getPolicies() as $policy) {
1660
            if ($policy->module === 'content' && $policy->function === 'remove') {
1661
                break;
1662
            }
1663
        }
1664
1665
        // Create an update struct and set a modified limitation
1666
        $policyUpdate = $roleService->newPolicyUpdateStruct();
1667
        $policyUpdate->addLimitation(
1668
            new SubtreeLimitation(
1669
                array(
1670
                    'limitationValues' => array('/mountain/forest/tree/42/'),
1671
                )
1672
            )
1673
        );
1674
1675
        // This call will fail with an LimitationValidationException, because subtree
1676
        // "/mountain/forest/tree/42/" does not exist
1677
        $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...
1678
        /* END: Use Case */
1679
    }
1680
1681
    /**
1682
     * Test for the removePolicy() method.
1683
     *
1684
     * @see \eZ\Publish\API\Repository\RoleService::removePolicy()
1685
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicy
1686
     */
1687 View Code Duplication
    public function testRemovePolicy()
1688
    {
1689
        $repository = $this->getRepository();
1690
1691
        /* BEGIN: Use Case */
1692
        $roleService = $repository->getRoleService();
1693
1694
        // Instantiate a new role create
1695
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
1696
1697
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1698
        // $roleCreate->mainLanguageCode = 'eng-US';
1699
1700
        // Create a new role with two policies
1701
        $roleDraft = $roleService->createRole($roleCreate);
1702
        $roleService->addPolicyByRoleDraft(
1703
            $roleDraft,
1704
            $roleService->newPolicyCreateStruct('content', 'create')
1705
        );
1706
        $roleService->addPolicyByRoleDraft(
1707
            $roleDraft,
1708
            $roleService->newPolicyCreateStruct('content', 'delete')
1709
        );
1710
        $roleService->publishRoleDraft($roleDraft);
1711
        $role = $roleService->loadRole($roleDraft->id);
1712
1713
        // Delete all policies from the new role
1714
        foreach ($role->getPolicies() as $policy) {
1715
            $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...
1716
        }
1717
        /* END: Use Case */
1718
1719
        $this->assertSame(array(), $role->getPolicies());
1720
    }
1721
1722
    /**
1723
     * Test for the removePolicyByRoleDraft() method.
1724
     *
1725
     * @see \eZ\Publish\API\Repository\RoleService::removePolicyByRoleDraft()
1726
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicyByRoleDraft
1727
     */
1728 View Code Duplication
    public function testRemovePolicyByRoleDraft()
1729
    {
1730
        $repository = $this->getRepository();
1731
1732
        /* BEGIN: Use Case */
1733
        $roleService = $repository->getRoleService();
1734
1735
        // Instantiate a new role create
1736
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
1737
1738
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1739
        // $roleCreate->mainLanguageCode = 'eng-US';
1740
1741
        // Create a new role with two policies
1742
        $roleDraft = $roleService->createRole($roleCreate);
1743
        $roleService->addPolicyByRoleDraft(
1744
            $roleDraft,
1745
            $roleService->newPolicyCreateStruct('content', 'create')
1746
        );
1747
        $roleService->addPolicyByRoleDraft(
1748
            $roleDraft,
1749
            $roleService->newPolicyCreateStruct('content', 'delete')
1750
        );
1751
1752
        // Delete all policies from the new role
1753
        foreach ($roleDraft->getPolicies() as $policy) {
1754
            $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...
1755
        }
1756
        /* END: Use Case */
1757
1758
        $this->assertSame(array(), $roleDraft->getPolicies());
1759
    }
1760
1761
    /**
1762
     * Test for the deletePolicy() method.
1763
     *
1764
     * @see \eZ\Publish\API\Repository\RoleService::deletePolicy()
1765
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRole
1766
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicy
1767
     */
1768 View Code Duplication
    public function testDeletePolicy()
1769
    {
1770
        $repository = $this->getRepository();
1771
1772
        /* BEGIN: Use Case */
1773
        $roleService = $repository->getRoleService();
1774
1775
        // Instantiate a new role create
1776
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
1777
1778
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
1779
        // $roleCreate->mainLanguageCode = 'eng-US';
1780
1781
        // Create a new role with two policies
1782
        $roleDraft = $roleService->createRole($roleCreate);
1783
        $roleService->addPolicyByRoleDraft(
1784
            $roleDraft,
1785
            $roleService->newPolicyCreateStruct('content', 'create')
1786
        );
1787
        $roleService->addPolicyByRoleDraft(
1788
            $roleDraft,
1789
            $roleService->newPolicyCreateStruct('content', 'delete')
1790
        );
1791
        $roleService->publishRoleDraft($roleDraft);
1792
        $role = $roleService->loadRole($roleDraft->id);
1793
1794
        // Delete all policies from the new role
1795
        foreach ($role->getPolicies() as $policy) {
1796
            $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...
1797
        }
1798
        /* END: Use Case */
1799
1800
        $role = $roleService->loadRole($role->id);
1801
        $this->assertSame(array(), $role->getPolicies());
1802
    }
1803
1804
    /**
1805
     * Test loading user/group role assignments.
1806
     *
1807
     * @return \eZ\Publish\API\Repository\Values\User\UserGroupRoleAssignment
1808
     *
1809
     * @covers \eZ\Publish\API\Repository\RoleService::loadRoleAssignment
1810
     */
1811
    public function testLoadRoleAssignment()
1812
    {
1813
        $repository = $this->getRepository();
1814
1815
        /* BEGIN: Use Case */
1816
        $roleService = $repository->getRoleService();
1817
1818
        // Assignment to user group
1819
        $groupRoleAssignment = $roleService->loadRoleAssignment(25);
1820
1821
        // Assignment to user
1822
        $role = $roleService->loadRole(2);
1823
        $user = $repository->getUserService()->loadUser(14);
1824
        $roleService->assignRoleToUser($role, $user);
1825
        $userRoleAssignments = $roleService->getRoleAssignmentsForUser($user);
1826
1827
        $userRoleAssignment = $roleService->loadRoleAssignment($userRoleAssignments[0]->id);
1828
        /* END: Use Case */
1829
1830
        $this->assertInstanceOf(
1831
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\UserGroupRoleAssignment',
1832
            $groupRoleAssignment
1833
        );
1834
1835
        $this->assertEquals(
1836
            [
1837
                12,
1838
                2,
1839
                25,
1840
            ],
1841
            [
1842
                $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...
1843
                $groupRoleAssignment->role->id,
1844
                $groupRoleAssignment->id,
1845
            ]
1846
        );
1847
1848
        self::assertInstanceOf('\\eZ\\Publish\\API\\Repository\\Values\\User\\UserRoleAssignment', $userRoleAssignment);
1849
        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...
1850
1851
        return $groupRoleAssignment;
1852
    }
1853
1854
    /**
1855
     * Test for the getRoleAssignments() method.
1856
     *
1857
     * @return \eZ\Publish\API\Repository\Values\User\RoleAssignment[]
1858
     *
1859
     * @see \eZ\Publish\API\Repository\RoleService::getRoleAssignments()
1860
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleByIdentifier
1861
     */
1862
    public function testGetRoleAssignments()
1863
    {
1864
        $repository = $this->getRepository();
1865
1866
        /* BEGIN: Use Case */
1867
        $roleService = $repository->getRoleService();
1868
1869
        // Load the editor role
1870
        $role = $roleService->loadRoleByIdentifier('Editor');
1871
1872
        // Load all assigned users and user groups
1873
        $roleAssignments = $roleService->getRoleAssignments($role);
1874
1875
        /* END: Use Case */
1876
1877
        $this->assertEquals(2, count($roleAssignments));
1878
        $this->assertInstanceOf(
1879
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\UserGroupRoleAssignment',
1880
            $roleAssignments[0]
1881
        );
1882
        $this->assertInstanceOf(
1883
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\UserGroupRoleAssignment',
1884
            $roleAssignments[1]
1885
        );
1886
1887
        return $roleAssignments;
1888
    }
1889
1890
    /**
1891
     * Test for the getRoleAssignments() method.
1892
     *
1893
     * @param \eZ\Publish\API\Repository\Values\User\RoleAssignment[] $roleAssignments
1894
     *
1895
     * @see \eZ\Publish\API\Repository\RoleService::getRoleAssignments()
1896
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testGetRoleAssignments
1897
     */
1898
    public function testGetRoleAssignmentsContainExpectedLimitation(array $roleAssignments)
1899
    {
1900
        $this->assertEquals(
1901
            'Subtree',
1902
            reset($roleAssignments)->limitation->getIdentifier()
1903
        );
1904
    }
1905
1906
    /**
1907
     * Test for the assignRoleToUser() method.
1908
     *
1909
     * @see \eZ\Publish\API\Repository\RoleService::assignRoleToUser()
1910
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testGetRoleAssignments
1911
     */
1912 View Code Duplication
    public function testAssignRoleToUser()
1913
    {
1914
        $repository = $this->getRepository();
1915
        $roleService = $repository->getRoleService();
1916
1917
        /* BEGIN: Use Case */
1918
        $user = $this->createUserVersion1();
1919
1920
        // Load the existing "Administrator" role
1921
        $role = $roleService->loadRoleByIdentifier('Administrator');
1922
1923
        // Assign the "Administrator" role to the newly created user
1924
        $roleService->assignRoleToUser($role, $user);
1925
1926
        // The assignments array will contain the new role<->user assignment
1927
        $roleAssignments = $roleService->getRoleAssignments($role);
1928
        /* END: Use Case */
1929
1930
        // Administrator + Example User
1931
        $this->assertEquals(2, count($roleAssignments));
1932
    }
1933
1934
    /**
1935
     * Test for the assignRoleToUser() method.
1936
     *
1937
     * @see \eZ\Publish\API\Repository\RoleService::assignRoleToUser($role, $user, $roleLimitation)
1938
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUser
1939
     */
1940 View Code Duplication
    public function testAssignRoleToUserWithRoleLimitation()
1941
    {
1942
        $repository = $this->getRepository();
1943
        $roleService = $repository->getRoleService();
1944
1945
        /* BEGIN: Use Case */
1946
        $user = $this->createUserVersion1();
1947
1948
        // Load the existing "Anonymous" role
1949
        $role = $roleService->loadRoleByIdentifier('Anonymous');
1950
1951
        // Assign the "Anonymous" role to the newly created user
1952
        $roleService->assignRoleToUser(
1953
            $role,
1954
            $user,
1955
            new SubtreeLimitation(
1956
                array(
1957
                    'limitationValues' => array('/1/43/'),
1958
                )
1959
            )
1960
        );
1961
1962
        // The assignments array will contain the new role<->user assignment
1963
        $roleAssignments = $roleService->getRoleAssignments($role);
1964
        /* END: Use Case */
1965
1966
        // Members + Partners + Anonymous + Example User
1967
        $this->assertEquals(4, count($roleAssignments));
1968
1969
        // Get the role limitation
1970
        $roleLimitation = null;
1971
        foreach ($roleAssignments as $roleAssignment) {
1972
            $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...
1973
            if ($roleLimitation) {
1974
                $this->assertInstanceOf(
1975
                    '\\eZ\\Publish\\API\\Repository\\Values\\User\\UserRoleAssignment',
1976
                    $roleAssignment
1977
                );
1978
                break;
1979
            }
1980
        }
1981
1982
        $this->assertEquals(
1983
            new SubtreeLimitation(
1984
                array(
1985
                    'limitationValues' => array('/1/43/'),
1986
                )
1987
            ),
1988
            $roleLimitation
1989
        );
1990
1991
        // Test again to see values being merged
1992
        $roleService->assignRoleToUser(
1993
            $role,
1994
            $user,
1995
            new SubtreeLimitation(
1996
                array(
1997
                    'limitationValues' => array('/1/43/', '/1/2/'),
1998
                )
1999
            )
2000
        );
2001
2002
        // The assignments array will contain the new role<->user assignment
2003
        $roleAssignments = $roleService->getRoleAssignments($role);
2004
2005
        // Members + Partners + Anonymous + Example User
2006
        $this->assertEquals(5, count($roleAssignments));
2007
2008
        // Get the role limitation
2009
        $roleLimitations = [];
2010
        foreach ($roleAssignments as $roleAssignment) {
2011
            $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...
2012
            if ($roleLimitation) {
2013
                $this->assertInstanceOf(
2014
                    '\\eZ\\Publish\\API\\Repository\\Values\\User\\UserRoleAssignment',
2015
                    $roleAssignment
2016
                );
2017
                $roleLimitations[] = $roleLimitation;
2018
            }
2019
        }
2020
        array_multisort($roleLimitations);
2021
2022
        $this->assertEquals(
2023
            [
2024
                new SubtreeLimitation(
2025
                    array(
2026
                        'limitationValues' => array('/1/2/'),
2027
                    )
2028
                ),
2029
                new SubtreeLimitation(
2030
                    array(
2031
                        'limitationValues' => array('/1/43/'),
2032
                    )
2033
                ),
2034
            ],
2035
            $roleLimitations
2036
        );
2037
    }
2038
2039
    /**
2040
     * Test for the assignRoleToUser() method.
2041
     *
2042
     * @see \eZ\Publish\API\Repository\RoleService::assignRoleToUser($role, $user, $roleLimitation)
2043
     * @expectedException \eZ\Publish\API\Repository\Exceptions\LimitationValidationException
2044
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUser
2045
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleByIdentifier
2046
     */
2047
    public function testAssignRoleToUserWithRoleLimitationThrowsLimitationValidationException()
2048
    {
2049
        $repository = $this->getRepository();
2050
2051
        /* BEGIN: Use Case */
2052
        $roleService = $repository->getRoleService();
2053
2054
        // Load the existing "Anonymous" role
2055
        $role = $roleService->loadRoleByIdentifier('Anonymous');
2056
2057
        // Get current user
2058
        $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...
2059
2060
        // Assign the "Anonymous" role to the current user
2061
        // This call will fail with an LimitationValidationException, because subtree "/lorem/ipsum/42/"
2062
        // does not exists
2063
        $roleService->assignRoleToUser(
2064
            $role,
2065
            $currentUser,
2066
            new SubtreeLimitation(
2067
                array(
2068
                    'limitationValues' => array('/lorem/ipsum/42/'),
2069
                )
2070
            )
2071
        );
2072
        /* END: Use Case */
2073
    }
2074
2075
    /**
2076
     * Test for the assignRoleToUser() method.
2077
     *
2078
     * Makes sure assigning role several times throws.
2079
     *
2080
     * @see \eZ\Publish\API\Repository\RoleService::assignRoleToUser($role, $user, $roleLimitation)
2081
     * @expectedException \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException
2082
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUser
2083
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleByIdentifier
2084
     */
2085 View Code Duplication
    public function testAssignRoleToUserThrowsInvalidArgumentException()
2086
    {
2087
        $repository = $this->getRepository();
2088
2089
        /* BEGIN: Use Case */
2090
        $roleService = $repository->getRoleService();
2091
2092
        // Load the existing "Anonymous" role
2093
        $role = $roleService->loadRoleByIdentifier('Anonymous');
2094
2095
        // Get current user
2096
        $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...
2097
2098
        // Assign the "Anonymous" role to the current user
2099
        try {
2100
            $roleService->assignRoleToUser(
2101
                $role,
2102
                $currentUser
2103
            );
2104
        } catch (Exception $e) {
2105
            $this->fail('Got exception at first valid attempt to assign role');
2106
        }
2107
2108
        // Re-Assign the "Anonymous" role to the current user
2109
        // This call will fail with an InvalidArgumentException, because limitation is already assigned
2110
        $roleService->assignRoleToUser(
2111
            $role,
2112
            $currentUser
2113
        );
2114
        /* END: Use Case */
2115
    }
2116
2117
    /**
2118
     * Test for the assignRoleToUser() method.
2119
     *
2120
     * Makes sure assigning role several times with same limitations throws.
2121
     *
2122
     * @see \eZ\Publish\API\Repository\RoleService::assignRoleToUser($role, $user, $roleLimitation)
2123
     * @expectedException \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException
2124
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUser
2125
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleByIdentifier
2126
     */
2127
    public function testAssignRoleToUserWithRoleLimitationThrowsInvalidArgumentException()
2128
    {
2129
        $repository = $this->getRepository();
2130
2131
        /* BEGIN: Use Case */
2132
        $roleService = $repository->getRoleService();
2133
2134
        // Load the existing "Anonymous" role
2135
        $role = $roleService->loadRoleByIdentifier('Anonymous');
2136
2137
        // Get current user
2138
        $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...
2139
2140
        // Assign the "Anonymous" role to the current user
2141
        try {
2142
            $roleService->assignRoleToUser(
2143
                $role,
2144
                $currentUser,
2145
                new SubtreeLimitation(
2146
                    array(
2147
                        'limitationValues' => array('/1/43/', '/1/2/'),
2148
                    )
2149
                )
2150
            );
2151
        } catch (Exception $e) {
2152
            $this->fail('Got exception at first valid attempt to assign role');
2153
        }
2154
2155
        // Re-Assign the "Anonymous" role to the current user
2156
        // This call will fail with an InvalidArgumentException, because limitation is already assigned
2157
        $roleService->assignRoleToUser(
2158
            $role,
2159
            $currentUser,
2160
            new SubtreeLimitation(
2161
                array(
2162
                    'limitationValues' => array('/1/43/'),
2163
                )
2164
            )
2165
        );
2166
        /* END: Use Case */
2167
    }
2168
2169
    /**
2170
     * Test for the unassignRoleFromUser() method.
2171
     *
2172
     * @see \eZ\Publish\API\Repository\RoleService::unassignRoleFromUser()
2173
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUser
2174
     */
2175 View Code Duplication
    public function testUnassignRoleFromUser()
2176
    {
2177
        $repository = $this->getRepository();
2178
        $roleService = $repository->getRoleService();
2179
2180
        /* BEGIN: Use Case */
2181
        $user = $this->createUserVersion1();
2182
2183
        // Load the existing "Member" role
2184
        $role = $roleService->loadRoleByIdentifier('Member');
2185
2186
        // Assign the "Member" role to the newly created user
2187
        $roleService->assignRoleToUser($role, $user);
2188
2189
        // Unassign user from role
2190
        $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...
2191
2192
        // The assignments array will not contain the new role<->user assignment
2193
        $roleAssignments = $roleService->getRoleAssignments($role);
2194
        /* END: Use Case */
2195
2196
        // Members + Editors + Partners
2197
        $this->assertEquals(3, count($roleAssignments));
2198
    }
2199
2200
    /**
2201
     * Test for the unassignRoleFromUser() method.
2202
     *
2203
     * @see \eZ\Publish\API\Repository\RoleService::unassignRoleFromUser()
2204
     * @expectedException \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException
2205
     */
2206 View Code Duplication
    public function testUnassignRoleFromUserThrowsInvalidArgumentException()
2207
    {
2208
        $repository = $this->getRepository();
2209
        $roleService = $repository->getRoleService();
2210
2211
        /* BEGIN: Use Case */
2212
        $user = $this->createUserVersion1();
2213
2214
        // Load the existing "Member" role
2215
        $role = $roleService->loadRoleByIdentifier('Member');
2216
2217
        // This call will fail with a "InvalidArgumentException", because the
2218
        // user does not have the "Member" role.
2219
        $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...
2220
        /* END: Use Case */
2221
    }
2222
2223
    /**
2224
     * Test for the getRoleAssignmentsForUser() method.
2225
     *
2226
     * @see \eZ\Publish\API\Repository\RoleService::getRoleAssignmentsForUser()
2227
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUser
2228
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRoleWithAddPolicy
2229
     */
2230 View Code Duplication
    public function testGetRoleAssignmentsForUserDirect()
2231
    {
2232
        $repository = $this->getRepository();
2233
        $roleService = $repository->getRoleService();
2234
2235
        /* BEGIN: Use Case */
2236
        $user = $this->createUserVersion1();
2237
2238
        // Instantiate a role create and add some policies
2239
        $roleCreate = $roleService->newRoleCreateStruct('Example Role');
2240
2241
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
2242
        // $roleCreate->mainLanguageCode = 'eng-US';
2243
2244
        $roleCreate->addPolicy(
2245
            $roleService->newPolicyCreateStruct('user', 'login')
2246
        );
2247
        $roleCreate->addPolicy(
2248
            $roleService->newPolicyCreateStruct('content', 'read')
2249
        );
2250
        $roleCreate->addPolicy(
2251
            $roleService->newPolicyCreateStruct('content', 'edit')
2252
        );
2253
2254
        // Create the new role instance
2255
        $roleDraft = $roleService->createRole($roleCreate);
2256
        $roleService->publishRoleDraft($roleDraft);
2257
        $role = $roleService->loadRole($roleDraft->id);
2258
2259
        // Assign role to new user
2260
        $roleService->assignRoleToUser($role, $user);
2261
2262
        // Load the currently assigned role
2263
        $roleAssignments = $roleService->getRoleAssignmentsForUser($user);
2264
        /* END: Use Case */
2265
2266
        $this->assertEquals(1, count($roleAssignments));
2267
        $this->assertInstanceOf(
2268
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\UserRoleAssignment',
2269
            reset($roleAssignments)
2270
        );
2271
    }
2272
2273
    /**
2274
     * Test for the getRoleAssignmentsForUser() method.
2275
     *
2276
     * @see \eZ\Publish\API\Repository\RoleService::getRoleAssignmentsForUser()
2277
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUser
2278
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRoleWithAddPolicy
2279
     */
2280
    public function testGetRoleAssignmentsForUserEmpty()
2281
    {
2282
        $repository = $this->getRepository();
2283
        $roleService = $repository->getRoleService();
2284
2285
        /* BEGIN: Use Case */
2286
        $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...
2287
2288
        // Load the currently assigned role
2289
        $roleAssignments = $roleService->getRoleAssignmentsForUser($adminUser);
2290
        /* END: Use Case */
2291
2292
        $this->assertEquals(0, count($roleAssignments));
2293
    }
2294
2295
    /**
2296
     * Test for the getRoleAssignmentsForUser() method.
2297
     *
2298
     * @see \eZ\Publish\API\Repository\RoleService::getRoleAssignmentsForUser()
2299
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUser
2300
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRoleWithAddPolicy
2301
     */
2302
    public function testGetRoleAssignmentsForUserInherited()
2303
    {
2304
        $repository = $this->getRepository();
2305
        $roleService = $repository->getRoleService();
2306
2307
        /* BEGIN: Use Case */
2308
        $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...
2309
2310
        // Load the currently assigned role + inherited role assignments
2311
        $roleAssignments = $roleService->getRoleAssignmentsForUser($adminUser, true);
2312
        /* END: Use Case */
2313
2314
        $this->assertEquals(1, count($roleAssignments));
2315
        $this->assertInstanceOf(
2316
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\UserGroupRoleAssignment',
2317
            reset($roleAssignments)
2318
        );
2319
    }
2320
2321
    /**
2322
     * Test for the assignRoleToUserGroup() method.
2323
     *
2324
     * @see \eZ\Publish\API\Repository\RoleService::assignRoleToUserGroup()
2325
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testGetRoleAssignments
2326
     */
2327 View Code Duplication
    public function testAssignRoleToUserGroup()
2328
    {
2329
        $repository = $this->getRepository();
2330
        $roleService = $repository->getRoleService();
2331
2332
        /* BEGIN: Use Case */
2333
        $userGroup = $this->createUserGroupVersion1();
2334
2335
        // Load the existing "Administrator" role
2336
        $role = $roleService->loadRoleByIdentifier('Administrator');
2337
2338
        // Assign the "Administrator" role to the newly created user group
2339
        $roleService->assignRoleToUserGroup($role, $userGroup);
2340
2341
        // The assignments array will contain the new role<->group assignment
2342
        $roleAssignments = $roleService->getRoleAssignments($role);
2343
        /* END: Use Case */
2344
2345
        // Administrator + Example Group
2346
        $this->assertEquals(2, count($roleAssignments));
2347
    }
2348
2349
    /**
2350
     * Test for the assignRoleToUserGroup() method.
2351
     *
2352
     * @see \eZ\Publish\API\Repository\RoleService::assignRoleToUserGroup($role, $userGroup, $roleLimitation)
2353
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUserGroup
2354
     */
2355 View Code Duplication
    public function testAssignRoleToUserGroupWithRoleLimitation()
2356
    {
2357
        $repository = $this->getRepository();
2358
        $roleService = $repository->getRoleService();
2359
2360
        /* BEGIN: Use Case */
2361
        $userGroup = $this->createUserGroupVersion1();
2362
2363
        // Load the existing "Anonymous" role
2364
        $role = $roleService->loadRoleByIdentifier('Anonymous');
2365
2366
        // Assign the "Anonymous" role to the newly created user group
2367
        $roleService->assignRoleToUserGroup(
2368
            $role,
2369
            $userGroup,
2370
            new SubtreeLimitation(
2371
                array(
2372
                    'limitationValues' => array('/1/43/'),
2373
                )
2374
            )
2375
        );
2376
2377
        // The assignments array will contain the new role<->group assignment
2378
        $roleAssignments = $roleService->getRoleAssignments($role);
2379
        /* END: Use Case */
2380
2381
        // Members + Partners + Anonymous + Example Group
2382
        $this->assertEquals(4, count($roleAssignments));
2383
2384
        // Get the role limitation
2385
        $roleLimitation = null;
2386
        foreach ($roleAssignments as $roleAssignment) {
2387
            $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...
2388
            if ($roleLimitation) {
2389
                break;
2390
            }
2391
        }
2392
2393
        $this->assertEquals(
2394
            new SubtreeLimitation(
2395
                array(
2396
                    'limitationValues' => array('/1/43/'),
2397
                )
2398
            ),
2399
            $roleLimitation
2400
        );
2401
2402
        // Test again to see values being merged
2403
        $roleService->assignRoleToUserGroup(
2404
            $role,
2405
            $userGroup,
2406
            new SubtreeLimitation(
2407
                array(
2408
                    'limitationValues' => array('/1/43/', '/1/2/'),
2409
                )
2410
            )
2411
        );
2412
2413
        // The assignments array will contain the new role<->user assignment
2414
        $roleAssignments = $roleService->getRoleAssignments($role);
2415
2416
        // Members + Partners + Anonymous + Example User
2417
        $this->assertEquals(5, count($roleAssignments));
2418
2419
        // Get the role limitation
2420
        $roleLimitations = [];
2421
        foreach ($roleAssignments as $roleAssignment) {
2422
            $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...
2423
            if ($roleLimitation) {
2424
                $this->assertInstanceOf(
2425
                    '\\eZ\\Publish\\API\\Repository\\Values\\User\\UserGroupRoleAssignment',
2426
                    $roleAssignment
2427
                );
2428
                $roleLimitations[] = $roleLimitation;
2429
            }
2430
        }
2431
        array_multisort($roleLimitations);
2432
2433
        $this->assertEquals(
2434
            [
2435
                new SubtreeLimitation(
2436
                    array(
2437
                        'limitationValues' => array('/1/2/'),
2438
                    )
2439
                ),
2440
                new SubtreeLimitation(
2441
                    array(
2442
                        'limitationValues' => array('/1/43/'),
2443
                    )
2444
                ),
2445
            ],
2446
            $roleLimitations
2447
        );
2448
    }
2449
2450
    /**
2451
     * Test for the assignRoleToUserGroup() method.
2452
     *
2453
     * @see \eZ\Publish\API\Repository\RoleService::assignRoleToUserGroup($role, $userGroup, $roleLimitation)
2454
     * @expectedException \eZ\Publish\API\Repository\Exceptions\LimitationValidationException
2455
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleByIdentifier
2456
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUserGroup
2457
     */
2458
    public function testAssignRoleToUserGroupWithRoleLimitationThrowsLimitationValidationException()
2459
    {
2460
        $repository = $this->getRepository();
2461
2462
        $mainGroupId = $this->generateId('group', 4);
2463
        /* BEGIN: Use Case */
2464
        // $mainGroupId is the ID of the main "Users" group
2465
2466
        $userService = $repository->getUserService();
2467
        $roleService = $repository->getRoleService();
2468
2469
        $userGroup = $userService->loadUserGroup($mainGroupId);
2470
2471
        // Load the existing "Anonymous" role
2472
        $role = $roleService->loadRoleByIdentifier('Anonymous');
2473
2474
        // Assign the "Anonymous" role to the newly created user group
2475
        // This call will fail with an LimitationValidationException, because subtree "/lorem/ipsum/42/"
2476
        // does not exists
2477
        $roleService->assignRoleToUserGroup(
2478
            $role,
2479
            $userGroup,
2480
            new SubtreeLimitation(
2481
                array(
2482
                    'limitationValues' => array('/lorem/ipsum/42/'),
2483
                )
2484
            )
2485
        );
2486
        /* END: Use Case */
2487
    }
2488
2489
    /**
2490
     * Test for the assignRoleToUserGroup() method.
2491
     *
2492
     * Makes sure assigning role several times throws.
2493
     *
2494
     * @see \eZ\Publish\API\Repository\RoleService::assignRoleToUserGroup($role, $userGroup, $roleLimitation)
2495
     * @expectedException \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException
2496
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleByIdentifier
2497
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUserGroup
2498
     */
2499
    public function testAssignRoleToUserGroupThrowsInvalidArgumentException()
2500
    {
2501
        $repository = $this->getRepository();
2502
2503
        $mainGroupId = $this->generateId('group', 4);
2504
        /* BEGIN: Use Case */
2505
        // $mainGroupId is the ID of the main "Users" group
2506
2507
        $userService = $repository->getUserService();
2508
        $roleService = $repository->getRoleService();
2509
2510
        $userGroup = $userService->loadUserGroup($mainGroupId);
2511
2512
        // Load the existing "Anonymous" role
2513
        $role = $roleService->loadRoleByIdentifier('Anonymous');
2514
2515
        // Assign the "Anonymous" role to the newly created user group
2516
        try {
2517
            $roleService->assignRoleToUserGroup(
2518
                $role,
2519
                $userGroup
2520
            );
2521
        } catch (Exception $e) {
2522
            $this->fail('Got exception at first valid attempt to assign role');
2523
        }
2524
2525
        // Re-Assign the "Anonymous" role to the newly created user group
2526
        // This call will fail with an InvalidArgumentException, because role is already assigned
2527
        $roleService->assignRoleToUserGroup(
2528
            $role,
2529
            $userGroup
2530
        );
2531
        /* END: Use Case */
2532
    }
2533
2534
    /**
2535
     * Test for the assignRoleToUserGroup() method.
2536
     *
2537
     * Makes sure assigning role several times with same limitations throws.
2538
     *
2539
     * @see \eZ\Publish\API\Repository\RoleService::assignRoleToUserGroup($role, $userGroup, $roleLimitation)
2540
     * @expectedException \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException
2541
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadRoleByIdentifier
2542
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUserGroup
2543
     */
2544
    public function testAssignRoleToUserGroupWithRoleLimitationThrowsInvalidArgumentException()
2545
    {
2546
        $repository = $this->getRepository();
2547
2548
        $mainGroupId = $this->generateId('group', 4);
2549
        /* BEGIN: Use Case */
2550
        // $mainGroupId is the ID of the main "Users" group
2551
2552
        $userService = $repository->getUserService();
2553
        $roleService = $repository->getRoleService();
2554
2555
        $userGroup = $userService->loadUserGroup($mainGroupId);
2556
2557
        // Load the existing "Anonymous" role
2558
        $role = $roleService->loadRoleByIdentifier('Anonymous');
2559
2560
        // Assign the "Anonymous" role to the newly created user group
2561
        try {
2562
            $roleService->assignRoleToUserGroup(
2563
                $role,
2564
                $userGroup,
2565
                new SubtreeLimitation(
2566
                    array(
2567
                        'limitationValues' => array('/1/43/', '/1/2/'),
2568
                    )
2569
                )
2570
            );
2571
        } catch (Exception $e) {
2572
            $this->fail('Got exception at first valid attempt to assign role');
2573
        }
2574
2575
        // Re-Assign the "Anonymous" role to the newly created user group
2576
        // This call will fail with an InvalidArgumentException, because limitation is already assigned
2577
        $roleService->assignRoleToUserGroup(
2578
            $role,
2579
            $userGroup,
2580
            new SubtreeLimitation(
2581
                array(
2582
                    'limitationValues' => array('/1/43/'),
2583
                )
2584
            )
2585
        );
2586
        /* END: Use Case */
2587
    }
2588
2589
    /**
2590
     * Test for the unassignRoleFromUserGroup() method.
2591
     *
2592
     * @see \eZ\Publish\API\Repository\RoleService::unassignRoleFromUserGroup()
2593
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUserGroup
2594
     */
2595 View Code Duplication
    public function testUnassignRoleFromUserGroup()
2596
    {
2597
        $repository = $this->getRepository();
2598
        $roleService = $repository->getRoleService();
2599
2600
        /* BEGIN: Use Case */
2601
        $userGroup = $this->createUserGroupVersion1();
2602
2603
        // Load the existing "Member" role
2604
        $role = $roleService->loadRoleByIdentifier('Member');
2605
2606
        // Assign the "Member" role to the newly created user group
2607
        $roleService->assignRoleToUserGroup($role, $userGroup);
2608
2609
        // Unassign group from role
2610
        $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...
2611
2612
        // The assignments array will not contain the new role<->group assignment
2613
        $roleAssignments = $roleService->getRoleAssignments($role);
2614
        /* END: Use Case */
2615
2616
        // Members + Editors + Partners
2617
        $this->assertEquals(3, count($roleAssignments));
2618
    }
2619
2620
    /**
2621
     * Test for the unassignRoleFromUserGroup() method.
2622
     *
2623
     * @see \eZ\Publish\API\Repository\RoleService::unassignRoleFromUserGroup()
2624
     * @expectedException \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException
2625
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testUnassignRoleFromUserGroup
2626
     */
2627 View Code Duplication
    public function testUnassignRoleFromUserGroupThrowsInvalidArgumentException()
2628
    {
2629
        $repository = $this->getRepository();
2630
        $roleService = $repository->getRoleService();
2631
2632
        /* BEGIN: Use Case */
2633
        $userGroup = $this->createUserGroupVersion1();
2634
2635
        // Load the existing "Member" role
2636
        $role = $roleService->loadRoleByIdentifier('Member');
2637
2638
        // This call will fail with a "InvalidArgumentException", because the
2639
        // user group does not have the "Member" role.
2640
        $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...
2641
        /* END: Use Case */
2642
    }
2643
2644
    /**
2645
     * Test unassigning role by assignment.
2646
     *
2647
     * @covers \eZ\Publish\API\Repository\RoleService::removeRoleAssignment
2648
     */
2649
    public function testUnassignRoleByAssignment()
2650
    {
2651
        $repository = $this->getRepository();
2652
        $roleService = $repository->getRoleService();
2653
2654
        $role = $roleService->loadRole(2);
2655
        $user = $repository->getUserService()->loadUser(14);
2656
2657
        $originalAssignmentCount = count($roleService->getRoleAssignmentsForUser($user));
2658
2659
        $roleService->assignRoleToUser($role, $user);
2660
        $newAssignmentCount = count($roleService->getRoleAssignmentsForUser($user));
2661
        self::assertEquals($originalAssignmentCount + 1, $newAssignmentCount);
2662
2663
        $assignments = $roleService->getRoleAssignmentsForUser($user);
2664
        $roleService->removeRoleAssignment($assignments[0]);
2665
        $finalAssignmentCount = count($roleService->getRoleAssignmentsForUser($user));
2666
        self::assertEquals($newAssignmentCount - 1, $finalAssignmentCount);
2667
    }
2668
2669
    /**
2670
     * Test unassigning role by assignment.
2671
     *
2672
     * But on current admin user so he lacks access to read roles.
2673
     *
2674
     * @covers \eZ\Publish\API\Repository\RoleService::removeRoleAssignment
2675
     * @expectedException \eZ\Publish\API\Repository\Exceptions\UnauthorizedException
2676
     */
2677 View Code Duplication
    public function testUnassignRoleByAssignmentThrowsUnauthorizedException()
2678
    {
2679
        $repository = $this->getRepository();
2680
        $roleService = $repository->getRoleService();
2681
2682
        try {
2683
            $adminUserGroup = $repository->getUserService()->loadUserGroup(12);
2684
            $assignments = $roleService->getRoleAssignmentsForUserGroup($adminUserGroup);
2685
            $roleService->removeRoleAssignment($assignments[0]);
2686
        } catch (Exception $e) {
2687
            self::fail(
2688
                'Unexpected exception: ' . $e->getMessage() . " \n[" . $e->getFile() . ' (' . $e->getLine() . ')]'
2689
            );
2690
        }
2691
2692
        $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...
2693
    }
2694
2695
    /**
2696
     * Test unassigning role by non-existing assignment.
2697
     *
2698
     * @covers \eZ\Publish\API\Repository\RoleService::removeRoleAssignment
2699
     * @expectedException \eZ\Publish\API\Repository\Exceptions\NotFoundException
2700
     */
2701 View Code Duplication
    public function testUnassignRoleByAssignmentThrowsNotFoundException()
2702
    {
2703
        $repository = $this->getRepository();
2704
        $roleService = $repository->getRoleService();
2705
2706
        try {
2707
            $editorsUserGroup = $repository->getUserService()->loadUserGroup(13);
2708
            $assignments = $roleService->getRoleAssignmentsForUserGroup($editorsUserGroup);
2709
            $roleService->removeRoleAssignment($assignments[0]);
2710
        } catch (Exception $e) {
2711
            self::fail(
2712
                'Unexpected exception: ' . $e->getMessage() . " \n[" . $e->getFile() . ' (' . $e->getLine() . ')]'
2713
            );
2714
        }
2715
2716
        $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...
2717
    }
2718
2719
    /**
2720
     * Test for the getRoleAssignmentsForUserGroup() method.
2721
     *
2722
     * @see \eZ\Publish\API\Repository\RoleService::getRoleAssignmentsForUserGroup()
2723
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUserGroup
2724
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRoleWithAddPolicy
2725
     */
2726 View Code Duplication
    public function testGetRoleAssignmentsForUserGroup()
2727
    {
2728
        $repository = $this->getRepository();
2729
        $roleService = $repository->getRoleService();
2730
2731
        /* BEGIN: Use Case */
2732
        $userGroup = $this->createUserGroupVersion1();
2733
2734
        // Instantiate a role create and add some policies
2735
        $roleCreate = $roleService->newRoleCreateStruct('Example Role');
2736
2737
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
2738
        // $roleCreate->mainLanguageCode = 'eng-US';
2739
2740
        $roleCreate->addPolicy(
2741
            $roleService->newPolicyCreateStruct('user', 'login')
2742
        );
2743
        $roleCreate->addPolicy(
2744
            $roleService->newPolicyCreateStruct('content', 'read')
2745
        );
2746
        $roleCreate->addPolicy(
2747
            $roleService->newPolicyCreateStruct('content', 'edit')
2748
        );
2749
2750
        // Create the new role instance
2751
        $roleDraft = $roleService->createRole($roleCreate);
2752
        $roleService->publishRoleDraft($roleDraft);
2753
        $role = $roleService->loadRole($roleDraft->id);
2754
2755
        // Assign role to new user group
2756
        $roleService->assignRoleToUserGroup($role, $userGroup);
2757
2758
        // Load the currently assigned role
2759
        $roleAssignments = $roleService->getRoleAssignmentsForUserGroup($userGroup);
2760
        /* END: Use Case */
2761
2762
        $this->assertEquals(1, count($roleAssignments));
2763
        $this->assertInstanceOf(
2764
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\UserGroupRoleAssignment',
2765
            reset($roleAssignments)
2766
        );
2767
    }
2768
2769
    /**
2770
     * Test for the loadPoliciesByUserId() method.
2771
     *
2772
     * @see \eZ\Publish\API\Repository\RoleService::loadPoliciesByUserId()
2773
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUser
2774
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAssignRoleToUserGroup
2775
     */
2776
    public function testLoadPoliciesByUserId()
2777
    {
2778
        $repository = $this->getRepository();
2779
2780
        $anonUserId = $this->generateId('user', 10);
2781
        /* BEGIN: Use Case */
2782
        // $anonUserId is the ID of the "Anonymous" user.
2783
2784
        $userService = $repository->getUserService();
2785
        $roleService = $repository->getRoleService();
2786
2787
        // Load "Anonymous" user
2788
        $user = $userService->loadUser($anonUserId);
2789
2790
        // Instantiate a role create and add some policies
2791
        $roleCreate = $roleService->newRoleCreateStruct('User Role');
2792
2793
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
2794
        // $roleCreate->mainLanguageCode = 'eng-US';
2795
2796
        $roleCreate->addPolicy(
2797
            $roleService->newPolicyCreateStruct('notification', 'use')
2798
        );
2799
        $roleCreate->addPolicy(
2800
            $roleService->newPolicyCreateStruct('user', 'password')
2801
        );
2802
        $roleCreate->addPolicy(
2803
            $roleService->newPolicyCreateStruct('user', 'selfedit')
2804
        );
2805
2806
        // Create the new role instance
2807
        $roleDraft = $roleService->createRole($roleCreate);
2808
        $roleService->publishRoleDraft($roleDraft);
2809
        $role = $roleService->loadRole($roleDraft->id);
2810
2811
        // Assign role to anon user
2812
        $roleService->assignRoleToUser($role, $user);
2813
2814
        // Load the currently assigned role
2815
        $policies = array();
2816
        foreach ($roleService->loadPoliciesByUserId($user->id) as $policy) {
2817
            $policies[] = array($policy->roleId, $policy->module, $policy->function);
2818
        }
2819
        /* END: Use Case */
2820
        array_multisort($policies);
2821
2822
        $this->assertEquals(
2823
            array(
2824
                array(1, 'content', 'pdf'),
2825
                array(1, 'content', 'read'),
2826
                array(1, 'content', 'read'),
2827
                array(1, 'rss', 'feed'),
2828
                array(1, 'user', 'login'),
2829
                array(1, 'user', 'login'),
2830
                array(1, 'user', 'login'),
2831
                array(1, 'user', 'login'),
2832
                array($role->id, 'notification', 'use'),
2833
                array($role->id, 'user', 'password'),
2834
                array($role->id, 'user', 'selfedit'),
2835
            ),
2836
            $policies
2837
        );
2838
    }
2839
2840
    /**
2841
     * Test for the loadPoliciesByUserId() method.
2842
     *
2843
     * @see \eZ\Publish\API\Repository\RoleService::loadPoliciesByUserId()
2844
     * @expectedException \eZ\Publish\API\Repository\Exceptions\NotFoundException
2845
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testLoadPoliciesByUserId
2846
     */
2847
    public function testLoadPoliciesByUserIdThrowsNotFoundException()
2848
    {
2849
        $repository = $this->getRepository();
2850
2851
        $nonExistingUserId = $this->generateId('user', self::DB_INT_MAX);
2852
        /* BEGIN: Use Case */
2853
        $roleService = $repository->getRoleService();
2854
2855
        // This call will fail with a "NotFoundException", because hopefully no
2856
        // user with an ID equal to self::DB_INT_MAX exists.
2857
        $roleService->loadPoliciesByUserId($nonExistingUserId);
2858
        /* END: Use Case */
2859
    }
2860
2861
    /**
2862
     * Test for the publishRoleDraft() method.
2863
     *
2864
     * @see \eZ\Publish\API\Repository\RoleService::publishRoleDraft()
2865
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRoleDraft
2866
     */
2867 View Code Duplication
    public function testPublishRoleDraft()
2868
    {
2869
        $repository = $this->getRepository();
2870
2871
        /* BEGIN: Use Case */
2872
        $roleService = $repository->getRoleService();
2873
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
2874
2875
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
2876
        // $roleCreate->mainLanguageCode = 'eng-US';
2877
2878
        $roleDraft = $roleService->createRole($roleCreate);
2879
2880
        $roleDraft = $roleService->addPolicyByRoleDraft(
2881
            $roleDraft,
2882
            $roleService->newPolicyCreateStruct('content', 'delete')
2883
        );
2884
        $roleDraft = $roleService->addPolicyByRoleDraft(
2885
            $roleDraft,
2886
            $roleService->newPolicyCreateStruct('content', 'create')
2887
        );
2888
2889
        $roleService->publishRoleDraft($roleDraft);
2890
        /* END: Use Case */
2891
2892
        $this->assertInstanceOf(
2893
            '\\eZ\\Publish\\API\\Repository\\Values\\User\\Role',
2894
            $roleService->loadRoleByIdentifier($roleCreate->identifier)
2895
        );
2896
    }
2897
2898
    /**
2899
     * Test for the publishRoleDraft() method.
2900
     *
2901
     * @see \eZ\Publish\API\Repository\RoleService::publishRoleDraft()
2902
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testCreateRoleDraft
2903
     * @depends eZ\Publish\API\Repository\Tests\RoleServiceTest::testAddPolicyByRoleDraft
2904
     */
2905
    public function testPublishRoleDraftAddPolicies()
2906
    {
2907
        $repository = $this->getRepository();
2908
2909
        /* BEGIN: Use Case */
2910
        $roleService = $repository->getRoleService();
2911
        $roleCreate = $roleService->newRoleCreateStruct('newRole');
2912
2913
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
2914
        // $roleCreate->mainLanguageCode = 'eng-US';
2915
2916
        $roleDraft = $roleService->createRole($roleCreate);
2917
2918
        $roleDraft = $roleService->addPolicyByRoleDraft(
2919
            $roleDraft,
2920
            $roleService->newPolicyCreateStruct('content', 'delete')
2921
        );
2922
        $roleDraft = $roleService->addPolicyByRoleDraft(
2923
            $roleDraft,
2924
            $roleService->newPolicyCreateStruct('content', 'create')
2925
        );
2926
2927
        $roleService->publishRoleDraft($roleDraft);
2928
        $role = $roleService->loadRoleByIdentifier($roleCreate->identifier);
2929
        /* END: Use Case */
2930
2931
        $actual = array();
2932
        foreach ($role->getPolicies() as $policy) {
2933
            $actual[] = array(
2934
                'module' => $policy->module,
2935
                'function' => $policy->function,
2936
            );
2937
        }
2938
        usort(
2939
            $actual,
2940
            function ($p1, $p2) {
2941
                return strcasecmp($p1['function'], $p2['function']);
2942
            }
2943
        );
2944
2945
        $this->assertEquals(
2946
            array(
2947
                array(
2948
                    'module' => 'content',
2949
                    'function' => 'create',
2950
                ),
2951
                array(
2952
                    'module' => 'content',
2953
                    'function' => 'delete',
2954
                ),
2955
            ),
2956
            $actual
2957
        );
2958
    }
2959
2960
    /**
2961
     * Create a user group fixture in a variable named <b>$userGroup</b>,.
2962
     *
2963
     * @return \eZ\Publish\API\Repository\Values\User\UserGroup
2964
     */
2965
    private function createUserGroupVersion1()
2966
    {
2967
        $repository = $this->getRepository();
2968
2969
        $mainGroupId = $this->generateId('group', 4);
2970
        /* BEGIN: Inline */
2971
        // $mainGroupId is the ID of the main "Users" group
2972
2973
        $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...
2974
        $userService = $repository->getUserService();
2975
2976
        // Load main group
2977
        $parentUserGroup = $userService->loadUserGroup($mainGroupId);
2978
2979
        // Instantiate a new create struct
2980
        $userGroupCreate = $userService->newUserGroupCreateStruct('eng-US');
2981
        $userGroupCreate->setField('name', 'Example Group');
2982
2983
        // Create the new user group
2984
        $userGroup = $userService->createUserGroup(
2985
            $userGroupCreate,
2986
            $parentUserGroup
2987
        );
2988
        /* END: Inline */
2989
2990
        return $userGroup;
2991
    }
2992
}
2993