Passed
Push — main ( 495c0a...a633e0 )
by Daniel
05:04
created

UserCreationApplication::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 1
b 0
f 0
nc 1
nop 4
dl 0
loc 8
ccs 2
cts 2
cp 1
crap 1
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Uxmp\Core\Api\Settings;
6
7
use PH7\Generator\Password;
8
use Psr\Http\Message\ResponseInterface;
9
use Psr\Http\Message\ServerRequestInterface;
10
use Teapot\StatusCode;
11
use Uxmp\Core\Api\Lib\SchemaValidatorInterface;
12
use Uxmp\Core\Component\User\PrivilegeCheckerInterface;
13
use Uxmp\Core\Component\User\UserCreatorInterface;
14
use Uxmp\Core\Orm\Repository\UserRepositoryInterface;
15
16
/**
17
 * Adds a user
18
 */
19
final class UserCreationApplication extends AbstractSettingsApplication
20
{
21
    /**
22
     * @param SchemaValidatorInterface<array{name: string}> $schemaValidator
23
     */
24 2
    public function __construct(
25
        PrivilegeCheckerInterface $privilegeChecker,
26
        private readonly UserRepositoryInterface $userRepository,
27
        private readonly UserCreatorInterface $userCreator,
28
        private readonly SchemaValidatorInterface $schemaValidator,
29
    ) {
30 2
        parent::__construct(
31
            $privilegeChecker,
32
        );
33
    }
34
35 2
    protected function serve(
36
        ServerRequestInterface $request,
37
        ResponseInterface $response,
38
        array $args
39
    ): ResponseInterface {
40 2
        $body = $this->schemaValidator->getValidatedBody(
41
            $request,
42
            'UserCreation.json',
43
        );
44
45 2
        $userName = $body['name'];
46
47
        // check if a user with that name already exists
48 2
        $result = $this->userRepository->findOneBy(['name' => $userName]);
49 2
        if ($result !== null) {
50 1
            return $response->withStatus(StatusCode::BAD_REQUEST);
51
        }
52
53
        // Adds user and sets a temporary password
54 1
        $user = $this->userCreator->create(
55
            $userName,
56 1
            Password::generate()
57
        );
58
59 1
        return $this->asJson(
60
            $response,
61 1
            ['result' => $user->getId()]
62
        );
63
    }
64
}
65