Lines 93.68% 89 / 95
Methods 66.66% 4 / 6
Classes 0.00% 0 / 1
Name Lines Methods CRAP
 readResponse 100.00% 32 / 32 100.00% 1 / 1 5
 writeNewRole 95.45% 21 / 22 0.00% 0 / 1 4
 [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
9class RoleAdd extends BaseController
10{
11    /**
12     * @return \Psr\Http\Message\ResponseInterface
13     */
14    #[\Override]
15    public function readResponse(
16        \Psr\Http\Message\RequestInterface $request,
17        \Psr\Http\Message\ResponseInterface $response,
18        array $args
19    ) {
20        $workstation = \App::$http->readGetResult('/workstation/', ['resolveReferences' => 1])->getEntity();
21        if (!$workstation->getUseraccount()->hasPermissions(['superuser'])) {
22            throw new UserAccountMissingRights();
23        }
24
25        $validator = $request->getAttribute('validator');
26        $confirmSuccess = $validator->getParameter('success')->isString()->getValue();
27        $permissionList = \App::$http->readGetResult('/permissions/', [])->getCollection();
28
29        $submitted = null;
30        $result = null;
31        if ($request->getMethod() === 'POST') {
32            $input = $request->getParsedBody();
33            $submitted = is_array($input) ? $input : [];
34            $result = $this->writeNewRole($submitted);
35            if ($result instanceof Role) {
36                return Render::redirect(
37                    'roleEdit',
38                    ['id' => $result->id],
39                    ['success' => 'role_added']
40                );
41            }
42        }
43
44        return Render::withHtml(
45            $response,
46            'page/roleForm.twig',
47            [
48                'title' => 'Rolle hinzufügen',
49                'menuActive' => 'roles',
50                'workstation' => $workstation,
51                'permissionList' => $permissionList,
52                'role' => $submitted,
53                'formAction' => 'add',
54                'success' => $confirmSuccess,
55                'exception' => $result,
56            ]
57        );
58    }
59
60    protected function writeNewRole(array $input): Role|array|null
61    {
62        $data = $input;
63        unset($data['id'], $data['assignedUserCount']);
64        $permissions = $data['permissions'] ?? [];
65        $data['permissions'] = is_array($permissions)
66            ? array_values(array_unique($permissions))
67            : [];
68        $entity = (new Role($data))->withCleanedUpFormData();
69
70        $roles = \App::$http->readGetResult('/roles/', [])->getCollection();
71        foreach ($roles as $existing) {
72            if ((string) $existing->name === $entity->name) {
73                return [
74                    'template' => 'exception/bo/zmsentities/exception/schemavalidation.twig',
75                    'include' => true,
76                    'data' => [
77                        'name' => [
78                            'messages' => ['Eine Rolle mit diesem Namen existiert bereits.'],
79                        ],
80                    ],
81                ];
82            }
83        }
84
85        return $this->handleEntityWrite(function () use ($entity) {
86            return \App::$http->readPostResult('/roles/', $entity)->getEntity();
87        });
88    }
89}

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    }