Completed
Pull Request — master (#20)
by Andreas
01:51
created

CfpPersistenceLayer::search()   C

Complexity

Conditions 12
Paths 16

Size

Total Lines 85
Code Lines 62

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 85
c 0
b 0
f 0
rs 5.034
cc 12
eloc 62
nc 16
nop 1

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/**
4
 * Copyright (c) 2016-2016} Andreas Heigl<[email protected]>
5
 *
6
 * Permission is hereby granted, free of charge, to any person obtaining a copy
7
 * of this software and associated documentation files (the "Software"), to deal
8
 * in the Software without restriction, including without limitation the rights
9
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
 * copies of the Software, and to permit persons to whom the Software is
11
 * furnished to do so, subject to the following conditions:
12
 *
13
 * The above copyright notice and this permission notice shall be included in
14
 * all copies or substantial portions of the Software.
15
 *
16
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22
 * THE SOFTWARE.
23
 *
24
 * @author    Andreas Heigl<[email protected]>
25
 * @copyright 2016-2016 Andreas Heigl
26
 * @license   http://www.opensource.org/licenses/mit-license.php MIT-License
27
 * @version   0.0
28
 * @since     19.01.2016
29
 * @link      http://github.com/joindin/callingallpapers-api
30
 */
31
32
namespace Callingallpapers\Api\PersistenceLayer;
33
34
use Callingallpapers\Api\Entity\Cfp;
35
use Camel\CaseTransformer;
36
use Camel\Format\CamelCase;
37
use Camel\Format\SnakeCase;
38
use DateTime;
39
use Monolog\Logger;
40
41
class CfpPersistenceLayer
42
{
43
    protected $pdo;
44
45
    public function __construct(\PDO $pdo)
46
    {
47
        $this->pdo = $pdo;
48
    }
49
50
    public function insert(Cfp $cfp)
51
    {
52
        try {
53
            $this->select($cfp->getHash());
54
            $cfpExists = true;
55
        } catch (\UnexpectedValueException $e) {
56
            $cfpExists = false;
57
        }
58
59
        if ($cfpExists) {
60
            throw new \UnexpectedValueException(sprintf(
61
                'There is already a CFP with URL "%1$s".',
62
                $cfp->getEventUri()
63
            ), 400);
64
        }
65
66
        if ($cfp->getDateCfpStart()->getTimestamp() < 10000) {
67
            $cfp->setDateCfpStart(new \DateTimeImmutable());
68
        }
69
        $statement = 'INSERT into `cfp`(`dateCfpStart`, `dateCfpEnd`, `dateEventStart`, `dateEventEnd`, `name`, `uri`, `hash`, `timezone`, `description`, `eventUri`, `iconUri`, `latitude`, `longitude`, `location`, `tags`, `lastUpdate`) ' .
70
                     'VALUES (:dateCfpStart, :dateCfpEnd, :dateEventStart, :dateEventEnd, :name, :uri, :hash, :timezone, :description, :eventUri, :iconUri, :latitude, :longitude, :location, :tags, :lastUpdate);';
71
        $statement = $this->pdo->prepare($statement);
72
73
        $values = [
74
            'dateCfpStart'   => $cfp->getDateCfpStart()->format('c'),
75
            'dateCfpEnd'     => $cfp->getDateCfpEnd()->format('c'),
76
            'dateEventStart' => $cfp->getDateEventStart()->format('c'),
77
            'dateEventEnd'   => $cfp->getDateEventEnd()->format('c'),
78
            'name'           => $cfp->getName(),
79
            'uri'            => $cfp->getUri(),
80
            'hash'           => $cfp->getHash(),
81
            'timezone'       => $cfp->getTimezone()->getName(),
82
            'description'    => $cfp->getDescription(),
83
            'eventUri'       => $cfp->getEventUri(),
84
            'iconUri'        => $cfp->getIconUri(),
85
            'latitude'       => $cfp->getLatitude(),
86
            'longitude'      => $cfp->getLongitude(),
87
            'location'       => $cfp->getLocation(),
88
            'tags'           => implode(',', $cfp->getTags()),
89
            'lastUpdate'     => (new \DateTime('now', new \DateTimezone('UTC')))->format('c'),
90
        ];
91
92
        if ($statement->execute($values)) {
93
            return $values['hash'];
94
        }
95
96
        throw new \UnexpectedValueException('The CfP could not be stored', 400);
97
    }
98
99
    public function update(Cfp $cfp, $fetchHash)
100
    {
101
        if (! $fetchHash) {
102
            throw new \UnexpectedValueException('No Hash given', 400);
103
        }
104
        $oldValues = $this->select($fetchHash);
105
        if ($oldValues->count() != 1) {
106
            throw new \UnexpectedValueException('There is no CFP with this URL.', 404);
107
        }
108
        $statementElements = [];
109
        $values = [];
110
        $oldValues = $oldValues->current();
111
        $options = [
112
            'dateCfpStart',
113
            'dateCfpEnd',
114
            'name',
115
            'uri',
116
            'hash',
117
            'timezone',
118
            'dateEventStart',
119
            'dateEventEnd',
120
            'description',
121
            'eventUri',
122
            'iconUri',
123
            'latitude',
124
            'longitude',
125
            'location',
126
            'tags',
127
            'source',
128
        ];
129
130
        foreach ($options as $option) {
131
            $method = 'get' . $option;
132
           // Merge values from tags and source before comparing!
133
            if (in_array($option, ['tags', 'source'])) {
134
                $setter = 'set' . $option;
135
                $cfp->$setter(array_merge($oldValues->$method(), $cfp->$method()));
136
            }
137
            if ($cfp->$method() !== $oldValues->$method()) {
138
                if ($option == 'dateCfpStart' && $cfp->$method()->getTimestamp() < 100000) {
139
                    continue;
140
                }
141
                $statementElements[] = '`' . $option . '` = :' . $option;
142
                $values[$option]     = $cfp->$method();
143
                if ($values[$option] instanceof \DateTimeInterface) {
144
                    $values[$option] = $values[$option]->format('c');
145
                }
146
                if ($values[$option] instanceof \DateTimeZone) {
147
                    $values[$option] = $values[$option]->getName();
148
                }
149
                if (is_array($values[$option])) {
150
                    $values[$option] = implode(',', array_unique($values[$option]));
151
                }
152
            }
153
        }
154
155
        // No values to update, just, return
156
        if (empty($values)) {
157
            return $cfp->getHash();
158
        }
159
160
        $statement = 'UPDATE `cfp` SET '
161
                   . implode(',', $statementElements) . ','
162
                   . '`lastUpdate` = :lastUpdate '
163
                   . 'WHERE `hash` = :fetchHash';
164
        $statement = $this->pdo->prepare($statement);
165
        $values['fetchHash']  = $fetchHash;
166
        $values['lastUpdate'] = (new \DateTime('now', new \DateTimezone('UTC')))->format('c');
167
168
        if ($statement->execute($values)) {
169
            return $cfp->getHash();
170
        }
171
172
        throw new \UnexpectedValueException('The CfP could not be updated', 400);
173
    }
174
175
176
    public function select($hash = null)
177
    {
178
        $statement = 'SELECT * FROM `cfp`';
179
        $values = [];
180
        if ($hash !== null) {
181
            $statement .= ' WHERE `hash`= :hash';
182
            $values['hash'] = $hash;
183
        }
184
185
        $statement = $this->pdo->prepare($statement);
186
187
        $list = new \Callingallpapers\Api\Entity\CfpList();
188
        $statement->execute($values);
189
        $content = $statement->fetchAll();
190
        if (count($content) < 1) {
191
            throw new \UnexpectedValueException('No CFPs found', 404);
192
        }
193
194 View Code Duplication
        foreach ($content as $item) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
195
            $cfp = new \Callingallpapers\Api\Entity\Cfp();
196
            $cfp->setName($item['name']);
197
            $cfp->setDateCfpEnd(new \DateTimeImmutable($item['dateCfpEnd']));
198
            $cfp->setDateCfpStart(new \DateTimeImmutable($item['dateCfpStart']));
199
            $cfp->setUri($item['uri']);
200
            $cfp->setTimezone(new \DateTimeZone($item['timezone']));
201
            $cfp->setDateEventStart(new \DateTimeImmutable($item['dateEventStart']));
202
            $cfp->setDateEventEnd(new \DateTimeImmutable($item['dateEventEnd']));
203
            $cfp->setDescription($item['description']);
204
            $cfp->setEventUri($item['eventUri']);
205
            $cfp->setIconUri($item['iconUri']);
206
            $cfp->setLatitude($item['latitude']);
207
            $cfp->setLongitude($item['longitude']);
208
            $cfp->setLocation($item['location']);
209
            $cfp->setTags(explode(',', $item['tags']));
210
            $cfp->setLastUpdated(new \DateTimeImmutable($item['lastUpdate']));
211
            $cfp->setSource(explode(',', $item['source']));
212
213
            $list->add($cfp);
214
        }
215
216
        return $list;
217
    }
218
219
    public function delete($hash)
220
    {
221
        $statement = 'DELETE FROM `cfp` WHERE `hash` = :hash';
222
223
        $statement = $this->pdo->prepare($statement);
224
225
        return $statement->execute(['hash' => $hash]);
226
    }
227
228
    public function getCurrent(\DateTimeInterface $startDate = null, \DateTimeInterface $endDate = null)
229
    {
230
        $statement = 'SELECT * FROM `cfp` WHERE dateCfpEnd > :end AND dateCfpStart < :start';
231
232
        $statement = $this->pdo->prepare($statement);
233
234
        $now = new \DateTime();
235
        if (null === $startDate) {
236
            $startDate = $now;
237
        }
238
        if (null === $endDate) {
239
            $endDate = $now;
240
        }
241
242
        $list = new \Callingallpapers\Api\Entity\CfpList();
243
        $statement->execute([
244
            'end'   => $endDate->format('c'),
245
            'start' => $startDate->format('c'),
246
        ]);
247
248
        $content = $statement->fetchAll();
249
        if (count($content) < 1) {
250
            throw new \UnexpectedValueException('No CFPs found', 404);
251
        }
252
253 View Code Duplication
        foreach ($content as $item) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
254
            $cfp = new \Callingallpapers\Api\Entity\Cfp();
255
            $cfp->setName($item['name']);
256
            $cfp->setDateCfpEnd(new \DateTimeImmutable($item['dateCfpEnd']));
257
            $cfp->setDateCfpStart(new \DateTimeImmutable($item['dateCfpStart']));
258
            $cfp->setUri($item['uri']);
259
            $cfp->setTimezone(new \DateTimeZone($item['timezone']));
260
            $cfp->setDateEventStart(new \DateTimeImmutable($item['dateEventStart']));
261
            $cfp->setDateEventEnd(new \DateTimeImmutable($item['dateEventEnd']));
262
            $cfp->setDescription($item['description']);
263
            $cfp->setEventUri($item['eventUri']);
264
            $cfp->setIconUri($item['iconUri']);
265
            $cfp->setLatitude($item['latitude']);
266
            $cfp->setLongitude($item['longitude']);
267
            $cfp->setLocation($item['location']);
268
            $cfp->setTags(explode(',', $item['tags']));
269
            $cfp->setLastUpdated(new \DateTimeImmutable($item['lastUpdate']));
270
            $cfp->setSource(explode(',', $item['source']));
271
272
            $list->add($cfp);
273
        }
274
275
        return $list;
276
    }
