Completed
Push — EZP-29891 ( 916cf6...0402ff )
by
unknown
16:53
created

RoleBase::testCreateRoleWithPolicies()   C

Complexity

Conditions 11
Paths 9

Size

Total Lines 106

Duplication

Lines 24
Ratio 22.64 %

Importance

Changes 0
Metric Value
cc 11
nc 9
nop 0
dl 24
loc 106
rs 5.8533
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/**
4
 * File contains: eZ\Publish\Core\Repository\Tests\Service\Integration\RoleBase 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\Core\Repository\Tests\Service\Integration;
10
11
use eZ\Publish\Core\Repository\Tests\Service\Integration\Base as BaseServiceTest;
12
use eZ\Publish\Core\Repository\Values\User\Role;
13
use eZ\Publish\Core\Repository\Values\User\Policy;
14
use eZ\Publish\API\Repository\Values\User\Limitation;
15
use eZ\Publish\API\Repository\Exceptions\PropertyNotFoundException as PropertyNotFound;
16
use eZ\Publish\API\Repository\Exceptions\PropertyReadOnlyException;
17
use eZ\Publish\API\Repository\Exceptions\NotFoundException;
18
use eZ\Publish\API\Repository\Tests\BaseTest as APIBaseTest;
19
use Exception;
20
21
/**
22
 * Test case for Role Service.
23
 */
24
abstract class RoleBase extends BaseServiceTest
25
{
26
    /**
27
     * Test a new class and default values on properties.
28
     *
29
     * @covers \eZ\Publish\API\Repository\Values\User\Role::__construct
30
     * @covers \eZ\Publish\API\Repository\Values\User\Policy::__construct
31
     */
32
    public function testNewClass()
33
    {
34
        $this->assertPropertiesCorrect(
35
            array(
36
                'id' => null,
37
                'identifier' => null,
38
                // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
39
                // 'mainLanguageCode' => null,
40
                'policies' => array(),
41
            ),
42
            new Role()
43
        );
44
45
        $this->assertPropertiesCorrect(
46
            array(
47
                'id' => null,
48
                'roleId' => null,
49
                'module' => null,
50
                'function' => null,
51
                'limitations' => array(),
52
            ),
53
            new Policy()
54
        );
55
    }
56
57
    /**
58
     * Test retrieving missing property.
59
     *
60
     * @covers \eZ\Publish\API\Repository\Values\User\Role::__get
61
     * @covers \eZ\Publish\API\Repository\Values\User\Policy::__get
62
     */
63 View Code Duplication
    public function testMissingProperty()
64
    {
65
        try {
66
            $role = new Role();
67
            $value = $role->notDefined;
0 ignored issues
show
Documentation introduced by
The property notDefined does not exist on object<eZ\Publish\Core\R...itory\Values\User\Role>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write 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.");
        }
    }

}

Since the property has write access only, you can use the @property-write 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...
Unused Code introduced by
$value 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...
68
            self::fail('Succeeded getting non existing property');
69
        } catch (PropertyNotFound $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
70
        }
71
72
        try {
73
            $policy = new Policy();
74
            $value = $policy->notDefined;
0 ignored issues
show
Documentation introduced by
The property notDefined does not exist on object<eZ\Publish\Core\R...ory\Values\User\Policy>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write 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.");
        }
    }

}

Since the property has write access only, you can use the @property-write 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...
Unused Code introduced by
$value 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...
75
            self::fail('Succeeded getting non existing property');
76
        } catch (PropertyNotFound $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
77
        }
78
    }
79
80
    /**
81
     * Test setting read only property.
82
     *
83
     * @covers \eZ\Publish\API\Repository\Values\User\Role::__set
84
     * @covers \eZ\Publish\API\Repository\Values\User\Policy::__set
85
     */
86 View Code Duplication
    public function testReadOnlyProperty()
87
    {
88
        try {
89
            $role = new Role();
90
            $role->id = 42;
91
            self::fail('Succeeded setting read only property');
92
        } catch (PropertyReadOnlyException $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
93
        }
94
95
        try {
96
            $policy = new Policy();
97
            $policy->id = 42;
98
            self::fail('Succeeded setting read only property');
99
        } catch (PropertyReadOnlyException $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
100
        }
101
    }
102
103
    /**
104
     * Test if property exists.
105
     *
106
     * @covers \eZ\Publish\API\Repository\Values\User\Role::__isset
107
     * @covers \eZ\Publish\API\Repository\Values\User\Policy::__isset
108
     */
109 View Code Duplication
    public function testIsPropertySet()
