Lines 92.37% 109 / 118
Methods 85.71% 12 / 14
Classes 0.00% 0 / 1
Name Lines Methods CRAP
 withMaxAndAverage 100.00% 14 / 14 100.00% 1 / 1 11
 withTotalCustomers 88.46% 23 / 26 0.00% 0 / 1 9.12
 withGlobalMaxAndAverage 77.77% 21 / 27 0.00% 0 / 1 17.47
 formatTimeValue 100.00% 7 / 7 100.00% 1 / 1 3
 extractSelectedScopes 100.00% 7 / 7 100.00% 1 / 1 4
 getWorkstationScopeId 100.00% 2 / 2 100.00% 1 / 1 2
 resolveScopeIdParam 100.00% 3 / 3 100.00% 1 / 1 3
 extractDateRange 100.00% 7 / 7 100.00% 1 / 1 5
 isValidDateFormat 100.00% 4 / 4 100.00% 1 / 1 3
 getYearsForDateRange 100.00% 6 / 6 100.00% 1 / 1 2
 getYearDateBounds 100.00% 12 / 12 100.00% 1 / 1 4
 hasValues 100.00% 1 / 1 100.00% 1 / 1 2
 hasText 100.00% 1 / 1 100.00% 1 / 1 2
 hasNamedPeriod 100.00% 1 / 1 100.00% 1 / 1 3
