Completed
Push — master ( 7a8d8f...cf063a )
by Andreas
09:46 queued 05:03
created

CfpFactory::setEventUri()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 25
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 25
rs 8.5806
c 0
b 0
f 0
cc 4
eloc 15
nc 4
nop 3
1
<?php
2
/**
3
 * Copyright (c) 2016-2016} Andreas Heigl<[email protected]>
4
 * Permission is hereby granted, free of charge, to any person obtaining a copy
5
 * of this software and associated documentation files (the "Software"), to deal
6
 * in the Software without restriction, including without limitation the rights
7
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
 * copies of the Software, and to permit persons to whom the Software is
9
 * furnished to do so, subject to the following conditions:
10
 * The above copyright notice and this permission notice shall be included in
11
 * all copies or substantial portions of the Software.
12
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
13
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
14
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
15
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
16
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
17
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
18
 * THE SOFTWARE.
19
 *
20
 * @author    Andreas Heigl<[email protected]>
21
 * @copyright 2016-2016 Andreas Heigl
22
 * @license   http://www.opensource.org/licenses/mit-license.php MIT-License
23
 * @version   0.0
24
 * @since     18.02.2016
25
 * @link      http://github.com/heiglandreas/callingallpapers
26
 */
27
28
namespace Callingallpapers\Api\Service;
29
30
use Callingallpapers\Api\Entity\Cfp;
31
use DateTimeImmutable;
32
use GuzzleHttp\Client;
33
use GuzzleHttp\TransferStats;
34
35
class CfpFactory
36
{
37
38
    /**
39
     * Create a CFP from unfiltered values.
40
     * This method takes an array of unfiltered values, checks for required
41
     * values and validates resp. sanitizes those values before injecting them
42
     * into a new CfP
43
     *
44
     * @param array $params
45
     *
46
     * @return Cfp
47
     */
48
    public function createCfp(array $params, Client $client)
49
    {
50
        $requiredFields = ['name', 'dateCfpEnd', 'uri', 'eventUri', 'timezone'];
51
        $missingFields = [];
52
53
        foreach ($requiredFields as $field) {
54
            if (! isset($params[$field])) {
55
                $missingFields[] = $field;
56
            }
57
        }
58
59
        if ($missingFields) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $missingFields 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...
60
            throw new \UnexpectedValueException(sprintf(
61
                'The following fields are missing: "%1$s"',
62
                implode(', ', $missingFields)
63
            ), 400);
64
        }
65
        $cfp = new Cfp();
66
67
        self::setName($cfp, $params);
68
        self::setDateCfpStart($cfp, $params);
69
        self::setDateCfpEnd($cfp, $params);
70
        self::setTimezone($cfp, $params);
71
        self::setUri($cfp, $params);
72
        self::setEventUri($cfp, $params, $client);
73
        self::setDateEventStart($cfp, $params);
74
        self::setDateEventEnd($cfp, $params);
75
        self::setIconUri($cfp, $params);
76
        self::setDescription($cfp, $params);
77
        self::setLocation($cfp, $params);
78
        self::setGeolocation($cfp, $params);
79
        self::setTags($cfp, $params);
80
        self::setSource($cfp, $params);
81
82
        return $cfp;
83
    }
84
85 View Code Duplication
    public static function setName(Cfp $cfp, array $array)
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...
86
    {
87
        if (! isset($array['name'])) {
88
            throw new \InvalidArgumentException('Name has to be specified');
89
        }
90
        $cfp->setName(filter_var($array['name'], FILTER_SANITIZE_STRING));
91
    }
92
93
    public static function setDateCfpStart(Cfp $cfp, array $array)
94
    {
95
        if (! isset($array['dateCfpStart'])) {
96
            $array['dateCfpStart'] = '@0';
97
        }
98
        $cfp->setDateCfpStart(new DateTimeImmutable($array['dateCfpStart']));
99
    }
100
101
    public static function setDateCfpEnd(Cfp $cfp, array $array)
102
    {
103
        if (! isset($array['dateCfpEnd'])) {
104
            throw new \InvalidArgumentException('CFP-EndDate has to be specified');
105
        }
106
        $cfp->setDateCfpEnd(new DateTimeImmutable($array['dateCfpEnd']));
107
    }
108
109
    public static function setTimezone(Cfp $cfp, array $array)
110
    {
111
        if (! isset($array['timezone'])) {
112
            throw new \InvalidArgumentException('Timezone has to be specified');
113
        }
114
115
        if (isset($array['timezone']['timezone'])) {
116
            $array['timezone'] = $array['timezone']['timezone'];
117
        }
118
119
        $cfp->setTimezone(filter_var($array['timezone'], FILTER_SANITIZE_STRING));
120
    }
121
122
    public static function setUri(Cfp $cfp, array $array)