110
    {
111
        $role = new Role();
112
        $value = isset($role->notDefined);
113
        self::assertEquals(false, $value);
114
115
        $value = isset($role->id);
116
        self::assertEquals(true, $value);
117
118
        $policy = new Policy();
119
        $value = isset($policy->notDefined);
120
        self::assertEquals(false, $value);
121
122
        $value = isset($policy->id);
123
        self::assertEquals(true, $value);
124
    }
125
126
    /**
127
     * Test unsetting a property.
128
     *
129
     * @covers \eZ\Publish\API\Repository\Values\User\Role::__unset
130
     * @covers \eZ\Publish\API\Repository\Values\User\Policy::__unset
131
     */
132
    public function testUnsetProperty()
133
    {
134
        $role = new Role(array('id' => 1));
135
        try {
136
            unset($role->id);
137
            self::fail('Unsetting read-only property succeeded');
138
        } catch (PropertyReadOnlyException $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
139
        }
140
141
        $policy = new Policy(array('id' => 1));
142
        try {
143
            unset($policy->id);
144
            self::fail('Unsetting read-only property succeeded');
145
        } catch (PropertyReadOnlyException $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
146
        }
147
    }
148
149
    /**
150
     * Test creating a role.
151
     *
152
     * @covers \eZ\Publish\API\Repository\RoleService::createRole
153
     */
154
    public function testCreateRole()
155
    {
156
        $roleService = $this->repository->getRoleService();
157
        $roleCreateStruct = $roleService->newRoleCreateStruct('ultimate_permissions');
158
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
159
        // $roleCreateStruct->mainLanguageCode = 'eng-GB';
160
        // $roleCreateStruct->names = array( 'eng-GB' => 'Ultimate permissions' );
161
        // $roleCreateStruct->descriptions = array( 'eng-GB' => 'This is a role with ultimate permissions' );
162
163
        $createdRole = $roleService->createRole($roleCreateStruct);
164
165
        self::assertInstanceOf('\\eZ\\Publish\\API\\Repository\\Values\\User\\Role', $createdRole);
166
        self::assertGreaterThan(0, $createdRole->id);
167
168
        /* @todo uncomment when support for multilingual names and descriptions is added EZP-24776
169
        self::assertEquals(
170
            array(
171
                'eng-GB' => $roleCreateStruct->names['eng-GB']
172
            ),
173
            $createdRole->getNames()
174
        );
175
176
        self::assertEquals(
177
            array(
178
                'eng-GB' => $roleCreateStruct->descriptions['eng-GB']
179
            ),
180
            $createdRole->getDescriptions()
181
        );
182
        */
183
184
        $this->assertPropertiesCorrect(
185
            array(
186
                'identifier' => $roleCreateStruct->identifier,
187
                'policies' => array(),
188
            ),
189
            $createdRole
190
        );
191
    }
192
193
    /**
194
     * Test creating a role throwing InvalidArgumentException.
195
     *
196
     * @expectedException \eZ\Publish\Core\Base\Exceptions\InvalidArgumentException
197
     * @covers \eZ\Publish\API\Repository\RoleService::createRole
198
     */
199
    public function testCreateRoleThrowsInvalidArgumentException()
200
    {
201
        $roleService = $this->repository->getRoleService();
202
        $roleCreateStruct = $roleService->newRoleCreateStruct('Anonymous');
203
204
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
205
        // $roleCreateStruct->mainLanguageCode = 'eng-GB';
206
        // $roleCreateStruct->names = array( 'eng-GB' => 'Anonymous' );
207
        // $roleCreateStruct->descriptions = array( 'eng-GB' => 'Anonymous role' );
208
209
        $roleService->createRole($roleCreateStruct);
210
    }
211
212
    /**
213
     * Test creating a role with policies.
214
     *
215
     * @covers \eZ\Publish\API\Repository\RoleService::createRole
216
     */
217
    public function testCreateRoleWithPolicies()
