Lines 96.89% 156 / 161
Functions and Methods 69.23% 9 / 13
Classes and Traits 0.00% 0 / 1
Name Lines Functions and Methods CRAP Classes and Traits
Search 96.89% 156 / 161 69.23% 9 / 13 58 0.00% 0 / 1
 readResponse 100.00% 32 / 32 100.00% 1 / 1 2
 readSearchParameters 100.00% 31 / 31 100.00% 1 / 1 12
 readProcessSearchResults 100.00% 12 / 12 100.00% 1 / 1 5
 shouldRunProcessSearch 100.00% 6 / 6 100.00% 1 / 1 4
 hasStructuredSearchFilters 100.00% 3 / 3 100.00% 1 / 1 3
 shouldRunLogSearch 100.00% 6 / 6 100.00% 1 / 1 4
 hasLogSearchFilters 100.00% 5 / 5 100.00% 1 / 1 5
 buildProcessSearchParameters 88.23% 15 / 17 0.00% 0 / 1 6.06
 readLogSearchResults 96.00% 24 / 25 0.00% 0 / 1 4
 filterProcessListForUserRights 85.71% 6 / 7 0.00% 0 / 1 4.05
 filterLogListForUserRights 88.88% 8 / 9 0.00% 0 / 1 7.07
 readStringParameter 100.00% 4 / 4 100.00% 1 / 1 1
 readNumberParameter 100.00% 4 / 4 100.00% 1 / 1 1
