Lines 97.23% 281 / 289
Methods 84.61% 22 / 26
Classes 0.00% 0 / 1
Name Lines Methods CRAP
 readEntity 100.00% 44 / 44 100.00% 1 / 1 3
 readSubjectList 100.00% 11 / 11 100.00% 1 / 1 2
 readPeriodList 100.00% 22 / 22 100.00% 1 / 1 4
 readByDateTime 100.00% 19 / 19 100.00% 1 / 1 2
 writeWaitingTimeCalculated 95.23% 20 / 21 0.00% 0 / 1 3
 writeWaitingTime 96.29% 26 / 27 0.00% 0 / 1 4
 updateWaitingStatistics 96.42% 27 / 28 0.00% 0 / 1 2
 [BO\Zmsbackend\Base] __construct 100.00% 2 / 2 100.00% 1 / 1 1
 [BO\Zmsbackend\Base] init 100.00% 2 / 2 100.00% 1 / 1 1
 [BO\Zmsbackend\Base] getWriter 100.00% 4 / 4 100.00% 1 / 1 2
 [BO\Zmsbackend\Base] getReader 100.00% 5 / 5 100.00% 1 / 1 3
 [BO\Zmsbackend\Base] fetchPreparedStatement 100.00% 9 / 9 100.00% 1 / 1 3
 [BO\Zmsbackend\Base] startExecute 100.00% 5 / 5 100.00% 1 / 1 1
 [BO\Zmsbackend\Base] pdoExceptionHandler 100.00% 13 / 13 100.00% 1 / 1 4
 [BO\Zmsbackend\Base] fetchStatement 100.00% 3 / 3 100.00% 1 / 1 1
 [BO\Zmsbackend\Base] fetchOne 100.00% 7 / 7 100.00% 1 / 1 2
 [BO\Zmsbackend\Base] fetchRow 100.00% 7 / 7 100.00% 1 / 1 1
 [BO\Zmsbackend\Base] fetchValue 100.00% 7 / 7 100.00% 1 / 1 1
 [BO\Zmsbackend\Base] fetchAll 100.00% 7 / 7 100.00% 1 / 1 1
 [BO\Zmsbackend\Base] fetchHandle 100.00% 5 / 5 100.00% 1 / 1 1
 [BO\Zmsbackend\Base] fetchList 100.00% 8 / 8 100.00% 1 / 1 2
 [BO\Zmsbackend\Base] writeItem 100.00% 7 / 7 100.00% 1 / 1 1
 [BO\Zmsbackend\Base] deleteItem 100.00% 1 / 1 100.00% 1 / 1 1
 [BO\Zmsbackend\Base] perform 100.00% 7 / 7 100.00% 1 / 1 1
 [BO\Zmsbackend\Base] fetchAffected 100.00% 8 / 8 100.00% 1 / 1 1
 [BO\Zmsbackend\Base] readResolvedReferences n/a 0 / 0 n/a 0 / 0 1
 [BO\Zmsbackend\Base] hashStringValue 50.00% 5 / 10 0.00% 0 / 1 8.12
