Lines 88.28% 226 / 256
Methods 84.37% 27 / 32
Classes 0.00% 0 / 1
Name Lines Methods CRAP
 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% 23 / 23 100.00% 1 / 1 4
 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
 [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
9class Provider extends \BO\Zmsbackend\Base
10{
11    public function readEntity($source, $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($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($source, int $resolveReferences = 0, bool|null $isAssigned = null, $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($providerList, $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($provider, $source = 'dldb')
174    {
175        if ($provider['address']['postal_code']) {
176            $query = new \BO\Zmsbackend\Provider\Repository\Provider(\BO\Zmsbackend\Query\Base::REPLACE);
177            $query->addValues([
178                'source' => $source,
179                'id' => $provider['id'],
180                'name' => $provider['name'],
181                'display_name' => $provider['displayName'] ?? $provider['name'],
182                'contact__city' => $provider['address']['city'],
183                'contact__country' => $provider['address']['city'],
184                'contact__lat' => $provider['geo']['lat'],
185                'contact__lon' => $provider['geo']['lon'],
186                'contact__postalCode' => (string) $provider['address']['postal_code'],
187                'contact__region' => $provider['address']['city'],
188                'contact__street' => $provider['address']['street'],
189                'contact__streetNumber' => $provider['address']['house_number'],
190                'link' => ('dldb' == $source)
191                    ? 'https://service.berlin.de/standort/' . $provider['id'] . '/'
192                    : ((isset($provider['link'])) ? $provider['link'] : ''),
193                'data' => json_encode($provider)
194            ]);
195            $this->writeItem($query);
196            $provider = $this->readEntity($source, $provider['id'], 0, true);
197        }
198        return $provider;
199    }
200
201    public function writeDeleteEntity($providerId, $source): bool
202    {
203        $provider = $this->readEntity($source, $providerId);
204        $query = new \BO\Zmsbackend\Provider\Repository\Provider(\BO\Zmsbackend\Query\Base::DELETE);
205        $query->addConditionProviderId($providerId);
206        $query->addConditionProviderSource($source);
207        $this->removeCache($provider);
208        return $this->deleteItem($query);
209    }
210
211    public function writeDeleteListBySource(string $source): bool
212    {
213        $query = new \BO\Zmsbackend\Provider\Repository\Provider(\BO\Zmsbackend\Query\Base::DELETE);
214        $query->addConditionProviderSource($source);
215        return $this->deleteItem($query);
216    }
217
218    /**
219     * @return void
220     */
221    protected function testSource($source)
222    {
223        if (! (new \BO\Zmsbackend\Source\Service\Source())->readEntity($source)) {
224            throw new \BO\Zmsbackend\Source\Exception\UnknownDataSource();
225        }
226    }
227
228    /**
229     * @return void
230     */
231    public function removeCache(Entity $provider)
232    {
233        if (!App::$cache || !isset($provider->id)) {
234            return;
235        }
236
237        $source = $provider->getSource();
238        $providerId = $provider->getId();
239
240        foreach ([0, 1, 2] as $resolveReferences) {
241            foreach (
242                [
243                    "provider-$source-$providerId-$resolveReferences",
244                    "provider-byid-$providerId-$resolveReferences",
245                    "request-$source-$providerId-$resolveReferences",
246                ] as $key
247            ) {
248                if (App::$cache->has($key)) {
249                    App::$cache->delete($key);
250                }
251            }
252        }
253    }
254}

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    }