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

TestWithTransactionAndUser   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 4
eloc 16
dl 0
loc 40
rs 10
c 2
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A tearDown() 0 9 1
A setUp() 0 4 1
A setCurrentUser() 0 10 2
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