1<?php
2
3/**
4 * @package Zmsadmin
5 * @copyright BerlinOnline Stadtportal GmbH & Co. KG
6 **/
7
8namespace BO\Zmsadmin;
9
10use BO\Slim\Render;
11use BO\Zmsentities\Collection\LogList;
12use BO\Zmsentities\Log as LogEntity;
13use BO\Zmsentities\Collection\ProcessList;
14
15class Search extends BaseController
16{
17    private const int DEFAULT_RESULTS_PER_PAGE = 100;
18
19    private const int MAX_RESULTS_PER_PAGE = 1000;
20
21    /**
22     * @SuppressWarnings(Param)
23     * @return \Psr\Http\Message\ResponseInterface
24     */
25    #[\Override]
26    public function readResponse(
27        \Psr\Http\Message\RequestInterface $request,
28        \Psr\Http\Message\ResponseInterface $response,
29        array $args
30    ): \Psr\Http\Message\ResponseInterface {
31        $workstation = \App::$http->readGetResult('/workstation/', ['resolveReferences' => 2])->getEntity();
32        $parameters = $this->readSearchParameters($request->getAttribute('validator'));
33        if ($workstation->getUseraccount()->hasRole('audit_viewer')) {
34            $parameters['hideNavigation'] = 1;
35        }
36        $scopeIds = $workstation->getUseraccount()->getDepartmentList()->getUniqueScopeList()->getIds();
37
38        [$processList, $processSearchTotal] = $this->readProcessSearchResults(
39            $workstation,
40            $parameters,
41            $scopeIds
42        );
43        [$logList, $logSearchTotal] = $this->readLogSearchResults($workstation, $parameters, $scopeIds);
44
45        return Render::withHtml(
46            $response,
47            'page/search.twig',
48            array(
49                'title' => 'Suche',
50                'hideNavigation' => (bool) $parameters['hideNavigation'],
51                'service' => $parameters['service'],
52                'provider' => $parameters['provider'],
53                'userAction' => $parameters['userAction'],
54                'date' => $parameters['date'],
55                'page' => $parameters['page'],
56                'perPage' => $parameters['perPage'],
57                'workstation' => $workstation,
58                'processList' => $processList,
59                'logList' => $logList ?? [],
60                'searchProcessQuery' => $parameters['queryString'],
61                'processSearchTotal' => $processSearchTotal,
62                'logSearchTotal' => $logSearchTotal,
63                'menuActive' => 'search'
64            )
65        );
66    }
67
68    private function readSearchParameters(\BO\Mellon\Validator $validator): array
69    {
70        $queryString = $validator->getParameter('query')
71            ->isString('', false)
72            ->getValue();
73        if ($queryString !== null && $queryString !== '') {
74            $queryString = html_entity_decode((string) $queryString, ENT_QUOTES | ENT_HTML5, 'UTF-8');
75        } else {
76            $queryString = $queryString ?? '';
77        }
78
79        $service = $this->readStringParameter($validator, 'service');
80        $provider = $this->readStringParameter($validator, 'provider');
81        $date = $validator->getParameter('date')->isString()->setDefault(null)->getValue();
82        $page = $this->readNumberParameter($validator, 'page', 1);
83        $userAction = $this->readNumberParameter($validator, 'user', 0);
84        $requestedResultsPerPage = $this->readNumberParameter($validator, 'perPage', self::DEFAULT_RESULTS_PER_PAGE);
85        $resultsPerPage = max(1, min($requestedResultsPerPage, self::MAX_RESULTS_PER_PAGE));
86        $hideNavigation = $this->readNumberParameter($validator, 'hideNavigation', 0);
87
88        return [
89            'queryString' => $queryString,
90            'page' => $page,
91            'service' => $service ? trim($service) : null,
92            'provider' => $provider ? trim($provider) : null,
93            'date' => $date !== null && trim($date) !== '' ? trim($date) : null,
94            'userAction' => $userAction,
95            'perPage' => $resultsPerPage,
96            'hideNavigation' => $hideNavigation,
97            'isSearchRequested' => (
98                trim($queryString) !== ''
99                || trim($service) !== ''
100                || trim($provider) !== ''
101                || ($date !== null && trim($date) !== '')
102                || $userAction !== 0
103            ),
104        ];
105    }
106
107    private function readProcessSearchResults(\BO\Zmsentities\Workstation $workstation, array $parameters, array $scopeIds): array
108    {
109        if (!$this->shouldRunProcessSearch($workstation, $parameters)) {
110            return [new ProcessList(), 0];
111        }
112
113        $searchParameters = $this->buildProcessSearchParameters($workstation, $parameters, $scopeIds);
114        $searchResult = \App::$http->readGetResult('/process/search/', $searchParameters);
115        $processList = $searchResult->getCollection() ?? new ProcessList();
116        $searchMeta = $searchResult->getMeta();
117        $processSearchTotal = isset($searchMeta->totalCount)
118            ? (int) $searchMeta->totalCount
119            : $processList->count();
120
121        if (!empty($processList) && !$workstation->getUseraccount()->isSuperUser()) {
122            $processList = $this->filterProcessListForUserRights($processList, $scopeIds);
123        }
124
125        return [$processList, $processSearchTotal];
126    }
127
128    private function shouldRunProcessSearch(\BO\Zmsentities\Workstation $workstation, array $parameters): bool
129    {
130        if (!$parameters['isSearchRequested']) {
131            return false;
132        }
133
134        if (!$workstation->getUseraccount()->hasPermissions(['customersearch'])) {
135            return false;
136        }
137
138        $queryString = trim((string) $parameters['queryString']);
139
140        return $queryString !== '' || $this->hasStructuredSearchFilters($parameters);
141    }
142
143    private function hasStructuredSearchFilters(array $parameters): bool
144    {
145        return $parameters['service'] !== null
146            || $parameters['provider'] !== null
147            || $parameters['date'] !== null;
148    }
149
150    private function shouldRunLogSearch(\BO\Zmsentities\Workstation $workstation, array $parameters): bool
151    {
152        if (!$workstation->getUseraccount()->hasPermissions(['logs'])) {
153            return false;
154        }
155
156        if ($this->hasLogSearchFilters($parameters)) {
157            return true;
158        }
159
160        return $workstation->getUseraccount()->isSuperUser()
161            && !$parameters['isSearchRequested'];
162    }
163
164    private function hasLogSearchFilters(array $parameters): bool
165    {
166        return trim((string) $parameters['queryString']) !== ''
167            || $parameters['service'] !== null
168            || $parameters['provider'] !== null
169            || $parameters['date'] !== null
170            || $parameters['userAction'] !== 0;
171    }
172
173    private function buildProcessSearchParameters(\BO\Zmsentities\Workstation $workstation, array $parameters, array $scopeIds): array
174    {
175        $queryString = trim((string) $parameters['queryString']);
176        $searchParameters = [
177            'resolveReferences' => 1,
178            'page' => $parameters['page'],
179            'limit' => $parameters['perPage'],
180        ];
181        if ($queryString !== '') {
182            $searchParameters['query'] = $queryString;
183        }
184        if ($parameters['service'] !== null) {
185            $searchParameters['service'] = $parameters['service'];
186        }
187        if ($parameters['provider'] !== null) {
188            $searchParameters['provider'] = $parameters['provider'];
189        }
190        if ($parameters['date'] !== null) {
191            $searchParameters['date'] = $parameters['date'];
192        }
193        if (!$workstation->getUseraccount()->isSuperUser()) {
194            $searchParameters['scopeIds'] = implode(',', $scopeIds);
195        }
196
197        return $searchParameters;
198    }
199
200    private function readLogSearchResults(\BO\Zmsentities\Workstation $workstation, array $parameters, array $scopeIds): array
201    {
202        if (!$this->shouldRunLogSearch($workstation, $parameters)) {
203            return [null, 0];
204        }
205
206        $logParameters = [
207            'searchQuery' => urlencode((string) $parameters['queryString']),
208            'page' => $parameters['page'],
209            'perPage' => $parameters['perPage'],
210            'service' => $parameters['service'],
211            'provider' => $parameters['provider'],
212            'userAction' => $parameters['userAction'],
213            'date' => $parameters['date'],
214        ];
215        if (!$workstation->getUseraccount()->isSuperUser()) {
216            $logParameters['scopeIds'] = implode(',', $scopeIds);
217        }
218
219        $logResult = \App::$http->readGetResult("/log/process/", $logParameters);
220        $logList = $logResult->getCollection();
221        $logMeta = $logResult->getMeta();
222
223        $filteredLogList = $this->filterLogListForUserRights(
224            $logList,
225            $scopeIds,
226            $workstation->getUseraccount()->isSuperUser()
227        );
228        $logSearchTotal = isset($logMeta->totalCount)
229            ? (int) $logMeta->totalCount
230            : $filteredLogList->count();
231
232        return [$filteredLogList, $logSearchTotal];
233    }
234
235    private function filterProcessListForUserRights(?ProcessList $processList, array $scopeIds): ProcessList
236    {
237        if (empty($processList)) {
238            return new ProcessList();
239        }
240
241        $list = new ProcessList();
242
243        foreach ($processList as $process) {
244            if (in_array($process->scope->id, $scopeIds)) {
245                $list->addEntity(clone $process);
246            }
247        }
248
249        return $list;
250    }
251
252    private function filterLogListForUserRights(
253        ?LogList $logList,
254        array $scopeIds,
255        bool $bypassScopeFilter = false
256    ): LogList {
257        if (!isset($logList) || !$logList) {
258            $logList = new LogList();
259        }
260
261        $list = new LogList();
262
263        foreach ($logList as $log) {
264            $log->display = LogEntity::formatDisplayFields($log->getArrayCopy());
265
266            if (
267                $bypassScopeFilter
268                || (isset($log->scope_id) && in_array($log->scope_id, $scopeIds))
269            ) {
270                $list->addEntity(clone $log);
271            }
272        }
273
274        return $list;
275    }
276
277    private function readStringParameter(\BO\Mellon\Validator $validator, string $name, string $default = ''): string
278    {
279        return $validator->getParameter($name)
280            ->isString()
281            ->setDefault($default)
282            ->getValue() ?? $default;
283    }
284
285    private function readNumberParameter(\BO\Mellon\Validator $validator, string $name, int $default): int
286    {
287        return (int) $validator->getParameter($name)
288            ->isNumber()
289            ->setDefault($default)
290            ->getValue();
291    }
292}