Passed
Push — master ( c3677e...93f23d )
by Ryosuke
07:29
created

Credential   A

Complexity

Total Complexity 28

Size/Duplication

Total Lines 193
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 79.17%

Importance

Changes 0
Metric Value
wmc 28
lcom 1
cbo 1
dl 0
loc 193
ccs 95
cts 120
cp 0.7917
rs 10
c 0
b 0
f 0

19 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 9 4
A toArray() 0 5 2
A offsetGet() 0 4 1
A __get() 0 4 1
A getAuthorizeUrl() 0 8 2
A getOAuthHeaders() 0 13 1
A getBasicHeaders() 0 8 1
A getBearerHeaders() 0 4 1
A getOAuthHeadersForOAuthEcho() 0 9 1
A getOAuthHeadersForRequestToken() 0 15 2
A getOAuthHeadersForAccessToken() 0 14 1
A getXAuthHeadersForAccessToken() 0 16 1
B buildOAuthHeaders() 0 26 2
A with() 0 8 2
A offsetSet() 0 4 1
A offsetUnset() 0 4 1
A offsetExists() 0 4 1
A __isset() 0 4 1
A getAuthenticateUrl() 0 8 2
1
<?php
2
3
namespace mpyw\Cowitter\Components;
4
use mpyw\Cowitter\Helpers\CredentialNormalizer;
5
6
class Credential implements \ArrayAccess
7
{
8
    protected $consumer_key;
9
    protected $consumer_secret;
10
    protected $token = '';
11
    protected $token_secret = '';
12
13 69
    public function __construct(array $params = [])
14 69
    {
15 69
        foreach ($params as $key => $value) {
16 69
            $this->{CredentialNormalizer::normalizeCredentialParamName($key)} = $value;
17
        }
18 69
        if ($this->consumer_key === null || $this->consumer_secret === null) {
19 1
            throw new \DomainException('"consumer_key" and "consumer_secret" are at least required.');
20
        }
21 68
    }
22
23
    public function with(array $params = [])
24
    {
25
        $clone = clone $this;
26
        foreach ($params as $key => $value) {
27
            $this->{CredentialNormalizer::normalizeCredentialParamName($key)} = $value;
28
        }
29
        return $clone;
30
    }
31
32 18
    public function toArray($assoc = false)
33 18
    {
34 18
        $values = get_object_vars($this);
35 18
        return $assoc ? $values : array_values($values);
36
    }
37
38 12
    public function offsetGet($offset)
39 12
    {
40 12
        return $this->{CredentialNormalizer::normalizeCredentialParamName($offset)};
41
    }
42
43
    public function offsetSet($offset, $value)
44
    {
45
        throw new \BadMethodCallException('Unsupported operation.');
46
    }
47
48
    public function offsetUnset($offset)
49
    {
50
        throw new \BadMethodCallException('Unsupported operation.');
51
    }
52
53
    public function offsetExists($offset)
54
    {
55
        return isset($this->$offset);
56
    }
57
58 2
    public function __get($key)
59 2
    {
60 2
        return $this->{CredentialNormalizer::normalizeCredentialParamName($key)};
61
    }
62
63
    public function __isset($key)
64
    {
65
        return isset($this->{CredentialNormalizer::normalizeCredentialParamName($key)});
66
    }
67
68 4
    public function getAuthorizeUrl($force_login = false)
69 4
    {
70 4
        $params = http_build_query([
71 4
            'oauth_token' => $this->token,
72 4
            'force_login' => $force_login ? 1 : null,
73 4
        ], '', '&');
74 4
        return 'https://api.twitter.com/oauth/authorize?' . $params;
75
    }
76
77
    public function getAuthenticateUrl($force_login = false)
78
    {
79
        $params = http_build_query([
80
            'oauth_token' => $this->token,
81
            'force_login' => $force_login ? 1 : null,
82
        ], '', '&');
83
        return 'https://api.twitter.com/oauth/authenticate?' . $params;
84
    }
85
86 46
    public function getOAuthHeaders($url, $method, array $endpoint_params)
87 46
    {
88 46
        return static::buildOAuthHeaders(
89
            $url,
90
            $method,
91
            [
92 46
                'oauth_consumer_key' => $this->consumer_key,
93 46
                'oauth_token'        => $this->token,
94
            ],
95 46
            [$this->consumer_secret, $this->token_secret],
96
            $endpoint_params
97
        );
98
    }
99
100 4
    public function getBasicHeaders()
101 4
    {
102 4
        $header = base64_encode(implode(':', array_map('rawurlencode', [
103 4
            $this->consumer_key,
104 4
            $this->consumer_secret,
105
        ])));
106 4
        return ['Authorization: Basic ' . $header];
107
    }
108
109 2
    public function getBearerHeaders()
110 2
    {
111 2
        return ['Authorization: Bearer ' . $this->token];
112
    }
113
114 6
    public function getOAuthHeadersForOAuthEcho()
115 6
    {
116 6
        $url     = 'https://api.twitter.com/1.1/account/verify_credentials.json';
117 6
        $headers = static::getOAuthHeaders($url, 'GET', []);
118
        return [
119 6
            'X-Auth-Service-Provider: ' . $url,
120 6
            'X-Verify-Credentials-Authorization: OAuth realm="http://api.twitter.com/", ' . substr($headers[0], 21),
121
        ];
122
    }
123
124 6
    public function getOAuthHeadersForRequestToken($oauth_callback = null)
125 6
    {
126 6
        return static::buildOAuthHeaders(
127 6
            'https://api.twitter.com/oauth/request_token',
128 6
            'POST',
129
            [
130 6
                'oauth_consumer_key' => $this->consumer_key,
131 6
            ] + ($oauth_callback === null ? [] :
132
            [
133 6
                'oauth_callback' => $oauth_callback,
134
            ]),
135 6
            [$this->consumer_secret, ''],
136 6
            []
137
        );
138
    }
139
140 4
    public function getOAuthHeadersForAccessToken($oauth_verifier)
141 4
    {
142 4
        return static::buildOAuthHeaders(
143 4
            'https://api.twitter.com/oauth/access_token',
144 4
            'POST',
145
            [
146 4
                'oauth_consumer_key' => $this->consumer_key,
147 4
                'oauth_token'        => $this->token,
148 4
                'oauth_verifier'     => $oauth_verifier,
149
            ],
150 4
            [$this->consumer_secret, $this->token_secret],
151 4
            []
152
        );
153
    }
154
155 2
    public function getXAuthHeadersForAccessToken($username, $password)
156 2
    {
157 2
        return static::buildOAuthHeaders(
158 2
            'https://api.twitter.com/oauth/access_token',
159 2
            'POST',
160
            [
161 2
                'oauth_consumer_key' => $this->consumer_key,
162
            ],
163 2
            [$this->consumer_secret, ''],
164
            [
165 2
                'x_auth_username' => $username,
166 2
                'x_auth_password' => $password,
167 2
                'x_auth_mode'     => 'client_auth',
168
            ]
169
        );
170
    }
171
172 56
    protected static function buildOAuthHeaders($url, $method, array $oauth_params, array $key_params, array $endpoint_params)
173 56
    {
174
        $oauth_params += [
175 56
            'oauth_signature_method' => 'HMAC-SHA1',
176 56
            'oauth_timestamp'        => time(),
177 56
            'oauth_version'          => '1.0a',
178 56
            'oauth_nonce'            => sha1(openssl_random_pseudo_bytes(32)),
179
        ];
180 56
        $base = $oauth_params + $endpoint_params;
181 56
        uksort($base, 'strnatcmp');
182 56
        $oauth_params['oauth_signature'] = base64_encode(hash_hmac(
183 56
            'sha1',
184 56
            implode('&', array_map('rawurlencode', [
185 56
                strtoupper($method),
186 56
                $url,
187 56
                http_build_query($base, '', '&', PHP_QUERY_RFC3986)
188
            ])),
189 56
            implode('&', array_map('rawurlencode', $key_params)),
190 56
            true
191
        ));
192 56
        $tmp = [];
193 56
        foreach ($oauth_params as $key => $value) {
194 56
            $tmp[] = urlencode($key) . '="' . urlencode($value) . '"';
195
        }
196 56
        return ['Authorization: OAuth ' . implode(', ', $tmp)];
197
    }
198
}
199