Passed
Pull Request — master (#1833)
by Nico
34:40
created

CreateDatabaseEntry   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 56
Duplicated Lines 0 %

Test Coverage

Coverage 8%

Importance

Changes 0
Metric Value
eloc 22
dl 0
loc 56
ccs 2
cts 25
cp 0.08
rs 10
c 0
b 0
f 0
wmc 9

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A checkForCompletion() 0 11 3
A createDatabaseEntryForUser() 0 33 5
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Stu\Module\Database\Lib;
6
7
use Stu\Module\Award\Lib\CreateUserAwardInterface;
8
use Stu\Module\Prestige\Lib\CreatePrestigeLogInterface;
9
use Stu\Orm\Entity\DatabaseCategoryInterface;
10
use Stu\Orm\Entity\DatabaseEntryInterface;
11
use Stu\Orm\Entity\UserInterface;
12
use Stu\Orm\Repository\DatabaseEntryRepositoryInterface;
13
use Stu\Orm\Repository\DatabaseUserRepositoryInterface;
14
15
final class CreateDatabaseEntry implements CreateDatabaseEntryInterface
16
{
17 4
    public function __construct(
18
        private DatabaseEntryRepositoryInterface $databaseEntryRepository,
19
        private DatabaseUserRepositoryInterface $databaseUserRepository,
20
        private CreatePrestigeLogInterface $createPrestigeLog,
21
        private CreateUserAwardInterface $createUserAward
22
    ) {
23 4
    }
24
25
    public function createDatabaseEntryForUser(UserInterface $user, int $databaseEntryId): ?DatabaseEntryInterface
26
    {
27
        if ($databaseEntryId === 0) {
28
            return null;
29
        }
30
31
        if (!$user->hasColony()) {
32
            return null;
33
        }
34
35
        $databaseEntry = $this->databaseEntryRepository->find($databaseEntryId);
36
37
        if ($databaseEntry === null) {
38
            return null;
39
        }
40
41
        //create new user entry
42
        $userEntry = $this->databaseUserRepository->prototype()
43
            ->setUser($user)
44
            ->setDatabaseEntry($databaseEntry)
45
            ->setDate(time());
46
47
        $this->databaseUserRepository->save($userEntry);
48
49
50
        if (!$user->isNpc()) {
51
            //create prestige log
52
            $this->createPrestigeLog->createLogForDatabaseEntry($databaseEntry, $user, $userEntry->getDate());
53
54
            $this->checkForCompletion($user, $databaseEntry->getCategory(), $databaseEntryId);
55
        }
56
57
        return $databaseEntry;
58
    }
59
60
    private function checkForCompletion(UserInterface $user, DatabaseCategoryInterface $category, int $databaseEntryId): void
61
    {
62
        //check if an award is configured for this category
63
        if ($category->getAward() === null) {
64
            return;
65
        }
66
67
        $award = $category->getAward();
68
69
        if ($this->databaseUserRepository->hasUserCompletedCategory($user->getId(), $category->getId(), $databaseEntryId)) {
70
            $this->createUserAward->createAwardForUser($user, $award);
71
        }
72
    }
73
}
74