218
    {
219
        $roleService = $this->repository->getRoleService();
220
221
        $limitation1 = new Limitation\ContentTypeLimitation();
222
        $limitation1->limitationValues = array('1', '3', '13');
223
224
        $limitation2 = new Limitation\SectionLimitation();
225
        $limitation2->limitationValues = array('2', '3');
226
227
        $limitation3 = new Limitation\OwnerLimitation();
228
        $limitation3->limitationValues = array('1', '2');
229
230
        $limitation4 = new Limitation\UserGroupLimitation();
231
        $limitation4->limitationValues = array('1');
232
233
        $policyCreateStruct1 = $roleService->newPolicyCreateStruct('content', 'read');
234
        $policyCreateStruct1->addLimitation($limitation1);
235
        $policyCreateStruct1->addLimitation($limitation2);
236
237
        $policyCreateStruct2 = $roleService->newPolicyCreateStruct('content', 'edit');
238
        $policyCreateStruct2->addLimitation($limitation3);
239
        $policyCreateStruct2->addLimitation($limitation4);
240
241
        $roleCreateStruct = $roleService->newRoleCreateStruct('ultimate_permissions');
242
243
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
244
        // $roleCreateStruct->mainLanguageCode = 'eng-GB';
245
        // $roleCreateStruct->names = array( 'eng-GB' => 'Ultimate permissions' );
246
        // $roleCreateStruct->descriptions = array( 'eng-GB' => 'This is a role with ultimate permissions' );
247
248
        $roleCreateStruct->addPolicy($policyCreateStruct1);
249
        $roleCreateStruct->addPolicy($policyCreateStruct2);
250
251
        $createdRole = $roleService->createRole($roleCreateStruct);
252
253
        self::assertInstanceOf('\\eZ\\Publish\\API\\Repository\\Values\\User\\Role', $createdRole);
254
        self::assertGreaterThan(0, $createdRole->id);
255
256
        /* @todo uncomment when support for multilingual names and descriptions is added EZP-24776
257
        self::assertEquals(
258
            array(
259
                'eng-GB' => $roleCreateStruct->names['eng-GB']
260
            ),
261
            $createdRole->getNames()
262
        );
263
264
        self::assertEquals(
265
            array(
266
                'eng-GB' => $roleCreateStruct->descriptions['eng-GB']
267
            ),
268
            $createdRole->getDescriptions()
269
        );
270
        */
271
272
        $this->assertPropertiesCorrect(
273
            array(
274
                'identifier' => $roleCreateStruct->identifier,
275
            ),
276
            $createdRole
277
        );
278
279
        self::assertCount(2, $createdRole->getPolicies());
280
281
        foreach ($createdRole->getPolicies() as $policy) {
282
            self::assertInstanceOf('\\eZ\\Publish\\API\\Repository\\Values\\User\\Policy', $policy);
283
            self::assertGreaterThan(0, $policy->id);
284
            self::assertEquals($createdRole->id, $policy->roleId);
285
286
            self::assertCount(2, $policy->getLimitations());
287
288
            foreach ($policy->getLimitations() as $limitation) {
289
                self::assertInstanceOf('\\eZ\\Publish\\API\\Repository\\Values\\User\\Limitation', $limitation);
290
291
                if ($policy->module == 'content' && $policy->function == 'read') {
292 View Code Duplication
                    switch ($limitation->getIdentifier()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
293
                        case Limitation::CONTENTTYPE:
294
                            self::assertEquals($limitation1->limitationValues, $limitation->limitationValues);
295
                            break;
296
297
                        case Limitation::SECTION:
298
                            self::assertEquals($limitation2->limitationValues, $limitation->limitationValues);
299
                            break;
300
301
                        default:
302
                            self::fail('Created role contains limitations not defined with create struct');
303
                    }
304
                } elseif ($policy->module == 'content' && $policy->function == 'edit') {
305 View Code Duplication
                    switch ($limitation->getIdentifier()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
306
                        case Limitation::OWNER:
307
                            self::assertEquals($limitation3->limitationValues, $limitation->limitationValues);
308
                            break;
309
310
                        case Limitation::USERGROUP:
311
                            self::assertEquals($limitation4->limitationValues, $limitation->limitationValues);
312
                            break;
313
314
                        default:
315
                            self::fail('Created role contains limitations not defined with create struct');
316
                    }
317
                } else {
318
                    self::fail('Created role contains policy not defined with create struct');
319
                }
320
            }
321
        }
322
    }
323
324
    /**
325
     * Test updating role.
326
     *
327
     * @covers \eZ\Publish\API\Repository\RoleService::updateRole
328
     */
329
    public function testUpdateRole()
