Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
Total | |
93.55% |
29 / 31 |
|
50.00% |
1 / 2 |
CRAP | |
0.00% |
0 / 1 |
CreateRoleEndpoint | |
93.55% |
29 / 31 |
|
50.00% |
1 / 2 |
8.02 | |
0.00% |
0 / 1 |
configure | |
100.00% |
2 / 2 |
|
100.00% |
1 / 1 |
1 | |||
handle | |
93.10% |
27 / 29 |
|
0.00% |
0 / 1 |
7.02 |
1 | <?php |
2 | |
3 | namespace Olz\Roles\Endpoints; |
4 | |
5 | use Olz\Api\OlzCreateEntityTypedEndpoint; |
6 | use Olz\Entity\Roles\Role; |
7 | use Olz\Entity\Users\User; |
8 | use PhpTypeScriptApi\Fields\ValidationError; |
9 | use PhpTypeScriptApi\HttpError; |
10 | |
11 | /** |
12 | * @phpstan-import-type OlzRoleId from RoleEndpointTrait |
13 | * @phpstan-import-type OlzRoleData from RoleEndpointTrait |
14 | * |
15 | * @extends OlzCreateEntityTypedEndpoint<OlzRoleId, OlzRoleData> |
16 | */ |
17 | class CreateRoleEndpoint extends OlzCreateEntityTypedEndpoint { |
18 | use RoleEndpointTrait; |
19 | |
20 | public function configure(): void { |
21 | parent::configure(); |
22 | $this->phpStanUtils->registerTypeImport(RoleEndpointTrait::class); |
23 | } |
24 | |
25 | protected function handle(mixed $input): mixed { |
26 | $parent_role = $input['data']['parentRole'] ?? null; |
27 | if (!$this->authUtils()->hasRoleEditPermission($parent_role)) { |
28 | throw new HttpError(403, "Kein Zugriff!"); |
29 | } |
30 | |
31 | $user_repo = $this->entityManager()->getRepository(User::class); |
32 | $role_repo = $this->entityManager()->getRepository(Role::class); |
33 | |
34 | // Username validation |
35 | $new_username = $input['data']['username']; |
36 | if (!$this->authUtils()->isUsernameAllowed($new_username)) { |
37 | throw new ValidationError(['username' => ["Der Benutzername darf nur Buchstaben, Zahlen, und die Zeichen -_. enthalten."]]); |
38 | } |
39 | $same_username_user = $user_repo->findOneBy(['username' => $new_username]); |
40 | $same_old_username_user = $user_repo->findOneBy(['old_username' => $new_username]); |
41 | $same_username_role = $role_repo->findOneBy(['username' => $new_username]); |
42 | $same_old_username_role = $role_repo->findOneBy(['old_username' => $new_username]); |
43 | $is_existing_username = (bool) ( |
44 | $same_username_user || $same_old_username_user |
45 | || $same_username_role || $same_old_username_role |
46 | ); |
47 | if ($is_existing_username) { |
48 | throw new ValidationError(['username' => ["Dieser Benutzername ist bereits vergeben."]]); |
49 | } |
50 | |
51 | $entity = new Role(); |
52 | $this->entityUtils()->createOlzEntity($entity, $input['meta']); |
53 | $entity->setOldUsername(null); |
54 | $entity->setPermissions(''); |
55 | $this->updateEntityWithData($entity, $input['data']); |
56 | |
57 | $this->entityManager()->persist($entity); |
58 | $this->entityManager()->flush(); |
59 | $this->persistUploads($entity, $input['data']); |
60 | |
61 | return [ |
62 | 'id' => $entity->getId() ?? 0, |
63 | ]; |
64 | } |
65 | } |