Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
93.10% |
27 / 29 |
|
0.00% |
0 / 1 |
CRAP | |
0.00% |
0 / 1 |
| CreateRoleEndpoint | |
93.10% |
27 / 29 |
|
0.00% |
0 / 1 |
7.02 | |
0.00% |
0 / 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 | protected function handle(mixed $input): mixed { |
| 21 | $parent_role = $input['data']['parentRole'] ?? null; |
| 22 | if (!$this->authUtils()->hasRoleEditPermission($parent_role)) { |
| 23 | throw new HttpError(403, "Kein Zugriff!"); |
| 24 | } |
| 25 | |
| 26 | $user_repo = $this->entityManager()->getRepository(User::class); |
| 27 | $role_repo = $this->entityManager()->getRepository(Role::class); |
| 28 | |
| 29 | // Username validation |
| 30 | $new_username = $input['data']['username']; |
| 31 | if (!$this->authUtils()->isUsernameAllowed($new_username)) { |
| 32 | throw new ValidationError(['username' => ["Der Benutzername darf nur Buchstaben, Zahlen, und die Zeichen -_. enthalten."]]); |
| 33 | } |
| 34 | $same_username_user = $user_repo->findOneBy(['username' => $new_username]); |
| 35 | $same_old_username_user = $user_repo->findOneBy(['old_username' => $new_username]); |
| 36 | $same_username_role = $role_repo->findOneBy(['username' => $new_username]); |
| 37 | $same_old_username_role = $role_repo->findOneBy(['old_username' => $new_username]); |
| 38 | $is_existing_username = (bool) ( |
| 39 | $same_username_user || $same_old_username_user |
| 40 | || $same_username_role || $same_old_username_role |
| 41 | ); |
| 42 | if ($is_existing_username) { |
| 43 | throw new ValidationError(['username' => ["Dieser Benutzername ist bereits vergeben."]]); |
| 44 | } |
| 45 | |
| 46 | $entity = new Role(); |
| 47 | $this->entityUtils()->createOlzEntity($entity, $input['meta']); |
| 48 | $entity->setOldUsername(null); |
| 49 | $entity->setPermissions(''); |
| 50 | $this->updateEntityWithData($entity, $input['data']); |
| 51 | |
| 52 | $this->entityManager()->persist($entity); |
| 53 | $this->entityManager()->flush(); |
| 54 | $this->persistUploads($entity, $input['data']); |
| 55 | |
| 56 | return [ |
| 57 | 'id' => $entity->getId() ?? 0, |
| 58 | ]; |
| 59 | } |
| 60 | } |