330
    {
331
        $roleService = $this->repository->getRoleService();
332
333
        $role = $roleService->loadRoleByIdentifier('Anonymous');
334
335
        $roleUpdateStruct = $roleService->newRoleUpdateStruct();
336
        $roleUpdateStruct->identifier = 'Anonymous 2';
337
338
        // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
339
        // $roleUpdateStruct->mainLanguageCode = 'eng-US';
340
        // $roleUpdateStruct->names['eng-US'] = 'Anonymous 2';
341
        // $roleUpdateStruct->descriptions['eng-US'] = 'Anonymous 2 role';
342
343
        $updatedRole = $roleService->updateRole($role, $roleUpdateStruct);
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...
344
345
        self::assertInstanceOf('\\eZ\\Publish\\API\\Repository\\Values\\User\\Role', $updatedRole);
346
347
        // @todo: enable
348
        /*
349
                self::assertEquals(
350
                    array(
351
                        'eng-US' => $roleUpdateStruct->names['eng-US']
352
                    ),
353
                    $updatedRole->getNames()
354
                );
355
356
                self::assertEquals(
357
                    array(
358
                        'eng-US' => $roleUpdateStruct->descriptions['eng-US']
359
                    ),
360
                    $updatedRole->getDescriptions()
361
                );
362
        */
363
        $this->assertPropertiesCorrect(
364
            array(
365
                'id' => $role->id,
366
                'identifier' => $roleUpdateStruct->identifier,
367
                'policies' => $role->getPolicies(),
368
            ),
369
            $updatedRole
370
        );
371
    }
372
373
    /**
374
     * Test updating role throwing InvalidArgumentException.
375
     *
376
     * @expectedException \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException
377
     * @covers \eZ\Publish\API\Repository\RoleService::updateRole
378
     */
379
    public function testUpdateRoleThrowsInvalidArgumentException()
380
    {
381
        $roleService = $this->repository->getRoleService();
382
383
        $role = $roleService->loadRoleByIdentifier('Anonymous');
384
385
        $roleUpdateStruct = $roleService->newRoleUpdateStruct();
386
        $roleUpdateStruct->identifier = 'Administrator';
387
388
        $roleService->updateRole($role, $roleUpdateStruct);
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...
389
    }
390
391
    /**
392
     * Test adding policy to role.
393
     *
394
     * @covers \eZ\Publish\API\Repository\RoleService::addPolicy
395
     */
396
    public function testAddPolicy()
397
    {
398
        $roleService = $this->repository->getRoleService();
399
400
        $role = $roleService->loadRole(1);
401
        $policyCount = count($role->getPolicies());
402
403
        $limitation1 = new Limitation\ContentTypeLimitation();
404
        $limitation1->limitationValues = array('1', '3', '13');
405
406
        $limitation2 = new Limitation\SectionLimitation();
407
        $limitation2->limitationValues = array('2', '3');
408
409
        $policyCreateStruct = $roleService->newPolicyCreateStruct('content', 'read');
410
        $policyCreateStruct->addLimitation($limitation1);
411
        $policyCreateStruct->addLimitation($limitation2);
412
413
        $updatedRole = $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...
414
415
        self::assertInstanceOf('\\eZ\\Publish\\API\\Repository\\Values\\User\\Role', $updatedRole);
416
        self::assertCount($policyCount + 1, $updatedRole->getPolicies());
417
418
        foreach ($updatedRole->getPolicies() as $policy) {
419
            self::assertInstanceOf('\\eZ\\Publish\\API\\Repository\\Values\\User\\Policy', $policy);
420
            self::assertGreaterThan(0, $policy->id);
421
            self::assertEquals($role->id, $policy->roleId);
422
        }
423
    }
424
425
    /**
426
     * Test removing policy from the role.
427
     *
428
     * @covers \eZ\Publish\API\Repository\RoleService::removePolicy
429
     */
430
    public function testRemovePolicy()
431
    {
432
        $roleService = $this->repository->getRoleService();
433
434
        $role = $roleService->loadRole(1);
435
        $policies = $role->getPolicies();
436
        $policyCount = count($policies);
437
438
        self::assertGreaterThan(0, $policyCount);
439
440
        $updatedRole = $roleService->removePolicy($role, $policies[0]);
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...
441
        self::assertCount($policyCount - 1, $updatedRole->getPolicies());
442
    }
443
444
    /**
445
     * Test updating policies of a role, depends on proper eZ Publish clean data
446
     * which has a number of policies and limitations applied to Anonymous role.
447
     *
448
     * @covers \eZ\Publish\API\Repository\RoleService::updatePolicy
449
     */
450
    public function testUpdatePolicy()
