Completed
Push — development ( daed94...13a157 )
by Thomas
18s
created

GeoCacheLogRepository::update()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 18
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

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