Completed
Push — master ( 3cf178...59e65f )
by Ryosuke
03:33
created

Credential::with()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 5

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 5
nc 2
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 26
    public function __construct(array $params = [])
14 26
    {
15 26
        foreach ($params as $key => $value) {
16 26
            $this->{CredentialNormalizer::normalizeCredentialParamName($key)} = $value;
17
        }
18 26
        if ($this->consumer_key === null || $this->consumer_secret === null) {
19
            throw new \DomainException('"consumer_key" and "consumer_secret" are at least required.');
20
        }
21 26
    }
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 2
    public function toArray($assoc = false)
33 2
    {
34 2
        $values = get_object_vars($this);
35 2
        return $assoc ? $values : array_values($values);
36
    }
37
38
    public function offsetGet($offset)
39
    {
40
        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 26
    public function getOAuthHeaders($url, $method, array $endpoint_params)
87 26
    {
88 26
        return static::buildOAuthHeaders(
89
            $url,
90
            $method,
91
            [
92 26
                'oauth_consumer_key' => $this->consumer_key,
93 26
                'oauth_token'        => $this->token,
94
            ],
95 26
            [$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
    public function getOAuthHeadersForOAuthEcho()
115
    {
116
        $url     = 'https://api.twitter.com/1.1/account/verify_credentials.json';
117
        $headers = static::getOAuthHeaders($url, 'GET', []);
118
        return [
119
            'X-Auth-Service-Provider: ' . $url,
120
            'X-Verify-Credentials-Authorization: OAuth realm="http://api.twitter.com/", ' . substr($headers[0], 21),
121
        ];
122
    }
123
124
    public function getOAuthHeadersForRequestToken($oauth_callback = null)
125
    {
126
        return static::buildOAuthHeaders(
127
            'https://api.twitter.com/oauth/request_token',
128
            'POST',
129
            [
130
                'oauth_consumer_key' => $this->consumer_key,
131
            ] + ($oauth_callback === null ? [] :
132
            [
133
                'oauth_callback' => $oauth_callback,
134
            ]),
135
            [$this->consumer_secret, ''],
136
            []
137
        );
138
    }
139
140
    public function getOAuthHeadersForAccessToken($oauth_verifier)
141
    {
142
        return static::buildOAuthHeaders(
143
            'https://api.twitter.com/oauth/access_token',
144
            'POST',
145
            [
146
                'oauth_consumer_key' => $this->consumer_key,
147
                'oauth_token'        => $this->token,
148
                'oauth_verifier'     => $oauth_verifier,
149
            ],
150
            [$this->consumer_secret, $this->token_secret],
151
            []
152
        );
153
    }
154
155
    public function getXAuthHeadersForAccessToken($username, $password)
156
    {
157
        return static::buildOAuthHeaders(
158
            'https://api.twitter.com/oauth/access_token',
159
            'POST',
160
            [
161
                'oauth_consumer_key' => $this->consumer_key,
162
            ],
163
            [$this->consumer_secret, ''],
164
            [
165
                'x_auth_username' => $username,
166
                'x_auth_password' => $password,
167
                'x_auth_mode'     => 'client_auth',
168
            ]
169
        );
170
    }
171
172 26
    protected static function buildOAuthHeaders($url, $method, array $oauth_params, array $key_params, array $endpoint_params)
173 26
    {
174
        $oauth_params += [
175 26
            'oauth_signature_method' => 'HMAC-SHA1',
176 26
            'oauth_timestamp'        => time(),
177 26
            'oauth_version'          => '1.0a',
178 26
            'oauth_nonce'            => sha1(openssl_random_pseudo_bytes(32)),
179
        ];
180 26
        $base = $oauth_params + $endpoint_params;
181 26
        uksort($base, 'strnatcmp');
182 26
        $oauth_params['oauth_signature'] = base64_encode(hash_hmac(
183 26
            'sha1',
184 26
            implode('&', array_map('rawurlencode', [
185 26
                strtoupper($method),
186 26
                $url,
187 26
                http_build_query($base, '', '&', PHP_QUERY_RFC3986)
188
            ])),
189 26
            implode('&', array_map('rawurlencode', $key_params)),
190 26
            true
191
        ));
192 26
        $tmp = [];
193 26
        foreach ($oauth_params as $key => $value) {
194 26
            $tmp[] = urlencode($key) . '="' . urlencode($value) . '"';
195
        }
196 26
        return ['Authorization: OAuth ' . implode(', ', $tmp)];
197
    }
198
}
199