451
    {
452
        $roleService = $this->repository->getRoleService();
453
454
        $role = $roleService->loadRole(1);
455
        $policies = $role->getPolicies();
456
        $policy = $policies[0];
457
458
        // Verify we get correct data from backend
459
        self::assertEquals('content', $policy->module);
460
        self::assertEquals('read', $policy->function);
461
462
        $limitation = new Limitation\ContentTypeLimitation();
463
        $limitation->limitationValues = array('1', '3', '13');
464
465
        $policyUpdateStruct = $roleService->newPolicyUpdateStruct();
466
        $policyUpdateStruct->addLimitation($limitation);
467
468
        $updatedPolicy = $roleService->updatePolicy($policy, $policyUpdateStruct);
0 ignored issues
show
Deprecated Code introduced by
The method eZ\Publish\API\Repositor...Service::updatePolicy() has been deprecated with message: since 6.0, use {@link updatePolicyByRoleDraft()} instead.

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

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

Loading history...
469
470
        $this->assertPropertiesCorrect(
471
            array(
472
                'id' => $policy->id,
473
                'roleId' => $policy->roleId,
474
                'module' => $policy->module,
475
                'function' => $policy->function,
476
            ),
477
            $updatedPolicy
478
        );
479
480
        $limitations = $updatedPolicy->getLimitations();
481
482
        self::assertCount(1, $limitations);
483
        self::assertInstanceOf('\\eZ\\Publish\\API\\Repository\\Values\\User\\Limitation', $limitations[0]);
484
        self::assertEquals(Limitation::CONTENTTYPE, $limitations[0]->getIdentifier());
485
        self::assertEquals($limitation->limitationValues, $limitations[0]->limitationValues);
486
    }
487
488
    /**
489
     * Test loading role by id.
490
     *
491
     * @covers \eZ\Publish\API\Repository\RoleService::loadRole
492
     */
493 View Code Duplication
    public function testLoadRole()
494
    {
495
        $roleService = $this->repository->getRoleService();
496
497
        $role = $roleService->loadRole(1);
498
        self::assertInstanceOf('\\eZ\\Publish\\API\\Repository\\Values\\User\\Role', $role);
499
500
        $this->assertPropertiesCorrect(
501
            array(
502
                'id' => 1,
503
                'identifier' => 'Anonymous',
504
            ),
505
            $role
506
        );
507
    }
508
509
    /**
510
     * Test loading role by id throwing NotFoundException.
511
     *
512
     * @expectedException \eZ\Publish\API\Repository\Exceptions\NotFoundException
513
     * @covers \eZ\Publish\API\Repository\RoleService::loadRole
514
     */
515
    public function testLoadRoleThrowsNotFoundException()
516
    {
517
        $roleService = $this->repository->getRoleService();
518
519
        $roleService->loadRole(APIBaseTest::DB_INT_MAX);
520
    }
521
522
    /**
523
     * Test loading role by identifier.
524
     *
525
     * @covers \eZ\Publish\API\Repository\RoleService::loadRoleByIdentifier
526
     */
527 View Code Duplication
    public function testLoadRoleByIdentifier()
528
    {
529
        $roleService = $this->repository->getRoleService();
530
531
        $role = $roleService->loadRoleByIdentifier('Anonymous');
532
        self::assertInstanceOf('\\eZ\\Publish\\API\\Repository\\Values\\User\\Role', $role);
533
534
        $this->assertPropertiesCorrect(
535
            array(
536
                'id' => 1,
537
                'identifier' => 'Anonymous',
538
            ),
539
            $role
540
        );
541
    }
542
543
    /**
544
     * Test loading role by identifier throwing NotFoundException.
545
     *
546
     * @expectedException \eZ\Publish\API\Repository\Exceptions\NotFoundException
547
     * @covers \eZ\Publish\API\Repository\RoleService::loadRoleByIdentifier
548
     */
549
    public function testLoadRoleByIdentifierThrowsNotFoundException()
550
    {
551
        $roleService = $this->repository->getRoleService();
552
553
        $roleService->loadRoleByIdentifier('non-existing');
554
    }
555
556
    /**
557
     * Test loading all roles.
558
     *
559
     * @covers \eZ\Publish\API\Repository\RoleService::loadRoles
560
     */
561 View Code Duplication
    public function testLoadRoles()
562
    {
563
        $roleService = $this->repository->getRoleService();
564
565
        $roles = $roleService->loadRoles();
566
        self::assertInternalType('array', $roles);
567
        self::assertGreaterThan(0, count($roles));
568
569
        foreach ($roles as $role) {
570
            self::assertInstanceOf('\\eZ\\Publish\\API\\Repository\\Values\\User\\Role', $role);
571
            self::assertGreaterThan(0, $role->id);
572
        }
573
    }
574
575
    /**
576
     * Test deleting a role.
577
     *
578
     * @covers \eZ\Publish\API\Repository\RoleService::deleteRole
579
     */
580
    public function testDeleteRole()
581
    {
582
        $roleService = $this->repository->getRoleService();
583
584
        $role = $roleService->loadRole(1);
585
        self::assertInstanceOf('\\eZ\\Publish\\API\\Repository\\Values\\User\\Role', $role);
586
587
        $roleService->deleteRole($role);
588
589
        try {
590
            $roleService->loadRole(1);
591
            self::fail('Succeeded loading role after deleting it');
592
        } catch (NotFoundException $e) {
593
            // Do nothing
594
        }
595
    }
