Lines 88.38% 137 / 155
Methods 55.55% 5 / 9
Classes 0.00% 0 / 1
Name Lines Methods CRAP
 readResponse 92.85% 26 / 28 0.00% 0 / 1 4.01
 getProcess 100.00% 4 / 4 100.00% 1 / 1 1
 getValidatedForm 85.29% 58 / 68 0.00% 0 / 1 4.05
 writeReservedProcess 88.88% 8 / 9 0.00% 0 / 1 4.02
 writeConfirmedProcess 100.00% 5 / 5 100.00% 1 / 1 2
 [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 ProcessReserve extends BaseController
21{
22    /**
23     * @SuppressWarnings(Param)
24     * @return \Psr\Http\Message\ResponseInterface
25     */
26    #[\Override]
27    public function readResponse(
28        \Psr\Http\Message\RequestInterface $request,
29        \Psr\Http\Message\ResponseInterface $response,
30        array $args
31    ): \Psr\Http\Message\ResponseInterface {
32        $workstation = \App::$http->readGetResult('/workstation/', ['resolveReferences' => 2])->getEntity();
33        $input = $request->getParams();
34        $scope = Helper\AppointmentFormHelper::readSelectedScope($request, $workstation);
35        $process = $this->getProcess($input, $scope);
36        $validatedForm = static::getValidatedForm($request->getAttribute('validator'), $process);
37        if ($validatedForm['failed']) {
38            return Render::withJson(
39                $response,
40                $validatedForm
41            );
42        }
43
44        $process = static::writeReservedProcess($input, $process);
45        $process = static::writeConfirmedProcess($input, $process);
46        $appointment = $process->getFirstAppointment();
47        $conflictList = ($process->isWithAppointment()) ?
48            ProcessSave::getConflictList($scope->getId(), $appointment) :
49            null;
50        $queryParams = ('confirmed' == $process->getStatus()) ?
51            [
52                'selectedprocess' => $process,
53                'success' => 'process_reserved',
54                'conflictlist' => $conflictList
55            ] :
56            [];
57
58        return Render::withHtml(
59            $response,
60            'element/helper/messageHandler.twig',
61            $queryParams
62        );
63    }
64
65    protected function getProcess($input, $scope)
66    {
67        $process = new Process();
68        $selectedTime = str_replace('-', ':', $input['selectedtime']);
69        $dateTime = \DateTime::createFromFormat('Y-m-d H:i', $input['selecteddate'] . ' ' . $selectedTime);
70
71        return $process->withUpdatedData($input, $dateTime, $scope);
72    }
73
74    /**
75     * @return (bool|mixed)[]
76     *
77     */
78    public static function getValidatedForm($validator, Process $process): array
79    {
80        $processValidator = new ProcessValidator($process);
81        $delegatedProcess = $processValidator->getDelegatedProcess();
82        $processValidator
83            ->validateName(
84                $validator->getParameter('familyName'),
85                $delegatedProcess->setter('clients', 0, 'familyName')
86            )
87            ->validateRequests(
88                $validator->getParameter('requests'),
89                function () use ($process, $delegatedProcess) {
90                    $arrayKeys = array_keys(json_decode(json_encode($process->requests), true));
91                    foreach ($arrayKeys as $key) {
92                        $delegatedProcess->setter('requests', $key, 'id');
93                        $delegatedProcess->setter('requests', $key, 'source');
94                    }
95                }
96            )
97            ->validateMail(
98                $validator->getParameter('email'),
99                $delegatedProcess->setter('clients', 0, 'email'),
100                new Condition(
101                    $validator->getParameter('sendMailConfirmation')->isNumber()->isNotEqualTo(1),
102                    $validator->getParameter('surveyAccepted')->isString()->isDevoidOf([1])
103                )
104            )
105            ->validateTelephone(
106                $validator->getParameter('telephone'),
107                $delegatedProcess->setter('clients', 0, 'telephone'),
108                new Condition(
109                    $validator->getParameter('sendConfirmation')->isNumber()->isNotEqualTo(1),
110                    $validator->getParameter('sendReminder')->isNumber()->isNotEqualTo(1)
111                )
112            )
113            ->validateSurvey(
114                $validator->getParameter('surveyAccepted'),
115                $delegatedProcess->setter('clients', 0, 'surveyAccepted')
116            )
117            ->validateText(
118                $validator->getParameter('amendment'),
119                $delegatedProcess->setter('amendment')
120            )
121            ->validateReminderTimestamp(
122                $validator->getParameter('headsUpTime'),
123                $delegatedProcess->setter('reminderTimestamp'),
124                new Condition(
125                    $validator->getParameter('sendReminder')->isNumber()->isNotEqualTo(1)
126                )
127            )
128        ;
129
130        $scope = $process->getCurrentScope();
131        if ((int) $scope->getCustomTextfieldActivated()) {
132            $processValidator->validateCustomTextfield(
133                $validator->getParameter('customTextfield'),
134                $delegatedProcess->setter('customTextfield'),
135                (bool) (int) $scope->getCustomTextfieldRequired()
136            );
137        }
138
139        if ((int) $scope->getCustomTextfield2Activated()) {
140            $processValidator->validateCustomTextfield(
141                $validator->getParameter('customTextfield2'),
142                $delegatedProcess->setter('customTextfield2'),
143                (bool) (int) $scope->getCustomTextfield2Required()
144            );
145        }
146
147        $processValidator->getCollection()->addValid(
148            $validator->getParameter('sendConfirmation')->isNumber(),
149            $validator->getParameter('sendReminder')->isNumber()
150        );
151
152        $form = $processValidator->getCollection()->getStatus(null, true);
153        $form['failed'] = $processValidator->getCollection()->hasFailed();
154        return $form;
155    }
156
157    public static function writeReservedProcess($input, $process)
158    {
159        $response = \App::$http
160            ->readPostResult('/process/status/reserved/', $process, [
161                'slotType' => 'intern',
162                'clientkey' => \App::CLIENTKEY,
163                'slotsRequired' => (isset($input['slotCount']) && 1 < $input['slotCount']) ? $input['slotCount'] : 0
164            ]);
165        if (!$response) {
166            throw new \RuntimeException('Failed to reserve process - no response from API');
167        }
168        return $response->getEntity();
169    }
170
171    public static function writeConfirmedProcess($input, $process)
172    {
173        $confirmedProcess = \App::$http->readPostResult('/process/status/confirmed/', $process)->getEntity();
174        if ('confirmed' == $confirmedProcess->getStatus()) {
175            $process = $confirmedProcess;
176            Helper\AppointmentFormHelper::updateMail($input, $process);
177        }
178        return $process;
179    }
180}

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    }