7class ExchangeWaitingscope extends \BO\Zmsbackend\Base implements \BO\Zmsbackend\Interfaces\ExchangeSubject
8{
9    /**
10     * @return Exchange
11     */
12    #[\Override]
13    public function readEntity(
14        string|int $subjectid,
15        \DateTimeInterface $datestart,
16        \DateTimeInterface $dateend,
17        string $period = 'day'
18    ) {
19        $scope = (new \BO\Zmsbackend\Scope\Service\Scope())->readEntity($subjectid);
20        $entity = new Exchange();
21        $entity['title'] = "Wartestatistik " . $scope->contact->name . " " . $scope->shortName;
22        $entity->setPeriod($datestart, $dateend, $period);
23        $entity->addDictionaryEntry('subjectid', 'string', 'ID of a scope', 'scope.id');
24        $entity->addDictionaryEntry('date', 'string', 'date of report entry');
25        $entity->addDictionaryEntry('hour', 'string', 'hour of report entry');
26        $entity->addDictionaryEntry('waitingcount', 'number', 'amount of waiting spontaneous clients');
27        $entity->addDictionaryEntry('waitingtime', 'number', 'real waitingtime for spontaneous clients');
28        $entity->addDictionaryEntry('waytime', 'number', 'real waytime for spontaneous clients');
29        $entity->addDictionaryEntry('waitingcalculated', 'number', 'calculated waitingtime for spontaneous clients');
30        $entity->addDictionaryEntry('waitingcount_termin', 'number', 'amount of waiting clients with termin');
31        $entity->addDictionaryEntry('waitingtime_termin', 'number', 'real waitingtime with termin');
32        $entity->addDictionaryEntry('waytime_termin', 'number', 'real waytime with appointment');
33        $entity->addDictionaryEntry('waitingcalculated_termin', 'number', 'calculated waitingtime with termin');
34        $entity->addDictionaryEntry('waycount_termin', 'number', 'clients included in appointment way time');
35        $subjectIdList = explode(',', $subjectid);
36
37        $raw = $this
38            ->getReader()
39            ->fetchAll(
40                constant("\BO\Zmsbackend\Exchange\Repository\ExchangeWaitingscope::QUERY_READ_" . strtoupper($period)),
41                [
42                    'scopeid' => $subjectIdList,
43                    'datestart' => $datestart->format('Y-m-d'),
44                    'dateend' => $dateend->format('Y-m-d')
45                ]
46            );
47
48        foreach ($raw as $entry) {
49            foreach (range(7, 19) as $hour) {
50                $entity->addDataSet([
51                    $entry['standortid'],
52                    $entry['datum'],
53                    $hour,
54                    $entry[sprintf('hour_%02d_waiting_count_spontaneous', $hour)],
55                    $entry[sprintf('hour_%02d_waiting_time_spontaneous', $hour)],
56                    $entry[sprintf('hour_%02d_way_time_spontaneous', $hour)],
57                    $entry[sprintf('hour_%02d_estimated_waiting_time_spontaneous', $hour)],
58                    $entry[sprintf('hour_%02d_waiting_count_appointment', $hour)],
59                    $entry[sprintf('hour_%02d_waiting_time_appointment', $hour)],
60                    $entry[sprintf('hour_%02d_way_time_appointment', $hour)],
61                    $entry[sprintf('hour_%02d_estimated_waiting_time_appointment', $hour)],
62                    $entry[sprintf('hour_%02d_way_count_appointment', $hour)],
63                ]);
64            }
65        }
66
67        return $entity;
68    }
69
70    /**
71     * @return Exchange
72     */
73    #[\Override]
74    public function readSubjectList()
75    {
76        $raw = $this->getReader()->fetchAll(\BO\Zmsbackend\Exchange\Repository\ExchangeWaitingscope::QUERY_SUBJECTS, []);
77        $entity = new Exchange();
78        $entity['title'] = "Wartestatistik";
79        $entity->setPeriod(new \DateTimeImmutable(), new \DateTimeImmutable());
80        $entity->addDictionaryEntry('subject', 'string', 'Standort ID', 'scope.id');
81        $entity->addDictionaryEntry('periodstart', 'string', 'Datum von');
82        $entity->addDictionaryEntry('periodend', 'string', 'Datum bis');
83        $entity->addDictionaryEntry('description', 'string', 'Standort Beschreibung');
84        foreach ($raw as $entry) {
85            $entity->addDataSet(array_values($entry));
86        }
87        return $entity;
88    }
89
90    /**
91     * @return Exchange
92     */
93    #[\Override]
94    public function readPeriodList(string|int $subjectid, string $period = 'day')
95    {
96        $scope = (new \BO\Zmsbackend\Scope\Service\Scope())->readEntity($subjectid);
97        $entity = new Exchange();
98        $entity['title'] = "Wartestatistik " . $scope->contact->name . " " . $scope->shortName;
99        $entity->setPeriod(new \DateTimeImmutable(), new \DateTimeImmutable(), $period);
100        $entity->addDictionaryEntry('period');
101
102        $montsList = $this->getReader()->fetchAll(
103            constant("\BO\Zmsbackend\Exchange\Repository\ExchangeWaitingscope::QUERY_PERIODLIST_MONTH"),
104            [
105                'scopeid' => $subjectid,
106            ]
107        );
108        $raw = [];
109        foreach ($montsList as $month) {
110            $date = new \DateTimeImmutable($month['date']);
111            $raw[$date->format('Y')][] = $month['date'];
112            rsort($raw[$date->format('Y')]);
113        }
114        krsort($raw);
115
116        foreach ($raw as $year => $months) {
117            $entity->addDataSet([$year]);
118            foreach ($months as $month) {
119                $entity->addDataSet([$month]);
120            }
121        }
122        return $entity;
123    }
124
125    /**
126     * fetch entry by scope and date or create an entry, if it does not exists
127     * the returned entry is save for updating
128     */
129    public function readByDateTime(
130        \BO\Zmsentities\Scope $scope,
131        \DateTimeInterface $date,
132        bool $isWithAppointment = false
133    ) {
134        $sql = \BO\Zmsbackend\Exchange\Repository\ExchangeWaitingscope::getQuerySelectByDateTime($date, $isWithAppointment);
135        $existingEntry = $this->getReader()->fetchOne(
136            $sql,
137            [
138                'scopeid' => $scope->id,
139                'date' => $date->format('Y-m-d'),
140                'hour' => $date->format('H')
141            ]
142        );
143        if (!$existingEntry) {
144            $this->perform(
145                \BO\Zmsbackend\Exchange\Repository\ExchangeWaitingscope::QUERY_CREATE,
146                [
147                    'scopeid' => $scope->id,
148                    'date' => $date->format('Y-m-d'),
149                ]
150            );
151            $existingEntry = $this->readByDateTime($scope, $date, $isWithAppointment);
152        }
153        return $existingEntry;
154    }
155
156    /**
157     * Write calculated waiting time and count of queued processes into statistic
158     */
159    public function writeWaitingTimeCalculated(
160        \BO\Zmsentities\Scope $scope,
161        \DateTimeInterface $now,
162        bool $isWithAppointment = false
163    ): static {
164        if ($now > (new \DateTime())) {
165            return $this;
166        }
167
168        $queueList = (new \BO\Zmsbackend\Scope\Service\Scope())->readQueueListWithWaitingTime($scope, $now);
169
170        $existingEntry = $this->readByDateTime($scope, $now, $isWithAppointment);
171        $queueEntry = $queueList->getFakeOrLastWaitingnumber();
172        $waitingCalculated = $existingEntry['waitingcalculated'] > $queueEntry['waitingTimeEstimate'] ?
173            $existingEntry['waitingcalculated']
174            : $queueEntry['waitingTimeEstimate'];
175
176        $this->perform(
177            \BO\Zmsbackend\Exchange\Repository\ExchangeWaitingscope::getQueryUpdateByDateTime($now, $isWithAppointment),
178            [
179                'waitingcalculated' => $waitingCalculated,
180                'waitingcount' => $existingEntry['waitingcount'],
181                'waitingtime' => $existingEntry['waitingtime'],
182                'waytime' => $existingEntry['waytime'],
183                'scopeid' => $scope->id,
184                'date' => $now->format('Y-m-d'),
185                'hour' => $now->format('H')
186            ]
187        );
188        return $this;
189    }
190
191    /**
192     * Write real waiting time into statistics
193     */
194    public function writeWaitingTime(
195        \BO\Zmsentities\Process $process,
196        \DateTimeInterface $now
197    ): static {
198        if ($now > (new \DateTime())) {
199            return $this;
200        }
201
202        $waitingTime = $process->getWaitedMinutes($now);
203        $wayTime = $process->getWayMinutes($now);
204        $existingEntry = $this->readByDateTime(
205            $process->scope,
206            $process->getArrivalTime($now),
207            $process->isWithAppointment()
208        );
209        $waitingTime = $existingEntry['waitingtime'] > $waitingTime ? $existingEntry['waitingtime'] : $waitingTime;
210        $wayTime = $existingEntry['waytime'] > $wayTime ? $existingEntry['waytime'] : $wayTime;
211        $this->perform(
212            \BO\Zmsbackend\Exchange\Repository\ExchangeWaitingscope::getQueryUpdateByDateTime(
213                $process->getArrivalTime($now),
214                $process->isWithAppointment()
215            ),
216            [
217                'waitingcalculated' => $existingEntry['waitingcalculated'],
218                'waitingcount' => $existingEntry['waitingcount'],
219                'waitingtime' => $waitingTime,
220                'waytime' => $wayTime,
221                'scopeid' => $process->scope->id,
222                'date' => $now->format('Y-m-d'),
223                'hour' => $now->format('H')
224            ]
225        );
226        return $this;
227    }
228
229    public function updateWaitingStatistics(
230        \BO\Zmsentities\Process $process,
231        \DateTimeInterface $now
232    ): static {
233        if ($now > (new \DateTime())) {
234            return $this;
235        }
236
237        $newWaitingTime = $process->getWaitedMinutes($now);
238        $newWayTime = $process->getWayMinutes($now);
239
240        $existingEntry = $this->readByDateTime(
241            $process->scope,
242            $process->getArrivalTime($now),
243            $process->isWithAppointment()
244        );
245
246        $waitingCount = $existingEntry['waitingcount'] + 1;
247
248        $averageWaitingTime = ($existingEntry['waitingtime'] * $existingEntry['waitingcount'] + $newWaitingTime) / $waitingCount;
249        $averageWayTime = ($existingEntry['waytime'] * $existingEntry['waitingcount'] + $newWayTime) / $waitingCount;
250
251        $this->perform(
252            \BO\Zmsbackend\Exchange\Repository\ExchangeWaitingscope::getQueryUpdateByDateTime(
253                $process->getArrivalTime($now),
254                $process->isWithAppointment()
255            ),
256            [
257                'waitingcalculated' => $existingEntry['waitingcalculated'],
258                'waitingcount' => $waitingCount,
259                'waitingtime' => $averageWaitingTime,
260                'waytime' => $averageWayTime,
261                'scopeid' => $process->scope->id,
262                'date' => $now->format('Y-m-d'),
263                'hour' => $now->format('H')
264            ]
265        );
266
267        return $this;
268    }
269}

