Completed
Push — master ( c1e856...c5f4d1 )
by Benjamin
02:08
created

Request   B

Complexity

Total Complexity 36

Size/Duplication

Total Lines 287
Duplicated Lines 6.27 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 7
Bugs 0 Features 1
Metric Value
wmc 36
c 7
b 0
f 1
lcom 1
cbo 0
dl 18
loc 287
rs 8.8

24 Methods

Rating   Name   Duplication   Size   Complexity  
A camelize() 0 4 1
A __set() 10 10 2
A __get() 8 10 2
A __construct() 0 8 1
A normalize() 0 12 3
A setUrl() 0 6 2
A getUrl() 0 4 1
A setPostData() 0 8 2
A getPostData() 0 4 1
A getTime() 0 4 1
A startTimer() 0 4 1
A stopTimer() 0 4 1
A getResult() 0 4 1
A callBack() 0 16 3
A addListener() 0 6 2
A notify() 0 6 2
A setTimeout() 0 7 2
A getTimeout() 0 4 1
A getHandle() 0 9 2
A setHeaders() 0 5 1
A getHeaders() 0 4 1
A setOptions() 0 4 1
A getOptions() 0 4 1
A getResponse() 0 4 1

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: lejla
5
 * Date: 2016.02.09.
6
 * Time: 17:34
7
 */
8
9
namespace CurlX;
10
11
/**
12
 * Class Request
13
 * @package CurlX
14
 *
15
 * @property string $url
16
 * @property array $post
17
 * @property float $time
18
 * @property int $timeout
19
 * @property array $options
20
 * @property array $headers
21
 * @property resource $handle
22
 * @property mixed $response
23
 * @property callable[] $listeners
24
 */
