Completed
Pull Request — development (#720)
by Thomas
24:05
created

CachesRepository::fetchBy()   A

Complexity

Conditions 5
Paths 6

Size

Total Lines 28

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
nc 6
nop 1
dl 0
loc 28
rs 9.1608
c 0
b 0
f 0
1
<?php 
2
3
use Doctrine\DBAL\Connection;
4
use Oc\Repository\Exception\RecordAlreadyExistsException;
5
use Oc\Repository\Exception\RecordNotFoundException;
6
use Oc\Repository\Exception\RecordNotPersistedException;
7
use Oc\Repository\Exception\RecordsNotFoundException;
8
9
class CachesRepository
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
10
{
11
    const TABLE = 'caches';
12
13
    /** @var Connection */
14
    private $connection;
15
16
    public function __construct(Connection $connection)
17
    {
18
        $this->connection = $connection;
19
    }
20
21
    /**
22
     * @return GeoCachesEntity[]
23
     */
24
    public function fetchAll()
25
    {
26
        $statement = $this->connection->createQueryBuilder()
27
                    ->select('*')
28
                    ->from(self::TABLE)
29
                    ->execute();
30
31
        $result = $statement->fetchAll();
32
33
        if ($statement->rowCount() === 0) {
34
            throw new RecordsNotFoundException('No records found');
35
        }
36
37
        $records = [];
38
39
        foreach ($result as $item) {
40
            $records[] = $this->getEntityFromDatabaseArray($item);
41
        }
42
43
        return $records;
44
    }
45
46
    /**
47
     * @param array $where
48
     * @return GeoCachesEntity
49
     */
50
    public function fetchOneBy(array $where = [])
51
    {
52
        $queryBuilder = $this->connection->createQueryBuilder()
53
                     ->select('*')
54
                     ->from(self::TABLE)
55
                     ->setMaxResults(1);
56
57
        if (count($where) > 0) {
58
            foreach ($where as $column => $value) {
59
                $queryBuilder->andWhere($column . ' = ' . $queryBuilder->createNamedParameter($value));
60
            }
61
        }
62
63
        $statement = $queryBuilder->execute();
64
65
        $result = $statement->fetch();
66
67
        if ($statement->rowCount() === 0) {
68
            throw new RecordNotFoundException('Record with given where clause not found');
69
        }
70
71
        return $this->getEntityFromDatabaseArray($result);
72
    }
73
74
    /**
75
     * @param array $where
76
     * @return GeoCachesEntity[]
77
     */
78
    public function fetchBy(array $where = [])
79
    {
80
        $queryBuilder = $this->connection->createQueryBuilder()
81
                     ->select('*')
82
                     ->from(self::TABLE);
83
84
        if (count($where) > 0) {
85
            foreach ($where as $column => $value) {
86
                $queryBuilder->andWhere($column . ' = ' . $queryBuilder->createNamedParameter($value));
87
            }
88
        }
89
90
        $statement = $queryBuilder->execute();
91
92
        $result = $statement->fetchAll();
93
94
        if ($statement->rowCount() === 0) {
95
            throw new RecordsNotFoundException('No records with given where clause found');
96
        }
97
98
        $entities = [];
99
100
        foreach ($result as $item) {
101
            $entities[] = $this->getEntityFromDatabaseArray($item);
102
        }
103
104
        return $entities;
105
    }
106
107
    /**
108
     * @param GeoCachesEntity $entity
109
     * @return GeoCachesEntity
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
     * @param GeoCachesEntity $entity
131
     * @return GeoCachesEntity
132
     */
133
    public function update(GeoCachesEntity $entity)
134
    {
135
        if ($entity->isNew()) {
136
            throw new RecordNotPersistedException('The entity does not exist.');
137
        }
138
139
        $databaseArray = $this->getDatabaseArrayFromEntity($entity);
140
141
        $this->connection->update(
142
                    self::TABLE,
143
                    $databaseArray,
144
                    ['cache_id' => $entity->cacheId]
145
                );
146
147
        return $entity;
148
    }
149
150
    /**
151
     * @param GeoCachesEntity $entity
152
     * @return GeoCachesEntity
153
     */
154
    public function remove(GeoCachesEntity $entity)
155
    {
156
        if ($entity->isNew()) {
157
            throw new RecordNotPersistedException('The entity does not exist.');
158
        }
159
160
        $this->connection->delete(
161
                    self::TABLE,
162
                    ['cache_id' => $entity->cacheId]
163
                );
164
165
        $entity->cacheId = null;
166
167
        return $entity;
168
    }
169
170
    /**
171
     * @param GeoCachesEntity $entity
172
     * @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...
173
     */
174
    public function getDatabaseArrayFromEntity(GeoCachesEntity $entity)
175
    {
176
        return [
177
        'cache_id' => $entity->cacheId,
178
        'uuid' => $entity->uuid,
179
        'node' => $entity->node,
180
        'date_created' => $entity->dateCreated,
181
        'is_publishdate' => $entity->isPublishdate,
182
        'last_modified' => $entity->lastModified,
183
        'okapi_syncbase' => $entity->okapiSyncbase,
184
        'listing_last_modified' => $entity->listingLastModified,
185
        'meta_last_modified' => $entity->metaLastModified,
186
        'user_id' => $entity->userId,
187
        'name' => $entity->name,
188
        'longitude' => $entity->longitude,
189
        'latitude' => $entity->latitude,
190
        'type' => $entity->type,
191
        'status' => $entity->status,
192
        'country' => $entity->country,
193
        'date_hidden' => $entity->dateHidden,
194
        'size' => $entity->size,
195
        'difficulty' => $entity->difficulty,
196
        'terrain' => $entity->terrain,
197
        'logpw' => $entity->logpw,
198
        'search_time' => $entity->searchTime,
199
        'way_length' => $entity->wayLength,
200
        'wp_gc' => $entity->wpGc,
201
        'wp_gc_maintained' => $entity->wpGcMaintained,
202
        'wp_nc' => $entity->wpNc,
203
        'wp_oc' => $entity->wpOc,
204
        'desc_languages' => $entity->descLanguages,
205
        'default_desclang' => $entity->defaultDesclang,
206
        'date_activate' => $entity->dateActivate,
207
        'need_npa_recalc' => $entity->needNpaRecalc,
208
        'show_cachelists' => $entity->showCachelists,
209
        'protect_old_coords' => $entity->protectOldCoords,
210
        'needs_maintenance' => $entity->needsMaintenance,
211
        'listing_outdated' => $entity->listingOutdated,
212
        'flags_last_modified' => $entity->flagsLastModified,
213
        ];
214
    }
215
216
    /**
217
     * @param array $data
218
     * @return GeoCachesEntity
219
     */
220
    public function getEntityFromDatabaseArray(array $data)
221
    {
222
        $entity = new GeoCachesEntity();
223
        $entity->cacheId = (int) $data['cache_id'];
224
        $entity->uuid = (string) $data['uuid'];
225
        $entity->node = (int) $data['node'];
226
        $entity->dateCreated =  new DateTime($data['date_created']);
227
        $entity->isPublishdate = (int) $data['is_publishdate'];
228
        $entity->lastModified =  new DateTime($data['last_modified']);
229
        $entity->okapiSyncbase = (string) $data['okapi_syncbase'];
230
        $entity->listingLastModified =  new DateTime($data['listing_last_modified']);
231
        $entity->metaLastModified =  new DateTime($data['meta_last_modified']);
232
        $entity->userId = (int) $data['user_id'];
233
        $entity->name = (string) $data['name'];
234
        $entity->longitude = $data['longitude'];
235
        $entity->latitude = $data['latitude'];
236
        $entity->type = (int) $data['type'];
237
        $entity->status = (int) $data['status'];
238
        $entity->country = (string) $data['country'];
239
        $entity->dateHidden =  new DateTime($data['date_hidden']);
240
        $entity->size = (int) $data['size'];
241
        $entity->difficulty = (int) $data['difficulty'];
242
        $entity->terrain = (int) $data['terrain'];
243
        $entity->logpw = (string) $data['logpw'];
244
        $entity->searchTime = $data['search_time'];
245
        $entity->wayLength = $data['way_length'];
246
        $entity->wpGc = (string) $data['wp_gc'];
247
        $entity->wpGcMaintained = (string) $data['wp_gc_maintained'];
248
        $entity->wpNc = (string) $data['wp_nc'];
249
        $entity->wpOc = (string) $data['wp_oc'];
250
        $entity->descLanguages = (string) $data['desc_languages'];
251
        $entity->defaultDesclang = (string) $data['default_desclang'];
252
        $entity->dateActivate =  new DateTime($data['date_activate']);
253
        $entity->needNpaRecalc = (int) $data['need_npa_recalc'];
254
        $entity->showCachelists = (int) $data['show_cachelists'];
255
        $entity->protectOldCoords = (int) $data['protect_old_coords'];
256
        $entity->needsMaintenance = (int) $data['needs_maintenance'];
257
        $entity->listingOutdated = (int) $data['listing_outdated'];
258
        $entity->flagsLastModified =  new DateTime($data['flags_last_modified']);
259
260
        return $entity;
261
    }
262
}
263