Completed
Push — master ( 483eda...cb59ac )
by Дмитрий
03:04
created

Request::getNormalizedHttpUrl()   B

Complexity

Conditions 10
Paths 64

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 15
rs 7.2765
cc 10
eloc 9
nc 64
nop 0

How to fix   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
 * SocialConnect project
4
 * @author: Patsura Dmitry https://github.com/ovr <[email protected]>
5
 */
6
7
namespace SocialConnect\OAuth1;
8
9
use SocialConnect\Auth\Consumer;
10
use SocialConnect\OAuth1\Signature\AbstractSignatureMethod;
11
12
class Request
13
{
14
    public $parameters;
15
16
    public $http_method;
17
18
    public $http_url;
19
20
    public function __construct($http_method, $http_url, $parameters = null)
21
    {
22
        $this->http_method = $http_method;
23
        $this->http_url    = $http_url;
24
25
        $parameters = ($parameters) ? $parameters : array();
26
        $parameters = array_merge(Util::parseParameters(parse_url($http_url, PHP_URL_QUERY)), $parameters);
27
28
        $this->parameters  = $parameters;
29
    }
30
    
31
    /**
32
     * @param Consumer $consumer
33
     * @param Token $token
34
     * @param string $method
35
     * @param string $url
36
     * @param array $parameters
37
     * @return Request
38
     */
39
    public static function fromConsumerAndToken(Consumer $consumer, Token $token, $method, $url, array $parameters = array())
40
    {
41
        $defaults   = array(
42
            'oauth_version' => '1.0',
43
            'oauth_nonce' => self::generateNonce(),
44
            'oauth_timestamp' => time(),
45
            'oauth_consumer_key' => $consumer->getKey()
46
        );
47
48
        if ($token) {
49
            $defaults['oauth_token'] = $token->getKey();
50
        }
51
52
        $parameters = array_merge($defaults, $parameters);
53
        return new self($method, $url, $parameters);
54
    }
55
56
    public function setParameter($name, $value, $allow_duplicates = true)
57
    {
58
        if ($allow_duplicates && isset($this->parameters[$name])) {
59
            // We have already added parameter(s) with this name, so add to the list
60
            if (is_scalar($this->parameters[$name])) {
61
                // This is the first duplicate, so transform scalar (string)
62
                // into an array so we can add the duplicates
63
                $this->parameters[$name] = array(
64
                    $this->parameters[$name]
65
                );
66
            }
67
68
            $this->parameters[$name][] = $value;
69
        } else {
70
            $this->parameters[$name] = $value;
71
        }
72
    }
73
74
    /**
75
     * The request parameters, sorted and concatenated into a normalized string.
76
     *
77
     * @return string
78
     */
79
    public function getSignableParameters()
80
    {
81
        // Grab all parameters
82
        $params = $this->parameters;
83
84
        // Remove oauth_signature if present
85
        // Ref: Spec: 9.1.1 ("The oauth_signature parameter MUST be excluded.")
86
        if (isset($params['oauth_signature'])) {
87
            unset($params['oauth_signature']);
88
        }
89
90
        return Util::buildHttpQuery($params);
91
    }
92
93
    /**
94
     * Returns the base string of this request
95
     *
96
     * The base string defined as the method, the url
97
     * and the parameters (normalized), each urlencoded
98
     * and the concated with &.
99
     *
100
     * @return string
101
     */
102
    public function getSignatureBaseString()
103
    {
104
        $parts = array(
105
            $this->getNormalizedHttpMethod(),
106
            $this->getNormalizedHttpUrl(),
107
            $this->getSignableParameters()
108
        );
109
110
        $parts = Util::urlencodeRFC3986($parts);
111
112
        return implode('&', $parts);
113
    }
114
115
    /**
116
     * just uppercases the http method
117
     */
118
    public function getNormalizedHttpMethod()
119
    {
120
        return strtoupper($this->http_method);
121
    }
122
123
    /**
124
     * parses the url and rebuilds it to be
125
     * scheme://host/path
126
     */
127
    public function getNormalizedHttpUrl()
128
    {
129
        $parts = parse_url($this->http_url);
130
131
        $scheme = (isset($parts['scheme'])) ? $parts['scheme'] : 'http';
132
        $port   = (isset($parts['port'])) ? $parts['port'] : (($scheme == 'https') ? '443' : '80');
133
        $host   = (isset($parts['host'])) ? strtolower($parts['host']) : '';
134
        $path   = (isset($parts['path'])) ? $parts['path'] : '';
135
136
        if (($scheme == 'https' && $port != '443') || ($scheme == 'http' && $port != '80')) {
137
            $host = "$host:$port";
138
        }
139
140
        return "$scheme://$host$path";
141
    }
142
143
    /**
144
     * builds a url usable for a GET request
145
     */
146
    public function toUrl()
147
    {
148
        $post_data = $this->toPostData();
149
        $out       = $this->getNormalizedHttpUrl();
150
151
        if ($post_data) {
152
            $out .= '?' . $post_data;
153
        }
154
155
        return $out;
156
    }
157
158
    /**
159
     * builds the data one would send in a POST request
160
     */
161
    public function toPostData()
162
    {
163
        return Util::buildHttpQuery($this->parameters);
164
    }
165
166
    /**
167
     * builds the Authorization: header
168
     * @param mixed $realm
169
     * @return array
170
     */
171
    public function toHeader($realm = null)
172
    {
173
        $first = true;
174
175
        if ($realm) {
176
            $out   = 'OAuth realm="' . Util::urlencodeRFC3986($realm) . '"';
177
            $first = false;
178
        } else {
179
            $out = 'OAuth';
180
        }
181
182
        foreach ($this->parameters as $k => $v) {
183
            if (substr($k, 0, 5) != "oauth") {
184
                continue;
185
            }
186
            if (is_array($v)) {
187
                continue;
188
            }
189
            $out .= ($first) ? ' ' : ', ';
190
            $out .= Util::urlencodeRFC3986($k) . '="' . Util::urlencodeRFC3986($v) . '"';
191
            $first = false;
192
        }
193
194
        return array(
195
            'Authorization' => $out
196
        ); //- hacked into this to make it return an array. 15/11/2014.
197
    }
198
199
    public function __toString()
200
    {
201
        return $this->toUrl();
202
    }
203
204
    /**
205
     * @param AbstractSignatureMethod $signatureMethod
206
     * @param Consumer $consumer
207
     * @param Token $token
208
     */
209
    public function signRequest(AbstractSignatureMethod $signatureMethod, Consumer $consumer, Token $token)
210
    {
211
        $this->setParameter('oauth_signature_method', $signatureMethod->getName(), false);
212
213
        $signature = $signatureMethod->buildSignature($this, $consumer, $token);
214
        $this->setParameter('oauth_signature', $signature, false);
215
    }
216
217
    /**
218
     * util function: current nonce
219
     */
220
    private static function generateNonce()
221
    {
222
        return md5(microtime() . mt_rand());
223
    }
224
}
225