Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
82.38% covered (warning)
82.38%
304 / 369
75.00% covered (warning)
75.00%
24 / 32
CRAP
0.00% covered (danger)
0.00%
0 / 1
Scope
82.38% covered (warning)
82.38%
304 / 369
75.00% covered (warning)
75.00%
24 / 32
208.04
0.00% covered (danger)
0.00%
0 / 1
 readEntity
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
1 / 1
7
 readEntitiesByIds
0.00% covered (danger)
0.00%
0 / 28
0.00% covered (danger)
0.00%
0 / 1
110
 readResolvedReferences
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 readByClusterId
100.00% covered (success)
100.00%
34 / 34
100.00% covered (success)
100.00%
1 / 1
11
 readByProviderId
76.67% covered (warning)
76.67%
23 / 30
0.00% covered (danger)
0.00%
0 / 1
11.27
 readByRequestId
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
3
 readByDepartmentId
100.00% covered (success)
100.00%
32 / 32
100.00% covered (success)
100.00%
1 / 1
11
 readListBySource
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
6
 testSource
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
6
 readCollection
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
6
 readList
100.00% covered (success)
100.00%
17 / 17
100.00% covered (success)
100.00%
1 / 1
9
 readIsOpened
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
2
 readIsEnabled
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
3
 readWaitingNumberUpdated
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
3
 readDisplayNumberUpdated
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
2
 readIsGivenNumberInContingent
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 readQueueList
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
2
 readWithWorkstationCount
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
2
 readQueueListWithWaitingTime
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
2
 readScopesQueueListWithWaitingTime
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
2
 readListWithScopeAdminEmail
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
4
 writeEntity
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
1
 updateEntity
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
1
 replacePreferences
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
4
 updateGhostWorkstationCount
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
1
 updateEmergency
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
1
 writeImageData
93.33% covered (success)
93.33%
14 / 15
0.00% covered (danger)
0.00%
0 / 1
4.00
 readImageData
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
2
 deleteImage
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 deleteEntity
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
3
 deletePreferences
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
3
 removeCache