277
278
    public function search(array $parameters)
279
    {
280
        $fields = [
281
            'name',
282
            'tags',
283
            'date_cfp_end',
284
            'date_cfp_start',
285
            'date_event_end',
286
            'date_event_start',
287
            'latitude',
288
            'longitude',
289
290
        ];
291
        $transformer = new CaseTransformer(new SnakeCase(), new CamelCase());
292
293
        $statement = 'SELECT * FROM `cfp` WHERE ';
294
        $values    = [];
295
        $where = [];
296
        foreach ($parameters as $key => $value) {
297
            if (! in_array($key, $fields)) {
298
                continue;
299
            }
300
            if (! is_array($value)) {
301
                $value = [$value];
302
            }
303
            foreach ($value as $itemkey => $item) {
304
                $compare = '=';
305
                if (in_array($key, [
306
                    'date_cfp_end',
307
                    'date_cfp_start',
308
                    'date_event_end',
309
                    'date_event_start'
310
                ])) {
311
                    if (array_key_exists($key . '_compare', $parameters) && isset($parameters[$key . '_compare'][$itemkey]) && in_array($parameters[$key . '_compare'][$itemkey], ['=', '<', '>', '<>'])) {
312
                        $compare = $parameters[$key . '_compare'][$itemkey];
313
                    }
314
                    $where[] = 'datetime(`' . $transformer->transform($key) . '`) ' . $compare . ' datetime(:' . $key . '_' . $itemkey . ')';
315
//                    $where[] = '`' . $transformer->transform($key) . '` ' . $compare . ' CONVERT_TZ(:' . $key . ', timezone, \'UTC\')';
0 ignored issues
show
Unused Code Comprehensibility introduced by
40% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
316
                    $value = (new DateTime($item))->setTimezone(new \DateTimeZone('UTC'))->format('c');
317
                } else {
318
                    $where[] = '`' . $transformer->transform($key) . '` ' . $compare . ' :' . $key;
319
                }
320
                $values[$key . '_' . $itemkey] = $value;
321
            }
322
        }
323
        if (! $where) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $where of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
324
            throw new \UnexpectedValueException('No CFPs found', 404);
325
        }