123
    {
124
        if (! isset($array['uri'])) {
125
            throw new \InvalidArgumentException('URI has to be specified');
126
        }
127
128
        $cfp->setUri(filter_var($array['uri'], FILTER_VALIDATE_URL));
129
    }
130
131
    public static function setEventUri(Cfp $cfp, array $array, Client $client)
132
    {
133
        if (! isset($array['eventUri'])) {
134
            throw new \InvalidArgumentException('Event-URI has to be specified');
135
        }
136
137
        try {
138
            $uri = '';
139
            $client->get($array['eventUri'], [
140
                'on_stats' => function (TransferStats $stats) use (&$uri) {
141
                    $uri = $stats->getEffectiveUri();
142
                }
143
            ]);
144
        } catch (\Exception $e) {
145
            throw new \InvalidArgumentException('Event-URI could not be verified: ' . $e->getMessage());
146
        }
147
148
        $uri = (string) $uri;
149
        $pos = strpos($uri, '?');
150
        if ($pos !== false) {
151
            $uri = substr($uri, 0, $pos);
152
        }
153
154
        $cfp->setEventUri(filter_var($uri, FILTER_VALIDATE_URL));
155
    }
156
157
    public static function setDateEventStart(Cfp $cfp, array $array)
158
    {
159
        if (isset($array['dateEventStart'])) {
160
            $cfp->setDateEventStart(new DateTimeImmutable($array['dateEventStart']));
161
        } else {
162
            $cfp->setDateEventStart(new DateTimeImmutable('0000-00-00 00:00:00+00:00'));
163
        }
164
    }
165
166
    public static function setDateEventEnd(Cfp $cfp, array $array)
167
    {
168
        if (isset($array['dateEventEnd'])) {
169
            $cfp->setDateEventEnd(new DateTimeImmutable($array['dateEventEnd']));
170
        } else {
171
            $cfp->setDateEventEnd(new DateTimeImmutable('0000-00-00 00:00:00+00:00'));
172
        }
173
    }
174
175
    public static function setIconUri(Cfp $cfp, array $array)
176
    {
177
        if (! isset($array['iconUri'])) {
178
            return;
179
        }
180
181
        $cfp->setIconUri(filter_var($array['iconUri'], FILTER_VALIDATE_URL));
182
    }
183
184 View Code Duplication
    public static function setDescription(Cfp $cfp, array $array)
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...
185
    {
186
        if (! isset($array['description'])) {
187
            return;
188
        }
189
190
        $cfp->setDescription(filter_var($array['description'], FILTER_SANITIZE_STRING));
191
    }
192
193 View Code Duplication
    public static function setLocation(Cfp $cfp, array $array)
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...
194
    {
195
        if (! isset($array['location'])) {
196
            return;
197
        }
198
199
        $cfp->setLocation(filter_var($array['location'], FILTER_SANITIZE_STRING));
200
    }
201
202
    public static function setGeolocation(Cfp $cfp, array $array)
203
    {
204
        if (! isset($array['latitude'])) {
205
            return;
206
        }
207
208
        if (! isset($array['longitude'])) {
209
            return;
210
        }
211
212
        $latitude  = filter_var(
213
            $array['latitude'],
214
            FILTER_SANITIZE_NUMBER_FLOAT,
215
            FILTER_FLAG_ALLOW_FRACTION
216
        );
217
        $longitude = filter_var(
218
            $array['longitude'],
219
            FILTER_SANITIZE_NUMBER_FLOAT,
220
            FILTER_FLAG_ALLOW_FRACTION
221
        );
222
223
        if ($latitude > 90 || $latitude < - 90) {
224
            throw new \UnexpectedValueException(sprintf(
225
                'latitude has to be within a range of -90.0 to 90.0 bus is %1$f',
226
                $latitude
227
            ), 400);
228
        }
229
230
        if ($longitude > 180 || $longitude < - 180) {
231
            throw new \UnexpectedValueException(sprintf(
232
                'longitude has to be within a range of -180.0 to 180.0 but is %1$f',
233
                $longitude
234
            ), 400);
235
        }
236
237
        // TODO: Rewrite lat and long to be in the correct range
238
239
        $cfp->setLatitude($latitude);
240
        $cfp->setLongitude($longitude);
241
    }
242
243
    public static function setTags(Cfp $cfp, array $array)
244
    {
245
        if (! isset($array['tags'])) {
246
            return;
247
        }
248
249
        $cfp->setTags(array_map(function ($item) {
250
            return filter_var($item, FILTER_SANITIZE_STRING);
251
        }, $array['tags']));
252
    }
253
254
    public static function setSource(Cfp $cfp, array $array)
255
    {
256
        if (! isset($array['source'])) {
257
            return;
258
        }
259
260
        $cfp->addSource(filter_var($array['source'], FILTER_SANITIZE_STRING));
261
    }
262
}
263