UserHandlerTest   F
last analyzed

Complexity

Total Complexity 60

Size/Duplication

Total Lines 1161
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 17

Importance

Changes 0
Metric Value
dl 0
loc 1161
c 0
b 0
f 0
wmc 60
lcom 1
cbo 17
rs 2.556

55 Methods

Rating   Name   Duplication   Size   Complexity  
A createRole() 0 25 1
A testImplicitlyCreatePolicies() 0 13 1
A testDeletePolicy() 0 16 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 getUserHandler() 0 11 1
A getValidUser() 0 14 1
A getValidUserToken() 0 9 1
A testCreateUser() 0 7 1
A getGatewayReturnValue() 0 10 1
A getDummyUser() 0 16 1
A testLoadUser() 0 19 1
A testLoadUnknownUser() 0 15 1
A testLoadUserByLogin() 0 19 1
A testLoadMultipleUsersByLogin() 0 20 1
A testLoadMultipleUsersByEmail() 0 20 1
A testLoadUserByEmailNotFound() 0 9 1
A testLoadUserByEmail() 0 19 1
A testLoadUsersByEmail() 0 19 1
A testLoadUserByTokenNotFound() 0 9 1
A testLoadUserByToken() 0 21 1
A testUpdateUserToken() 0 24 1
A testExpireUserToken() 0 24 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 testDeletePolicyLimitations() 0 12 1
A testDeletePolicyLimitationValues() 0 12 1
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
 * @copyright Copyright (C) eZ Systems AS. All rights reserved.
5
 * @license For full copyright and license information view LICENSE file distributed with this source code.
6
 */
7
namespace eZ\Publish\Core\Persistence\Legacy\Tests\User;
8
9
use DateInterval;
10
use DateTime;
11
use eZ\Publish\API\Repository\Exceptions\NotFoundException;
12
use eZ\Publish\API\Repository\Exceptions\NotImplementedException;
13
use eZ\Publish\API\Repository\Values\User\Role as APIRole;
14
use eZ\Publish\Core\Persistence\Legacy\Tests\TestCase;
15
use eZ\Publish\Core\Persistence\Legacy\User;
16
use eZ\Publish\Core\Persistence\Legacy\User\Role\LimitationConverter;
17
use eZ\Publish\Core\Persistence\Legacy\User\Role\LimitationHandler\ObjectStateHandler as ObjectStateLimitationHandler;
18
use eZ\Publish\SPI\Persistence;
19
use eZ\Publish\SPI\Persistence\User\Handler;
20
use eZ\Publish\SPI\Persistence\User\Role;
21
use LogicException;
22
23
/**
24
 * Test case for UserHandlerTest.
25
 */