Inherited from BO\Zmsbackend\Base

38    public function __construct(?Connection\Pdo $writeConnection = null, ?Connection\Pdo $readConnection = null)
39    {
40        $this->writeDb = $writeConnection;
41        $this->readDb = $readConnection;
42    }
44    public static function init(?Connection\Pdo $writeConnection = null, ?Connection\Pdo $readConnection = null): static
45    {
46        $instance = new static($writeConnection, $readConnection);
47        return $instance;
48    }
50    public function getWriter(): Connection\Pdo
51    {
52        if (null === $this->writeDb) {
53            $this->writeDb = Connection\Select::getWriteConnection();
54            $this->readDb = $this->writeDb;
55        }
56        return $this->writeDb;
57    }
59    public function getReader(): Connection\Pdo
60    {
61        if (null !== $this->writeDb) {
62            // if readDB gets a reset, still use writeDB
63            return $this->writeDb;
64        }
65        if (null === $this->readDb) {
66            $this->readDb = Connection\Select::getReadConnection();
67        }
68        return $this->readDb;
69    }
71    public function fetchPreparedStatement(Query\Base|string $query)
72    {
73        $sql = "$query";
74        $reader = $this->getReader();
75        if (spl_object_hash($reader) != static::$preparedConnectionId) {
76            // do not use prepared statements on a different connection
77            static::$preparedCache = [];
78            static::$preparedConnectionId = spl_object_hash($reader);
79        }
80        if (!isset(static::$preparedCache[$sql])) {
81            $prepared = $this->getReader()->prepare($sql);
82            static::$preparedCache[$sql] = $prepared;
83        }
84        return static::$preparedCache[$sql];
85    }
87    public function startExecute(\PDOStatement $statement, array $parameters)
88    {
89        $statement = static::pdoExceptionHandler(function () use ($statement, $parameters) {
90            $statement->execute($parameters);
91            return $statement;
92        });
93        return $statement;
94    }
96    protected static function pdoExceptionHandler(\Closure $pdoFunction, array $parameters = [])
97    {
98        try {
99            $statement = $pdoFunction($parameters);
100        } catch (\PDOException $pdoException) {
101            if (stripos($pdoException->getMessage(), 'Lock wait timeout') !== false) {
102                throw new \BO\Zmsbackend\Exception\Pdo\LockTimeout();
103            }
104            //@codeCoverageIgnoreStart
105            if (stripos($pdoException->getMessage(), 'Deadlock found') !== false) {
106                throw new \BO\Zmsbackend\Exception\Pdo\DeadLockFound();
107            }
108            //@codeCoverageIgnoreEnd
109            $message = "SQL: "
110                . " Err: "
111                . $pdoException->getMessage()
112                //. " || Statement: "
113                //.$statement->queryString
114                //." || Parameters=". var_export($parameters, true)
115                ;
116            throw new \BO\Zmsbackend\Exception\Pdo\PDOFailed($message, 0, $pdoException);
117        }
118        return $statement;
119    }
121    public function fetchStatement(Query\Base $query)
122    {
123        $parameters = $query->getParameters();
124        $statement = $this->startExecute($this->fetchPreparedStatement($query), $parameters);
125        return $statement;
126    }
133    public function fetchOne(Query\Base $query, \BO\Zmsentities\Schema\Entity $entity)
134    {
135        $statement = $this->fetchStatement($query);
136        $data = $statement->fetch(\PDO::FETCH_ASSOC);
137        if ($data) {
138            $entity->exchangeArray($query->postProcessJoins($data));
139            $entity->setResolveLevel($query->getResolveLevel());
140        }
141        $statement->closeCursor();
142        return $entity;
143    }
145    public function fetchRow(Query\Base|string $query, array|null $parameters = null)
146    {
147        return static::pdoExceptionHandler(function () use ($query, $parameters) {
148            $prepared = $this->fetchPreparedStatement($query);
149            $prepared->execute($parameters);
150            $row = $prepared->fetch(\PDO::FETCH_ASSOC);
151            $prepared->closeCursor();
152            return $row;
153        });
154    }
156    public function fetchValue(Query\Base|string $query, array|null $parameters = null)
157    {
158        return static::pdoExceptionHandler(function () use ($query, $parameters) {
159            $prepared = $this->fetchPreparedStatement($query);
160            $prepared->execute($parameters);
161            $value = $prepared->fetchColumn();
162            $prepared->closeCursor();
163            return $value;
164        });
165    }
167    public function fetchAll(Query\Base|string $query, array|null $parameters = null)
168    {
169        return static::pdoExceptionHandler(function () use ($query, $parameters) {
170            $prepared = $this->fetchPreparedStatement($query);
171            $prepared->execute($parameters);
172            $list = $prepared->fetchAll(\PDO::FETCH_ASSOC);
173            $prepared->closeCursor();
174            return $list;
175        });
176    }
178    public function fetchHandle(Query\Base|string $query, array|null $parameters = null)
179    {
180        return static::pdoExceptionHandler(function () use ($query, $parameters) {
181            $prepared = $this->fetchPreparedStatement($query);
182            $prepared->execute($parameters);
183            return $prepared;
184        });
185    }
187    public function fetchList(Query\Base $query, \BO\Zmsentities\Schema\Entity $entity, array|\ArrayAccess $resultList = [])
188    {
189        $statement = $this->fetchStatement($query);
190        while ($data = $statement->fetch(\PDO::FETCH_ASSOC)) {
191            $dataEntity = clone $entity;
192            $dataEntity->exchangeArray($query->postProcessJoins($data));
193            $dataEntity->setResolveLevel($query->getResolveLevel());
194            $resultList[] = $dataEntity;
195        }
196        $statement->closeCursor();
197        return $resultList;
198    }
206    public function writeItem(Query\Base $query)
207    {
208        return static::pdoExceptionHandler(function () use ($query) {
209            $this->getWriter(); //Switch to writer for write/delete
210            $statement = $this->fetchPreparedStatement($query);
211            $status = $statement->execute($query->getParameters());
212            $statement->closeCursor();
213            return $status;
214        });
215    }
221    public function deleteItem(Query\Base $query)
222    {
223        return $this->writeItem($query);
224    }
226    public function perform(string $sql, array|null $parameters = null)
227    {
228        return static::pdoExceptionHandler(function () use ($sql, $parameters) {
229            $this->getWriter(); //Switch to writer for perform
230            $prepared = $this->fetchPreparedStatement($sql);
231            $status = $prepared->execute($parameters);
232            $prepared->closeCursor();
233            return $status;
234        });
235    }
237    public function fetchAffected(string $sql, array|null $parameters = null)
238    {
239        return static::pdoExceptionHandler(function () use ($sql, $parameters) {
240            $this->getWriter(); //Switch to writer for perform
241            $prepared = $this->fetchPreparedStatement($sql);
242            $prepared->execute($parameters);
243            $count = $prepared->rowCount();
244            $prepared->closeCursor();
245            return $count;
246        });
247    }
256    public function readResolvedReferences(\BO\Zmsentities\Schema\Entity $entity, int $resolveReferences)
257    {
258        return $entity;
259    }
268    public function hashStringValue(string $value, ?callable $callable = null): string
269    {
270        if ($callable === null) {
271            $callable = 'sha1';
272        }
273
274        if (is_callable($callable)) {
275            $hash = $callable($value);
276
277            if (is_string($callable)) {
278                return $callable . ':' . $hash;
279            }
280            if ($callable instanceof \Closure) {
281                return 'closure:' . $hash;
282            }
283            // else
284            return 'custom:' . $hash;
285        }
286
287        throw new \InvalidArgumentException('hashStringValue() should be called with a callable as second parameter.');
288    }