Completed
Pull Request — development (#813)
by
unknown
04:11
created

CachesRepository::fetchOneBy()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
nc 4
nop 1
dl 0
loc 23
rs 9.552
c 0
b 0
f 0
1
<?php
2
3
namespace Oc\Repository;
4
5
use DateTime;
6
use Doctrine\DBAL\Connection;
7
use Oc\Entity\GeoCachesEntity;
8
use Oc\Repository\Exception\RecordAlreadyExistsException;
9
use Oc\Repository\Exception\RecordNotFoundException;
10
use Oc\Repository\Exception\RecordNotPersistedException;
11
use Oc\Repository\Exception\RecordsNotFoundException;
12
13
/**
14
 * Class CachesRepository
15
 *
16
 * @package Oc\Repository
17
 */
18
class CachesRepository
19
{
20
    const TABLE = 'caches';
21
22
    /** @var Connection */
23
    private $connection;
24
25
    /**
26
     * @var CacheSizeRepository
27
     */
28
    private $cacheSizeRepository;
29
30
    /**
31
     * @var CacheStatusRepository
32
     */
33
    private $cacheStatusRepository;
34
35
    /**
36
     * @var CacheTypeRepository
37
     */
38
    private $cacheTypeRepository;
39
40
    /**
41
     * @var UserRepository
42
     */
43
    private $userRepository;
44
45
    /**
46
     * CachesRepository constructor.
47
     *
48
     * @param Connection $connection
49
     * @param UserRepository $userRepository
50
     * @param CacheSizeRepository $cacheSizeRepository
51
     * @param CacheStatusRepository $cacheStatusRepository
52
     * @param CacheTypeRepository $cacheTypeRepository
53
     */
54
    public function __construct(
55
        Connection $connection,
56
        UserRepository $userRepository,
57
        CacheSizeRepository $cacheSizeRepository,
58
        CacheStatusRepository $cacheStatusRepository,
59
        CacheTypeRepository $cacheTypeRepository
60
    ) {
61
        $this->connection = $connection;
62
        $this->userRepository = $userRepository;
63
        $this->cacheSizeRepository = $cacheSizeRepository;
64
        $this->cacheStatusRepository = $cacheStatusRepository;
65
        $this->cacheTypeRepository = $cacheTypeRepository;
66
    }
67
68
    /**
69
     * @return array
70
     * @throws RecordsNotFoundException
71
     */
72
    public function fetchAll()
73
    : array
74
    {
75
        $statement = $this->connection->createQueryBuilder()
76
            ->select('*')
77
            ->from(self::TABLE)
78
            ->execute();
79
80
        $result = $statement->fetchAll();
81
82
        if ($statement->rowCount() === 0) {
83
            throw new RecordsNotFoundException('No records found');
84
        }
85
86
        $records = [];
87
88
        foreach ($result as $item) {
89
            $records[] = $this->getEntityFromDatabaseArray($item);
90
        }
91
92
        return $records;
93
    }
94
95
    /**
96
     * @param array $where
97
     *
98
     * @return GeoCachesEntity
99
     * @throws RecordNotFoundException
100
     */
101
    public function fetchOneBy(array $where = [])
102
    : GeoCachesEntity {
103
        $queryBuilder = $this->connection->createQueryBuilder()
104
            ->select('*')
105
            ->from(self::TABLE)
106
            ->setMaxResults(1);
107
108
        if (count($where) > 0) {
109
            foreach ($where as $column => $value) {
110
                $queryBuilder->andWhere($column . ' = ' . $queryBuilder->createNamedParameter($value));
111
            }
112
        }
113
114
        $statement = $queryBuilder->execute();
115
116
        $result = $statement->fetch();
117
118
        if ($statement->rowCount() === 0) {
119
            throw new RecordNotFoundException('Record with given where clause not found');
120
        }
121
122
        return $this->getEntityFromDatabaseArray($result);
123
    }
124
125
    /**
126
     * @param array $where
127
     *
128
     * @return array
129
     * @throws RecordsNotFoundException
130
     */
131
    public function fetchBy(array $where = [])
132
    : array {
133
        $entities = [];
134
135
        $queryBuilder = $this->connection->createQueryBuilder()
136
            ->select('*')
137
            ->from(self::TABLE);
138
139
        if (count($where) > 0) {
140
            foreach ($where as $column => $value) {
141
                $queryBuilder->orWhere($column . ' = ' . $queryBuilder->createNamedParameter($value));
142
            }
143
        }
144
145
        $statement = $queryBuilder->execute();
146
147
        $result = $statement->fetchAll();
148
149
        if ($statement->rowCount() === 0) {
150
            throw new RecordsNotFoundException('No records with given where clause found');
151
        } else {
152
            foreach ($result as $item) {
153
                $entities[] = $this->getEntityFromDatabaseArray($item);
154
            }
155
        }
156
157
        return $entities;
158
    }
159
160
    /**
161
     * @param GeoCachesEntity $entity
162
     *
163
     * @return GeoCachesEntity
164
     * @throws RecordAlreadyExistsException
165
     * @throws \Doctrine\DBAL\DBALException
166
     */
167
    public function create(GeoCachesEntity $entity)
168
    : GeoCachesEntity {
169
        if (!$entity->isNew()) {
170
            throw new RecordAlreadyExistsException('The entity does already exist.');
171
        }
172
173
        $databaseArray = $this->getDatabaseArrayFromEntity($entity);
174
175
        $this->connection->insert(
176
            self::TABLE,
177
            $databaseArray
178
        );
179
180
        $entity->cacheId = (int) $this->connection->lastInsertId();
181
182
        return $entity;
183
    }
184
185
    /**
186
     * @param GeoCachesEntity $entity
187
     *
188
     * @return GeoCachesEntity
189
     * @throws \Doctrine\DBAL\DBALException
190
     */
191
    public function update(GeoCachesEntity $entity)
192
    : GeoCachesEntity {
193
        if ($entity->isNew()) {
194
            throw new RecordNotPersistedException('The entity does not exist.');
195
        }
196
197
        $databaseArray = $this->getDatabaseArrayFromEntity($entity);
198
199
        $this->connection->update(self::TABLE, $databaseArray, ['cache_id' => $entity->cacheId]);
200
201
        return $entity;
202
    }
203
204
    /**
205
     * @param GeoCachesEntity $entity
206
     *
207
     * @return GeoCachesEntity
208
     * @throws \Doctrine\DBAL\DBALException
209
     * @throws \Doctrine\DBAL\Exception\InvalidArgumentException
210
     */
211
    public function remove(GeoCachesEntity $entity)
212
    : GeoCachesEntity {
213
        if ($entity->isNew()) {
214
            throw new RecordNotPersistedException('The entity does not exist.');
215
        }
216
217
        $this->connection->delete(self::TABLE, ['cache_id' => $entity->cacheId]);
218
219
        $entity->cacheId = null;
220
221
        return $entity;
222
    }
223
224
    /**
225
     * @param string $wp
226
     *
227
     * @return int
228
     * @throws RecordNotFoundException
229
     */
230
    public function getIdByWP(string $wp = '')
231
    : int {
232
        $queryBuilder = $this->connection->createQueryBuilder()
233
            ->select('*')
234
            ->from(self::TABLE)
235
            ->setMaxResults(1);
236
237
        if ($wp != '') {
238
            $queryBuilder->where('wp_oc = ' . $queryBuilder->createNamedParameter($wp));
239
            $queryBuilder->orWhere('wp_gc = ' . $queryBuilder->createNamedParameter($wp));
240
        }
241
242
        $statement = $queryBuilder->execute();
243
244
        $result = $statement->fetch();
245
246
        if ($statement->rowCount() === 0) {
247
            throw new RecordNotFoundException('Record with given where clause not found');
248
        } else {
249
            return $result['cache_id'];
250
        }
251
    }
252
253
    /**
254
     * @param GeoCachesEntity $entity
255
     *
256
     * @return array
257
     */
258
    public function getDatabaseArrayFromEntity(GeoCachesEntity $entity)
259
    : array {
260
        return [
261
            'cache_id' => $entity->cacheId,
262
            'uuid' => $entity->uuid,
263
            'node' => $entity->node,
264
            'date_created' => $entity->dateCreated,
265
            'is_publishdate' => $entity->isPublishdate,
266
            'last_modified' => $entity->lastModified,
267
            'okapi_syncbase' => $entity->okapiSyncbase,
268
            'listing_last_modified' => $entity->listingLastModified,
269
            'meta_last_modified' => $entity->metaLastModified,
270
            'user_id' => $entity->userId,
271
            'name' => $entity->name,
272
            'longitude' => $entity->longitude,
273
            'latitude' => $entity->latitude,
274
            'type' => $entity->type,
275
            'status' => $entity->status,
276
            'country' => $entity->country,
277
            'date_hidden' => $entity->dateHidden,
278
            'size' => $entity->size,
279
            'difficulty' => $entity->difficulty,
280
            'terrain' => $entity->terrain,
281
            'logpw' => $entity->logpw,
282
            'search_time' => $entity->searchTime,
283
            'way_length' => $entity->wayLength,
284
            'wp_gc' => $entity->wpGc,
285
            'wp_gc_maintained' => $entity->wpGcMaintained,
286
            'wp_nc' => $entity->wpNc,
287
            'wp_oc' => $entity->wpOc,
288
            'desc_languages' => $entity->descLanguages,
289
            'default_desclang' => $entity->defaultDesclang,
290
            'date_activate' => $entity->dateActivate,
291
            'need_npa_recalc' => $entity->needNpaRecalc,
292
            'show_cachelists' => $entity->showCachelists,
293
            'protect_old_coords' => $entity->protectOldCoords,
294
            'needs_maintenance' => $entity->needsMaintenance,
295
            'listing_outdated' => $entity->listingOutdated,
296
            'flags_last_modified' => $entity->flagsLastModified,
297
            'cache_size' => $entity->cacheSize,
298
            'cache_status' => $entity->cacheStatus,
299
            'cache_type' => $entity->cacheType,
300
            'user' => $entity->user,
301
        ];
302
    }
303
304
    /**
305
     * @param array $data
306
     *
307
     * @return GeoCachesEntity
308
     * @throws \Exception
309
     */
310
    public function getEntityFromDatabaseArray(array $data)
311
    : GeoCachesEntity {
312
        $entity = new GeoCachesEntity();
313
314
        $entity->cacheId = (int) $data['cache_id'];
315
        $entity->uuid = (string) $data['uuid'];
316
        $entity->node = (int) $data['node'];
317
        $entity->dateCreated = new DateTime($data['date_created']);
318
        $entity->isPublishdate = (int) $data['is_publishdate'];
319
        $entity->lastModified = new DateTime($data['last_modified']);
320
        $entity->okapiSyncbase = (string) $data['okapi_syncbase'];
321
        $entity->listingLastModified = new DateTime($data['listing_last_modified']);
322
        $entity->metaLastModified = new DateTime($data['meta_last_modified']);
323
        $entity->userId = (int) $data['user_id'];
324
        $entity->name = (string) $data['name'];
325
        $entity->longitude = $data['longitude'];
326
        $entity->latitude = $data['latitude'];
327
        $entity->type = (int) $data['type'];
328
        $entity->status = (int) $data['status'];
329
        $entity->country = (string) $data['country'];
330
        $entity->dateHidden = new DateTime($data['date_hidden']);
331
        $entity->size = (int) $data['size'];
332
        $entity->difficulty = (float) $data['difficulty'] / 2;
0 ignored issues
show
Documentation Bug introduced by
The property $difficulty was declared of type integer, but (double) $data['difficulty'] / 2 is of type double. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
333
        $entity->terrain = (float) $data['terrain'] / 2;
0 ignored issues
show
Documentation Bug introduced by
The property $terrain was declared of type integer, but (double) $data['terrain'] / 2 is of type double. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
334
        //        $entity->logpw = (string) $data['logpw'];
335
        $entity->logpw = ($data['logpw'] == '') ? '' : '1';
336
        $entity->searchTime = $data['search_time'];
337
        $entity->wayLength = $data['way_length'];
338
        $entity->wpGc = (string) $data['wp_gc'];
339
        $entity->wpGcMaintained = (string) $data['wp_gc_maintained'];
340
        $entity->wpNc = (string) $data['wp_nc'];
341
        $entity->wpOc = (string) $data['wp_oc'];
342
        $entity->descLanguages = (string) $data['desc_languages'];
343
        $entity->defaultDesclang = (string) $data['default_desclang'];
344
        $entity->dateActivate = new DateTime($data['date_activate']);
345
        $entity->needNpaRecalc = (int) $data['need_npa_recalc'];
346
        $entity->showCachelists = (int) $data['show_cachelists'];
347
        $entity->protectOldCoords = (int) $data['protect_old_coords'];
348
        $entity->needsMaintenance = (int) $data['needs_maintenance'];
349
        $entity->listingOutdated = (int) $data['listing_outdated'];
350
        $entity->flagsLastModified = new DateTime($data['flags_last_modified']);
351
        $entity->cacheSize = $this->cacheSizeRepository->fetchOneBy(['id' => $entity->size]);
352
        $entity->cacheStatus = $this->cacheStatusRepository->fetchOneBy(['id' => $entity->status]);
353
        $entity->cacheType = $this->cacheTypeRepository->fetchOneBy(['id' => $entity->type]);
354
        $entity->user = $this->userRepository->fetchOneById($entity->userId);
355
356
        return $entity;
357
    }
358
}
359