596
597
    /**
598
     * Test loading policies by user ID.
599
     *
600
     * @covers \eZ\Publish\API\Repository\RoleService::loadPoliciesByUserId
601
     */
602 View Code Duplication
    public function testLoadPoliciesByUserId()
603
    {
604
        $roleService = $this->repository->getRoleService();
605
606
        $policies = $roleService->loadPoliciesByUserId(10);
607
        self::assertInternalType('array', $policies);
608
        self::assertNotEmpty($policies);
609
610
        foreach ($policies as $policy) {
611
            self::assertInstanceOf('\\eZ\\Publish\\API\\Repository\\Values\\User\\Policy', $policy);
612
            self::assertGreaterThan(0, $policy->id);
613
            self::assertGreaterThan(0, $policy->roleId);
614
        }
615
    }
616
617
    /**
618
     * Test loading policies by non existing user ID.
619
     *
620
     * @expectedException \eZ\Publish\API\Repository\Exceptions\NotFoundException
621
     * @covers \eZ\Publish\API\Repository\RoleService::loadPoliciesByUserId
622
     */
623
    public function testLoadPoliciesByNonExistingUserId()
624
    {
625
        $roleService = $this->repository->getRoleService();
626
627
        $roleService->loadPoliciesByUserId(APIBaseTest::DB_INT_MAX);
628
    }
629
630
    /**
631
     * Test assigning role to user group.
632
     *
633
     * @covers \eZ\Publish\API\Repository\RoleService::assignRoleToUserGroup
634
     */
635 View Code Duplication
    public function testAssignRoleToUserGroup()
636
    {
637
        $roleService = $this->repository->getRoleService();
638
639
        $role = $roleService->loadRole(1);
640
        $userGroup = $this->repository->getUserService()->loadUserGroup(12);
641
642
        $originalAssignmentCount = count($roleService->getRoleAssignmentsForUserGroup($userGroup));
643
644
        $roleService->assignRoleToUserGroup($role, $userGroup);
645
        $newAssignmentCount = count($roleService->getRoleAssignmentsForUserGroup($userGroup));
646
        self::assertEquals($originalAssignmentCount + 1, $newAssignmentCount);
647
    }
648
649
    /**
650
     * Test unassigning role from user group.
651
     *
652
     * @covers \eZ\Publish\API\Repository\RoleService::unassignRoleFromUserGroup
653
     */
654 View Code Duplication
    public function testUnassignRoleFromUserGroup()
655
    {
656
        $roleService = $this->repository->getRoleService();
657
658
        $anonymousRole = $roleService->loadRole(1);
659
        $anonymousUserGroup = $this->repository->getUserService()->loadUserGroup(42);
660
661
        $originalAssignmentCount = count($roleService->getRoleAssignmentsForUserGroup($anonymousUserGroup));
662
663
        $roleService->unassignRoleFromUserGroup($anonymousRole, $anonymousUserGroup);
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...
664
        $newAssignmentCount = count($roleService->getRoleAssignmentsForUserGroup($anonymousUserGroup));
665
        self::assertEquals($originalAssignmentCount - 1, $newAssignmentCount);
666
    }
667
668
    /**
669
     * Test unassigning role from user group.
670
     *
671
     * But on current admin user so he lacks access to read roles.
672
     *
673
     * @covers \eZ\Publish\API\Repository\RoleService::unassignRoleFromUserGroup
674
     * @expectedException \eZ\Publish\API\Repository\Exceptions\UnauthorizedException
675
     */
676
    public function testUnassignRoleFromUserGroupUnauthorizedException()
677
    {
678
        $roleService = $this->repository->getRoleService();
679
680
        try {
681
            $adminRole = $roleService->loadRole(2);
682
            $adminUserGroup = $this->repository->getUserService()->loadUserGroup(12);
683
            $roleService->getRoleAssignmentsForUserGroup($adminUserGroup);
684
            $roleService->unassignRoleFromUserGroup($adminRole, $adminUserGroup);
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...
685
        } catch (Exception $e) {
686
            self::fail('Unexpected exception: ' . $e->getMessage() . " \n[" . $e->getFile() . ' (' . $e->getLine() . ')]');
687
        }
688
689
        $roleService->getRoleAssignmentsForUserGroup($adminUserGroup);
0 ignored issues
show
Bug introduced by
The variable $adminUserGroup 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...
690
    }
