Passed
Push — master ( a4d77f...c3a602 )
by Adrien
15:17
created

TestWithTransactionAndUser::setCurrentUser()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 6
dl 0
loc 10
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace ApplicationTest\Traits;
6
7
use Application\Model\Account;
8
use Application\Model\User;
9
use Application\Repository\AccountRepository;
10
use Ecodev\Felix\Testing\Traits\TestWithTransaction;
11
12
/**
13
 * Allow to run test within a database transaction, so database will be unchanged after test.
14
 */
15
trait TestWithTransactionAndUser
16
{
17
    use TestWithTransaction {
18
        setUp as traitSetupWithTransaction;
19
        tearDown as traitTearDownWithTransaction;
20
    }
21
22
    /**
23
     * Start transaction.
24
     */
25
    protected function setUp(): void
26
    {
27
        $this->traitSetupWithTransaction();
28
        User::setCurrent(null);
29
    }
30
31
    /**
32
     * Cancel transaction, to undo all changes made.
33
     */
34
    protected function tearDown(): void
35
    {
36
        User::setCurrent(null);
37
38
        /** @var AccountRepository $accountRepository */
39
        $accountRepository = $this->getEntityManager()->getRepository(Account::class);
40
        $accountRepository->clearCache();
41
42
        $this->traitTearDownWithTransaction();
43
    }
44
45
    protected function setCurrentUser(string $login): void
46
    {
47
        $user = null;
48
        if ($login !== 'anonymous') {
49
            $userRepository = $this->getEntityManager()->getRepository(User::class);
50
            $user = $userRepository->getOneByLoginOrEmail($login);
51
            self::assertNotNull($user, 'given login must exist in test DB: ' . $login);
52
        }
53
54
        User::setCurrent($user);
55
    }
56
}
57