Completed
Push — 6.13.7 ( b1546d )
by
unknown
14:00
created

UserHandlerTest   D

Complexity

Total Complexity 56

Size/Duplication

Total Lines 1076
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 16

Importance

Changes 0
Metric Value
dl 0
loc 1076
rs 4.816
c 0
b 0
f 0
wmc 56
lcom 1
cbo 16

51 Methods

Rating   Name   Duplication   Size   Complexity  
A getUserHandler() 0 11 1
A getValidUser() 0 14 1
A getValidUserToken() 0 9 1
A testCreateUser() 0 7 1
A getGatewayReturnValue() 0 15 1
A testLoadUser() 0 19 1
A testLoadUnknownUser() 0 15 1
A testLoadUserByLogin() 0 19 1
A testLoadUserByEmailNotFound() 0 9 1
A testLoadUserByEmail() 0 19 1
A testLoadUserByTokenNotFound() 0 9 1
A testLoadUserByToken() 0 21 1
A testUpdateUserToken() 0 20 1
A testExpireUserToken() 0 20 1
A testDeleteNonExistingUser() 0 7 1
A testUpdateUser() 0 9 1
A testUpdateUserSettings() 0 9 1
A testCreateNewRoleWithoutPolicies() 0 15 1
A testCreateRoleDraftWithoutPolicies() 0 22 1
A testCreateNewRoleRoleId() 0 11 1
A testLoadRole() 0 16 1
A testLoadRoleWithPolicies() 0 33 1
A testLoadRoleWithPoliciesAndGroups() 0 37 1
A testLoadRoleWithPolicyLimitations() 0 40 1
A testLoadRoles() 0 16 1
A testUpdateRole() 0 18 1
A testDeleteRole() 0 26 1
A testDeleteRoleDraft() 0 27 1
A testAddPolicyToRoleLimitations() 0 18 1
A testAddPolicyPolicyId() 0 14 1
A testAddPolicyLimitations() 0 13 1
A testAddPolicyLimitationValues() 0 14 1
A createRole() 0 25 1
A testImplicitlyCreatePolicies() 0 13 1
A testDeletePolicy() 0 16 1
A testDeletePolicyLimitations() 0 12 1
A testDeletePolicyLimitationValues() 0 12 1
A testUpdatePolicies() 0 29 1
A testAddRoleToUser() 0 19 1
A testAddRoleToUserWithLimitation() 0 25 1
A testAddRoleToUserWithComplexLimitation() 0 28 1
A testRemoveUserRoleAssociation() 0 26 1
A testLoadPoliciesForUser() 0 24 2
A testLoadRoleAssignmentsByGroupId() 0 43 1
A testLoadRoleAssignmentsByGroupIdInherited() 0 18 1
B testLoadComplexRoleAssignments() 0 67 1
A testLoadRoleAssignmentsByRoleId() 0 32 1
A testLoadRoleDraftByRoleId() 0 12 1
A testRoleDraftOnlyHavePolicyDraft() 0 36 5
A createTestRole() 0 10 1
A createTestRoleWithTestPolicy() 0 16 1

How to fix   Complexity   

Complex Class

Complex classes like UserHandlerTest often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use UserHandlerTest, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
/**
4
 * File contains: eZ\Publish\Core\Persistence\Legacy\Tests\User\UserHandlerTest 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\Persistence\Legacy\Tests\User;
10
11
use eZ\Publish\API\Repository\Exceptions\NotImplementedException;
12
use eZ\Publish\API\Repository\Values\User\Role as APIRole;
13
use eZ\Publish\Core\Persistence\Legacy\Tests\TestCase;
14
use eZ\Publish\Core\Persistence\Legacy\User;
15
use eZ\Publish\Core\Persistence\Legacy\User\Role\LimitationConverter;
16
use eZ\Publish\Core\Persistence\Legacy\User\Role\LimitationHandler\ObjectStateHandler as ObjectStateLimitationHandler;
17
use eZ\Publish\SPI\Persistence;
18
use eZ\Publish\SPI\Persistence\User\Role;
19
20
/**
21
 * Test case for UserHandlerTest.
22
 */
