Completed
Push — master ( 458684...f006a2 )
by Ryosuke
02:58
created

Credential::getAuthenticateUrl()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 8
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 8
ccs 0
cts 0
cp 0
rs 9.4285
cc 2
eloc 6
nc 1
nop 1
crap 6
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 53
    public function __construct(array $params = [])
14 53
    {
15 53
        foreach ($params as $key => $value) {
16 53
            $this->{CredentialNormalizer::normalizeCredentialParamName($key)} = $value;
17
        }
18 53
        if ($this->consumer_key === null || $this->consumer_secret === null) {
19
            throw new \DomainException('"consumer_key" and "consumer_secret" are at least required.');
20
        }
21 53
    }
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 9
    public function toArray($assoc = false)
33 9
    {
34 9
        $values = get_object_vars($this);
35 9
        return $assoc ? $values : array_values($values);
36
    }
37
38 6
    public function offsetGet($offset)
39 6
    {
40 6
        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
    public function __get($key)
59
    {
60
        return $this->{CredentialNormalizer::normalizeCredentialParamName($key)};
61
    }
62
63
    public function __isset($key)
64
    {
65
        return isset($this->{CredentialNormalizer::normalizeCredentialParamName($key)});
66
    }
67
68
    public function getAuthorizeUrl($force_login = false)
69
    {
70
        $params = http_build_query([
71
            'oauth_token' => $this->token,
72
            'force_login' => $force_login ? 1 : null,
73
        ], '', '&');
74
        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 40
    public function getOAuthHeaders($url, $method, array $endpoint_params)
87 40
    {
88 40
        return static::buildOAuthHeaders(
89
            $url,
90
            $method,
91
            [
92 40
                'oauth_consumer_key' => $this->consumer_key,
93 40
                'oauth_token'        => $this->token,
94
            ],
95 40
            [$this->consumer_secret, $this->token_secret],
96
            $endpoint_params
97
        );
98
    }
99
100
    public function getBasicHeaders()
101
    {
102
        $header = base64_encode(implode(':', array_map('rawurlencode', [
103
            $this->consumer_key,
104
            $this->consumer_secret,
105
        ])));
106
        return ['Authorization: Basic ' . $header];
107
    }
108
109
    public function getBearerHeaders()
110
    {
111
        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 2
    public function getOAuthHeadersForRequestToken($oauth_callback = null)
125 2
    {
126 2
        return static::buildOAuthHeaders(
127 2
            'https://api.twitter.com/oauth/request_token',
128 2
            'POST',
129
            [
130 2
                'oauth_consumer_key' => $this->consumer_key,
131 2
            ] + ($oauth_callback === null ? [] :
132
            [
133 2
                'oauth_callback' => $oauth_callback,
134
            ]),
135 2
            [$this->consumer_secret, ''],
136 2
            []
137
        );
138
    }
139
140 2
    public function getOAuthHeadersForAccessToken($oauth_verifier)
141 2
    {
142 2
        return static::buildOAuthHeaders(
143 2
            'https://api.twitter.com/oauth/access_token',
144 2
            'POST',
145
            [
146 2
                'oauth_consumer_key' => $this->consumer_key,
147 2
                'oauth_token'        => $this->token,
148 2
                'oauth_verifier'     => $oauth_verifier,
149
            ],
150 2
            [$this->consumer_secret, $this->token_secret],
151 2
            []
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 46
    protected static function buildOAuthHeaders($url, $method, array $oauth_params, array $key_params, array $endpoint_params)
173 46
    {
174
        $oauth_params += [
175 46
            'oauth_signature_method' => 'HMAC-SHA1',
176 46
            'oauth_timestamp'        => time(),
177 46
            'oauth_version'          => '1.0a',
178 46
            'oauth_nonce'            => sha1(openssl_random_pseudo_bytes(32)),
179
        ];
180 46
        $base = $oauth_params + $endpoint_params;
181 46
        uksort($base, 'strnatcmp');
182 46
        $oauth_params['oauth_signature'] = base64_encode(hash_hmac(
183 46
            'sha1',
184 46
            implode('&', array_map('rawurlencode', [
185 46
                strtoupper($method),
186 46
                $url,
187 46
                http_build_query($base, '', '&', PHP_QUERY_RFC3986)
188
            ])),
189 46
            implode('&', array_map('rawurlencode', $key_params)),
190 46
            true
191
        ));
192 46
        $tmp = [];
193 46
        foreach ($oauth_params as $key => $value) {
194 46
            $tmp[] = urlencode($key) . '="' . urlencode($value) . '"';
195
        }
196 46
        return ['Authorization: OAuth ' . implode(', ', $tmp)];
197
    }
198
}
199