Lines 93.06% 94 / 101
Methods 62.50% 5 / 8
Classes 0.00% 0 / 1
Name Lines Methods CRAP
 readResponse 97.67% 42 / 43 0.00% 0 / 1 10
 writeUpdatedEntity 100.00% 7 / 7 100.00% 1 / 1 1
 loadRoleList 100.00% 6 / 6 100.00% 1 / 1 2
 hasSuperuserOnlyRole 75.00% 3 / 4 0.00% 0 / 1 2.06
 [BO\Zmsadmin\BaseController] __invoke 100.00% 3 / 3 100.00% 1 / 1 1
 [BO\Zmsadmin\BaseController] getSchemaConstraintList 100.00% 8 / 8 100.00% 1 / 1 4
 [BO\Zmsadmin\BaseController] transformValidationErrors 61.53% 8 / 13 0.00% 0 / 1 15.69
 [BO\Zmsadmin\BaseController] handleEntityWrite 100.00% 17 / 17 100.00% 1 / 1 5
20class UseraccountEdit extends BaseController
21{
22    private const array SUPERUSER_ONLY_ROLES = [
23        'system_admin',
24        'audit_viewer',
25    ];
26
27    /**
28     *
29     * @return \Psr\Http\Message\ResponseInterface
30     */
31    #[\Override]
32    public function readResponse(
33        \Psr\Http\Message\RequestInterface $request,
34        \Psr\Http\Message\ResponseInterface $response,
35        array $args
36    ): \Psr\Http\Message\ResponseInterface {
37        $workstation = \App::$http->readGetResult('/workstation/', ['resolveReferences' => 1])->getEntity();
38        if (! $workstation->getUseraccount()->hasPermissions(['useraccount'])) {
39            throw new UserAccountMissingRights();
40        }
41
42        $userAccountName = Validator::value($args['loginname'])->isString()->getValue();
43        $confirmSuccess = $request->getAttribute('validator')->getParameter('success')->isString()->getValue();
44        $userAccount = \App::$http->readGetResult('/useraccount/' . $userAccountName . '/')->getEntity();
45        if (
46            ! $workstation->getUseraccount()->isSuperUser()
47            && $this->hasSuperuserOnlyRole($userAccount)
48        ) {
49            throw new UserAccountAccessRightsFailed();
50        }
51        $ownerList = \App::$http->readGetResult('/owner/', ['resolveReferences' => 2])->getCollection();
52
53        if ($request->getMethod() === 'POST') {
54            $input = $request->getParsedBody();
55            $result = $this->writeUpdatedEntity($input, $userAccountName);
56            if ($result instanceof Useraccount) {
57                return Render::redirect(
58                    'useraccountEdit',
59                    array('loginname' => $result->id),
60                    array('success' => 'useraccount_saved')
61                );
62            }
63        }
64
65        $config = \App::$http->readGetResult('/config/', [], \App::CONFIG_SECURE_TOKEN)->getEntity();
66        $allowedProviderList = explode(',', $config->getPreference('oidc', 'provider') ?? '');
67
68        $roleList = $this->loadRoleList();
69
70        $userAccountRoles = (isset($userAccount->roles) && is_array($userAccount->roles))
71            ? $userAccount->roles
72            : [];
73
74
75        return Render::withHtml(
76            $response,
77            'page/useraccountEdit.twig',
78            [
79                'debug' => \App::DEBUG,
80                'userAccount' => $userAccount,
81                'success' => $confirmSuccess,
82                'ownerList' => $ownerList ? $ownerList->toDepartmentListByOrganisationName() : [],
83                'workstation' => $workstation,
84                'title' => 'Nutzer: Einrichtung und Administration','menuActive' => 'useraccount',
85                'exception' => (isset($result)) ? $result : null,
86                'metadata' => $this->getSchemaConstraintList(Loader::asArray(Useraccount::$schema)),
87                'oidcProviderList' => array_filter($allowedProviderList),
88                'isFromOidc' => in_array($userAccount->getOidcProviderFromName(), $allowedProviderList),
89                'roleList' => $roleList,
90                'userAccountRoles' => $userAccountRoles,
91            ]
92        );
93    }
94
95    protected function writeUpdatedEntity($input, $userAccountName)
96    {
97        $entity = (new Useraccount($input))->withCleanedUpFormData();
98        // TODO: Remove the password fields when password authentication is removed in the future
99        $entity->setPassword($input);
100        return $this->handleEntityWrite(function () use ($entity, $userAccountName) {
101            return \App::$http
102                ->readPostResult('/useraccount/' . $userAccountName . '/', $entity)
103                ->getEntity();
104        });
105    }
106
107    private function loadRoleList(): RoleList
108    {
109        $roleList = new RoleList();
110
111        $roleResult = \App::$http->readGetResult('/roles/', []);
112        $loaded = $roleResult->getCollection();
113        if ($loaded !== null) {
114            $roleList = $loaded;
115        }
116
117        return $roleList;
118    }
119
120    protected function hasSuperuserOnlyRole(Useraccount $userAccount): bool
121    {
122        $roles = $userAccount->roles ?? [];
123
124        if (! is_array($roles)) {
125            return false;
126        }
127
128        return (bool) array_intersect($roles, self::SUPERUSER_ONLY_ROLES);
129    }
130}

