Lines 82.14% 115 / 140
Functions and Methods 69.23% 9 / 13
Classes and Traits 0.00% 0 / 1
Name Lines Functions and Methods CRAP Classes and Traits
Provider 82.14% 115 / 140 69.23% 9 / 13 59.58 0.00% 0 / 1
 readEntity 93.33% 14 / 15 0.00% 0 / 1 5.01
 readEntityById 0.00% 0 / 13 0.00% 0 / 1 42
 readSourceMapByIds 90.90% 10 / 11 0.00% 0 / 1 3.01
 readCollection 100.00% 6 / 6 100.00% 1 / 1 2
 readListBySource 100.00% 12 / 12 100.00% 1 / 1 4
 writeEntity 100.00% 28 / 28 100.00% 1 / 1 6
 writeListBySource 100.00% 5 / 5 100.00% 1 / 1 2
 writeImportList 100.00% 3 / 3 100.00% 1 / 1 2
 writeImportEntity 100.00% 24 / 24 100.00% 1 / 1 7
 writeDeleteEntity 100.00% 6 / 6 100.00% 1 / 1 1
 writeDeleteListBySource 100.00% 3 / 3 100.00% 1 / 1 1
 testSource 100.00% 2 / 2 100.00% 1 / 1 2
 removeCache 16.66% 2 / 12 0.00% 0 / 1 26.83
