Completed
Pull Request — development (#812)
by
unknown
04:32
created

CachesRepository::fetchBy()   A

Complexity

Conditions 5
Paths 4

Size

Total Lines 28

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
nc 4
nop 1
dl 0
loc 28
rs 9.1608
c 0
b 0
f 0
1
<?php
2
3
namespace Oc\Repository;
4
5
use Doctrine\DBAL\Connection;
6
use Oc\Entity\CachesEntity;
7
use Oc\Repository\Exception\RecordAlreadyExistsException;
8
use Oc\Repository\Exception\RecordNotFoundException;
9
use Oc\Repository\Exception\RecordNotPersistedException;
10
use Oc\Repository\Exception\RecordsNotFoundException;
11
12
class CachesRepository
13
{
14
    const TABLE = 'caches';
15
16
    /** @var Connection */
17
    private $connection;
18
19
    public function __construct(Connection $connection)
20
    {
21
        $this->connection = $connection;
22
    }
23
24
    /**
25
     * @return CachesEntity[]
26
     */
27
    public function fetchAll()
28
    {
29
        $statement = $this->connection->createQueryBuilder()
30
            ->select('*')
31
            ->from(self::TABLE)
32
            ->execute();
33
34
        $result = $statement->fetchAll();
35
36
        if ($statement->rowCount() === 0) {
37
            throw new RecordsNotFoundException('No records found');
38
        }
39
40
        $records = [];
41
42
        foreach ($result as $item) {
43
            $records[] = $this->getEntityFromDatabaseArray($item);
44
        }
45
46
        return $records;
47
    }
48
49
    /**
50
     * @return CachesEntity
51
     */
52
    public function fetchOneBy(array $where = [])
53
    {
54
        $queryBuilder = $this->connection->createQueryBuilder()
55
            ->select('*')
56
            ->from(self::TABLE)
57
            ->setMaxResults(1);
58
59
        if (count($where) > 0) {
60
            foreach ($where as $column => $value) {
61
                $queryBuilder->andWhere($column . ' = ' . $queryBuilder->createNamedParameter($value));
62
            }
63
        }
64
65
        $statement = $queryBuilder->execute();
66
67
        $result = $statement->fetch();
68
69
        if ($statement->rowCount() === 0) {
70
            //            throw new RecordNotFoundException('Record with given where clause not found');
71
        } else {
72
            return $this->getEntityFromDatabaseArray($result);
73
        }
74
    }
75
76
    /**
77
     * @return CachesEntity[]
78
     */
79
    public function fetchBy(array $where = [])
80
    {
81
        $entities = [];
82
83
        $queryBuilder = $this->connection->createQueryBuilder()
84
            ->select('*')
85
            ->from(self::TABLE);
86
87
        if (count($where) > 0) {
88
            foreach ($where as $column => $value) {
89
                $queryBuilder->orWhere($column . ' = ' . $queryBuilder->createNamedParameter($value));
90
            }
91
        }
92
93
        $statement = $queryBuilder->execute();
94
95
        $result = $statement->fetchAll();
96
97
        if ($statement->rowCount() === 0) {
98
            //            throw new RecordsNotFoundException('No records with given where clause found');
99
        } else {
100
            foreach ($result as $item) {
101
                $entities[] = $this->getEntityFromDatabaseArray($item);
102
            }
103
        }
104
105
        return $entities;
106
    }
107
108
    /**
109
     * @return CachesEntity
110
     */
111
    public function create(GeoCachesEntity $entity)
112
    {
113
        if (!$entity->isNew()) {
114
            throw new RecordAlreadyExistsException('The entity does already exist.');
115
        }
116
117
        $databaseArray = $this->getDatabaseArrayFromEntity($entity);
118
119
        $this->connection->insert(
120
            self::TABLE,
121
            $databaseArray
122
        );
123
124
        $entity->cacheId = (int) $this->connection->lastInsertId();
125
126
        return $entity;
127
    }
128
129
    /**
130
     * @return CachesEntity
131
     */
132
    public function update(GeoCachesEntity $entity)
133
    {
134
        if ($entity->isNew()) {
135
            throw new RecordNotPersistedException('The entity does not exist.');
136
        }
137
138
        $databaseArray = $this->getDatabaseArrayFromEntity($entity);
139
140
        $this->connection->update(
141
            self::TABLE,
142
            $databaseArray,
143
            ['cache_id' => $entity->cacheId]
144
        );
145
146
        return $entity;
147
    }
148
149
    /**
150
     * @return CachesEntity
151
     */
152
    public function remove(GeoCachesEntity $entity)
153
    {
154
        if ($entity->isNew()) {
155
            throw new RecordNotPersistedException('The entity does not exist.');
156
        }
157
158
        $this->connection->delete(
159
            self::TABLE,
160
            ['cache_id' => $entity->cacheId]
161
        );
162
163
        $entity->cacheId = null;
164
165
        return $entity;
166
    }
167
168
    /**
169
     * @return CachesEntity
170
     */
171
    public function getIdByWP(string $wp = '')
172
    {
173
        $queryBuilder = $this->connection->createQueryBuilder()
174
            ->select('*')
175
            ->from(self::TABLE)
176
            ->setMaxResults(1);
177
178
        if ($wp != '') {
179
            $queryBuilder->where('wp_oc = ' . $queryBuilder->createNamedParameter($wp));
180
            $queryBuilder->orWhere('wp_gc = ' . $queryBuilder->createNamedParameter($wp));
181
        }
182
183
        $statement = $queryBuilder->execute();
184
185
        $result = $statement->fetch();
186
187
        if ($statement->rowCount() === 0) {
188
            //            throw new RecordNotFoundException('Record with given where clause not found');
189
        } else {
190
            return $result['cache_id'];
191
        }
192
    }
193
194
    /**
195
     * @return []
0 ignored issues
show
Documentation introduced by
The doc-type [] could not be parsed: Unknown type name "" at position 0. [(view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
196
     */
197 View Code Duplication
    public function getDatabaseArrayFromEntity(GeoCachesEntity $entity)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
198
    {
199
        return [
200
            'cache_id' => $entity->cacheId,
201
            'uuid' => $entity->uuid,
202
            'node' => $entity->node,
203
            'date_created' => $entity->dateCreated,
204
            'is_publishdate' => $entity->isPublishdate,
205
            'last_modified' => $entity->lastModified,
206
            'okapi_syncbase' => $entity->okapiSyncbase,
207
            'listing_last_modified' => $entity->listingLastModified,
208
            'meta_last_modified' => $entity->metaLastModified,
209
            'user_id' => $entity->userId,
210
            'name' => $entity->name,
211
            'longitude' => $entity->longitude,
212
            'latitude' => $entity->latitude,
213
            'type' => $entity->type,
214
            'status' => $entity->status,
215
            'country' => $entity->country,
216
            'date_hidden' => $entity->dateHidden,
217
            'size' => $entity->size,
218
            'difficulty' => $entity->difficulty,
219
            'terrain' => $entity->terrain,
220
            'logpw' => $entity->logpw,
221
            'search_time' => $entity->searchTime,
222
            'way_length' => $entity->wayLength,
223
            'wp_gc' => $entity->wpGc,
224
            'wp_gc_maintained' => $entity->wpGcMaintained,
225
            'wp_nc' => $entity->wpNc,
226
            'wp_oc' => $entity->wpOc,
227
            'desc_languages' => $entity->descLanguages,
228
            'default_desclang' => $entity->defaultDesclang,
229
            'date_activate' => $entity->dateActivate,
230
            'need_npa_recalc' => $entity->needNpaRecalc,
231
            'show_cachelists' => $entity->showCachelists,
232
            'protect_old_coords' => $entity->protectOldCoords,
233
            'needs_maintenance' => $entity->needsMaintenance,
234
            'listing_outdated' => $entity->listingOutdated,
235
            'flags_last_modified' => $entity->flagsLastModified,
236
        ];
237
    }
238
239
    /**
240
     * @return CachesEntity
241
     */
242 View Code Duplication
    public function getEntityFromDatabaseArray(array $data)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
243
    {
244
        $entity = new CachesEntity();
245
246
        $entity->cacheId = (int) $data['cache_id'];
247
        $entity->uuid = (string) $data['uuid'];
248
        $entity->node = (int) $data['node'];
249
        $entity->dateCreated = new DateTime($data['date_created']);
0 ignored issues
show
Documentation Bug introduced by
It seems like new \Oc\Repository\DateT...($data['date_created']) of type object<Oc\Repository\DateTime> is incompatible with the declared type object<Oc\Entity\DateTime> of property $dateCreated.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
250
        $entity->isPublishdate = (int) $data['is_publishdate'];
251
        $entity->lastModified = new DateTime($data['last_modified']);
0 ignored issues
show
Documentation Bug introduced by
It seems like new \Oc\Repository\DateT...$data['last_modified']) of type object<Oc\Repository\DateTime> is incompatible with the declared type object<Oc\Entity\DateTime> of property $lastModified.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
252
        $entity->okapiSyncbase = (string) $data['okapi_syncbase'];
253
        $entity->listingLastModified = new DateTime($data['listing_last_modified']);
0 ignored issues
show
Documentation Bug introduced by
It seems like new \Oc\Repository\DateT...isting_last_modified']) of type object<Oc\Repository\DateTime> is incompatible with the declared type object<Oc\Entity\DateTime> of property $listingLastModified.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
254
        $entity->metaLastModified = new DateTime($data['meta_last_modified']);
0 ignored issues
show
Documentation Bug introduced by
It seems like new \Oc\Repository\DateT...['meta_last_modified']) of type object<Oc\Repository\DateTime> is incompatible with the declared type object<Oc\Entity\DateTime> of property $metaLastModified.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
255
        $entity->userId = (int) $data['user_id'];
256
        $entity->name = (string) $data['name'];
257
        $entity->longitude = $data['longitude'];
258
        $entity->latitude = $data['latitude'];
259
        $entity->type = (int) $data['type'];
260
        $entity->status = (int) $data['status'];
261
        $entity->country = (string) $data['country'];
262
        $entity->dateHidden = new DateTime($data['date_hidden']);
0 ignored issues
show
Documentation Bug introduced by
It seems like new \Oc\Repository\DateTime($data['date_hidden']) of type object<Oc\Repository\DateTime> is incompatible with the declared type object<Oc\Entity\DateTime> of property $dateHidden.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
263
        $entity->size = (int) $data['size'];
264
        $entity->difficulty = (int) $data['difficulty'];
265
        $entity->terrain = (int) $data['terrain'];
266
        $entity->logpw = (string) $data['logpw'];
267
        $entity->searchTime = $data['search_time'];
268
        $entity->wayLength = $data['way_length'];
269
        $entity->wpGc = (string) $data['wp_gc'];
270
        $entity->wpGcMaintained = (string) $data['wp_gc_maintained'];
271
        $entity->wpNc = (string) $data['wp_nc'];
272
        $entity->wpOc = (string) $data['wp_oc'];
273
        $entity->descLanguages = (string) $data['desc_languages'];
274
        $entity->defaultDesclang = (string) $data['default_desclang'];
275
        $entity->dateActivate = new DateTime($data['date_activate']);
0 ignored issues
show
Documentation Bug introduced by
It seems like new \Oc\Repository\DateT...$data['date_activate']) of type object<Oc\Repository\DateTime> is incompatible with the declared type object<Oc\Entity\DateTime> of property $dateActivate.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
276
        $entity->needNpaRecalc = (int) $data['need_npa_recalc'];
277
        $entity->showCachelists = (int) $data['show_cachelists'];
278
        $entity->protectOldCoords = (int) $data['protect_old_coords'];
279
        $entity->needsMaintenance = (int) $data['needs_maintenance'];
280
        $entity->listingOutdated = (int) $data['listing_outdated'];
281
        $entity->flagsLastModified = new DateTime($data['flags_last_modified']);
0 ignored issues
show
Documentation Bug introduced by
It seems like new \Oc\Repository\DateT...'flags_last_modified']) of type object<Oc\Repository\DateTime> is incompatible with the declared type object<Oc\Entity\DateTime> of property $flagsLastModified.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
282
283
        return $entity;
284
    }
285
}
286