23
class UserHandlerTest extends TestCase
24
{
25
    private const TEST_USER_ID = 42;
26
27
    protected function getUserHandler(User\Gateway $userGateway = null)
28
    {
29
        $dbHandler = $this->getDatabaseHandler();
30
31
        return new User\Handler(
32
            $userGateway ?? new User\Gateway\DoctrineDatabase($dbHandler),
33
            new User\Role\Gateway\DoctrineDatabase($dbHandler),
34
            new User\Mapper(),
35
            new LimitationConverter([new ObjectStateLimitationHandler($dbHandler)])
36
        );
37
    }
38
39
    protected function getValidUser()
40
    {
41
        $user = new Persistence\User();
42
        $user->id = self::TEST_USER_ID;
43
        $user->login = 'kore';
44
        $user->email = '[email protected]';
45
        $user->passwordHash = '1234567890';
46
        $user->hashAlgorithm = 2;
47
        $user->isEnabled = true;
48
        $user->maxLogin = 23;
49
        $user->passwordUpdatedAt = 1569229200;
50
51
        return $user;
52
    }
53
54
    protected function getValidUserToken($time = null)
55
    {
56
        $userToken = new Persistence\User\UserTokenUpdateStruct();
57
        $userToken->userId = self::TEST_USER_ID;
58
        $userToken->hashKey = md5('hash');
59
        $userToken->time = $time ?? (new \DateTime())->add(new \DateInterval('P1D'))->getTimestamp();
60
61
        return $userToken;
62
    }
63
64
    public function testCreateUser()
65
    {
66
        $handler = $this->getUserHandler();
67
68
        $this->expectException(NotImplementedException::class);
69
        $handler->create($this->getValidUser());
70
    }
71
72
    protected function getGatewayReturnValue(): array
73
    {
74
        return [
75
            [
76
                'contentobject_id' => self::TEST_USER_ID,
77
                'login' => 'kore',
78
                'email' => '[email protected]',
79
                'password_hash' => '1234567890',
80
                'password_hash_type' => 2,
81
                'is_enabled' => true,
82
                'max_login' => 23,
83
                'password_updated_at' => 1569229200,
84
            ],
85
        ];
86
    }
87
88
    public function testLoadUser()
89
    {
90
        $gatewayMock = $this
91
            ->createMock(User\Gateway\DoctrineDatabase::class);
92
93
        $gatewayMock
0 ignored issues
show
Bug introduced by
The method method() does not seem to exist on object<PHPUnit\Framework\MockObject\MockObject>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
94
            ->method('load')
95
            ->with(self::TEST_USER_ID)
96
            ->willReturn($this->getGatewayReturnValue());
97
98
        $handler = $this->getUserHandler($gatewayMock);
99
100
        $user = $this->getValidUser();
101
102
        $this->assertEquals(
103
            $user,
104
            $handler->load($user->id)
105
        );
106
    }
107
108
    public function testLoadUnknownUser()
109
    {
110
        $this->expectException(\eZ\Publish\API\Repository\Exceptions\NotFoundException::class);
111
        $gatewayMock = $this
112
            ->createMock(User\Gateway\DoctrineDatabase::class);
113
114
        $gatewayMock
0 ignored issues
show
Bug introduced by
The method method() does not seem to exist on object<PHPUnit\Framework\MockObject\MockObject>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
115
            ->method('load')
116
            ->with(1337)
117
            ->willReturn([]);
118
119
        $handler = $this->getUserHandler($gatewayMock);
120
121
        $handler->load(1337);
122
    }
123
124
    public function testLoadUserByLogin()
125
    {
126
        $gatewayMock = $this
127
            ->createMock(User\Gateway\DoctrineDatabase::class);
128
129
        $gatewayMock
0 ignored issues
show
Bug introduced by
The method method() does not seem to exist on object<PHPUnit\Framework\MockObject\MockObject>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
130
            ->method('loadByLogin')
131
            ->with('kore')
132
            ->willReturn($this->getGatewayReturnValue());
133
134
        $handler = $this->getUserHandler($gatewayMock);
135
        $user = $this->getValidUser();
136
137
        $loadedUser = $handler->loadByLogin($user->login);
138
        $this->assertEquals(
139
            $user,
140
            $loadedUser
141
        );
142
    }
143
144
    public function testLoadUserByEmailNotFound()
145
    {
146
        $this->expectException(\eZ\Publish\API\Repository\Exceptions\NotFoundException::class);
147
148
        $handler = $this->getUserHandler();
149
        $user = $this->getValidUser();
150
151
        $handler->loadByLogin($user->email);
152
    }
153
154
    public function testLoadUserByEmail()
155
    {
156
        $gatewayMock = $this
157
            ->createMock(User\Gateway\DoctrineDatabase::class);
158
159
        $gatewayMock
0 ignored issues
show
Bug introduced by
The method method() does not seem to exist on object<PHPUnit\Framework\MockObject\MockObject>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
160
            ->method('loadByEmail')
161
            ->with('[email protected]')
162
            ->willReturn($this->getGatewayReturnValue());
163
164
        $handler = $this->getUserHandler($gatewayMock);
165
        $user = $this->getValidUser();
166
167
        $users = $handler->loadByEmail($user->email);
168
        $this->assertEquals(
169
            $user,
170
            $users[0]
171
        );
172
    }
173
174
    public function testLoadUserByTokenNotFound()
175
    {
176
        $this->expectException(\eZ\Publish\API\Repository\Exceptions\NotFoundException::class);
177
178
        $handler = $this->getUserHandler();
179
        $handler->updateUserToken($this->getValidUserToken());
180
181
        $handler->loadUserByToken('asd');
182
    }
183
184
    public function testLoadUserByToken()
185
    {
186
        $gatewayMock = $this
187
            ->createMock(User\Gateway\DoctrineDatabase::class);
188
189
        $userToken = $this->getValidUserToken();
190
        $gatewayMock
0 ignored issues
show
Bug introduced by
The method method() does not seem to exist on object<PHPUnit\Framework\MockObject\MockObject>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
191
            ->method('loadUserByToken')
192
            ->with($userToken->hashKey)
193
            ->willReturn($this->getGatewayReturnValue());
194
195
        $handler = $this->getUserHandler($gatewayMock);
196
        $user = $this->getValidUser();
197
        $handler->updateUserToken($userToken);
198
199
        $loadedUser = $handler->loadUserByToken($userToken->hashKey);
200
        $this->assertEquals(
201
            $user,
202
            $loadedUser
203
        );
204
    }
205
206
    public function testUpdateUserToken()
207
    {
208
        $handler = $this->getUserHandler();
209
210
        $handler->updateUserToken($this->getValidUserToken(1234567890));
211
212
        $this->assertQueryResult(
213
            [['0800fc577294c34e0b28ad2839435945', 1, 1234567890, self::TEST_USER_ID]],
214
            $this->handler->createSelectQuery()->select('*')->from('ezuser_accountkey'),
215
            'Expected user data to be updated.'
216
        );
217
218
        $handler->updateUserToken($this->getValidUserToken(2234567890));
219
220
        $this->assertQueryResult(
221
            [['0800fc577294c34e0b28ad2839435945', 1, 2234567890, self::TEST_USER_ID]],
222
            $this->handler->createSelectQuery()->select('*')->from('ezuser_accountkey'),
223
            'Expected user token data to be updated.'
224
        );
225
    }
226
227
    public function testExpireUserToken()
228
    {
229
        $handler = $this->getUserHandler();
230
231
        $handler->updateUserToken($userToken = $this->getValidUserToken(1234567890));
232
233
        $this->assertQueryResult(
234
            [['0800fc577294c34e0b28ad2839435945', 1, 1234567890, self::TEST_USER_ID]],
235
            $this->handler->createSelectQuery()->select('*')->from('ezuser_accountkey'),
236
            'Expected user data to be updated.'
237
        );
238
239
        $handler->expireUserToken($userToken->hashKey);
240
241
        $this->assertQueryResult(
242
            [['0800fc577294c34e0b28ad2839435945', 1, 0, self::TEST_USER_ID]],
243
            $this->handler->createSelectQuery()->select('*')->from('ezuser_accountkey'),
244
            'Expected user token to be expired.'
245
        );
246
    }
247
248
    public function testDeleteNonExistingUser()
249
    {
250
        $handler = $this->getUserHandler();
251
252
        $this->expectException(NotImplementedException::class);
253
        $handler->delete(1337);
254
    }
255
256
    public function testUpdateUser()
257
    {
258
        $handler = $this->getUserHandler();
259
        $user = $this->getValidUser();
260
261
        $user->login = 'New_lögin';
262
        $this->expectException(NotImplementedException::class);
263
        $handler->update($user);
264
    }
265
266
    public function testUpdateUserSettings()
267
    {
268
        $handler = $this->getUserHandler();
269
        $user = $this->getValidUser();
270
271
        $user->maxLogin = 42;
272
        $this->expectException(NotImplementedException::class);
273
        $handler->update($user);
274
    }
275
276
    public function testCreateNewRoleWithoutPolicies()
277
    {
278
        $handler = $this->getUserHandler();
279
280
        $createStruct = new Persistence\User\RoleCreateStruct();
281
        $createStruct->identifier = 'Test';
282
283
        $handler->createRole($createStruct);
284
285
        $this->assertQueryResult(
286
            [[1, 'Test', -1]],
287
            $this->handler->createSelectQuery()->select('id', 'name', 'version')->from('ezrole'),
288
            'Expected a new role draft.'
289
        );
290
    }
291
292
    public function testCreateRoleDraftWithoutPolicies()
293
    {
294
        $handler = $this->getUserHandler();
295
296
        $createStruct = new Persistence\User\RoleCreateStruct();
297
        $createStruct->identifier = 'Test';
298
299
        $roleDraft = $handler->createRole($createStruct);
300
        $handler->publishRoleDraft($roleDraft->id);
301
302
        $handler->createRoleDraft($roleDraft->id);
303
304
        $publishedRoleId = 1;
305
        $this->assertQueryResult(
306
            [
307
                [$publishedRoleId, 'Test', APIRole::STATUS_DEFINED],
308
                [2, 'Test', $publishedRoleId],
309
            ],
310
            $this->handler->createSelectQuery()->select('id', 'name', 'version')->from('ezrole'),
311
            'Expected a role and a role draft.'
312
        );
313
    }
314
315
    public function testCreateNewRoleRoleId()
316
    {
317
        $handler = $this->getUserHandler();
318
319
        $createStruct = new Persistence\User\RoleCreateStruct();
320
        $createStruct->identifier = 'Test';
321
322
        $roleDraft = $handler->createRole($createStruct);
323
324
        $this->assertSame('1', $roleDraft->id);
325
    }
326
327
    public function testLoadRole()
328
    {
329
        $handler = $this->getUserHandler();
330
331
        $createStruct = new Persistence\User\RoleCreateStruct();
332
        $createStruct->identifier = 'Test';
333
334
        $roleDraft = $handler->createRole($createStruct);
335
        $handler->publishRoleDraft($roleDraft->id);
336
        $role = $handler->loadRole($roleDraft->id);
337
338
        $this->assertEquals(
339
            $roleDraft->id,
340
            $role->id
341
        );
342
    }
343
344
    public function testLoadRoleWithPolicies()
345
    {
346
        $handler = $this->getUserHandler();
347
348
        $createStruct = new Persistence\User\RoleCreateStruct();
349
        $createStruct->identifier = 'Test';
350
351
        $roleDraft = $handler->createRole($createStruct);
352
353
        $policy = new Persistence\User\Policy();
354
        $policy->module = 'foo';
355
        $policy->function = 'bar';
356
357
        $handler->addPolicyByRoleDraft($roleDraft->id, $policy);
358
        $handler->publishRoleDraft($roleDraft->id);
359
360
        $loaded = $handler->loadRole($roleDraft->id);
361
        $this->assertEquals(
362
            [
363
                new Persistence\User\Policy(
364
                    [
365
                        'id' => 1,
366
                        'roleId' => 1,
367
                        'module' => 'foo',
368
                        'function' => 'bar',
369
                        'limitations' => '*',
370
                        'originalId' => null,
371
                    ]
372
                ),
373
            ],
374
            $loaded->policies
375
        );
376
    }
377
378
    public function testLoadRoleWithPoliciesAndGroups()
379
    {
380
        $handler = $this->getUserHandler();
381
382
        $createStruct = new Persistence\User\RoleCreateStruct();
383
        $createStruct->identifier = 'Test';
384
385
        $roleDraft = $handler->createRole($createStruct);
386
387
        $policy = new Persistence\User\Policy();
388
        $policy->module = 'foo';
389
        $policy->function = 'bar';
390
391
        $handler->addPolicyByRoleDraft($roleDraft->id, $policy);
392
393
        $handler->assignRole(23, $roleDraft->id);
394
        $handler->assignRole(42, $roleDraft->id);
395
396
        $handler->publishRoleDraft($roleDraft->id);
397
398
        $loaded = $handler->loadRole($roleDraft->id);
399
        $this->assertEquals(
400
            [
401
                new Persistence\User\Policy(
402
                    [
403
                        'id' => 1,
404
                        'roleId' => 1,
405
                        'module' => 'foo',
406
                        'function' => 'bar',
407
                        'limitations' => '*',
408
                        'originalId' => null,
409
                    ]
410
                ),
411
            ],
412
            $loaded->policies
413
        );
414
    }
415
416
    public function testLoadRoleWithPolicyLimitations()
417
    {
418
        $handler = $this->getUserHandler();
419
420
        $createStruct = new Persistence\User\RoleCreateStruct();
421
        $createStruct->identifier = 'Test';
422
423
        $roleDraft = $handler->createRole($createStruct);
424
425
        $policy = new Persistence\User\Policy();
426
        $policy->module = 'foo';
427
        $policy->function = 'bar';
428
        $policy->limitations = [
429
            'Subtree' => ['/1', '/1/2'],
430
            'Foo' => ['Bar'],
431
        ];
432
433
        $handler->addPolicyByRoleDraft($roleDraft->id, $policy);
434
        $handler->publishRoleDraft($roleDraft->id);
435
436
        $loaded = $handler->loadRole($roleDraft->id);
437
        $this->assertEquals(
438
            [
439
                new Persistence\User\Policy(
440
                    [
441
                        'id' => 1,
442
                        'roleId' => 1,
443
                        'module' => 'foo',
444
                        'function' => 'bar',
445
                        'limitations' => [
446
                            'Subtree' => ['/1', '/1/2'],
447
                            'Foo' => ['Bar'],
448
                        ],
449
                        'originalId' => null,
450
                    ]
451
                ),
452
            ],
453
            $loaded->policies
454
        );
455
    }
456
457
    public function testLoadRoles()
458
    {
459
        $handler = $this->getUserHandler();
460
461
        $this->assertEquals(
462
            [],
463
            $handler->loadRoles()
464
        );
465
466
        $role = $this->createTestRole($handler);
467
468
        $this->assertEquals(
469
            [$role],
470
            $handler->loadRoles()
471
        );
472
    }
473
474
    public function testUpdateRole()
475
    {
476
        $handler = $this->getUserHandler();
477
478
        $role = $this->createTestRole($handler);
479
480
        $update = new Persistence\User\RoleUpdateStruct();
481
        $update->id = $role->id;
482
        $update->identifier = 'Changed';
483
484
        $handler->updateRole($update);
485
486
        $this->assertQueryResult(
487
            [[1, 'Changed']],
488
            $this->handler->createSelectQuery()->select('id', 'name')->from('ezrole'),
489
            'Expected a changed role.'
490
        );
491
    }
492
493
    public function testDeleteRole()
494
    {
495
        $this->insertDatabaseFixture(__DIR__ . '/../../../../Repository/Tests/Service/Integration/Legacy/_fixtures/test_data.php');
496
        $handler = $this->getUserHandler();
497
498
        // 3 is the ID of Editor role
499
        $handler->deleteRole(3);
500
501
        $this->assertQueryResult(
502
            [],
503
            $this->handler->createSelectQuery()->select('id')->from('ezrole')->where('id = 3'),
504
            'Expected an empty set.'
505
        );
506
507
        $this->assertQueryResult(
508
            [],
509
            $this->handler->createSelectQuery()->select('role_id')->from('ezpolicy')->where('role_id = 3'),
510
            'Expected an empty set.'
511
        );
512
513
        $this->assertQueryResult(
514
            [],
515
            $this->handler->createSelectQuery()->select('role_id')->from('ezuser_role')->where('role_id = 3'),
516
            'Expected an empty set.'
517
        );
518
    }
519
520
    public function testDeleteRoleDraft()
521
    {
522
        $this->insertDatabaseFixture(__DIR__ . '/../../../../Repository/Tests/Service/Integration/Legacy/_fixtures/test_data.php');
523
        $handler = $this->getUserHandler();
524
525
        // 3 is the ID of Editor role
526
        $roleDraft = $handler->createRoleDraft(3);
527
        $handler->deleteRole($roleDraft->id, APIRole::STATUS_DRAFT);
528
529
        $this->assertQueryResult(
530
            [['3', APIRole::STATUS_DEFINED]],
531
            $this->handler->createSelectQuery()->select('id, version')->from('ezrole')->where('id = 3'),
532
            'Expected a published role.'
533
        );
534
535
        $this->assertQueryResult(
536
            [[implode("\n", array_fill(0, 28, '3, ' . APIRole::STATUS_DEFINED))]],
537
            $this->handler->createSelectQuery()->select('role_id, original_id')->from('ezpolicy')->where('role_id = 3'),
538
            'Expected 28 policies for the published role.'
539
        );
540
541
        $this->assertQueryResult(
542
            [[3], [3]],
543
            $this->handler->createSelectQuery()->select('role_id')->from('ezuser_role')->where('role_id = 3'),
544
            'Expected that role assignments still exist.'
545
        );
546
    }
547
548
    public function testAddPolicyToRoleLimitations()
549
    {
550
        $handler = $this->getUserHandler();
551
552
        $role = $this->createTestRole($handler);
553
554
        $policy = new Persistence\User\Policy();
555
        $policy->module = 'foo';
556
        $policy->function = 'bar';
557
558
        $handler->addPolicy($role->id, $policy);
559
560
        $this->assertQueryResult(
561
            [[1, 'foo', 'bar', 1]],
562
            $this->handler->createSelectQuery()->select('id', 'module_name', 'function_name', 'role_id')->from('ezpolicy'),
563
            'Expected a new policy.'
564
        );
565
    }
566
567
    public function testAddPolicyPolicyId()
568
    {
569
        $handler = $this->getUserHandler();
570
571
        $role = $this->createTestRole($handler);
572
573
        $policy = new Persistence\User\Policy();
574
        $policy->module = 'foo';
575
        $policy->function = 'bar';
576
577
        $policy = $handler->addPolicy($role->id, $policy);
578
579
        $this->assertEquals(1, $policy->id);
580
    }
581
582
    public function testAddPolicyLimitations()
583
    {
584
        $this->createTestRoleWithTestPolicy();
585
586
        $this->assertQueryResult(
587
            [
588
                [1, 'Subtree', 1],
589
                [2, 'Foo', 1],
590
            ],
591
            $this->handler->createSelectQuery()->select('id', 'identifier', 'policy_id')->from('ezpolicy_limitation'),
592
            'Expected a new policy.'
593
        );
594
    }
595
596
    public function testAddPolicyLimitationValues()
597
    {
598
        $this->createTestRoleWithTestPolicy();
599
600
        $this->assertQueryResult(
601
            [
602
                [1, '/1', 1],
603
                [2, '/1/2', 1],
604
                [3, 'Bar', 2],
605
            ],
606
            $this->handler->createSelectQuery()->select('id', 'value', 'limitation_id')->from('ezpolicy_limitation_value'),
607
            'Expected a new policy.'
608
        );
609
    }
610
611
    protected function createRole()
612
    {
613
        $handler = $this->getUserHandler();
614
615
        $policy1 = new Persistence\User\Policy();
616
        $policy1->module = 'foo';
617
        $policy1->function = 'bar';
618
        $policy1->limitations = [
619
            'Subtree' => ['/1', '/1/2'],
620
            'Foo' => ['Bar'],
621
        ];
622
623
        $policy2 = new Persistence\User\Policy();
624
        $policy2->module = 'foo';
625
        $policy2->function = 'blubb';
626
        $policy2->limitations = [
627
            'Foo' => ['Blubb'],
628
        ];
629
630
        $createStruct = new Persistence\User\RoleCreateStruct();
631
        $createStruct->identifier = 'Test';
632
        $createStruct->policies = [$policy1, $policy2];
633
634
        return $handler->createRole($createStruct);
635
    }
636
637
    public function testImplicitlyCreatePolicies()
638
    {
639
        $this->createRole();
640
641
        $this->assertQueryResult(
642
            [
643
                [1, 'foo', 'bar', 1],
644
                [2, 'foo', 'blubb', 1],
645
            ],
646
            $this->handler->createSelectQuery()->select('id', 'module_name', 'function_name', 'role_id')->from('ezpolicy'),
647
            'Expected a new policy.'
648
        );
649
    }
650
651
    public function testDeletePolicy()
652
    {
653
        $handler = $this->getUserHandler();
654
655
        $roleDraft = $this->createRole();
656
        $handler->publishRoleDraft($roleDraft->id);
657
        $handler->deletePolicy($roleDraft->policies[0]->id, $roleDraft->policies[0]->roleId);
658
659
        $this->assertQueryResult(
660
            [
661
                [2, 'foo', 'blubb', 1],
662
            ],
663
            $this->handler->createSelectQuery()->select('id', 'module_name', 'function_name', 'role_id')->from('ezpolicy')->where('original_id = 0'),
664
            'Expected a new policy.'
665
        );
666
    }
667
668
    public function testDeletePolicyLimitations()
669
    {
670
        $handler = $this->getUserHandler();
671
672
        $roleDraft = $this->createRole();
673
        $handler->deletePolicy($roleDraft->policies[0]->id, $roleDraft->policies[0]->roleId);
674
675
        $this->assertQueryResult(
676
            [[3, 'Foo', 2]],
677
            $this->handler->createSelectQuery()->select('*')->from('ezpolicy_limitation')
678
        );
679
    }
680
681
    public function testDeletePolicyLimitationValues()
682
    {
683
        $handler = $this->getUserHandler();
684
685
        $roleDraft = $this->createRole();
686
        $handler->deletePolicy($roleDraft->policies[0]->id, $roleDraft->policies[0]->roleId);
687
688
        $this->assertQueryResult(
689
            [[4, 3, 'Blubb']],
690
            $this->handler->createSelectQuery()->select('*')->from('ezpolicy_limitation_value')
691
        );
692
    }
693
694
    public function testUpdatePolicies()
695
    {
696
        $handler = $this->getUserHandler();
697
698
        $roleDraft = $this->createRole();
699
700
        $policy = $roleDraft->policies[0];
701
        $policy->limitations = [
702
            'new' => ['something'],
703
        ];
704
705
        $handler->updatePolicy($policy);
706
707
        $this->assertQueryResult(
708
            [
709
                [3, 'Foo', 2],
710
                [4, 'new', 1],
711
            ],
712
            $this->handler->createSelectQuery()->select('*')->from('ezpolicy_limitation')
713
        );
714
715
        $this->assertQueryResult(
716
            [
717
                [4, 3, 'Blubb'],
718
                [5, 4, 'something'],
719
            ],
720
            $this->handler->createSelectQuery()->select('*')->from('ezpolicy_limitation_value')
721
        );
722
    }
723
724
    public function testAddRoleToUser()
725
    {
726
        $handler = $this->getUserHandler();
727
728
        $roleDraft = $this->createRole();
729
        $handler->publishRoleDraft($roleDraft->id);
730
        $role = $handler->loadRole($roleDraft->id);
731
        $user = $this->getValidUser();
732
733
        $handler->assignRole($user->id, $role->id, []);
734
735
        $this->assertQueryResult(
736
            [
737
                [1, self::TEST_USER_ID, 1, null, null],
738
            ],
739
            $this->handler->createSelectQuery()->select('id', 'contentobject_id', 'role_id', 'limit_identifier', 'limit_value')->from('ezuser_role'),
740
            'Expected a new user policy association.'
741
        );
742
    }
743
744
    public function testAddRoleToUserWithLimitation()
745
    {
746
        $handler = $this->getUserHandler();
747
748
        $roleDraft = $this->createRole();
749
        $handler->publishRoleDraft($roleDraft->id);
750
        $role = $handler->loadRole($roleDraft->id);
751
        $user = $this->getValidUser();
752
753
        $handler->assignRole(
754
            $user->id,
755
            $role->id,
756
            [
757
                'Subtree' => ['/1'],
758
            ]
759
        );
760
761
        $this->assertQueryResult(
762
            [
763
                [1, self::TEST_USER_ID, 1, 'Subtree', '/1'],
764
            ],
765
            $this->handler->createSelectQuery()->select('id', 'contentobject_id', 'role_id', 'limit_identifier', 'limit_value')->from('ezuser_role'),
766
            'Expected a new user policy association.'
767
        );
768
    }
769
770
    public function testAddRoleToUserWithComplexLimitation()
771
    {
772
        $handler = $this->getUserHandler();
773
774
        $roleDraft = $this->createRole();
775
        $handler->publishRoleDraft($roleDraft->id);
776
        $role = $handler->loadRole($roleDraft->id);
777
        $user = $this->getValidUser();
778
779
        $handler->assignRole(
780
            $user->id,
781
            $role->id,
782
            [
783
                'Subtree' => ['/1', '/1/2'],
784
                'Foo' => ['Bar'],
785
            ]
786
        );
787
788
        $this->assertQueryResult(
789
            [
790
                [1, self::TEST_USER_ID, 1, 'Subtree', '/1'],
791
                [2, self::TEST_USER_ID, 1, 'Subtree', '/1/2'],
792
                [3, self::TEST_USER_ID, 1, 'Foo', 'Bar'],
793
            ],
794
            $this->handler->createSelectQuery()->select('id', 'contentobject_id', 'role_id', 'limit_identifier', 'limit_value')->from('ezuser_role'),
795
            'Expected a new user policy association.'
796
        );
797
    }
798
799
    public function testRemoveUserRoleAssociation()
800
    {
801
        $handler = $this->getUserHandler();
802
803
        $roleDraft = $this->createRole();
804
        $handler->publishRoleDraft($roleDraft->id);
805
        $role = $handler->loadRole($roleDraft->id);
806
        $user = $this->getValidUser();
807
808
        $handler->assignRole(
809
            $user->id,
810
            $role->id,
811
            [
812
                'Subtree' => ['/1', '/1/2'],
813
                'Foo' => ['Bar'],
814
            ]
815
        );
816
817
        $handler->unassignRole($user->id, $role->id);
818
819
        $this->assertQueryResult(
820
            [],
821
            $this->handler->createSelectQuery()->select('id', 'contentobject_id', 'role_id', 'limit_identifier', 'limit_value')->from('ezuser_role'),
822
            'Expected no user policy associations.'
823
        );
824
    }
825
826
    public function testLoadPoliciesForUser()
827
    {
828
        $this->insertDatabaseFixture(__DIR__ . '/../../../../Repository/Tests/Service/Integration/Legacy/_fixtures/test_data.php');
829
        $handler = $this->getUserHandler();
830
831
        $policies = $handler->loadPoliciesByUserId(10); // Anonymous user
832
833
        // Verify, that we received an array of Policy objects
834
        $this->assertTrue(
835
            array_reduce(
836
                array_map(
837
                    function ($policy) {
838
                        return $policy instanceof Persistence\User\Policy;
839
                    },
840
                    $policies
841
                ),
842
                function ($a, $b) {
843
                    return $a && $b;
844
                },
845
                true
846
            )
847
        );
848
        $this->assertCount(8, $policies);
849
    }
850
851
    public function testLoadRoleAssignmentsByGroupId()
852
    {
853
        $this->insertDatabaseFixture(__DIR__ . '/../../../../Repository/Tests/Service/Integration/Legacy/_fixtures/test_data.php');
854
        $handler = $this->getUserHandler();
855
856
        $this->assertEquals(
857
            [
858
                new Persistence\User\RoleAssignment(
859
                    [
860
                        'id' => 28,
861
                        'roleId' => 1,
862
                        'contentId' => 11,
863
                    ]
864
                ),
865
                new Persistence\User\RoleAssignment(
866
                    [
867
                        'id' => 34,
868
                        'roleId' => 5,
869
                        'contentId' => 11,
870
                    ]
871
                ),
872
            ],
873
            $handler->loadRoleAssignmentsByGroupId(11)// 11: Members
874
        );
875
876
        $this->assertEquals(
877
            [
878
                new Persistence\User\RoleAssignment(
879
                    [
880
                        'id' => 31,
881
                        'roleId' => 1,
882
                        'contentId' => 42,
883
                    ]
884
                ),
885
            ],
886
            $handler->loadRoleAssignmentsByGroupId(42)// 42: Anonymous Users
887
        );
888
889
        $this->assertEquals(
890
            [],
891
            $handler->loadRoleAssignmentsByGroupId(10)// 10: Anonymous User
892
        );
893
    }
894
895
    public function testLoadRoleAssignmentsByGroupIdInherited()
896
    {
897
        $this->insertDatabaseFixture(__DIR__ . '/../../../../Repository/Tests/Service/Integration/Legacy/_fixtures/test_data.php');
898
        $handler = $this->getUserHandler();
899
900
        $this->assertEquals(
901
            [
902
                new Persistence\User\RoleAssignment(
903
                    [
904
                        'id' => 31,
905
                        'roleId' => 1,
906
                        'contentId' => 42,
907
                    ]
908
                ),
909
            ],
910
            $handler->loadRoleAssignmentsByGroupId(10, true)// 10: Anonymous User
911
        );
912
    }
913
914
    public function testLoadComplexRoleAssignments()
915
    {
916
        $this->insertDatabaseFixture(__DIR__ . '/../../../../Repository/Tests/Service/Integration/Legacy/_fixtures/test_data.php');
917
        $handler = $this->getUserHandler();
918
919
        $this->assertEquals(
920
            [
921
                new Persistence\User\RoleAssignment(
922
                    [
923
                        'id' => 32,
924
                        'roleId' => 3,
925
                        'contentId' => 13,
926
                        'limitationIdentifier' => 'Subtree',
927
                        'values' => ['/1/2/'],
928
                    ]
929
                ),
930
                new Persistence\User\RoleAssignment(
931
                    [
932
                        'id' => 33,
933
                        'roleId' => 3,
934
                        'contentId' => 13,
935
                        'limitationIdentifier' => 'Subtree',
936
                        'values' => ['/1/43/'],
937
                    ]
938
                ),
939
                new Persistence\User\RoleAssignment(
940
                    [
941
                        'id' => 38,
942
                        'roleId' => 5,
943
                        'contentId' => 13,
944
                    ]
945
                ),
946
            ],
947
            $handler->loadRoleAssignmentsByGroupId(13)
948
        );
949
950
        $this->assertEquals(
951
            [
952
                new Persistence\User\RoleAssignment(
953
                    [
954
                        'id' => 32,
955
                        'roleId' => 3,
956
                        'contentId' => 13,
957
                        'limitationIdentifier' => 'Subtree',
958
                        'values' => ['/1/2/'],
959
                    ]
960
                ),
961
                new Persistence\User\RoleAssignment(
962
                    [
963
                        'id' => 33,
964
                        'roleId' => 3,
965
                        'contentId' => 13,
966
                        'limitationIdentifier' => 'Subtree',
967
                        'values' => ['/1/43/'],
968
                    ]
969
                ),
970
                new Persistence\User\RoleAssignment(
971
                    [
972
                        'id' => 38,
973
                        'roleId' => 5,
974
                        'contentId' => 13,
975
                    ]
976
                ),
977
            ],
978
            $handler->loadRoleAssignmentsByGroupId(13, true)
979
        );
980
    }
981
982
    public function testLoadRoleAssignmentsByRoleId()
983
    {
984
        $this->insertDatabaseFixture(__DIR__ . '/../../../../Repository/Tests/Service/Integration/Legacy/_fixtures/test_data.php');
985
        $handler = $this->getUserHandler();
986
987
        $this->assertEquals(
988
            [
989
                new Persistence\User\RoleAssignment(
990
                    [
991
                        'id' => 28,
992
                        'roleId' => 1,
993
                        'contentId' => 11,
994
                    ]
995
                ),
996
                new Persistence\User\RoleAssignment(
997
                    [
998
                        'id' => 31,
999
                        'roleId' => 1,
1000
                        'contentId' => 42,
1001
                    ]
1002
                ),
1003
                new Persistence\User\RoleAssignment(
1004
                    [
1005
                        'id' => 37,
1006
                        'roleId' => 1,
1007
                        'contentId' => 59,
1008
                    ]
1009
                ),
1010
            ],
1011
            $handler->loadRoleAssignmentsByRoleId(1)
1012
        );
1013
    }
1014
1015
    public function testLoadRoleDraftByRoleId()
1016
    {
1017
        $this->insertDatabaseFixture(__DIR__ . '/../../../../Repository/Tests/Service/Integration/Legacy/_fixtures/test_data.php');
1018
        $handler = $this->getUserHandler();
1019
1020
        // 3 is the ID of Editor role
1021
        $originalRoleId = 3;
1022
        $draft = $handler->createRoleDraft($originalRoleId);
1023
        $loadedDraft = $handler->loadRoleDraftByRoleId($originalRoleId);
1024
        self::assertSame($loadedDraft->originalId, $originalRoleId);
1025
        self::assertEquals($draft, $loadedDraft);
1026
    }
1027
1028
    public function testRoleDraftOnlyHavePolicyDraft()
1029
    {
1030
        $this->insertDatabaseFixture(__DIR__ . '/../../../../Repository/Tests/Service/Integration/Legacy/_fixtures/test_data.php');
1031
        $handler = $this->getUserHandler();
1032
        $originalRoleId = 3;
1033
        $originalRole = $handler->loadRole($originalRoleId);
1034
        $originalPolicies = [];
1035
        foreach ($originalRole->policies as $policy) {
1036
            $originalPolicies[$policy->id] = $policy;
1037
        }
1038
1039
        $draft = $handler->createRoleDraft($originalRoleId);
1040
        $loadedDraft = $handler->loadRole($draft->id, Role::STATUS_DRAFT);
1041
        self::assertSame($loadedDraft->originalId, $originalRoleId);
1042
        self::assertEquals($draft, $loadedDraft);
1043
        foreach ($loadedDraft->policies as $policy) {
1044
            self::assertTrue(isset($originalPolicies[$policy->originalId]));
1045
        }
1046
1047
        // Now add a new policy. Original ID of the new one must be the same as its actual ID.
1048
        $newPolicyModule = 'foo';
1049
        $newPolicyFunction = 'bar';
1050
        $policy = new Persistence\User\Policy(['module' => $newPolicyModule, 'function' => $newPolicyFunction]);
1051
        $policyDraft = $handler->addPolicyByRoleDraft($loadedDraft->id, $policy);
1052
1053
        // Test again by reloading the draft.
1054
        $loadedDraft = $handler->loadRole($draft->id, Role::STATUS_DRAFT);
1055
        foreach ($loadedDraft->policies as $policy) {
1056
            if ($policy->id != $policyDraft->id) {
1057
                continue;
1058
            }
1059
1060
            self::assertNotNull($policy->originalId);
1061
            self::assertSame($policy->id, $policy->originalId);
1062
        }
1063
    }
1064
1065
    /**
1066
     * @throws \eZ\Publish\API\Repository\Exceptions\NotFoundException
1067
     */
1068
    private function createTestRole(User\Handler $handler): Role
1069
    {
1070
        $createStruct = new Persistence\User\RoleCreateStruct();
1071
        $createStruct->identifier = 'Test';
1072
1073
        $roleDraft = $handler->createRole($createStruct);
1074
        $handler->publishRoleDraft($roleDraft->id);
1075
1076
        return $handler->loadRole($roleDraft->id);
1077
    }
1078
1079
    /**
1080
     * @throws \eZ\Publish\API\Repository\Exceptions\NotFoundException
1081
     */
1082
    private function createTestRoleWithTestPolicy(): void
1083
    {
1084
        $handler = $this->getUserHandler();
1085
1086
        $role = $this->createTestRole($handler);
1087
1088
        $policy = new Persistence\User\Policy();
1089
        $policy->module = 'foo';
1090
        $policy->function = 'bar';
1091
        $policy->limitations = [
1092
            'Subtree' => ['/1', '/1/2'],
1093
            'Foo' => ['Bar'],
1094
        ];
1095
1096
        $handler->addPolicy($role->id, $policy);
1097
    }
1098
}
1099