Passed
Pull Request — development (#682)
by Nick
07:18
created

GeoCacheLogRepository::fetchBy()   B

Complexity

Conditions 5
Paths 6

Size

Total Lines 28
Code Lines 15

Duplication

Lines 28
Ratio 100 %

Importance

Changes 0
Metric Value
cc 5
eloc 15
nc 6
nop 1
dl 28
loc 28
rs 8.439
c 0
b 0
f 0
1
<?php
2
3
namespace Oc\GeoCache\Persistence\GeoCacheLog;
4
5
use DateTime;
6
use Doctrine\DBAL\Connection;
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
/**
13
 * Class GeoCacheLogRepository
14
 *
15
 * @package Oc\GeoCache\Persistence\GeoCacheLog
0 ignored issues
show
introduced by
Unexpected tag type @package in doc block
Loading history...
16
 */
17
class GeoCacheLogRepository
18
{
19
    /**
20
     * Database table name that this repository maintains.
21
     *
22
     * @var string
23
     */
24
    const TABLE = 'cache_logs';
25
26
    /**
27
     * @var Connection
0 ignored issues
show
introduced by
Connection => \Doctrine\DBAL\Connection
Loading history...
28
     */
29
    private $connection;
30
31
    /**
32
     * GeoCacheLogRepository constructor.
33
     *
34
     * @param Connection $connection
0 ignored issues
show
introduced by
Connection => \Doctrine\DBAL\Connection
Loading history...
35
     */
36
    public function __construct(Connection $connection)
37
    {
38
        $this->connection = $connection;
39
    }
40
41
    /**
42
     * Fetches all GeoCacheLogs.
43
     *
44
     * @return GeoCacheLogEntity[]
0 ignored issues
show
introduced by
GeoCacheLogEntity[] => \Array\GeoCacheLogEntity[]
Loading history...
45
     *
46
     * @throws RecordsNotFoundException Thrown when no records are found
0 ignored issues
show
introduced by
RecordsNotFoundException => \Oc\Repository\Exception\RecordsNotFoundException
Loading history...
Coding Style introduced by
@throws tag comment must end with a full stop
Loading history...
47
     */
48 View Code Duplication
    public function fetchAll()
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...
49
    {
50
        $statement = $this->connection->createQueryBuilder()
51
            ->select('*')
52
            ->from(self::TABLE)
53
            ->execute();
54
55
        $result = $statement->fetchAll();
56
57
        if ($statement->rowCount() === 0) {
58
            throw new RecordsNotFoundException('No records found');
59
        }
60
61
        $records = [];
62
63
        foreach ($result as $item) {
64
            $records[] = $this->getEntityFromDatabaseArray($item);
65
        }
66
67
        return $records;
68
    }
69
70
    /**
71
     * Fetches a GeoCacheLog by given where clause.
72
     *
73
     * @param array $where
74
     *
75
     * @return null|GeoCacheLogEntity
0 ignored issues
show
introduced by
GeoCacheLogEntity => \Array\GeoCacheLogEntity
Loading history...
76
     *
77
     * @throws RecordNotFoundException Thrown when no record is found
0 ignored issues
show
introduced by
RecordNotFoundException => \Oc\Repository\Exception\RecordNotFoundException
Loading history...
Coding Style introduced by
@throws tag comment must end with a full stop
Loading history...
78
     */
79 View Code Duplication
    public function fetchOneBy(array $where = [])
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...
80
    {
81
        $queryBuilder = $this->connection->createQueryBuilder()
82
             ->select('*')
83
             ->from(self::TABLE)
84
             ->setMaxResults(1);
85
86
        if (count($where) > 0) {
87
            foreach ($where as $column => $value) {
88
                $queryBuilder->andWhere($column . ' = ' .  $queryBuilder->createNamedParameter($value));
0 ignored issues
show
introduced by
Expected 1 space after ., but 2 found
Loading history...
89
            }
90
        }
91
92
        $statement = $queryBuilder->execute();
93
94
        $result = $statement->fetch();
95
96
        if ($statement->rowCount() === 0) {
97
            throw new RecordNotFoundException('Record with given where clause not found');
98
        }
99
100
        return $this->getEntityFromDatabaseArray($result);
101
    }
102
103
    /**
104
     * Fetches all GeoCacheLogs by given where clause.
105
     *
106
     * @param array $where
107
     *
108
     * @return GeoCacheLogEntity[]
0 ignored issues
show
introduced by
GeoCacheLogEntity[] => \Array\GeoCacheLogEntity[]
Loading history...
109
     *
110
     * @throws RecordsNotFoundException Thrown when no records are found
0 ignored issues
show
introduced by
RecordsNotFoundException => \Oc\Repository\Exception\RecordsNotFoundException
Loading history...
Coding Style introduced by
@throws tag comment must end with a full stop
Loading history...
111
     */
112 View Code Duplication
    public function fetchBy(array $where = [])
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...
113
    {
114
        $queryBuilder = $this->connection->createQueryBuilder()
115
             ->select('*')
116
             ->from(self::TABLE);
117
118
        if (count($where) > 0) {
119
            foreach ($where as $column => $value) {
120
                $queryBuilder->andWhere($column . ' = ' .  $queryBuilder->createNamedParameter($value));
0 ignored issues
show
introduced by
Expected 1 space after ., but 2 found
Loading history...
121
            }
122
        }
123
124
        $statement = $queryBuilder->execute();
125
126
        $result = $statement->fetchAll();
127
128
        if ($statement->rowCount() === 0) {
129
            throw new RecordsNotFoundException('No records with given where clause found');
130
        }
131
132
        $geoCaches = [];
133
134
        foreach ($result as $item) {
135
            $geoCaches[] = $this->getEntityFromDatabaseArray($item);
136
        }
137
138
        return $geoCaches;
139
    }
140
141
    /**
142
     * Fetch latest user geo cache log.
143
     *
144
     * @param int $userId
145
     *
146
     * @return GeoCacheLogEntity
0 ignored issues
show
introduced by
GeoCacheLogEntity => \Array\GeoCacheLogEntity
Loading history...
147
     *
148
     * @throws RecordNotFoundException
0 ignored issues
show
introduced by
RecordNotFoundException => \Oc\Repository\Exception\RecordNotFoundException
Loading history...
149
     */
150 View Code Duplication
    public function getLatestUserLog($userId)
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...
151
    {
152
        $queryBuilder = $this->connection->createQueryBuilder()
153
            ->select('*')
154
            ->from(self::TABLE)
155
            ->where('user_id = :userId')
156
            ->orderBy('date', 'DESC')
157
            ->setParameter('userId', $userId)
158
            ->setMaxResults(1);
159
160
        $statement = $queryBuilder->execute();
161
162
        $result = $statement->fetch();
163
164
        if ($statement->rowCount() === 0) {
165
            throw new RecordNotFoundException('Record with given where clause not found');
166
        }
167
168
        return $this->getEntityFromDatabaseArray($result);
169
    }
170
171
    /**
172
     * Creates a GeoCacheLog in the database.
173
     *
174
     * @param GeoCacheLogEntity $entity
0 ignored issues
show
introduced by
GeoCacheLogEntity => \Array\GeoCacheLogEntity
Loading history...
175
     *
176
     * @return GeoCacheLogEntity
0 ignored issues
show
introduced by
GeoCacheLogEntity => \Array\GeoCacheLogEntity
Loading history...
177
     *
178
     * @throws RecordAlreadyExistsException
0 ignored issues
show
introduced by
RecordAlreadyExistsException => \Oc\Repository\Exception\RecordAlreadyExistsException
Loading history...
179
     */
180
    public function create(GeoCacheLogEntity $entity)
181
    {
182
        if (!$entity->isNew()) {
183
            throw new RecordAlreadyExistsException('The entity does already exist.');
184
        }
185
186
        $databaseArray = $this->getDatabaseArrayFromEntity($entity);
187
188
        $this->connection->insert(
189
            self::TABLE,
190
            $databaseArray
191
        );
192
193
        $entity->id = $this->connection->lastInsertId();
0 ignored issues
show
Documentation Bug introduced by
The property $id was declared of type integer, but $this->connection->lastInsertId() is of type string. 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...
194
195
        return $entity;
196
    }
197
198
    /**
199
     * Update a GeoCacheLog in the database.
200
     *
201
     * @param GeoCacheLogEntity $entity
0 ignored issues
show
introduced by
GeoCacheLogEntity => \Array\GeoCacheLogEntity
Loading history...
202
     *
203
     * @return GeoCacheLogEntity
0 ignored issues
show
introduced by
GeoCacheLogEntity => \Array\GeoCacheLogEntity
Loading history...
204
     *
205
     * @throws RecordNotPersistedException
0 ignored issues
show
introduced by
RecordNotPersistedException => \Oc\Repository\Exception\RecordNotPersistedException
Loading history...
206
     */
207
    public function update(GeoCacheLogEntity $entity)
208
    {
209
        if ($entity->isNew()) {
210
            throw new RecordNotPersistedException('The entity does not exist.');
211
        }
212
213
        $databaseArray = $this->getDatabaseArrayFromEntity($entity);
214
215
        $this->connection->update(
216
            self::TABLE,
217
            $databaseArray,
218
            ['id' => $entity->id]
219
        );
220
221
        $entity->id = $this->connection->lastInsertId();
0 ignored issues
show
Documentation Bug introduced by
The property $id was declared of type integer, but $this->connection->lastInsertId() is of type string. 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...
222
223
        return $entity;
224
    }
225
226
    /**
227
     * Removes a GeoCacheLog from the database.
228
     *
229
     * @param GeoCacheLogEntity $entity
0 ignored issues
show
introduced by
GeoCacheLogEntity => \Array\GeoCacheLogEntity
Loading history...
230
     *
231
     * @return GeoCacheLogEntity
0 ignored issues
show
introduced by
GeoCacheLogEntity => \Array\GeoCacheLogEntity
Loading history...
232
     *
233
     * @throws RecordNotPersistedException
0 ignored issues
show
introduced by
RecordNotPersistedException => \Oc\Repository\Exception\RecordNotPersistedException
Loading history...
234
     */
235 View Code Duplication
    public function remove(GeoCacheLogEntity $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...
236
    {
237
        if ($entity->isNew()) {
238
            throw new RecordNotPersistedException('The entity does not exist.');
239
        }
240
241
        $this->connection->delete(
242
            self::TABLE,
243
            ['id' => $entity->id]
244
        );
245
246
        $entity->id = null;
247
248
        return $entity;
249
    }
250
251
    /**
252
     * Maps the given entity to the database array.
253
     *
254
     * @param GeoCacheLogEntity $entity
0 ignored issues
show
introduced by
GeoCacheLogEntity => \Array\GeoCacheLogEntity
Loading history...
255
     *
256
     * @return array
257
     */
258
    public function getDatabaseArrayFromEntity(GeoCacheLogEntity $entity)
259
    {
260
        return [
261
            'id' => $entity->id,
262
            'uuid' => $entity->uuid,
263
            'node' => $entity->node,
264
            'date_created' => $entity->dateCreated->format(DateTime::ATOM),
265
            'entry_last_modified' => $entity->entryLastModified->format(DateTime::ATOM),
266
            'last_modified' => $entity->lastModified->format(DateTime::ATOM),
267
            'okapi_syncbase' => $entity->okapiSyncbase,
268
            'log_last_modified' => $entity->logLastModified->format(DateTime::ATOM),
269
            'cache_id' => $entity->cacheId,
270
            'user_id' => $entity->userId,
271
            'type' => $entity->type,
272
            'oc_team_comment' => $entity->ocTeamComment,
273
            'date' => $entity->date->format(DateTime::ATOM),
274
            'order_date' => $entity->orderDate->format(DateTime::ATOM),
275
            'needs_maintenance' => $entity->needsMaintenance,
276
            'listing_outdated' => $entity->listingOutdated,
277
            'text' => $entity->text,
278
            'text_html' => $entity->textHtml,
279
            'text_htmledit' => $entity->textHtmledit,
280
            'owner_notified' => $entity->ownerNotified,
281
            'picture' => $entity->picture
282
        ];
283
    }
284
285
    /**
286
     * Prepares database array from properties.
287
     *
288
     * @param array $data
289
     *
290
     * @return GeoCacheLogEntity
0 ignored issues
show
introduced by
GeoCacheLogEntity => \Array\GeoCacheLogEntity
Loading history...
291
     */
292
    public function getEntityFromDatabaseArray(array $data)
293
    {
294
        $entity = new GeoCacheLogEntity();
295
        $entity->id = (int) $data['id'];
0 ignored issues
show
introduced by
No whitespace should be between cast and variable.
Loading history...
296
        $entity->uuid = (string) $data['uuid'];
0 ignored issues
show
introduced by
No whitespace should be between cast and variable.
Loading history...
297
        $entity->node = (int) $data['node'];
0 ignored issues
show
introduced by
No whitespace should be between cast and variable.
Loading history...
298
        $entity->dateCreated = new DateTime($data['date_created']);
299
        $entity->entryLastModified = new DateTime($data['entry_last_modified']);
300
        $entity->lastModified = new DateTime($data['last_modified']);
301
        $entity->okapiSyncbase = (int) $data['okapi_syncbase'];
0 ignored issues
show
introduced by
No whitespace should be between cast and variable.
Loading history...
302
        $entity->logLastModified = new DateTime($data['log_last_modified']);
303
        $entity->cacheId = (int) $data['cache_id'];
0 ignored issues
show
introduced by
No whitespace should be between cast and variable.
Loading history...
304
        $entity->userId = (int) $data['user_id'];
0 ignored issues
show
introduced by
No whitespace should be between cast and variable.
Loading history...
305
        $entity->type = (int) $data['type'];
0 ignored issues
show
introduced by
No whitespace should be between cast and variable.
Loading history...
306
        $entity->ocTeamComment = (bool) $data['oc_team_comment'];
0 ignored issues
show
introduced by
No whitespace should be between cast and variable.
Loading history...
307
        $entity->date = new DateTime($data['date']);
308
        $entity->orderDate = new DateTime($data['order_date']);
309
        $entity->needsMaintenance = (bool) $data['needs_maintenance'];
0 ignored issues
show
introduced by
No whitespace should be between cast and variable.
Loading history...
310
        $entity->listingOutdated = (bool) $data['listing_outdated'];
0 ignored issues
show
introduced by
No whitespace should be between cast and variable.
Loading history...
311
        $entity->text = (string) $data['text'];
0 ignored issues
show
introduced by
No whitespace should be between cast and variable.
Loading history...
312
        $entity->textHtml = (bool) $data['text_html'];
0 ignored issues
show
introduced by
No whitespace should be between cast and variable.
Loading history...
313
        $entity->textHtmledit = (bool) $data['text_htmledit'];
0 ignored issues
show
introduced by
No whitespace should be between cast and variable.
Loading history...
314
        $entity->ownerNotified = (bool) $data['owner_notified'];
0 ignored issues
show
introduced by
No whitespace should be between cast and variable.
Loading history...
315
        $entity->picture = (int) $data['picture'];
0 ignored issues
show
introduced by
No whitespace should be between cast and variable.
Loading history...
316
317
        return $entity;
318
    }
319
}
320