326
327
        $statement .= implode(' AND ', $where);
328
329
        $statement = $this->pdo->prepare($statement);
330
331
        $statement->execute($values);
332
        error_log($statement->queryString);
333
        $content = $statement->fetchAll();
334
        if (count($content) < 1) {
335
            throw new \UnexpectedValueException('No CFPs found', 404);
336
        }
337
338
        $list = new \Callingallpapers\Api\Entity\CfpList();
339
        foreach ($content as $item) {
340
            $cfp = new \Callingallpapers\Api\Entity\Cfp();
341
            $cfp->setName($item['name']);
342
            $cfp->setDateCfpEnd(new \DateTimeImmutable($item['dateCfpEnd']));
343
            $cfp->setDateCfpStart(new \DateTimeImmutable($item['dateCfpStart']));
344
            $cfp->setUri($item['uri']);
345
            $cfp->setTimezone(new \DateTimeZone($item['timezone']));
346
            $cfp->setDateEventStart(new \DateTimeImmutable($item['dateEventStart']));
347
            $cfp->setDateEventEnd(new \DateTimeImmutable($item['dateEventEnd']));
348
            $cfp->setDescription($item['description']);
349
            $cfp->setEventUri($item['eventUri']);
350
            $cfp->setIconUri($item['iconUri']);
351
            $cfp->setLatitude($item['latitude']);
352
            $cfp->setLongitude($item['longitude']);
353
            $cfp->setLocation($item['location']);
354
            $cfp->setTags(explode(',', $item['tags']));
355
            $cfp->setLastUpdated(new \DateTimeImmutable($item['lastUpdate']));
356
         //   $cfp->setSource(explode(',', $item['source']));
0 ignored issues
show
Unused Code Comprehensibility introduced by
77% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
357
358
            $list->add($cfp);
359
        }
360
361
        return $list;
362
    }
363
}
364