1<?php
2
3namespace BO\Zmsbackend\Provider\Service;
4
5use BO\Zmsbackend\Application as App;
6use BO\Zmsentities\Provider as Entity;
7use BO\Zmsentities\Collection\ProviderList as Collection;
8
9class Provider extends \BO\Zmsbackend\Base
10{
11    public function readEntity(string $source, string|int $providerId, int $resolveReferences = 0, bool $disableCache = false)
12    {
13        $cacheKey = "provider-$source-$providerId-$resolveReferences";
14
15        if (!$disableCache && App::$cache && App::$cache->has($cacheKey)) {
16            return App::$cache->get($cacheKey);
17        }
18
19        $this->testSource($source);
20        $query = new \BO\Zmsbackend\Provider\Repository\Provider(\BO\Zmsbackend\Query\Base::SELECT);
21        $query
22            ->setResolveLevel($resolveReferences)
23            ->addEntityMapping()
24            ->addResolvedReferences($resolveReferences)
25            ->addConditionProviderSource($source)
26            ->addConditionProviderId($providerId);
27        $provider = $this->fetchOne($query, new Entity());
28
29        if (App::$cache) {
30            App::$cache->set($cacheKey, $provider);
31        }
32
33        return $provider;
34    }
35
36    /** @psalm-api */
37    public function readEntityById(string|int $providerId, int $resolveReferences = 0, bool $disableCache = false)
38    {
39        $cacheKey = "provider-byid-$providerId-$resolveReferences";
40
41        if (!$disableCache && App::$cache && App::$cache->has($cacheKey)) {
42            return App::$cache->get($cacheKey);
43        }
44
45        $query = new \BO\Zmsbackend\Provider\Repository\Provider(\BO\Zmsbackend\Query\Base::SELECT);
46        $query
47            ->setResolveLevel($resolveReferences)
48            ->addEntityMapping()
49            ->addResolvedReferences($resolveReferences)
50            ->addConditionProviderId($providerId);
51        $provider = $this->fetchOne($query, new Entity());
52
53        if (App::$cache && $provider->hasId()) {
54            App::$cache->set($cacheKey, $provider);
55        }
56
57        return $provider;
58    }
59
60    /**
61     * @return array<string, string>
62     */
63    public function readSourceMapByIds(array $providerIds): array
64    {
65        if ($providerIds === []) {
66            return [];
67        }
68
69        $query = new \BO\Zmsbackend\Provider\Repository\Provider(\BO\Zmsbackend\Query\Base::SELECT);
70        $query
71            ->setResolveLevel(0)
72            ->addEntityMapping()
73            ->addConditionProviderIdList($providerIds);
74
75        $map = [];
76        foreach ($this->readCollection($query) as $provider) {
77            $map[(string) $provider->getId()] = (string) $provider->getSource();
78        }
79
80        return $map;
81    }
82
83    /**
84     * @SuppressWarnings(Param)
85     */
86    protected function readCollection(\BO\Zmsbackend\Provider\Repository\Provider $query): Collection
87    {
88        $providerList = new Collection();
89        $statement = $this->fetchStatement($query);
90        while ($providerData = $statement->fetch(\PDO::FETCH_ASSOC)) {
91            $entity = new Entity($query->postProcessJoins($providerData));
92            $providerList->addEntity($entity);
93        }
94        return $providerList;
95    }
96
97    /**
98     * @param null|true $isAssigned
99     *
100     */
101    public function readListBySource(string $source, int $resolveReferences = 0, bool|null $isAssigned = null, ?string $requestIdCsv = null)
102    {
103        $this->testSource($source);
104        $query = new \BO\Zmsbackend\Provider\Repository\Provider(\BO\Zmsbackend\Query\Base::SELECT);
105        $query->setDistinctSelect();
106        $query->setResolveLevel($resolveReferences);
107        $query->addEntityMapping();
108        $query->addConditionProviderSource($source);
109        if (null !== $isAssigned) {
110            $query->addConditionIsAssigned($isAssigned);
111        }
112        if (null !== $requestIdCsv) {
113            $query->addConditionRequestCsv($requestIdCsv, $source);
114        }
115        $providerList = $this->readCollection($query);
116        return ($providerList->count()) ? $providerList->sortById() : $providerList;
117    }
118
119    public function writeEntity(Entity $entity)
120    {
121        $this->writeDeleteEntity($entity->getId(), $entity->getSource());
122        $contact =  $entity->getContact();
123        if (! $contact->count()) {
124            throw new \BO\Zmsbackend\Provider\Exception\ProviderContactMissed();
125        }
126        $query = new \BO\Zmsbackend\Provider\Repository\Provider(\BO\Zmsbackend\Query\Base::INSERT);
127        $additionalData = $entity->getAdditionalData() ?? [];
128
129        $query->addValues([
130            'source' => $entity->getSource(),
131            'id' => $entity->getId(),
132            'name' => $entity->getName(),
133            'parent_id' => $entity->getParentId(),
134            'display_name' => $additionalData && isset($additionalData['displayName'])
135                ? $additionalData['displayName']
136                : $entity->getName(),
137            'contact__city' => $contact->getProperty('city'),
138            'contact__country' => $contact->getProperty('country'),
139            'contact__lat' => $contact->getProperty('lat', 0),
140            'contact__lon' => $contact->getProperty('lon', 0),
141            'contact__postalCode' => (string) $contact->getProperty('postalCode'),
142            'contact__region' => $contact->getProperty('region'),
143            'contact__street' => $contact->getProperty('street'),
144            'contact__streetNumber' => $contact->getProperty('streetNumber', '-'),
145            'link' =>  ($entity->getLink()) ? $entity->getLink() : '',
146            'data' => ($entity->getAdditionalData()) ? json_encode($entity->getAdditionalData()) : '{}'
147        ]);
148        $this->writeItem($query);
149
150        $this->removeCache($entity);
151
152        return $this->readEntity($entity->getSource(), $entity->getId(), 0, true);
153    }
154
155    public function writeListBySource(\BO\Zmsentities\Source $source)
156    {
157        $this->writeDeleteListBySource($source->getSource());
158        foreach ($source->getProviderList() as $provider) {
159            $this->writeEntity($provider);
160            $this->removeCache($provider);
161        }
162        return $this->readListBySource($source->getSource());
163    }
164
165    public function writeImportList(iterable $providerList, string $source = 'dldb')
166    {
167        foreach ($providerList as $provider) {
168            $this->writeImportEntity($provider, $source);
169        }
170        return $this->readListBySource($source, 1);
171    }
172
173    public function writeImportEntity(array|\BO\Zmsdldb\Entity\Location $provider, string $source = 'dldb')
174    {
175        if ($provider['address']['postal_code']) {
176            $geo = is_array($provider['geo'] ?? null) ? $provider['geo'] : null;
177            $query = new \BO\Zmsbackend\Provider\Repository\Provider(\BO\Zmsbackend\Query\Base::REPLACE);
178            $query->addValues([
179                'source' => $source,
180                'id' => $provider['id'],
181                'name' => $provider['name'],
182                'display_name' => $provider['displayName'] ?? $provider['name'],
183                'contact__city' => $provider['address']['city'],
184                'contact__country' => $provider['address']['city'],
185                'contact__lat' => is_array($geo) ? ($geo['lat'] ?? null) : null,
186                'contact__lon' => is_array($geo) ? ($geo['lon'] ?? null) : null,
187                'contact__postalCode' => (string) $provider['address']['postal_code'],
188                'contact__region' => $provider['address']['city'],
189                'contact__street' => $provider['address']['street'],
190                'contact__streetNumber' => $provider['address']['house_number'],
191                'link' => ('dldb' == $source)
192                    ? 'https://service.berlin.de/standort/' . $provider['id'] . '/'
193                    : ((isset($provider['link'])) ? $provider['link'] : ''),
194                'data' => json_encode($provider)
195            ]);
196            $this->writeItem($query);
197            $provider = $this->readEntity($source, $provider['id'], 0, true);
198        }
199        return $provider;
200    }
201
202    public function writeDeleteEntity(string|int $providerId, string $source): bool
203    {
204        $provider = $this->readEntity($source, $providerId);
205        $query = new \BO\Zmsbackend\Provider\Repository\Provider(\BO\Zmsbackend\Query\Base::DELETE);
206        $query->addConditionProviderId($providerId);
207        $query->addConditionProviderSource($source);
208        $this->removeCache($provider);
209        return $this->deleteItem($query);
210    }
211
212    public function writeDeleteListBySource(string $source): bool
213    {
214        $query = new \BO\Zmsbackend\Provider\Repository\Provider(\BO\Zmsbackend\Query\Base::DELETE);
215        $query->addConditionProviderSource($source);
216        return $this->deleteItem($query);
217    }
218
219    /**
220     * @return void
221     */
222    protected function testSource(string $source)
223    {
224        if (! (new \BO\Zmsbackend\Source\Service\Source())->readEntity($source)) {
225            throw new \BO\Zmsbackend\Source\Exception\UnknownDataSource();
226        }
227    }
228
229    /**
230     * @return void
231     */
232    public function removeCache(Entity $provider)
233    {
234        if (!App::$cache || !isset($provider->id)) {
235            return;
236        }
237
238        $source = $provider->getSource();
239        $providerId = $provider->getId();
240
241        foreach ([0, 1, 2] as $resolveReferences) {
242            foreach (
243                [
244                    "provider-$source-$providerId-$resolveReferences",
245                    "provider-byid-$providerId-$resolveReferences",
246                    "request-$source-$providerId-$resolveReferences",
247                ] as $key
248            ) {
249                if (App::$cache->has($key)) {
250                    App::$cache->delete($key);
251                }
252            }
253        }
254    }
255}