25
class Request implements RequestInterface
26
{
27
    protected $url;
28
    protected $post = [];
29
    protected $startTime;
30
    protected $endTime;
31
    protected $result;
32
    protected $listeners = [];
33
    protected $timeout;
34
    protected $curlHandle;
35
    protected $headers = [];
36
    protected $options = [];
37
    protected $success;
38
    protected $response;
39
40
    /**
41
     * @param $str
42
     * @return mixed
43
     */
44
    private function camelize($str)
45
    {
46
        return str_replace('_', '', ucwords($str, '_'));
47
    }
48
49 View Code Duplication
    public function __set($name, $value)
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...
50
    {
51
        $c = $this->camelize($name);
52
        $m = "set$c";
53
        if (method_exists($this, $m)) {
54
            return $this->$m($value);
55
        } else {
56
            user_error("undefined property $name");
57
        }
58
    }
59
60 View Code Duplication
    public function __get($name)
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...
61
    {
62
        $c = $this->camelize($name);
63
        $m = "get$c";
64
        if (method_exists($this, $m)) {
65
            return $this->$m();
66
        } else {
67
            user_error("undefined property $name");
68
        }
69
    }
70
71
    /**
72
     * Request constructor.
73
     * @param string $url optional url
74
     */
75
    public function __construct($url = null)
76
    {
77
        $this->setUrl($url);
78
79
        // Defaults
80
        $this->options[CURLOPT_RETURNTRANSFER] = true;
81
        $this->options[CURLOPT_NOSIGNAL] = 1;
82
    }
83
84
    /**
85
     * Normalize an array
86
     * change from ['key' => 'value'] format to ['key: value']
87
     * @param array $array array to normalize
88
     * @return array normalized array
89
     */
90
    private function normalize(array $array)
91
    {
92
        $normalized = [];
93
        foreach($array as $key => $value) {
94
            if(is_string($key)) {
95
                $normalized[] = $key . ': ' . $value;
96
            } else {
97
                $normalized[] = $value;
98
            }
99
        }
100
        return $normalized;
101
    }
102
103
    /**
104
     * Setter for the url field
105
     * @param string $url url
106
     * @return void
107
     */
108
    public function setUrl($url)
109
    {
110
        if (!filter_var($url, FILTER_VALIDATE_URL) === false) {
111
            $this->url = $url;
112
        }
113
    }
114
115
    /**
116
     * Getter for url field
117
     * @return string url
118
     */
119
    public function getUrl()
120
    {
121
        return $this->url;
122
    }
123
124
    /**
125
     * Setter for the post data array
126
     * @param array $postData post data
0 ignored issues
show
Bug introduced by
There is no parameter named $postData. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
127
     * @return void
128
     */
129
    public function setPostData(array $postValues)
130
    {
131
        $this->post += $postValues;
132
        $this->options[CURLOPT_POST] = 1;
133
        if (!empty($this->post)) {
134
            $this->options[CURLOPT_POSTFIELDS] = http_build_query($this->post);
135
        }
136
    }
137
138
    /**
139
     * Getter for the post data array
140
     * @return array post data
141
     */
142
    public function getPostData()
143
    {
144
        return $this->post;
145
    }
146
147
    /**
148
     * Returns the time (msec) it took to make the request
149
     * @return float time
150
     */
151
    public function getTime()
152
    {
153
        return $this->endTime - $this->startTime;
154
    }
155
156
    /**
157
     * Start the request's internal timer
158
     * @return void
159
     */
160
    public function startTimer()
161
    {
162
        $this->startTime = microtime(true);
163
    }
164
165
    /**
166
     * Stops the request's internal timer
167
     * @return void
168
     */
169
    public function stopTimer()
170
    {
171
        $this->endTime = microtime(true);
172
    }
173
174
    /**
175
     * Get the result of a query
176
     * @return mixed result
177
     */
178
    public function getResult()
179
    {
180
        return $this->result;
181
    }
182
183
    /**
184
     * This gets called by an agent when a request has completed
185
     * @param mixed $result result
186
     * @return void
187
     */
188
    public function callBack($result)
189
    {
190
        $this->stopTimer();
191
        $this->result = $result;
192
193
        $requestInfo = curl_getinfo($this->curlHandle);
194
195
        if (curl_errno($this->curlHandle) !== 0 || intval($requestInfo['http_code']) !== 200) {
196
            $this->success = false;
197
        } else {
198
            $this->success = true;
199
            $this->response = curl_multi_getcontent($this->ch);
0 ignored issues
show
Documentation introduced by
The property ch does not exist on object<CurlX\Request>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
200
        }
201
202
        $this->notify();
203
    }
204
205
    /**
206
     * Add a listener that gets notified when the Request has completed
207
     * @param callable $function callback function
208
     * @return void
209
     */
210
    public function addListener(callable $function)
211
    {
212
        if (is_callable($function)) {
213
            $this->listeners += $function;
214
        }
215
    }
216
217
    /**
218
     * Notify all listeners of request completion
219
     * @return void
220
     */
221
    protected function notify()
222
    {
223
        foreach ($this->listeners as $listener) {
224
            call_user_func($listener, $this);
225
        }
226
    }
227
228
    /**
229
     * Set a timeout value for the request
230
     * @param float $timeout timeout (msec)
231
     * @return void
232
     */
233
    public function setTimeout($timeout)
234
    {
235
        if ($timeout > 0) {
236
            $this->timeout = $timeout;
237
            $this->options[CURLOPT_TIMEOUT_MS] = $this->timeout;
238
        }
239
    }
240
241
    /**
242
     * Get the timeout value registered for the request
243
     * @return float timeout
244
     */
245
    public function getTimeout()
246
    {
247
        return $this->timeout;
248
    }
249
250
    /**
251
     * Get the cUrl handle for the request
252
     * @return resource cUrl handle
253
     */
254
    public function getHandle()
255
    {
256
        if (!isset($this->curlHandle)) {
257
            $this->curlHandle = curl_init($this->url);
258
            curl_setopt_array($this->curlHandle, $this->options);
259
        }
260
261
        return $this->curlHandle;
262
    }
263
264
    /**
265
     * Add headers to the request
266
     * @param array $headers headers in ['key' => 'value] or ['key: value'] format
267
     * @return void
268
     */
269
    public function setHeaders(array $headers)
270
    {
271
        $this->headers += $this->normalize($headers);
272
        $this->options[CURLOPT_HTTPHEADER] = $this->headers;
273
    }
274
275
    /**
276
     * Get headers set for the request
277
     * @return array headers in ['key' => 'value'] format
278
     */
279
    public function getHeaders()
280
    {
281
        return $this->headers;
282
    }
283
284
    /**
285
     * Add cUrl options to the request
286
     * @param array $options options in ['key' => 'value'] format
287
     * @return void
288
     */
289
    public function setOptions(array $options)
290
    {
291
        $this->options += $options;
292
    }
293
294
    /**
295
     * Get cUrl options set for the request
296
     * @return array options in ['key' => 'value'] format
297
     */
298
    public function getOptions()
299
    {
300
        return $this->options;
301
    }
302
303
    /**
304
     * Get the response for the finished query
305
     * @return mixed response
306
     */
307
    public function getResponse()
308
    {
309
        return $this->response;
310
    }
311
}
312