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

CreateDatabaseEntry::checkForCompletion()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
cc 3
eloc 5
nc 3
nop 3
dl 0
loc 11
ccs 0
cts 6
cp 0
crap 12
rs 10
c 0
b 0
f 0
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