Lines 88.11% 215 / 244
Methods 89.18% 33 / 37
Classes 0.00% 0 / 1
Name Lines Methods CRAP
 readEntity 100.00% 8 / 8 100.00% 1 / 1 1
 readList 100.00% 5 / 5 100.00% 1 / 1 2
 readByHash 100.00% 8 / 8 100.00% 1 / 1 1
 readByButtonList 100.00% 7 / 7 100.00% 1 / 1 3
 omitButtonsWithMissingScopeOrRequest 100.00% 6 / 6 100.00% 1 / 1 3
 validateButton 80.00% 4 / 5 0.00% 0 / 1 3.07
 validateScopeButton 100.00% 12 / 12 100.00% 1 / 1 2
 validateRequestButton 0.00% 0 / 20 0.00% 0 / 1 12
 findRequest 0.00% 0 / 3 0.00% 0 / 1 6
 hasScopeOrRequestButton 100.00% 4 / 4 100.00% 1 / 1 3
 readExceptions 100.00% 4 / 4 100.00% 1 / 1 3
 readWithContactData 100.00% 6 / 6 100.00% 1 / 1 2
 readSingleScopeFromButtonList 100.00% 5 / 5 100.00% 1 / 1 2
 writeEntityWithHash 100.00% 11 / 11 100.00% 1 / 1 1
 writeEntity 100.00% 8 / 8 100.00% 1 / 1 1
 readByOrganisationId 100.00% 6 / 6 100.00% 1 / 1 1
 deleteEntity 100.00% 3 / 3 100.00% 1 / 1 1
 readExpiredTicketprinterList 100.00% 6 / 6 100.00% 1 / 1 1
 [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
12class Ticketprinter extends \BO\Zmsbackend\Base
13{
14    public function readEntity($itemId)
15    {
16        $query = new \BO\Zmsbackend\Ticketprinter\Repository\Ticketprinter(\BO\Zmsbackend\Query\Base::SELECT);
17        $query
18            ->addEntityMapping()
19            ->addConditionTicketprinterId($itemId);
20        $ticketprinter = $this->fetchOne($query, new Entity());
21        $ticketprinter = $this->readWithContactData($ticketprinter);
22        $ticketprinter->enabled = (1 == $ticketprinter->enabled);
23        return $ticketprinter;
24    }
25
26    protected function readList($statement)
27    {
28        $ticketprinterList = new Collection();
29        while ($entityData = $statement->fetch(\PDO::FETCH_ASSOC)) {
30            $entity = new Entity($entityData);
31            $ticketprinterList->addEntity($entity);
32        }
33        return $ticketprinterList;
34    }
35
36    public function readByHash($hash)
37    {
38        $query = new \BO\Zmsbackend\Ticketprinter\Repository\Ticketprinter(\BO\Zmsbackend\Query\Base::SELECT);
39        $query
40            ->addEntityMapping()
41            ->addConditionHash($hash);
42        $ticketprinter = $this->fetchOne($query, new Entity());
43        $ticketprinter = $this->readWithContactData($ticketprinter);
44        $ticketprinter->enabled = (1 == $ticketprinter->enabled);
45        return $ticketprinter;
46    }
47
48    public function readByButtonList(Entity $ticketprinter, \DateTimeImmutable $now)
49    {
50        if (count($ticketprinter->buttons) > 6) {
51            throw new \BO\Zmsbackend\Ticketprinter\Exception\TooManyButtons();
52        }
53
54        $ticketprinter->buttons = $this->omitButtonsWithMissingScopeOrRequest($ticketprinter->buttons, $now);
55        if (! $this->hasScopeOrRequestButton($ticketprinter)) {
56            throw new \BO\Zmsbackend\Ticketprinter\Exception\UnvalidButtonList();
57        }
58
59        $this->readExceptions($ticketprinter);
60        return $this->readWithContactData($ticketprinter);
61    }
62
63    /**
64     * @param iterable<int, array<string, mixed>> $buttons
65     * @return array<int, array<string, mixed>>
66     */
67    private function omitButtonsWithMissingScopeOrRequest(iterable $buttons, \DateTimeImmutable $now): array
68    {
69        $kept = [];
70        foreach ($buttons as $button) {
71            $button = $this->validateButton($button, $now);
72            if ($button !== null) {
73                $kept[] = $button;
74            }
75        }
76        return $kept;
77    }
78
79    /**
80     * @param array<string, mixed> $button
81     * @return array<string, mixed>|null
82     */
83    private function validateButton(array $button, \DateTimeImmutable $now): ?array
84    {
85        if (($button['type'] ?? '') === 'scope') {
86            return $this->validateScopeButton($button, $now);
87        }
88        if (($button['type'] ?? '') === 'request') {
89            return $this->validateRequestButton($button, $now);
90        }
91        return $button;
92    }
93
94    /**
95     * @param array<string, mixed> $button
96     * @return array<string, mixed>|null
97     */
98    private function validateScopeButton(array $button, \DateTimeImmutable $now): ?array
99    {
100        $scopeId = $button['scope']['id'];
101        $query = new \BO\Zmsbackend\Scope\Service\Scope();
102        $scope = $query->readWithWorkstationCount($scopeId, $now);
103        if (! $scope) {
104            \App::$log->warning('Ticketprinter: skip missing scope id', [
105                'scopeId' => $scopeId,
106            ]);
107            return null;
108        }
109        $button['scope'] = $scope;
110        $button['enabled'] = $query->readIsEnabled($scope->id, $now);
111        $button['name'] = $scope->getPreference('ticketprinter', 'buttonName');
112        return $button;
113    }
114
115    /**
116     * @param array<string, mixed> $button
117     * @return array<string, mixed>|null
118     */
119    private function validateRequestButton(array $button, \DateTimeImmutable $now): ?array
120    {
121        $parts = explode('-', (string) $button['request']['id']);
122        $scopeId = $parts[0];
123        $requestId = $parts[1] ?? '';
124        $scope = (new \BO\Zmsbackend\Scope\Service\Scope())->readWithWorkstationCount($scopeId, $now);
125        if (! $scope) {
126            \App::$log->warning('Ticketprinter: skip missing scope id', [
127                'scopeId' => $scopeId,
128            ]);
129            return null;
130        }
131        $request = $this->findRequest($requestId);
132        if (! $request) {
133            \App::$log->warning('Ticketprinter: skip missing request id', [
134                'requestId' => $requestId,
135            ]);
136            return null;
137        }
138        $button['scope'] = $scope;
139        $button['requestId'] = $requestId;
140        $button['enabled'] = (new \BO\Zmsbackend\Scope\Service\Scope())->readIsEnabled($scope->id, $now);
141        $button['name'] = $request->getProperty('name');
142        return $button;
143    }
144
145    private function findRequest(string $requestId): ?\BO\Zmsentities\Request
146    {
147        try {
148            return (new \BO\Zmsbackend\Request\Service\Request())->readEntity('dldb', $requestId);
149        } catch (\BO\Zmsbackend\Request\Exception\RequestNotFound) {
150            return null;
151        }
152    }
153
154    private function hasScopeOrRequestButton(Entity $ticketprinter): bool
155    {
156        foreach ($ticketprinter->buttons as $button) {
157            if (in_array($button['type'] ?? '', ['scope', 'request'], true)) {
158                return true;
159            }
160        }
161        return false;
162    }
163
164    protected function readExceptions(Entity $ticketprinter)
165    {
166        $query = new \BO\Zmsbackend\Scope\Service\Scope();
167        $scope = $this->readSingleScopeFromButtonList($ticketprinter);
168        if ($scope && ! $query->readIsGivenNumberInContingent($scope['id'])) {
169            throw new \BO\Zmsbackend\Scope\Exception\GivenNumberCountExceeded();
170        }
171    }
172
173    protected function readWithContactData(Entity $entity): Entity
174    {
175        $contact = new \BO\Zmsentities\Contact();
176
177        if (1 == $entity->getScopeList()->count()) {
178            $department = (new \BO\Zmsbackend\Department\Service\Department())->readByScopeId($entity->getScopeList()->getFirst()->id);
179            $contact->name = $department->name;
180        }
181
182        $entity->contact = $contact;
183        return $entity;
184    }
185
186    public function readSingleScopeFromButtonList(Entity $ticketprinter): \BO\Zmsentities\Scope|null
187    {
188        $scope = null;
189        if (1 == $ticketprinter->getScopeList()->count()) {
190            $scope = $ticketprinter->getScopeList()->getFirst();
191            $scope = (new \BO\Zmsbackend\Scope\Service\Scope())->readEntity($scope['id']);
192        }
193        return $scope;
194    }
195
196    public function writeEntityWithHash($organisationId, $ticketprinterName = '')
197    {
198        $query = new \BO\Zmsbackend\Ticketprinter\Repository\Ticketprinter(\BO\Zmsbackend\Query\Base::INSERT);
199        $ticketprinter = (new Entity())->getHashWith($organisationId);
200        $ticketprinter->name = $ticketprinterName;
201
202        $organisation = (new \BO\Zmsbackend\Organisation\Service\Organisation())->readEntity($organisationId);
203
204        $values = $query->reverseEntityMapping($ticketprinter, $organisation->id);
205        $owner = (new \BO\Zmsbackend\Owner\Service\Owner())->readByOrganisationId($organisationId);
206        $values['kundenid'] = $owner->id;
207        $query->addValues($values);
208        $this->writeItem($query);
209        $lastInsertId = $this->getWriter()->lastInsertId();
210        return $this->readEntity($lastInsertId);
211    }
212
213    public function writeEntity(Entity $entity, $organisationId)
214    {
215        $query = new \BO\Zmsbackend\Ticketprinter\Repository\Ticketprinter(\BO\Zmsbackend\Query\Base::INSERT);
216        $values = $query->reverseEntityMapping($entity, $organisationId);
217
218        $owner = (new \BO\Zmsbackend\Owner\Service\Owner())->readByOrganisationId($organisationId);
219        $values['kundenid'] = $owner->id;
220
221        $query->addValues($values);
222        $this->writeItem($query);
223        $lastInsertId = $this->getWriter()->lastInsertId();
224        return $this->readEntity($lastInsertId);
225    }
226
227    public function readByOrganisationId($organisationId)
228    {
229        $query = new \BO\Zmsbackend\Ticketprinter\Repository\Ticketprinter(\BO\Zmsbackend\Query\Base::SELECT);
230        $query
231            ->addEntityMapping()
232            ->addConditionOrganisationId($organisationId);
233        $statement = $this->fetchStatement($query);
234        return $this->readList($statement);
235    }
236
237    public function deleteEntity($itemId)
238    {
239        $query =  new \BO\Zmsbackend\Ticketprinter\Repository\Ticketprinter(\BO\Zmsbackend\Query\Base::DELETE);
240        $query->addConditionTicketprinterId($itemId);
241        return $this->deleteItem($query);
242    }
243
244    public function readExpiredTicketprinterList($expirationDate): Collection
245    {
246        $selectQuery = new \BO\Zmsbackend\Ticketprinter\Repository\Ticketprinter(\BO\Zmsbackend\Query\Base::SELECT);
247        $selectQuery
248            ->addEntityMapping()
249            ->addConditionDeleteInterval($expirationDate);
250        $statement = $this->fetchStatement($selectQuery);
251        return $this->readList($statement);
252    }
253}

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($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, $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    }