Inherited from BO\Zmsadmin\BaseController

21    public function __invoke(RequestInterface $request, ResponseInterface $response, array $args)
22    {
23        $request = $this->initRequest($request);
24        $noCacheResponse = \BO\Slim\Render::withLastModified($response, time(), '0');
25        return $this->readResponse($request, $noCacheResponse, $args);
26    }
41    public function getSchemaConstraintList($schema): array
42    {
43        $list = [];
44        $locale = \App::$language->getLocale();
45        foreach ($schema->properties as $key => $property) {
46            if (isset($property['x-locale'])) {
47                $constraints = $property['x-locale'][$locale];
48                if ($constraints) {
49                    $list[$key]['description'] = $constraints['messages'];
50                }
51            }
52        }
53        return $list;
54    }
65    protected function transformValidationErrors($errorData)
66    {
67        if (!is_array($errorData) && !($errorData instanceof \Traversable)) {
68            return [];
69        }
70        $transformed = [];
71        foreach ($errorData as $pointer => $item) {
72            // Extract field name from JSON pointer (e.g., "/id" -> "id", "/contact/email" -> "contact/email")
73            // If the key doesn't start with "/", it's already a field name, so use it as-is
74            $fieldName = (strpos($pointer, '/') === 0) ? ltrim($pointer, '/') : $pointer;
75            // Handle root level errors
76            if ($fieldName === '' || $fieldName === null) {
77                $fieldName = '_root';
78            }
79            // Ensure the item structure is correct (has 'messages' array)
80            if (is_array($item) && isset($item['messages'])) {
81                $transformed[$fieldName] = $item;
82            } elseif (is_array($item)) {
83                // If item is an array but doesn't have 'messages', wrap it
84                $transformed[$fieldName] = $item;
85            } else {
86                $transformed[$fieldName] = $item;
87            }
88        }
89        return $transformed;
90    }
99    protected function handleEntityWrite(callable $httpCall)
100    {
101        try {
102            return $httpCall();
103        } catch (\BO\Zmsclient\Exception $exception) {
104            if ('BO\Zmsentities\Exception\SchemaValidation' == $exception->template) {
105                return [
106                    'template' => 'exception/bo/zmsentities/exception/schemavalidation.twig',
107                    'include' => true,
108                    'data' => $this->transformValidationErrors($exception->data)
109                ];
110            }
111
112            $template = TwigExceptionHandler::getExceptionTemplate($exception);
113            if (
114                '' != $exception->template
115                && \App::$slim->getContainer()->get('view')->getLoader()->exists($template)
116            ) {
117                return [
118                    'template' => $template,
119                    'include' => true,
120                    'data' => $this->transformValidationErrors($exception->data)
121                ];
122            }
123
124            throw $exception;
125        }
126    }