56.25% covered (warning)
56.25%
9 / 16
0.00% covered (danger)
0.00%
0 / 1
21.13
1<?php
2
3namespace BO\Zmsdb;
4
5use BO\Zmsentities\Scope as Entity;
6use BO\Zmsentities\Collection\ScopeList as Collection;
7use BO\Zmsdb\Application as App;
8
9/**
10 *
11 * @SuppressWarnings(Public)
12 * @SuppressWarnings(Coupling)
13 * @SuppressWarnings(Complexity)
14 * @SuppressWarnings(TooManyMethods)
15 *
16 */
17class Scope extends Base
18{
19    public static $cache = [ ];
20
21    public function readEntity($scopeId, $resolveReferences = 0, $disableCache = false)
22    {
23        $cacheKey = "scope-$scopeId-$resolveReferences";
24
25        if (!$disableCache && App::$cache && App::$cache->has($cacheKey)) {
26            $scope = App::$cache->get($cacheKey);
27        }
28
29        if (empty($scope)) {
30            $query = new Query\Scope(Query\Base::SELECT);
31            $query->addEntityMapping()
32                ->addResolvedReferences($resolveReferences)
33                ->addConditionScopeId($scopeId);
34            $scope = $this->fetchOne($query, new Entity());
35            if (! $scope->hasId()) {
36                return null;
37            }
38
39            if (App::$cache) {
40                App::$cache->set($cacheKey, $scope);
41            }
42        }
43
44        return $this->readResolvedReferences($scope, $resolveReferences, $disableCache);
45    }
46
47    public function readEntitiesByIds(array $scopeIds, int $resolveReferences = 0, bool $disableCache = false): array
48    {
49        $scopeIds = array_values(array_unique(array_filter(array_map('intval', $scopeIds))));
50        if (!$scopeIds) {
51            return [];
52        }
53
54        $result  = [];
55        $missing = [];
56        foreach ($scopeIds as $scopeId) {
57            $cacheKey = "{$scopeId}-{$resolveReferences}";
58            if (!$disableCache && array_key_exists($cacheKey, self::$cache)) {
59                $result[$scopeId] = self::$cache[$cacheKey];
60            } else {
61                $missing[] = $scopeId;
62            }
63        }
64
65        if ($missing) {
66            $query = new Query\Scope(Query\Base::SELECT);
67            $query
68                ->addEntityMapping()
69                ->addResolvedReferences($resolveReferences)
70                ->addConditionScopeIds($missing);
71
72            $fetched = $this->fetchList($query, new Entity());
73            foreach ($fetched as $entity) {
74                if (!$entity->hasId()) {
75                    continue;
76                }
77                $entity = $this->readResolvedReferences($entity, $resolveReferences);
78                $result[$entity->id] = $entity;
79                self::$cache["{$entity->id}-{$resolveReferences}"] = $entity;
80            }
81        }
82
83        $ordered = [];
84        foreach ($scopeIds as $id) {
85            if (isset($result[$id])) {
86                $ordered[$id] = $result[$id];
87            }
88        }
89
90        return $ordered;
91    }
92
93    public function readResolvedReferences(
94        \BO\Zmsentities\Schema\Entity $scope,
95        $resolveReferences,
96        $disableCache = false
97    ) {
98        if (0 < $resolveReferences) {
99            $scope['dayoff'] = (new DayOff())->readByScopeId($scope->id, $disableCache);
100            $scope['closure'] = (new Closure())->readByScopeId($scope->id, $disableCache);
101        }
102        return $scope;
103    }
104
105    public function readByClusterId(
106        $clusterId,
107        $resolveReferences = 0,
108        $disableCache = false
109    ) {
110        $cacheKey = "scopeReadByClusterId-$clusterId-$resolveReferences";
111
112        if (!$disableCache && App::$cache && App::$cache->has($cacheKey)) {
113            $result = App::$cache->get($cacheKey);
114        }
115
116        if (empty($result)) {
117            if ($resolveReferences > 0) {
118                $query = new Query\Scope(Query\Base::SELECT);
119                $query->addEntityMapping()
120                    ->addResolvedReferences($resolveReferences - 1)
121                    ->addConditionClusterId($clusterId);
122                $result = $this->fetchList($query, new Entity());
123            } else {
124                $result = $this->getReader()->perform(
125                    (new Query\Scope(Query\Base::SELECT))->getQuerySimpleClusterMatch(),
126                    [$clusterId]
127                );
128            }
129
130            if (App::$cache && !($result instanceof \PDOStatement)) {
131                App::$cache->set($cacheKey, $result);
132            }
133        }
134
135        $scopeList = new Collection();
136        if (!$result) {
137            return $scopeList;
138        }
139
140        foreach ($result as $entity) {
141            if (0 == $resolveReferences) {
142                $entity = new Entity(
143                    array(
144                        'id' => $entity['id'],
145                        '$ref' => '/scope/' . $entity['id'] . '/'
146                    )
147                );
148                $scopeList->addEntity($entity);
149            } else {
150                $scopeList->addEntity($this->readResolvedReferences(
151                    $entity,
152                    $resolveReferences - 1,
153                    $disableCache
154                ));
155            }
156        }
157
158        return $scopeList;
159    }
160
161    public function readByProviderId($providerId, $resolveReferences = 0, $disableCache = false)
162    {
163        $cacheKey = "scopeReadByProviderId-$providerId-$resolveReferences";
164
165        if (!$disableCache && App::$cache && App::$cache->has($cacheKey)) {
166            $result = App::$cache->get($cacheKey);
167        }
168
169        if (empty($result)) {
170            $query = new Query\Scope(Query\Base::SELECT);
171            $query->addEntityMapping()
172                ->addResolvedReferences($resolveReferences)
173                ->addConditionProviderId($providerId);
174            $result = $this->fetchList($query, new Entity());
175
176            if (App::$cache) {
177                App::$cache->set($cacheKey, $result);
178            }
179        }
180
181        $scopeList = new Collection();
182        if (count($result)) {
183            foreach ($result as $entity) {
184                if (0 == $resolveReferences) {
185                    $entity = new Entity(
186                        array(
187                            'id' => $entity->id,
188                            '$ref' => '/scope/' . $entity->id . '/'
189                        )
190                    );
191                    $scopeList->addEntity($entity);
192                } else {
193                    if ($entity instanceof Entity) {
194                        $entity = $this->readResolvedReferences(
195                            $entity,
196                            $resolveReferences - 1,
197                            $disableCache
198                        );
199                        $scopeList->addEntity($entity);
200                    }
201                }
202            }
203        }
204
205        return $scopeList;
206    }
207
208    public function readByRequestId($requestId, $source, $resolveReferences = 0)
209    {
210        $scopeList = new Collection();
211        $providerList = (new Provider())->readListBySource($source, 0, true, $requestId);
212
213        foreach ($providerList as $provider) {
214            $scopeListByProvider = $this->readByProviderId($provider->getId(), $resolveReferences);
215            if ($scopeListByProvider->count()) {
216                $scopeList->addList($scopeListByProvider);
217            }
218        }
219        return $scopeList->withUniqueScopes();
220    }
221
222    public function readByDepartmentId($departmentId, $resolveReferences = 0, $disableCache = false)
223    {
224        $cacheKey = "scopeReadByDepartmentId-$departmentId-$resolveReferences";
225
226        if (!$disableCache && App::$cache && App::$cache->has($cacheKey)) {
227            $result = App::$cache->get($cacheKey);
228        }
229
230        $scopeList = new Collection();
231
232        if (empty($result)) {
233            if ($resolveReferences > 0) {
234                $query = new Query\Scope(Query\Base::SELECT);
235                $query->addEntityMapping()
236                    ->addResolvedReferences($resolveReferences)
237                    ->addConditionDepartmentId($departmentId);
238                $result = $this->fetchList($query, new Entity());
239
240                if (App::$cache) {
241                    App::$cache->set($cacheKey, $result);
242                }
243            } else {
244                $result = $this->getReader()->perform(
245                    (new Query\Scope(Query\Base::SELECT))->getQuerySimpleDepartmentMatch(),
246                    [$departmentId]
247                );
248            }
249        }
250
251        if ($result) {
252            foreach ($result as $entity) {
253                if (0 == $resolveReferences) {
254                    $entity = new Entity(
255                        array(
256                            'id' => $entity['id'],
257                            'contact' => ['name' => $entity['contact__name']],
258                            '$ref' => '/scope/' . $entity['id'] . '/'
259                        )
260                    );
261                    $scopeList->addEntity($entity);
262                } else {
263                    if ($entity instanceof Entity) {
264                        $entity = $this->readResolvedReferences($entity, $resolveReferences, $disableCache);
265                        $scopeList->addEntity($entity);
266                    }
267                }
268            }
269        }
270
271        return $scopeList;
272    }
273    public function readListBySource($source, $resolveReferences = 0)
274    {
275        $this->testSource($source);
276        $query = new Query\Request(Query\Base::SELECT);
277        $query->setResolveLevel($resolveReferences);
278        $query->addConditionRequestSource($source);
279        $query->addEntityMapping();
280        $requestList = $this->readCollection($query);
281        return ($requestList->count()) ? $requestList->sortByCustomKey('id') : $requestList;
282    }
283
284    protected function testSource($source)
285    {
286        if (! (new Source())->readEntity($source)) {
287            throw new Exception\Source\UnknownDataSource();
288        }
289    }
290
291    protected function readCollection($query)
292    {
293        $requestList = new Collection();
294        $statement = $this->fetchStatement($query);
295        while ($requestData = $statement->fetch(\PDO::FETCH_ASSOC)) {
296            $request = new Entity($query->postProcessJoins($requestData));
297            $requestList->addEntity($request);
298        }
299        return $requestList;
300    }
301
302    public function readList($resolveReferences = 0, $disableCache = false)
303    {
304        $cacheKey = "scopeReadList-$resolveReferences";
305
306        if (!$disableCache && App::$cache && App::$cache->has($cacheKey)) {
307            $result = App::$cache->get($cacheKey);
308        }
309
310        if (empty($result)) {
311            $query = new Query\Scope(Query\Base::SELECT);
312            $query->addEntityMapping()
313                ->addResolvedReferences($resolveReferences);
314            $result = $this->fetchList($query, new Entity());
315
316            if (App::$cache) {
317                App::$cache->set($cacheKey, $result);
318            }
319        }
320
321        $scopeList = new Collection();
322        if (count($result)) {
323            foreach ($result as $entity) {
324                if ($entity instanceof Entity) {
325                    $entity = $this->readResolvedReferences($entity, $resolveReferences);
326                    $scopeList->addEntity($entity);
327                }
328            }
329        }
330        return $scopeList;
331    }
332
333    /**
334     * get a scope and return true if it is opened
335     *
336     * * @param
337     * scopeId
338     * now
339     *
340     * @return Bool
341     */
342    public function readIsOpened($scopeId, $now)
343    {
344        $isOpened = false;
345        $availabilityList = (new Availability())->readOpeningHoursListByDate($scopeId, $now, 2);
346        if ($availabilityList->isOpened($now)) {
347            $isOpened = true;
348        }
349        return $isOpened;
350    }
351
352    public function readIsEnabled($scopeId, $now)
353    {
354        $query = new Query\Scope(Query\Base::SELECT);
355        $query->addEntityMapping()
356            ->setResolveLevel(0)
357            ->addConditionScopeId($scopeId);
358        $scope = $this->fetchOne($query, new Entity());
359        return (
360            $this->readIsOpened($scopeId, $now) &&
361            $this->readIsGivenNumberInContingent($scopeId) &&
362            ! $scope->getStatus('ticketprinter', 'deactivated')
363        );
364    }
365
366    /**
367     * get last given waitingnumer and return updated (+1) waitingnumber
368     *
369     * * @param
370     * scopeId
371     * now
372     *
373     * @return Bool
374     */
375    public function readWaitingNumberUpdated($scopeId, $dateTime, $respectContingent = true)
376    {
377        if (! $this->readIsGivenNumberInContingent($scopeId) && $respectContingent) {
378            throw new Exception\Scope\GivenNumberCountExceeded();
379        }
380        $this->perform(
381            (new Query\Scope(Query\Base::SELECT))->getQueryLastWaitingNumber(),
382            ['scope_id' => $scopeId]
383        );
384        $entity = $this->readEntity($scopeId, 0, true)->updateStatusQueue($dateTime);
385        $scope = $this->updateEntity($scopeId, $entity);
386        return $scope->getStatus('queue', 'lastGivenNumber');
387    }
388
389    public function readDisplayNumberUpdated($scopeId)
390    {
391        $this->perform(
392            (new Query\Scope(Query\Base::SELECT))->getQueryLastDisplayNumber(),
393            ['scope_id' => $scopeId]
394        );
395        $entity = $this->readEntity($scopeId, 0, true)->incrementDisplayNumber();
396        $scope = $this->updateEntity($scopeId, $entity);
397        return $scope->getStatus('queue', 'lastDisplayNumber');
398    }
399
400    /**
401     * get last given waitingnumer and return updated (+1) waitingnumber
402     *
403     * * @param
404     * scopeId
405     * now
406     *
407     * @return Bool
408     */
409    public function readIsGivenNumberInContingent($scopeId)
410    {
411        $isInContingent = $this->getReader()
412            ->fetchValue((new Query\Scope(Query\Base::SELECT))
413            ->getQueryGivenNumbersInContingent(), ['scope_id' => $scopeId]);
414        return ($isInContingent) ? true : false;
415    }
416
417    /**
418     * get list of queues on scope by daytime
419     *
420     * * @param
421     * scopeId
422     * now
423     *
424     * @return number
425     */
426    public function readQueueList($scopeIds, $dateTime, $resolveReferences = 0, $withEntities = [])
427    {
428        if ($resolveReferences > 0) {
429            $queueList = (new Process())
430                ->readProcessListByScopesAndTime(
431                    $scopeIds,
432                    $dateTime,
433                    $resolveReferences - 1,
434                    $withEntities
435                )
436                ->toQueueList($dateTime);
437        } else {
438            $queueList = (new Queue())
439                ->readListByScopeAndTime($scopeIds, $dateTime, $resolveReferences);
440        }
441
442        return $queueList->withSortedArrival();
443    }
444
445    /**
446     * get waitingtime of scope
447     *
448     * * @param
449     * scopeId
450     * now
451     *
452     * @return \BO\Zmsentities\Scope
453     */
454    public function readWithWorkstationCount($scopeId, $dateTime, $resolveReferences = 0, $withEntities = [])
455    {
456        $query = new Query\Scope(Query\Base::SELECT, '', false, null, $withEntities);
457        $query
458            ->addEntityMapping()
459            ->addConditionScopeId($scopeId)
460            ->addResolvedReferences($resolveReferences)
461            ->addSelectWorkstationCount($dateTime);
462        $scope = $this->fetchOne($query, new Entity());
463        $scope = $this->readResolvedReferences($scope, $resolveReferences);
464        return ($scope->hasId()) ? $scope : null;
465    }
466
467    public function readQueueListWithWaitingTime($scope, $dateTime, $resolveReferences = 0, $withEntities = [])
468    {
469        $timeAverage = $scope->getPreference('queue', 'processingTimeAverage');
470        $scope = (! $timeAverage) ? (new Scope())->readEntity($scope->id) : $scope;
471        $queueList = $this->readQueueList([$scope->id], $dateTime, $resolveReferences, $withEntities);
472        $workstationCount = $scope->getCalculatedWorkstationCount();
473        return $queueList->withEstimatedWaitingTime($timeAverage, $workstationCount, $dateTime);
474    }
475
476    public function readScopesQueueListWithWaitingTime(Collection $scopes, $dateTime, $resolveReferences = 0, $withEntities = [])
477    {
478        $timeSum = 0;
479        $workstationCount = 0;
480        $scopeIds = [];
481        foreach ($scopes as $scope) {
482            $timeSum += $scope->getPreference('queue', 'processingTimeAverage');
483            $workstationCount += $scope->getCalculatedWorkstationCount();
484            $scopeIds[] = $scope->id;
485        }
486
487        $timeAverage = $timeSum / $scopes->count();
488        $queueList = $this->readQueueList($scopeIds, $dateTime, $resolveReferences, $withEntities);
489
490        return $queueList->withEstimatedWaitingTime($timeAverage, $workstationCount, $dateTime);
491    }
492
493    /**
494     * get list of scopes with admin
495     *
496     * * @param
497     * scopeId
498     * now
499     *
500     * @return number
501     */
502    public function readListWithScopeAdminEmail($resolveReferences = 0)
503    {
504        $scopeList = new Collection();
505        $query = new Query\Scope(Query\Base::SELECT);
506        $query
507            ->addEntityMapping()
508            ->addConditionWithAdminEmail()
509            ->addResolvedReferences($resolveReferences);
510        $result = $this->fetchList($query, new Entity());
511        if (count($result)) {
512            foreach ($result as $entity) {
513                if ($entity instanceof Entity) {
514                    $entity = $this->readResolvedReferences($entity, $resolveReferences);
515                    $scopeList->addEntity($entity);
516                }
517            }
518        }
519        return $scopeList;
520    }
521
522    /**
523     * write a scope
524     *
525     * @return Entity
526     */
527    public function writeEntity(\BO\Zmsentities\Scope $entity, $parentId)
528    {
529        self::$cache = [];
530        $query = new Query\Scope(Query\Base::INSERT);
531        $values = $query->reverseEntityMapping($entity, $parentId);
532        $query->addValues($values);
533        $this->writeItem($query);
534        $lastInsertId = $this->getWriter()
535            ->lastInsertId();
536        $this->replacePreferences($entity);
537
538        $this->removeCache($entity);
539
540        return $this->readEntity($lastInsertId);
541    }
542
543    /**
544     * update a scope
545     *
546     * @param
547     *            scopeId
548     *
549     * @return Entity
550     */
551    public function updateEntity($scopeId, \BO\Zmsentities\Scope $entity, $resolveReferences = 0)
552    {
553        self::$cache = [];
554        $query = new Query\Scope(Query\Base::UPDATE);
555        $query->addConditionScopeId($scopeId);
556        $values = $query->reverseEntityMapping($entity);
557        $query->addValues($values);
558        $this->writeItem($query);
559        $this->replacePreferences($entity);
560
561        $this->removeCache($entity);
562
563        return $this->readEntity($scopeId, $resolveReferences, true);
564    }
565
566    public function replacePreferences(\BO\Zmsentities\Scope $entity)
567    {
568        if (isset($entity['preferences'])) {
569            $preferenceQuery = new Preferences();
570            $entityName = 'scope';
571            $entityId = $entity['id'];
572            foreach ($entity['preferences'] as $groupName => $groupValues) {
573                foreach ($groupValues as $name => $value) {
574                    $preferenceQuery->replaceProperty($entityName, $entityId, $groupName, $name, $value);
575                }
576            }
577
578            $this->removeCache($entity);
579        }
580    }
581
582    /**
583     * update ghostWorkstationCount
584     *
585     * @param
586     *         scopeId
587     *         entity
588     *         dateTime (now)
589     *
590     * @return Entity
591     */
592    public function updateGhostWorkstationCount(\BO\Zmsentities\Scope $entity, \DateTimeInterface $dateTime)
593    {
594        $query = new Query\Scope(Query\Base::UPDATE);
595        $query->addConditionScopeId($entity->id);
596        $values = $query->setGhostWorkstationCountEntityMapping($entity, $dateTime);
597        $query->addValues($values);
598        $this->writeItem($query);
599
600        $this->removeCache($entity);
601
602        return $entity;
603    }
604
605    /**
606     * update emergency
607     *
608     * @param
609     *         scopeId
610     *         entity
611     *
612     * @return Entity
613     */
614    public function updateEmergency($scopeId, \BO\Zmsentities\Scope $entity)
615    {
616        self::$cache = [];
617        $query = new Query\Scope(Query\Base::UPDATE);
618        $query->addConditionScopeId($scopeId);
619        $values = $query->setEmergencyEntityMapping($entity);
620        $query->addValues($values);
621        $this->writeItem($query);
622
623        $this->removeCache($entity);
624
625        return $this->readEntity($scopeId, 0, true);
626    }
627
628    /**
629     * update image data for call display image
630     *
631     * @param
632     *         scopeId
633     *         Mimepart entity
634     *
635     * @return Mimepart entity
636     */
637    public function writeImageData($scopeId, \BO\Zmsentities\Mimepart $entity)
638    {
639        if ($entity->mime && $entity->content) {
640            $this->deleteImage($scopeId);
641            $extension = $entity->getExtension();
642            if ($extension == 'jpeg') {
643                $extension = 'jpg'; //compatibility ZMS1
644            }
645            $imageName = 's_' . $scopeId . '_bild.' . $extension;
646            $this->getWriter()->perform(
647                (new Query\Scope(Query\Base::REPLACE))->getQueryWriteImageData(),
648                array(
649                    'imagename' => $imageName,
650                    'imagedata' => $entity->content
651                )
652            );
653        }
654        $entity->id = $scopeId;
655        return $entity;
656    }
657
658    /**
659     * read image data
660     *
661     * @param
662     *         scopeId
663     *
664     * @return Mimepart entity
665     */
666    public function readImageData($scopeId)
667    {
668        $imageName = 's_' . $scopeId . '_bild';
669        $imageData = new \BO\Zmsentities\Mimepart();
670        $fileData = $this->getReader()->fetchAll(
671            (new Query\Scope(Query\Base::SELECT))->getQueryReadImageData(),
672            ['imagename' => "$imageName%"]
673        );
674        if ($fileData) {
675            $imageData->content = $fileData[0]['imagecontent'];
676            $imageData->mime = pathinfo($fileData[0]['imagename'])['extension'];
677        }
678        return $imageData;
679    }
680
681    /**
682     * delete image data for call display image
683     *
684     * @param
685     *         scopeId
686     *
687     * @return Status
688     */
689    public function deleteImage($scopeId)
690    {
691        $imageName = 's_' . $scopeId . '_bild';
692        return $this->perform((new Query\Scope(Query\Base::DELETE))->getQueryDeleteImage(), array(
693            'imagename' => "$imageName%"
694        ));
695    }
696
697    /**
698     * remove a scope
699     *
700     * @param
701     *            scopeId
702     *
703     * @return Resource Status
704     */
705    public function deleteEntity($scopeId)
706    {
707        $processListCount = (new Process())->readProcessListCountByScope($scopeId);
708        if (0 < $processListCount) {
709            throw new Exception\Scope\ScopeHasProcesses();
710        }
711        self::$cache = [];
712        $entity = $this->readEntity($scopeId);
713        $query = new Query\Scope(Query\Base::DELETE);
714        $query->addConditionScopeId($scopeId);
715        $this->deletePreferences($entity);
716
717        $this->removeCache($entity);
718
719        return ($this->deleteItem($query)) ? $entity : null;
720    }
721
722    public function deletePreferences(\BO\Zmsentities\Scope $entity)
723    {
724        $preferenceQuery = new Preferences();
725        $entityName = 'scope';
726        $entityId = $entity['id'];
727        foreach ($entity['preferences'] as $groupName => $groupValues) {
728            foreach (array_keys($groupValues) as $name) {
729                $preferenceQuery->deleteProperty($entityName, $entityId, $groupName, $name);
730            }
731        }
732
733        $this->removeCache($entity);
734    }
735
736    public function removeCache($scope)
737    {
738        if (!App::$cache) {
739            return;
740        }
741
742        if (isset($scope->provider) && isset($this->provider->id)) {
743            if (App::$cache->has('scopeReadByProviderId-' . $scope->getProviderId() . '-0')) {
744                App::$cache->delete('scopeReadByProviderId-' . $scope->getProviderId() . '-0');
745            }
746
747            if (App::$cache->has('scopeReadByProviderId-' . $scope->getProviderId() . '-1')) {
748                App::$cache->delete('scopeReadByProviderId-' . $scope->getProviderId() . '-1');
749            }
750
751            if (App::$cache->has('scopeReadByProviderId-' . $scope->getProviderId() . '-2')) {
752                App::$cache->delete('scopeReadByProviderId-' . $scope->getProviderId() . '-2');
753            }
754        }
755
756        if (isset($scope->id)) {
757            if (App::$cache->has("scope-$scope->id-0")) {
758                App::$cache->delete("scope-$scope->id-0");
759            }
760
761            if (App::$cache->has("scope-$scope->id-1")) {
762                App::$cache->delete("scope-$scope->id-1");
763            }
764
765            if (App::$cache->has("scope-$scope->id-2")) {
766                App::$cache->delete("scope-$scope->id-2");
767            }
768        }
769    }
770}