691
692
    /**
693
     * Test unassigning role from user group which is not already assigned to the group.
694
     *
695
     * @expectedException \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException
696
     * @covers \eZ\Publish\API\Repository\RoleService::unassignRoleFromUserGroup
697
     */
698 View Code Duplication
    public function testUnassignRoleFromUserGroupThrowsInvalidArgumentException()
699
    {
700
        $roleService = $this->repository->getRoleService();
701
702
        $role = $roleService->loadRole(1);
703
        $userGroup = $this->repository->getUserService()->loadUserGroup(12);
704
705
        $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...
706
    }
707
708
    /**
709
     * Test assigning role to user.
710
     *
711
     * @covers \eZ\Publish\API\Repository\RoleService::assignRoleToUser
712
     */
713 View Code Duplication
    public function testAssignRoleToUser()
714
    {
715
        $roleService = $this->repository->getRoleService();
716
717
        $role = $roleService->loadRole(2);
718
        $user = $this->repository->getUserService()->loadUser(14);
719
720
        $originalAssignmentCount = count($roleService->getRoleAssignmentsForUser($user));
721
722
        $roleService->assignRoleToUser($role, $user);
723
        $newAssignmentCount = count($roleService->getRoleAssignmentsForUser($user));
724
        self::assertEquals($originalAssignmentCount + 1, $newAssignmentCount);
725
    }
726
727
    /**
728
     * Test unassigning role from user.
729
     *
730
     * @covers \eZ\Publish\API\Repository\RoleService::unassignRoleFromUser
731
     */
732
    public function testUnassignRoleFromUser()
733
    {
734
        $roleService = $this->repository->getRoleService();
735
736
        $role = $roleService->loadRole(2);
737
        $user = $this->repository->getUserService()->loadUser(14);
738
739
        $originalAssignmentCount = count($roleService->getRoleAssignmentsForUser($user));
740
741
        $roleService->assignRoleToUser($role, $user);
742
        $newAssignmentCount = count($roleService->getRoleAssignmentsForUser($user));
743
        self::assertEquals($originalAssignmentCount + 1, $newAssignmentCount);
744
745
        $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...
746
        $finalAssignmentCount = count($roleService->getRoleAssignmentsForUser($user));
747
        self::assertEquals($newAssignmentCount - 1, $finalAssignmentCount);
748
    }
749
750
    /**
751
     * Test unassigning role from user which is not already assigned to the user.
752
     *
753
     * @expectedException \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException
754
     * @covers \eZ\Publish\API\Repository\RoleService::unassignRoleFromUser
755
     */
756 View Code Duplication
    public function testUnassignRoleFromUserThrowsInvalidArgumentException()
757
    {
758
        $roleService = $this->repository->getRoleService();
759
760
        $role = $roleService->loadRole(2);
761
        $user = $this->repository->getUserService()->loadUser(14);
762
763
        $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...
764
    }
765
766
    /**
767
     * Test fetching all role assignments for specified role.
768
     *
769
     * @covers \eZ\Publish\API\Repository\RoleService::getRoleAssignments
770
     */
771
    public function testGetRoleAssignments()
772
    {
773
        $roleService = $this->repository->getRoleService();
774
775
        $role = $roleService->loadRole(2);
776
777
        $roleAssignments = $roleService->getRoleAssignments($role);
778
779
        self::assertInternalType('array', $roleAssignments);
780
        self::assertNotEmpty($roleAssignments);
781
782
        foreach ($roleAssignments as $assignment) {
783
            self::assertInstanceOf('\\eZ\\Publish\\API\\Repository\\Values\\User\\RoleAssignment', $assignment);
784
        }
785
    }
786
787
    /**
788
     * Test fetching role assignments for specified user.
789
     *
790
     * @covers \eZ\Publish\API\Repository\RoleService::getRoleAssignmentsForUser
791
     */
792
    public function testGetRoleAssignmentsForUser()
793
    {
794
        $roleService = $this->repository->getRoleService();
795
796
        $user = $this->repository->getUserService()->loadUser(14);
797
        $role = $roleService->loadRole(2);
798
        $roleService->assignRoleToUser($role, $user);
799
800
        $userAssignments = $roleService->getRoleAssignmentsForUser($user);
801
802
        self::assertInternalType('array', $userAssignments);
803
        self::assertNotEmpty($userAssignments);
804
805
        foreach ($userAssignments as $assignment) {
806
            self::assertInstanceOf('\\eZ\\Publish\\API\\Repository\\Values\\User\\UserRoleAssignment', $assignment);
807
        }
808
    }