8class ReportHelper
9{
10    public static function withMaxAndAverage(mixed $entity, string $targetKey): mixed
11    {
12        foreach ($entity->data as $date => $dateItems) {
13            $maxima = 0;
14            $total = 0;
15            $count = 0;
16            foreach ($dateItems as $hourItems) {
17                if (is_array($hourItems)) { // Check if $hourItems is an array
18                    foreach ($hourItems as $key => $value) {
19                        if (is_numeric($value) && $targetKey == $key && 0 < $value) {
20                            $total += $value;
21                            $count += 1;
22                            $maxima = ($maxima > $value) ? $maxima : $value;
23                        }
24                    }
25                }
26            }
27            $entity->data[$date]['max_' . $targetKey] = $maxima;
28            $entity->data[$date]['average_' . $targetKey] = (! $total || ! $count) ? 0 : $total / $count;
29        }
30        return $entity;
31    }
32
33    public static function withTotalCustomers(mixed $entity): mixed
34    {
35        foreach ($entity->data as $dateKey => $dateItems) {
36            if (!is_array($dateItems)) {
37                continue;
38            }
39
40            foreach ($dateItems as $hour => $hourItems) {
41                if (!is_array($hourItems)) {
42                    continue;
43                }
44
45                $countSpontan = (int) ($hourItems['waitingcount'] ?? 0);
46                $countTermin  = (int) ($hourItems['waitingcount_termin'] ?? 0);
47                $countTotal   = $countSpontan + $countTermin;
48                $countWayTermin = array_key_exists('waycount_termin', $hourItems)
49                    && $hourItems['waycount_termin'] !== null
50                    ? (int) $hourItems['waycount_termin']
51                    : $countTermin;
52                $countWayTotal = $countSpontan + $countWayTermin;
53
54                $waitSpontan = (float) ($hourItems['waitingtime'] ?? 0);
55                $waitTermin  = (float) ($hourItems['waitingtime_termin'] ?? 0);
56
57                $waySpontan  = (float) ($hourItems['waytime'] ?? 0);
58                $wayTermin   = (float) ($hourItems['waytime_termin'] ?? 0);
59
60                $entity->data[$dateKey][$hour]['waitingcount_total'] = $countTotal;
61
62                $entity->data[$dateKey][$hour]['waitingtime_total'] = ($countTotal > 0)
63                    ? (($waitSpontan * $countSpontan) + ($waitTermin * $countTermin)) / $countTotal
64                    : 0;
65
66                $entity->data[$dateKey][$hour]['waytime_total'] = ($countWayTotal > 0)
67                    ? (($waySpontan * $countSpontan) + ($wayTermin * $countWayTermin)) / $countWayTotal
68                    : 0;
69            }
70        }
71
72        return $entity;
73    }
74
75    public static function withGlobalMaxAndAverage(mixed $entity, string $targetKey): mixed
76    {
77        $maxima = 0;
78        $total  = 0;
79        $count  = 0;
80
81        foreach ($entity->data as $dateItems) {
82            if (!is_array($dateItems)) {
83                continue;
84            }
85            foreach ($dateItems as $hourItems) {
86                if (!is_array($hourItems)) {
87                    continue;
88                }
89                $value = $hourItems[$targetKey] ?? null;
90                if (is_numeric($value) && $value > 0) {
91                    $value  = (float) $value;
92                    $maxima = ($maxima > $value) ? $maxima : $value;
93                    $total += $value;
94                    $count++;
95                }
96            }
97        }
98
99        $average = ($count > 0) ? ($total / $count) : 0;
100
101        if (is_object($entity->data)) {
102            if (!isset($entity->data->max) || !is_array($entity->data->max)) {
103                $entity->data->max = [];
104            }
105            $entity->data->max['max_' . $targetKey] = $maxima;
106            $entity->data->max['average_' . $targetKey] = $average;
107        } elseif (is_array($entity->data)) {
108            if (!isset($entity->data['max']) || !is_array($entity->data['max'])) {
109                $entity->data['max'] = [];
110            }
111            $entity->data['max']['max_' . $targetKey] = $maxima;
112            $entity->data['max']['average_' . $targetKey] = $average;
113        }
114
115        return $entity;
116    }
117
118    /**
119     * Format minutes as mm:ss, rounding the full duration to the nearest second.
120     * Same rule as the Twig formatMinutesToTime macro, including its string cast
121     * via |replace, which changes some .5-second floats (e.g. 3:27 vs 3:28).
122     */
123    public static function formatTimeValue(mixed $value): mixed
124    {
125        if (!is_numeric($value)) {
126            return $value;
127        }
128        $totalMinutes = (float) str_replace(',', '.', (string) $value);
129        $totalSeconds = (int) round($totalMinutes * 60);
130        if ($totalSeconds <= 0) {
131            return '00:00';
132        }
133
134        return sprintf('%02d:%02d', intdiv($totalSeconds, 60), $totalSeconds % 60);
135    }
136
137    /**
138     * Extract selected scope IDs from request parameters
139     */
140    public function extractSelectedScopes(array $scopes): array
141    {
142        if (!empty($scopes)) {
143            $validScopes = array_filter($scopes, function ($scopeId) {
144                return is_numeric($scopeId) && $scopeId > 0;
145            });
146
147            if (!empty($validScopes)) {
148                return array_map('intval', $validScopes);
149            }
150        }
151
152        return [];
153    }
154
155    /**
156     * Workstation scope id when the user has selected a default location, otherwise null.
157     */
158    public function getWorkstationScopeId(mixed $workstation): ?int
159    {
160        $scopeId = (int) ($workstation->scope['id'] ?? 0);
161
162        return $scopeId > 0 ? $scopeId : null;
163    }
164
165    /**
166     * Scope id(s) for warehouse report queries from form selection or workstation default.
167     */
168    public function resolveScopeIdParam(array $selectedScopes, ?int $workstationScopeId): string
169    {
170        if (!empty($selectedScopes)) {
171            return implode(',', $selectedScopes);
172        }
173
174        return $workstationScopeId !== null ? (string) $workstationScopeId : '';
175    }
176
177    /**
178     * Extract and validate date range from request parameters
179     */
180    public function extractDateRange(?string $fromDate, ?string $toDate): ?array
181    {
182        if (
183            self::hasText($fromDate) && self::hasText($toDate)
184            && $this->isValidDateFormat($fromDate) && $this->isValidDateFormat($toDate)
185        ) {
186            return [
187                'from' => $fromDate,
188                'to' => $toDate
189            ];
190        }
191
192        return null;
193    }
194
195    /**
196     * Validate if the given string is a valid date format (YYYY-MM-DD)
197     */
198    public function isValidDateFormat(string $date): bool
199    {
200        if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $date)) {
201            return false;
202        }
203
204        $dateTime = DateTime::createFromFormat('Y-m-d', $date);
205        return $dateTime && $dateTime->format('Y-m-d') === $date;
206    }
207
208    /**
209     * Get all years that need to be fetched for a date range
210     */
211    public function getYearsForDateRange(string $fromDate, string $toDate): array
212    {
213        $fromYear = (int) substr($fromDate, 0, 4);
214        $toYear = (int) substr($toDate, 0, 4);
215
216        $years = [];
217        for ($year = $fromYear; $year <= $toYear; $year++) {
218            $years[] = $year;
219        }
220
221        return $years;
222    }
223    public function getYearDateBounds(int|string $year, string $fromDate, string $toDate): ?array
224    {
225        $requestedFrom = new DateTimeImmutable($fromDate);
226        $requestedTo = new DateTimeImmutable($toDate);
227        $yearStart = new DateTimeImmutable($year . '-01-01');
228        $yearEnd = new DateTimeImmutable($year . '-12-31');
229
230        $yearFrom = $requestedFrom > $yearStart ? $requestedFrom : $yearStart;
231        $yearTo = $requestedTo < $yearEnd ? $requestedTo : $yearEnd;
232
233        if ($yearFrom > $yearTo) {
234            return null;
235        }
236
237        return [
238            'from' => $yearFrom->format('Y-m-d'),
239            'to' => $yearTo->format('Y-m-d'),
240        ];
241    }
242
243    /**
244     * @psalm-assert-if-true non-empty-array $value
245     */
246    public static function hasValues(?array $value): bool
247    {
248        return $value !== null && $value !== [];
249    }
250
251    /**
252     * @psalm-assert-if-true non-empty-string $value
253     */
254    public static function hasText(?string $value): bool
255    {
256        return $value !== null && $value !== '';
257    }
258
259    /**
260     * @psalm-assert-if-true non-empty-string $period
261     */
262    public static function hasNamedPeriod(?string $period): bool
263    {
264        return $period !== null && $period !== '' && $period !== '_';
265    }
266}