Passed
Push — master ( 9669ff...b5fcce )
by Solo
02:07
created

Credential::getOAuthHeaders()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 18
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 2.0023

Importance

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