809
810
    /**
811
     * Test fetching role assignments for specified user group.
812
     *
813
     * @covers \eZ\Publish\API\Repository\RoleService::getRoleAssignmentsForUserGroup
814
     */
815
    public function testGetRoleAssignmentsForUserGroup()
816
    {
817
        $userGroup = $this->repository->getUserService()->loadUserGroup(12);
818
819
        $userGroupAssignments = $this->repository->getRoleService()->getRoleAssignmentsForUserGroup($userGroup);
820
821
        self::assertInternalType('array', $userGroupAssignments);
822
        self::assertNotEmpty($userGroupAssignments);
823
824
        foreach ($userGroupAssignments as $assignment) {
825
            self::assertInstanceOf('\\eZ\\Publish\\API\\Repository\\Values\\User\\UserGroupRoleAssignment', $assignment);
826
        }
827
    }
828
829
    /**
830
     * Test creating new RoleCreateStruct.
831
     *
832
     * @covers \eZ\Publish\API\Repository\RoleService::newRoleCreateStruct
833
     */
834 View Code Duplication
    public function testNewRoleCreateStruct()
835
    {
836
        $roleService = $this->repository->getRoleService();
837
838
        $roleCreateStruct = $roleService->newRoleCreateStruct('Ultimate permissions');
839
840
        self::assertInstanceOf('\\eZ\\Publish\\API\\Repository\\Values\\User\\RoleCreateStruct', $roleCreateStruct);
841
842
        $this->assertPropertiesCorrect(
843
            array(
844
                'identifier' => 'Ultimate permissions',
845
                // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
846
                // 'mainLanguageCode' => null,
847
                // 'names' => null,
848
                // 'descriptions' => null
849
            ),
850
            $roleCreateStruct
851
        );
852
853
        self::assertEquals('Ultimate permissions', $roleCreateStruct->identifier);
854
        self::assertInternalType('array', $roleCreateStruct->getPolicies());
855
        self::assertEmpty($roleCreateStruct->getPolicies());
856
    }
857
858
    /**
859
     * Test creating new PolicyCreateStruct.
860
     *
861
     * @covers \eZ\Publish\API\Repository\RoleService::newPolicyCreateStruct
862
     */
863 View Code Duplication
    public function testNewPolicyCreateStruct()
864
    {
865
        $roleService = $this->repository->getRoleService();
866
867
        $policyCreateStruct = $roleService->newPolicyCreateStruct('content', 'read');
868
869
        self::assertInstanceOf('\\eZ\\Publish\\API\\Repository\\Values\\User\\PolicyCreateStruct', $policyCreateStruct);
870
871
        $this->assertPropertiesCorrect(
872
            array(
873
                'module' => 'content',
874
                'function' => 'read',
875
            ),
876
            $policyCreateStruct
877
        );
878
879
        self::assertInternalType('array', $policyCreateStruct->getLimitations());
880
        self::assertEmpty($policyCreateStruct->getLimitations());
881
    }
882
883
    /**
884
     * Test creating new RoleUpdateStruct.
885
     *
886
     * @covers \eZ\Publish\API\Repository\RoleService::newRoleUpdateStruct
887
     */
888 View Code Duplication
    public function testNewRoleUpdateStruct()
889
    {
890
        $roleService = $this->repository->getRoleService();
891
892
        $roleUpdateStruct = $roleService->newRoleUpdateStruct();
893
894
        self::assertInstanceOf('\\eZ\\Publish\\API\\Repository\\Values\\User\\RoleUpdateStruct', $roleUpdateStruct);
895
896
        $this->assertPropertiesCorrect(
897
            array(
898
                'identifier' => null,
899
                // @todo uncomment when support for multilingual names and descriptions is added EZP-24776
900
                // 'mainLanguageCode' => null,
901
                // 'names' => null,
902
                // 'descriptions' => null
903
            ),
904
            $roleUpdateStruct
905
        );
906
    }
907
908
    /**
909
     * Test creating new PolicyUpdateStruct.
910
     *
911
     * @covers \eZ\Publish\API\Repository\RoleService::newPolicyUpdateStruct
912
     */
913
    public function testNewPolicyUpdateStruct()
914
    {
915
        $roleService = $this->repository->getRoleService();
916
917
        $policyUpdateStruct = $roleService->newPolicyUpdateStruct();
918
919
        self::assertInstanceOf('\\eZ\\Publish\\API\\Repository\\Values\\User\\PolicyUpdateStruct', $policyUpdateStruct);
920
921
        self::assertInternalType('array', $policyUpdateStruct->getLimitations());
922
        self::assertEmpty($policyUpdateStruct->getLimitations());
923
    }
924
}
925