Completed
Push — master ( 61044a...94728c )
by Rafał
24:26 queued 10:49
created

UserContext::theFollowingUsers()   B

Complexity

Conditions 6
Paths 6

Size

Total Lines 30

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 30
rs 8.8177
c 0
b 0
f 0
cc 6
nc 6
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace SWP\Behat\Contexts;
6
7
use Behat\Behat\Context\Context;
8
use Behat\Gherkin\Node\TableNode;
9
use FOS\UserBundle\Model\UserManagerInterface;
10
use SWP\Bundle\CoreBundle\Factory\ApiKeyFactory;
11
use SWP\Bundle\CoreBundle\Model\UserInterface;
12
use SWP\Bundle\CoreBundle\Repository\ApiKeyRepositoryInterface;
13
14
final class UserContext extends AbstractContext implements Context
15
{
16
    private $userManager;
17
18
    private $apiKeyFactory;
19
20
    private $apiKeyRepository;
21
22
    public function __construct(UserManagerInterface $userManager, ApiKeyFactory $apiKeyFactory, ApiKeyRepositoryInterface $apiKeyRepository)
23
    {
24
        $this->userManager = $userManager;
25
        $this->apiKeyFactory = $apiKeyFactory;
26
        $this->apiKeyRepository = $apiKeyRepository;
27
    }
28
29
    /**
30
     * @Given the following Users:
31
     */
32
    public function theFollowingUsers(TableNode $table): void
33
    {
34
        foreach ($table as $row => $columns) {
35
            if (isset($columns['email']) && null !== $this->userManager->findUserByEmail($columns['email'])) {
36
                continue;
37
            }
38
39
            /** @var UserInterface $user */
40
            $user = $this->userManager->createUser();
41
42
            if (isset($columns['role'])) {
43
                $user->addRole($columns['role']);
44
                unset($columns['role']);
45
            }
46
47
            $token = null;
48
            if (isset($columns['token'])) {
49
                $token = $columns['token'];
50
                unset($columns['token']);
51
            }
52
53
            $this->fillObject($user, $columns);
54
            $this->userManager->updateUser($user);
55
56
            $apiKey = $this->apiKeyFactory->create($user, base64_encode($token));
57
58
            $this->apiKeyRepository->add($apiKey);
59
            $this->apiKeyRepository->add($user);
60
        }
61
    }
62
}
63