26
class UserHandlerTest extends TestCase
27
{
28
    private const TEST_USER_ID = 42;
29
30
    /**
31
     * @throws \Doctrine\DBAL\DBALException
32
     */
33
    protected function getUserHandler(User\Gateway $userGateway = null): Handler
34
    {
35
        $dbHandler = $this->getDatabaseHandler();
36
37
        return new User\Handler(
38
            $userGateway ?? new User\Gateway\DoctrineDatabase($this->getDatabaseConnection()),
39
            new User\Role\Gateway\DoctrineDatabase($this->getDatabaseConnection()),
40
            new User\Mapper(),
41
            new LimitationConverter([new ObjectStateLimitationHandler($dbHandler)])
42
        );
43
    }
44
45
    protected function getValidUser()
46
    {
47
        $user = new Persistence\User();
48
        $user->id = self::TEST_USER_ID;
49
        $user->login = 'kore';
50
        $user->email = '[email protected]';
51
        $user->passwordHash = '1234567890';
52
        $user->hashAlgorithm = 2;
53
        $user->isEnabled = true;
54
        $user->maxLogin = 23;
55
        $user->passwordUpdatedAt = 1569229200;
56
57
        return $user;
58
    }
59
60
    protected function getValidUserToken($time = null)
61
    {
62
        $userToken = new Persistence\User\UserTokenUpdateStruct();
63
        $userToken->userId = self::TEST_USER_ID;
64
        $userToken->hashKey = md5('hash');
65
        $userToken->time = $time ?? (new DateTime())->add(new DateInterval('P1D'))->getTimestamp();
66
67
        return $userToken;
68
    }
69
70
    public function testCreateUser()
71
    {
72
        $handler = $this->getUserHandler();
73
74
        $this->expectException(NotImplementedException::class);
75
        $handler->create($this->getValidUser());
76
    }
77
78
    protected function getGatewayReturnValue(): array
79
    {
80
        return [
81
            $this->getDummyUser(
82
                self::TEST_USER_ID,
83
                'kore',
84
                '[email protected]'
85
            ),
86
        ];
87
    }
88
89
    protected function getDummyUser(
90
        int $id,
91
        string $login,
92
        string $email
93
    ): array {
94
        return [
95
            'contentobject_id' => $id,
96
            'login' => $login,
97
            'email' => $email,
98
            'password_hash' => '1234567890',
99
            'password_hash_type' => 2,
100
            'is_enabled' => true,
101
            'max_login' => 23,
102
            'password_updated_at' => 1569229200,
103
        ];
104
    }
105
106
    public function testLoadUser()
107
    {
108
        $gatewayMock = $this
109
            ->createMock(User\Gateway::class);
110
111
        $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...
112
            ->method('load')
113
            ->with(self::TEST_USER_ID)
114
            ->willReturn($this->getGatewayReturnValue());
115
116
        $handler = $this->getUserHandler($gatewayMock);
117
118
        $user = $this->getValidUser();
119
120
        $this->assertEquals(
121
            $user,
122
            $handler->load($user->id)
123
        );
124
    }
125
126
    public function testLoadUnknownUser()
127
    {
128
        $this->expectException(NotFoundException::class);
129
        $gatewayMock = $this
130
            ->createMock(User\Gateway::class);
131
132
        $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...
133
            ->method('load')
134
            ->with(1337)
135
            ->willReturn([]);
136
137
        $handler = $this->getUserHandler($gatewayMock);
138
139
        $handler->load(1337);
140
    }
141
142
    public function testLoadUserByLogin()
143
    {
144
        $gatewayMock = $this
145
            ->createMock(User\Gateway::class);
146
147
        $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...
148
            ->method('loadByLogin')
149
            ->with('kore')
150
            ->willReturn($this->getGatewayReturnValue());
151
152
        $handler = $this->getUserHandler($gatewayMock);
153
        $user = $this->getValidUser();
154
155
        $loadedUser = $handler->loadByLogin($user->login);
156
        $this->assertEquals(
157
            $user,
158
            $loadedUser
159
        );
160
    }
161
162
    public function testLoadMultipleUsersByLogin()
163
    {
164
        $this->expectException(LogicException::class);
165
166
        $gatewayMock = $this
167
            ->createMock(User\Gateway::class);
168
169
        $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...
170
            ->method('loadByLogin')
171
            ->with('kore')
172
            ->willReturn([
173
                $this->getDummyUser(self::TEST_USER_ID, 'kore', '[email protected]'),
174
                $this->getDummyUser(self::TEST_USER_ID + 1, 'kore', '[email protected]'),
175
            ]);
176
177
        $handler = $this->getUserHandler($gatewayMock);
178
        $user = $this->getValidUser();
179
180
        $handler->loadByLogin($user->login);
181
    }
182
183
    public function testLoadMultipleUsersByEmail()
184
    {
185
        $this->expectException(LogicException::class);
186
187
        $gatewayMock = $this
188
            ->createMock(User\Gateway::class);
189
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('loadByEmail')
192
            ->with('[email protected]')
193
            ->willReturn([
194
                $this->getDummyUser(self::TEST_USER_ID, 'kore_a', '[email protected]'),
195
                $this->getDummyUser(self::TEST_USER_ID + 1, 'kore_b', '[email protected]'),
196
            ]);
197
198
        $handler = $this->getUserHandler($gatewayMock);
199
        $user = $this->getValidUser();
200
201
        $handler->loadByEmail($user->email);
202
    }
203
204
    public function testLoadUserByEmailNotFound()
205
    {
206
        $this->expectException(NotFoundException::class);
207
208
        $handler = $this->getUserHandler();
209
        $user = $this->getValidUser();
210
211
        $handler->loadByLogin($user->email);
212
    }
213
214
    public function testLoadUserByEmail()
215
    {
216
        $gatewayMock = $this
217
            ->createMock(User\Gateway::class);
218
219
        $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...
220
            ->method('loadByEmail')
221
            ->with('[email protected]')
222
            ->willReturn($this->getGatewayReturnValue());
223
224
        $handler = $this->getUserHandler($gatewayMock);
225
        $validUser = $this->getValidUser();
226
227
        $user = $handler->loadByEmail($validUser->email);
228
        $this->assertEquals(
229
            $validUser,
230
            $user
231
        );
232
    }
233
234
    public function testLoadUsersByEmail()
235
    {
236
        $gatewayMock = $this
237
            ->createMock(User\Gateway::class);
238
239
        $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...
240
            ->method('loadByEmail')
241
            ->with('[email protected]')
242
            ->willReturn($this->getGatewayReturnValue());
243
244
        $handler = $this->getUserHandler($gatewayMock);
245
        $user = $this->getValidUser();
246
247
        $users = $handler->loadUsersByEmail($user->email);
248
        $this->assertEquals(
249
            $user,
250
            $users[0]
251
        );
252
    }
253
254
    public function testLoadUserByTokenNotFound()
255
    {
256
        $this->expectException(NotFoundException::class);
257
258
        $handler = $this->getUserHandler();
259
        $handler->updateUserToken($this->getValidUserToken());
260
261
        $handler->loadUserByToken('asd');
262
    }
263
264
    public function testLoadUserByToken()
265
    {
266
        $gatewayMock = $this
267
            ->createMock(User\Gateway::class);
268
269
        $userToken = $this->getValidUserToken();
270
        $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...
271
            ->method('loadUserByToken')
272
            ->with($userToken->hashKey)
273
            ->willReturn($this->getGatewayReturnValue());
274
275
        $handler = $this->getUserHandler($gatewayMock);
276
        $user = $this->getValidUser();
277
        $handler->updateUserToken($userToken);
278
279
        $loadedUser = $handler->loadUserByToken($userToken->hashKey);
280
        $this->assertEquals(
281
            $user,
282
            $loadedUser
283
        );
284
    }
285
286
    public function testUpdateUserToken()
287
    {
288
        $handler = $this->getUserHandler();
289
290
        $handler->updateUserToken($this->getValidUserToken(1234567890));
291
292
        $this->assertQueryResult(
293
            [['0800fc577294c34e0b28ad2839435945', 1, 1234567890, self::TEST_USER_ID]],
294
            $this->handler->createSelectQuery()->select(
295
                ['hash_key', 'id', 'time', 'user_id']
296
            )->from('ezuser_accountkey'),
297
            'Expected user data to be updated.'
298
        );
299
300
        $handler->updateUserToken($this->getValidUserToken(2234567890));
301
302
        $this->assertQueryResult(
303
            [['0800fc577294c34e0b28ad2839435945', 1, 2234567890, self::TEST_USER_ID]],
304
            $this->handler->createSelectQuery()->select(
305
                ['hash_key', 'id', 'time', 'user_id']
306
            )->from('ezuser_accountkey'),
307
            'Expected user token data to be updated.'
308
        );
309
    }
310
311
    public function testExpireUserToken()
312
    {
313
        $handler = $this->getUserHandler();
314
315
        $handler->updateUserToken($userToken = $this->getValidUserToken(1234567890));
316
317
        $this->assertQueryResult(
318
            [['0800fc577294c34e0b28ad2839435945', 1, 1234567890, self::TEST_USER_ID]],
319
            $this->handler->createSelectQuery()->select(
320
                ['hash_key', 'id', 'time', 'user_id']
321
            )->from('ezuser_accountkey'),
322
            'Expected user data to be updated.'
323
        );
324
325
        $handler->expireUserToken($userToken->hashKey);
326
327
        $this->assertQueryResult(
328
            [['0800fc577294c34e0b28ad2839435945', 1, 0, self::TEST_USER_ID]],
329
            $this->handler->createSelectQuery()->select(
330
                ['hash_key', 'id', 'time', 'user_id']
331
            )->from('ezuser_accountkey'),
332
            'Expected user token to be expired.'
333
        );
334
    }
335
336
    public function testDeleteNonExistingUser()
337
    {
338
        $handler = $this->getUserHandler();
339
340
        $this->expectException(NotImplementedException::class);
341
        $handler->delete(1337);
342
    }
343
344
    public function testUpdateUser()
345
    {
346
        $handler = $this->getUserHandler();
347
        $user = $this->getValidUser();
348
349
        $user->login = 'New_lögin';
350
        $this->expectException(NotImplementedException::class);
351
        $handler->update($user);
352
    }
353
354
    public function testUpdateUserSettings()
355
    {
356
        $handler = $this->getUserHandler();
357
        $user = $this->getValidUser();
358
359
        $user->maxLogin = 42;
360
        $this->expectException(NotImplementedException::class);
361
        $handler->update($user);
362
    }
363
364
    public function testCreateNewRoleWithoutPolicies()
365
    {
366
        $handler = $this->getUserHandler();
367
368
        $createStruct = new Persistence\User\RoleCreateStruct();
369
        $createStruct->identifier = 'Test';
370
371
        $handler->createRole($createStruct);
372
373
        $this->assertQueryResult(
374
            [[1, 'Test', -1]],
375
            $this->handler->createSelectQuery()->select('id', 'name', 'version')->from('ezrole'),
376
            'Expected a new role draft.'
377
        );
378
    }
379
380
    public function testCreateRoleDraftWithoutPolicies()
381
    {
382
        $handler = $this->getUserHandler();
383
384
        $createStruct = new Persistence\User\RoleCreateStruct();
385
        $createStruct->identifier = 'Test';
386
387
        $roleDraft = $handler->createRole($createStruct);
388
        $handler->publishRoleDraft($roleDraft->id);
389
390
        $handler->createRoleDraft($roleDraft->id);
391
392
        $publishedRoleId = 1;
393
        $this->assertQueryResult(
394
            [
395
                [$publishedRoleId, 'Test', APIRole::STATUS_DEFINED],
396
                [2, 'Test', $publishedRoleId],
397
            ],
398
            $this->handler->createSelectQuery()->select('id', 'name', 'version')->from('ezrole'),
399
            'Expected a role and a role draft.'
400
        );
401
    }
402
403
    public function testCreateNewRoleRoleId()
404
    {
405
        $handler = $this->getUserHandler();
406
407
        $createStruct = new Persistence\User\RoleCreateStruct();
408
        $createStruct->identifier = 'Test';
409
410
        $roleDraft = $handler->createRole($createStruct);
411
412
        $this->assertSame(1, $roleDraft->id);
413
    }
414
415
    public function testLoadRole()
416
    {
417
        $handler = $this->getUserHandler();
418
419
        $createStruct = new Persistence\User\RoleCreateStruct();
420
        $createStruct->identifier = 'Test';
421
422
        $roleDraft = $handler->createRole($createStruct);
423
        $handler->publishRoleDraft($roleDraft->id);
424
        $role = $handler->loadRole($roleDraft->id);
425
426
        $this->assertEquals(
427
            $roleDraft->id,
428
            $role->id
429
        );
430
    }
431
432
    public function testLoadRoleWithPolicies()
433
    {
434
        $handler = $this->getUserHandler();
435
436
        $createStruct = new Persistence\User\RoleCreateStruct();
437
        $createStruct->identifier = 'Test';
438
439
        $roleDraft = $handler->createRole($createStruct);
440
441
        $policy = new Persistence\User\Policy();
442
        $policy->module = 'foo';
443
        $policy->function = 'bar';
444
445
        $handler->addPolicyByRoleDraft($roleDraft->id, $policy);
446
        $handler->publishRoleDraft($roleDraft->id);
447
448
        $loaded = $handler->loadRole($roleDraft->id);
449
        $this->assertEquals(
450
            [
451
                new Persistence\User\Policy(
452
                    [
453
                        'id' => 1,
454
                        'roleId' => 1,
455
                        'module' => 'foo',
456
                        'function' => 'bar',
457
                        'limitations' => '*',
458
                        'originalId' => null,
459
                    ]
460
                ),
461
            ],
462
            $loaded->policies
463
        );
464
    }
465
466
    public function testLoadRoleWithPoliciesAndGroups()
467
    {
468
        $handler = $this->getUserHandler();
469
470
        $createStruct = new Persistence\User\RoleCreateStruct();
471
        $createStruct->identifier = 'Test';
472
473
        $roleDraft = $handler->createRole($createStruct);
474
475
        $policy = new Persistence\User\Policy();
476
        $policy->module = 'foo';
477
        $policy->function = 'bar';
478
479
        $handler->addPolicyByRoleDraft($roleDraft->id, $policy);
480
481
        $handler->assignRole(23, $roleDraft->id);
482
        $handler->assignRole(42, $roleDraft->id);
483
484
        $handler->publishRoleDraft($roleDraft->id);
485
486
        $loaded = $handler->loadRole($roleDraft->id);
487
        $this->assertEquals(
488
            [
489
                new Persistence\User\Policy(
490
                    [
491
                        'id' => 1,
492
                        'roleId' => 1,
493
                        'module' => 'foo',
494
                        'function' => 'bar',
495
                        'limitations' => '*',
496
                        'originalId' => null,
497
                    ]
498
                ),
499
            ],
500
            $loaded->policies
501
        );
502
    }
503
504
    public function testLoadRoleWithPolicyLimitations()
505
    {
506
        $handler = $this->getUserHandler();
507
508
        $createStruct = new Persistence\User\RoleCreateStruct();
509
        $createStruct->identifier = 'Test';
510
511
        $roleDraft = $handler->createRole($createStruct);
512
513
        $policy = new Persistence\User\Policy();
514
        $policy->module = 'foo';
515
        $policy->function = 'bar';
516
        $policy->limitations = [
517
            'Subtree' => ['/1', '/1/2'],
518
            'Foo' => ['Bar'],
519
        ];
520
521
        $handler->addPolicyByRoleDraft($roleDraft->id, $policy);
522
        $handler->publishRoleDraft($roleDraft->id);
523
524
        $loaded = $handler->loadRole($roleDraft->id);
525
        $this->assertEquals(
526
            [
527
                new Persistence\User\Policy(
528
                    [
529
                        'id' => 1,
530
                        'roleId' => 1,
531
                        'module' => 'foo',
532
                        'function' => 'bar',
533
                        'limitations' => [
534
                            'Subtree' => ['/1', '/1/2'],
535
                            'Foo' => ['Bar'],
536
                        ],
537
                        'originalId' => null,
538
                    ]
539
                ),
540
            ],
541
            $loaded->policies
542
        );
543
    }
544
545
    public function testLoadRoles()
546
    {
547
        $handler = $this->getUserHandler();
548
549
        $this->assertEquals(
550
            [],
551
            $handler->loadRoles()
552
        );
553
554
        $role = $this->createTestRole($handler);
0 ignored issues
show
Compatibility introduced by
$handler of type object<eZ\Publish\SPI\Persistence\User\Handler> is not a sub-type of object<eZ\Publish\Core\P...ce\Legacy\User\Handler>. It seems like you assume a concrete implementation of the interface eZ\Publish\SPI\Persistence\User\Handler to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
555
556
        $this->assertEquals(
557
            [$role],
558
            $handler->loadRoles()
559
        );
560
    }
561
562
    public function testUpdateRole()
563
    {
564
        $handler = $this->getUserHandler();
565
566
        $role = $this->createTestRole($handler);
0 ignored issues
show
Compatibility introduced by
$handler of type object<eZ\Publish\SPI\Persistence\User\Handler> is not a sub-type of object<eZ\Publish\Core\P...ce\Legacy\User\Handler>. It seems like you assume a concrete implementation of the interface eZ\Publish\SPI\Persistence\User\Handler to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
567
568
        $update = new Persistence\User\RoleUpdateStruct();
569
        $update->id = $role->id;
570
        $update->identifier = 'Changed';
571
572
        $handler->updateRole($update);
573
574
        $this->assertQueryResult(
575
            [[1, 'Changed']],
576
            $this->handler->createSelectQuery()->select('id', 'name')->from('ezrole'),
577
            'Expected a changed role.'
578
        );
579
    }
580
581
    public function testDeleteRole()
582
    {
583
        $this->insertDatabaseFixture(__DIR__ . '/../../../../Repository/Tests/Service/Integration/Legacy/_fixtures/test_data.php');
584
        $handler = $this->getUserHandler();
585
586
        // 3 is the ID of Editor role
587
        $handler->deleteRole(3);
588
589
        $this->assertQueryResult(
590
            [],
591
            $this->handler->createSelectQuery()->select('id')->from('ezrole')->where('id = 3'),
592
            'Expected an empty set.'
593
        );
594
595
        $this->assertQueryResult(
596
            [],
597
            $this->handler->createSelectQuery()->select('role_id')->from('ezpolicy')->where('role_id = 3'),
598
            'Expected an empty set.'
599
        );
600
601
        $this->assertQueryResult(
602
            [],
603
            $this->handler->createSelectQuery()->select('role_id')->from('ezuser_role')->where('role_id = 3'),
604
            'Expected an empty set.'
605
        );
606
    }
607
608
    public function testDeleteRoleDraft()
609
    {
610
        $this->insertDatabaseFixture(__DIR__ . '/../../../../Repository/Tests/Service/Integration/Legacy/_fixtures/test_data.php');
611
        $handler = $this->getUserHandler();
612
613
        // 3 is the ID of Editor role
614
        $roleDraft = $handler->createRoleDraft(3);
615
        $handler->deleteRole($roleDraft->id, APIRole::STATUS_DRAFT);
616
617
        $this->assertQueryResult(
618
            [['3', APIRole::STATUS_DEFINED]],
619
            $this->handler->createSelectQuery()->select('id, version')->from('ezrole')->where('id = 3'),
620
            'Expected a published role.'
621
        );
622
623
        $this->assertQueryResult(
624
            [[implode("\n", array_fill(0, 28, '3, ' . APIRole::STATUS_DEFINED))]],
625
            $this->handler->createSelectQuery()->select('role_id, original_id')->from('ezpolicy')->where('role_id = 3'),
626
            'Expected 28 policies for the published role.'
627
        );
628
629
        $this->assertQueryResult(
630
            [[3], [3]],
631
            $this->handler->createSelectQuery()->select('role_id')->from('ezuser_role')->where('role_id = 3'),
632
            'Expected that role assignments still exist.'
633
        );
634
    }
635
636
    public function testAddPolicyToRoleLimitations()
637
    {
638
        $handler = $this->getUserHandler();
639
640
        $role = $this->createTestRole($handler);
0 ignored issues
show
Compatibility introduced by
$handler of type object<eZ\Publish\SPI\Persistence\User\Handler> is not a sub-type of object<eZ\Publish\Core\P...ce\Legacy\User\Handler>. It seems like you assume a concrete implementation of the interface eZ\Publish\SPI\Persistence\User\Handler to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
641
642
        $policy = new Persistence\User\Policy();
643
        $policy->module = 'foo';
644
        $policy->function = 'bar';
645
646
        $handler->addPolicy($role->id, $policy);
647
648
        $this->assertQueryResult(
649
            [[1, 'foo', 'bar', 1]],
650
            $this->handler->createSelectQuery()->select('id', 'module_name', 'function_name', 'role_id')->from('ezpolicy'),
651
            'Expected a new policy.'
652
        );
653
    }
654
655
    public function testAddPolicyPolicyId()
656
    {
657
        $handler = $this->getUserHandler();
658
659
        $role = $this->createTestRole($handler);
0 ignored issues
show
Compatibility introduced by
$handler of type object<eZ\Publish\SPI\Persistence\User\Handler> is not a sub-type of object<eZ\Publish\Core\P...ce\Legacy\User\Handler>. It seems like you assume a concrete implementation of the interface eZ\Publish\SPI\Persistence\User\Handler to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
660
661
        $policy = new Persistence\User\Policy();
662
        $policy->module = 'foo';
663
        $policy->function = 'bar';
664
665
        $policy = $handler->addPolicy($role->id, $policy);
666
667
        $this->assertEquals(1, $policy->id);
668
    }
669
670
    public function testAddPolicyLimitations()
671
    {
672
        $this->createTestRoleWithTestPolicy();
673
674
        $this->assertQueryResult(
675
            [
676
                [1, 'Subtree', 1],
677
                [2, 'Foo', 1],
678
            ],
679
            $this->handler->createSelectQuery()->select('id', 'identifier', 'policy_id')->from('ezpolicy_limitation'),
680
            'Expected a new policy.'
681
        );
682
    }
683
684
    public function testAddPolicyLimitationValues()
685
    {
686
        $this->createTestRoleWithTestPolicy();
687
688
        $this->assertQueryResult(
689
            [
690
                [1, '/1', 1],
691
                [2, '/1/2', 1],
692
                [3, 'Bar', 2],
693
            ],
694
            $this->handler->createSelectQuery()->select('id', 'value', 'limitation_id')->from('ezpolicy_limitation_value'),
695
            'Expected a new policy.'
696
        );
697
    }
698
699
    protected function createRole()
700
    {
701
        $handler = $this->getUserHandler();
702
703
        $policy1 = new Persistence\User\Policy();
704
        $policy1->module = 'foo';
705
        $policy1->function = 'bar';
706
        $policy1->limitations = [
707
            'Subtree' => ['/1', '/1/2'],
708
            'Foo' => ['Bar'],
709
        ];
710
711
        $policy2 = new Persistence\User\Policy();
712
        $policy2->module = 'foo';
713
        $policy2->function = 'blubb';
714
        $policy2->limitations = [
715
            'Foo' => ['Blubb'],
716
        ];
717
718
        $createStruct = new Persistence\User\RoleCreateStruct();
719
        $createStruct->identifier = 'Test';
720
        $createStruct->policies = [$policy1, $policy2];
721
722
        return $handler->createRole($createStruct);
723
    }
724
725
    public function testImplicitlyCreatePolicies()
726
    {
727
        $this->createRole();
728
729
        $this->assertQueryResult(
730
            [
731
                [1, 'foo', 'bar', 1],
732
                [2, 'foo', 'blubb', 1],
733
            ],
734
            $this->handler->createSelectQuery()->select('id', 'module_name', 'function_name', 'role_id')->from('ezpolicy'),
735
            'Expected a new policy.'
736
        );
737
    }
738
739
    public function testDeletePolicy()
740
    {
741
        $handler = $this->getUserHandler();
742
743
        $roleDraft = $this->createRole();
744
        $handler->publishRoleDraft($roleDraft->id);
745
        $handler->deletePolicy($roleDraft->policies[0]->id, $roleDraft->policies[0]->roleId);
746
747
        $this->assertQueryResult(
748
            [
749
                [2, 'foo', 'blubb', 1],
750
            ],
751
            $this->handler->createSelectQuery()->select('id', 'module_name', 'function_name', 'role_id')->from('ezpolicy')->where('original_id = 0'),
752
            'Expected a new policy.'
753
        );
754
    }
755
756
    public function testDeletePolicyLimitations()
757
    {
758
        $handler = $this->getUserHandler();
759
760
        $roleDraft = $this->createRole();
761
        $handler->deletePolicy($roleDraft->policies[0]->id, $roleDraft->policies[0]->roleId);
762
763
        $this->assertQueryResult(
764
            [[3, 'Foo', 2]],
765
            $this->handler->createSelectQuery()->select('*')->from('ezpolicy_limitation')
766
        );
767
    }
768
769
    public function testDeletePolicyLimitationValues()
770
    {
771
        $handler = $this->getUserHandler();
772
773
        $roleDraft = $this->createRole();
774
        $handler->deletePolicy($roleDraft->policies[0]->id, $roleDraft->policies[0]->roleId);
775
776
        $this->assertQueryResult(
777
            [[4, 3, 'Blubb']],
778
            $this->handler->createSelectQuery()->select('*')->from('ezpolicy_limitation_value')
779
        );
780
    }
781
782
    public function testUpdatePolicies()
783
    {
784
        $handler = $this->getUserHandler();
785
786
        $roleDraft = $this->createRole();
787
788
        $policy = $roleDraft->policies[0];
789
        $policy->limitations = [
790
            'new' => ['something'],
791
        ];
792
793
        $handler->updatePolicy($policy);
794
795
        $this->assertQueryResult(
796
            [
797
                [3, 'Foo', 2],
798
                [4, 'new', 1],
799
            ],
800
            $this->handler->createSelectQuery()->select('*')->from('ezpolicy_limitation')
801
        );
802
803
        $this->assertQueryResult(
804
            [
805
                [4, 3, 'Blubb'],
806
                [5, 4, 'something'],
807
            ],
808
            $this->handler->createSelectQuery()->select('*')->from('ezpolicy_limitation_value')
809
        );
810
    }
811
812
    public function testAddRoleToUser()
813
    {
814
        $handler = $this->getUserHandler();
815
816
        $roleDraft = $this->createRole();
817
        $handler->publishRoleDraft($roleDraft->id);
818
        $role = $handler->loadRole($roleDraft->id);
819
        $user = $this->getValidUser();
820
821
        $handler->assignRole($user->id, $role->id, []);
822
823
        $this->assertQueryResult(
824
            [
825
                [1, self::TEST_USER_ID, 1, null, null],
826
            ],
827
            $this->handler->createSelectQuery()->select('id', 'contentobject_id', 'role_id', 'limit_identifier', 'limit_value')->from('ezuser_role'),
828
            'Expected a new user policy association.'
829
        );
830
    }
831
832
    public function testAddRoleToUserWithLimitation()
833
    {
834
        $handler = $this->getUserHandler();
835
836
        $roleDraft = $this->createRole();
837
        $handler->publishRoleDraft($roleDraft->id);
838
        $role = $handler->loadRole($roleDraft->id);
839
        $user = $this->getValidUser();
840
841
        $handler->assignRole(
842
            $user->id,
843
            $role->id,
844
            [
845
                'Subtree' => ['/1'],
846
            ]
847
        );
848
849
        $this->assertQueryResult(
850
            [
851
                [1, self::TEST_USER_ID, 1, 'Subtree', '/1'],
852
            ],
853
            $this->handler->createSelectQuery()->select('id', 'contentobject_id', 'role_id', 'limit_identifier', 'limit_value')->from('ezuser_role'),
854
            'Expected a new user policy association.'
855
        );
856
    }
857
858
    public function testAddRoleToUserWithComplexLimitation()
859
    {
860
        $handler = $this->getUserHandler();
861
862
        $roleDraft = $this->createRole();
863
        $handler->publishRoleDraft($roleDraft->id);
864
        $role = $handler->loadRole($roleDraft->id);
865
        $user = $this->getValidUser();
866
867
        $handler->assignRole(
868
            $user->id,
869
            $role->id,
870
            [
871
                'Subtree' => ['/1', '/1/2'],
872
                'Foo' => ['Bar'],
873
            ]
874
        );
875
876
        $this->assertQueryResult(
877
            [
878
                [1, self::TEST_USER_ID, 1, 'Subtree', '/1'],
879
                [2, self::TEST_USER_ID, 1, 'Subtree', '/1/2'],
880
                [3, self::TEST_USER_ID, 1, 'Foo', 'Bar'],
881
            ],
882
            $this->handler->createSelectQuery()->select('id', 'contentobject_id', 'role_id', 'limit_identifier', 'limit_value')->from('ezuser_role'),
883
            'Expected a new user policy association.'
884
        );
885
    }
886
887
    public function testRemoveUserRoleAssociation()
888
    {
889
        $handler = $this->getUserHandler();
890
891
        $roleDraft = $this->createRole();
892
        $handler->publishRoleDraft($roleDraft->id);
893
        $role = $handler->loadRole($roleDraft->id);
894
        $user = $this->getValidUser();
895
896
        $handler->assignRole(
897
            $user->id,
898
            $role->id,
899
            [
900
                'Subtree' => ['/1', '/1/2'],
901
                'Foo' => ['Bar'],
902
            ]
903
        );
904
905
        $handler->unassignRole($user->id, $role->id);
906
907
        $this->assertQueryResult(
908
            [],
909
            $this->handler->createSelectQuery()->select('id', 'contentobject_id', 'role_id', 'limit_identifier', 'limit_value')->from('ezuser_role'),
910
            'Expected no user policy associations.'
911
        );
912
    }
913
914
    public function testLoadPoliciesForUser()
915
    {
916
        $this->insertDatabaseFixture(__DIR__ . '/../../../../Repository/Tests/Service/Integration/Legacy/_fixtures/test_data.php');
917
        $handler = $this->getUserHandler();
918
919
        $policies = $handler->loadPoliciesByUserId(10); // Anonymous user
0 ignored issues
show
Deprecated Code introduced by
The method eZ\Publish\SPI\Persisten...:loadPoliciesByUserId() has been deprecated with message: Since 6.8, not currently in use as permission system needs to know about role assignment limitations.

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

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

Loading history...
920
921
        // Verify, that we received an array of Policy objects
922
        $this->assertTrue(
923
            array_reduce(
924
                array_map(
925
                    function ($policy) {
926
                        return $policy instanceof Persistence\User\Policy;
927
                    },
928
                    $policies
929
                ),
930
                function ($a, $b) {
931
                    return $a && $b;
932
                },
933
                true
934
            )
935
        );
936
        $this->assertCount(8, $policies);
937
    }
938
939
    public function testLoadRoleAssignmentsByGroupId()
940
    {
941
        $this->insertDatabaseFixture(__DIR__ . '/../../../../Repository/Tests/Service/Integration/Legacy/_fixtures/test_data.php');
942
        $handler = $this->getUserHandler();
943
944
        $this->assertEquals(
945
            [
946
                new Persistence\User\RoleAssignment(
947
                    [
948
                        'id' => 28,
949
                        'roleId' => 1,
950
                        'contentId' => 11,
951
                    ]
952
                ),
953
                new Persistence\User\RoleAssignment(
954
                    [
955
                        'id' => 34,
956
                        'roleId' => 5,
957
                        'contentId' => 11,
958
                    ]
959
                ),
960
            ],
961
            $handler->loadRoleAssignmentsByGroupId(11)// 11: Members
962
        );
963
964
        $this->assertEquals(
965
            [
966
                new Persistence\User\RoleAssignment(
967
                    [
968
                        'id' => 31,
969
                        'roleId' => 1,
970
                        'contentId' => 42,
971
                    ]
972
                ),
973
            ],
974
            $handler->loadRoleAssignmentsByGroupId(42)// 42: Anonymous Users
975
        );
976
977
        $this->assertEquals(
978
            [],
979
            $handler->loadRoleAssignmentsByGroupId(10)// 10: Anonymous User
980
        );
981
    }
982
983
    public function testLoadRoleAssignmentsByGroupIdInherited()
984
    {
985
        $this->insertDatabaseFixture(__DIR__ . '/../../../../Repository/Tests/Service/Integration/Legacy/_fixtures/test_data.php');
986
        $handler = $this->getUserHandler();
987
988
        $this->assertEquals(
989
            [
990
                new Persistence\User\RoleAssignment(
991
                    [
992
                        'id' => 31,
993
                        'roleId' => 1,
994
                        'contentId' => 42,
995
                    ]
996
                ),
997
            ],
998
            $handler->loadRoleAssignmentsByGroupId(10, true)// 10: Anonymous User
999
        );
1000
    }
1001
1002
    public function testLoadComplexRoleAssignments()
1003
    {
1004
        $this->insertDatabaseFixture(__DIR__ . '/../../../../Repository/Tests/Service/Integration/Legacy/_fixtures/test_data.php');
1005
        $handler = $this->getUserHandler();
1006
1007
        $this->assertEquals(
1008
            [
1009
                new Persistence\User\RoleAssignment(
1010
                    [
1011
                        'id' => 32,
1012
                        'roleId' => 3,
1013
                        'contentId' => 13,
1014
                        'limitationIdentifier' => 'Subtree',
1015
                        'values' => ['/1/2/'],
1016
                    ]
1017
                ),
1018
                new Persistence\User\RoleAssignment(
1019
                    [
1020
                        'id' => 33,
1021
                        'roleId' => 3,
1022
                        'contentId' => 13,
1023
                        'limitationIdentifier' => 'Subtree',
1024
                        'values' => ['/1/43/'],
1025
                    ]
1026
                ),
1027
                new Persistence\User\RoleAssignment(
1028
                    [
1029
                        'id' => 38,
1030
                        'roleId' => 5,
1031
                        'contentId' => 13,
1032
                    ]
1033
                ),
1034
            ],
1035
            $handler->loadRoleAssignmentsByGroupId(13)
1036
        );
1037
1038
        $this->assertEquals(
1039
            [
1040
                new Persistence\User\RoleAssignment(
1041
                    [
1042
                        'id' => 32,
1043
                        'roleId' => 3,
1044
                        'contentId' => 13,
1045
                        'limitationIdentifier' => 'Subtree',
1046
                        'values' => ['/1/2/'],
1047
                    ]
1048
                ),
1049
                new Persistence\User\RoleAssignment(
1050
                    [
1051
                        'id' => 33,
1052
                        'roleId' => 3,
1053
                        'contentId' => 13,
1054
                        'limitationIdentifier' => 'Subtree',
1055
                        'values' => ['/1/43/'],
1056
                    ]
1057
                ),
1058
                new Persistence\User\RoleAssignment(
1059
                    [
1060
                        'id' => 38,
1061
                        'roleId' => 5,
1062
                        'contentId' => 13,
1063
                    ]
1064
                ),
1065
            ],
1066
            $handler->loadRoleAssignmentsByGroupId(13, true)
1067
        );
1068
    }
1069
1070
    public function testLoadRoleAssignmentsByRoleId()
1071
    {
1072
        $this->insertDatabaseFixture(__DIR__ . '/../../../../Repository/Tests/Service/Integration/Legacy/_fixtures/test_data.php');
1073
        $handler = $this->getUserHandler();
1074
1075
        $this->assertEquals(
1076
            [
1077
                new Persistence\User\RoleAssignment(
1078
                    [
1079
                        'id' => 28,
1080
                        'roleId' => 1,
1081
                        'contentId' => 11,
1082
                    ]
1083
                ),
1084
                new Persistence\User\RoleAssignment(
1085
                    [
1086
                        'id' => 31,
1087
                        'roleId' => 1,
1088
                        'contentId' => 42,
1089
                    ]
1090
                ),
1091
                new Persistence\User\RoleAssignment(
1092
                    [
1093
                        'id' => 37,
1094
                        'roleId' => 1,
1095
                        'contentId' => 59,
1096
                    ]
1097
                ),
1098
            ],
1099
            $handler->loadRoleAssignmentsByRoleId(1)
1100
        );
1101
    }
1102
1103
    public function testLoadRoleDraftByRoleId()
1104
    {
1105
        $this->insertDatabaseFixture(__DIR__ . '/../../../../Repository/Tests/Service/Integration/Legacy/_fixtures/test_data.php');
1106
        $handler = $this->getUserHandler();
1107
1108
        // 3 is the ID of Editor role
1109
        $originalRoleId = 3;
1110
        $draft = $handler->createRoleDraft($originalRoleId);
1111
        $loadedDraft = $handler->loadRoleDraftByRoleId($originalRoleId);
1112
        self::assertSame($loadedDraft->originalId, $originalRoleId);
1113
        self::assertEquals($draft, $loadedDraft);
1114
    }
1115
1116
    public function testRoleDraftOnlyHavePolicyDraft()
1117
    {
1118
        $this->insertDatabaseFixture(__DIR__ . '/../../../../Repository/Tests/Service/Integration/Legacy/_fixtures/test_data.php');
1119
        $handler = $this->getUserHandler();
1120
        $originalRoleId = 3;
1121
        $originalRole = $handler->loadRole($originalRoleId);
1122
        $originalPolicies = [];
1123
        foreach ($originalRole->policies as $policy) {
1124
            $originalPolicies[$policy->id] = $policy;
1125
        }
1126
1127
        $draft = $handler->createRoleDraft($originalRoleId);
1128
        $loadedDraft = $handler->loadRole($draft->id, Role::STATUS_DRAFT);
1129
        self::assertSame($loadedDraft->originalId, $originalRoleId);
1130
        self::assertEquals($draft, $loadedDraft);
1131
        foreach ($loadedDraft->policies as $policy) {
1132
            self::assertTrue(isset($originalPolicies[$policy->originalId]));
1133
        }
1134
1135
        // Now add a new policy. Original ID of the new one must be the same as its actual ID.
1136
        $newPolicyModule = 'foo';
1137
        $newPolicyFunction = 'bar';
1138
        $policy = new Persistence\User\Policy(['module' => $newPolicyModule, 'function' => $newPolicyFunction]);
1139
        $policyDraft = $handler->addPolicyByRoleDraft($loadedDraft->id, $policy);
1140
1141
        // Test again by reloading the draft.
1142
        $loadedDraft = $handler->loadRole($draft->id, Role::STATUS_DRAFT);
1143
        foreach ($loadedDraft->policies as $policy) {
1144
            if ($policy->id != $policyDraft->id) {
1145
                continue;
1146
            }
1147
1148
            self::assertNotNull($policy->originalId);
1149
            self::assertSame($policy->id, $policy->originalId);
1150
        }
1151
    }
1152
1153
    /**
1154
     * @throws \eZ\Publish\API\Repository\Exceptions\NotFoundException
1155
     */
1156
    private function createTestRole(User\Handler $handler): Role
1157
    {
1158
        $createStruct = new Persistence\User\RoleCreateStruct();
1159
        $createStruct->identifier = 'Test';
1160
1161
        $roleDraft = $handler->createRole($createStruct);
1162
        $handler->publishRoleDraft($roleDraft->id);
1163
1164
        return $handler->loadRole($roleDraft->id);
1165
    }
1166
1167
    /**
1168
     * @throws \eZ\Publish\API\Repository\Exceptions\NotFoundException
1169
     */
1170
    private function createTestRoleWithTestPolicy(): void
1171
    {
1172
        $handler = $this->getUserHandler();
1173
1174
        $role = $this->createTestRole($handler);
0 ignored issues
show
Compatibility introduced by
$handler of type object<eZ\Publish\SPI\Persistence\User\Handler> is not a sub-type of object<eZ\Publish\Core\P...ce\Legacy\User\Handler>. It seems like you assume a concrete implementation of the interface eZ\Publish\SPI\Persistence\User\Handler to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
1175
1176
        $policy = new Persistence\User\Policy();
1177
        $policy->module = 'foo';
1178
        $policy->function = 'bar';
1179
        $policy->limitations = [
1180
            'Subtree' => ['/1', '/1/2'],
1181
            'Foo' => ['Bar'],
1182
        ];
1183
1184
        $handler->addPolicy($role->id, $policy);
1185
    }
1186
}
1187