Twitter   A
last analyzed

Complexity

Total Complexity 16

Size/Duplication

Total Lines 157
Duplicated Lines 20.38 %

Coupling/Cohesion

Components 2
Dependencies 8

Importance

Changes 0
Metric Value
wmc 16
c 0
b 0
f 0
lcom 2
cbo 8
dl 32
loc 157
rs 10

8 Methods

Rating   Name   Duplication   Size   Complexity  
C request() 0 38 7
A post() 0 22 2
A postMedia() 0 13 1
A getAuthorizationUri() 0 6 1
A storeOauthToken() 0 13 2
B getProfile() 24 24 1
A getPermissions() 0 4 1
A getStats() 8 8 1

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
namespace Borfast\Socializr\Connectors;
4
5
use Borfast\Socializr\Exceptions\DuplicatePostException;
6
use OAuth\Common\Storage\Exception\TokenNotFoundException;
7
use Borfast\Socializr\Exceptions\AuthorizationException;
8
use Borfast\Socializr\Exceptions\GenericPostingException;
9
use Borfast\Socializr\Post;
10
use Borfast\Socializr\Profile;
11
use Borfast\Socializr\Response;
12
use Borfast\Socializr\Exceptions\ExpiredTokenException;
13
14
class Twitter extends AbstractConnector
15
{
16
    public static $provider = 'Twitter';
17
18
    protected $user_id;
19
    protected $screen_name;
20
21
22
    public function request($path, $method = 'GET', $params = [], $headers = [])
23
    {
24
        $result = parent::request($path, $method, $params, $headers);
25
        $json_result = json_decode($result, true);
26
27
        // Since Twitter can return more than one error, we'll need to check if
28
        // we have an expired token separately.
29
        $error_type = 'generic';
30
        if (isset($json_result['errors'])) {
31
            $errors = $json_result['errors'];
32
            $msg = 'Error accessing Twitter. Error count: %s.';
33
            $msg = sprintf($msg, count($errors));
34
            $i = 0;
35
36
            foreach ($errors as $error) {
37
                $msg2 = "\nError %d -- Error code: %s. Message: %s";
38
                $msg .= sprintf($msg2, $i, $error['code'], $error['message']);
39
                $i++;
40
41
                // If it's an expired token...
42
                if ($error['code'] == 89) {
43
                    $error_type = 'expired';
44
                } elseif ($error['code'] == 187) {
45
                    $error_type = 'duplicate';
46
                }
47
            }
48
49
            if ($error_type == 'expired') {
50
                throw new ExpiredTokenException($msg);
51
            } elseif ($error_type == 'duplicate') {
52
                throw new DuplicatePostException($msg);
53
            } else {
54
                throw new GenericPostingException($msg);
55
            }
56
        }
57
58
        return $result;
59
    }
60
61
62
    public function post(Post $post)
63
    {
64
        $path = '/statuses/update.json';
65
        $method = 'POST';
66
        $params = [
67
            'status' => $post->body
68
        ];
69
70
        if (!empty($post->media)) {
71
            $params['media_ids'] = implode(',', $post->media);
72
        }
73
74
        $result = $this->request($path, $method, $params);
75
76
        $response = new Response;
77
        $response->setRawResponse(json_encode($result));
78
        $result_json = json_decode($result);
79
        $response->setProvider('Twitter');
80
        $response->setPostId($result_json->id_str);
81
82
        return $response;
83
    }
84
85
86
    public function postMedia($media)
87
    {
88
        $path = 'https://upload.twitter.com/1.1/media/upload.json';
89
        $method = 'POST';
90
        $params = [
91
            'media' => $media
92
        ];
93
94
        $result = $this->request($path, $method, $params);
95
        $json_result = json_decode($result, true);
96
97
        return $json_result;
98
    }
99
100
101
    /**
102
     * Twitter needs an extra step for authentication before providing an
103
     * authorization URL.
104
     *
105
     * @author Raúl Santos
106
     */
107
    public function getAuthorizationUri(array $params = [])
108
    {
109
        $token = $this->service->requestRequestToken();
0 ignored issues
show
Bug introduced by
The method requestRequestToken() does not exist on OAuth\Common\Service\ServiceInterface. Did you maybe mean request()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
110
        $extra = ['oauth_token' => $token->getRequestToken()];
111
        return parent::getAuthorizationUri($extra);
112
    }
113
114
115
    /**
116
     * Retrieve the auth token from the provider's response and store it.
117
     */
118
    public function storeOauthToken($params)
119
    {
120
        try {
121
            $token = $this->service->getStorage()->retrieveAccessToken('Twitter');
122
        } catch (TokenNotFoundException $e) {
123
            throw new AuthorizationException();
124
        }
125
        $result = $this->service->requestAccessToken($params['oauth_token'], $params['oauth_verifier'], $token->getRequestTokenSecret());
0 ignored issues
show
Bug introduced by
The method requestAccessToken() does not exist on OAuth\Common\Service\ServiceInterface. Did you maybe mean request()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
126
127
        $extra_params = $result->getExtraParams();
128
        $this->user_id = $extra_params['user_id'];
129
        $this->screen_name = $extra_params['screen_name'];
130
    }
131
132 View Code Duplication
    public function getProfile()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
133
    {
134
        $path = '/account/verify_credentials.json?skip_status=1';
135
        $result = $this->request($path);
136
        $profile_json = json_decode($result, true);
137
138
        $mapping = [
139
            'id' => 'id_str',
140
            // 'email' => 'email',
0 ignored issues
show
Unused Code Comprehensibility introduced by
58% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
141
            'name' => 'name',
142
            'first_name' => 'first_name',
143
            'middle_name' => 'middle_name',
144
            'last_name' => 'last_name',
145
            'username' => 'screen_name',
146
            'link' => 'link'
147
        ];
148
149
        $profile = Profile::create($mapping, $profile_json);
150
        $profile->provider = static::$provider;
151
        $profile->raw_response = $result;
152
        $profile->link = 'https://twitter.com/'.$profile_json['screen_name'];
153
154
        return $profile;
155
    }
156
157
    public function getPermissions()
158
    {
159
        return null;
160
    }
161
162 View Code Duplication
    public function getStats()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
163
    {
164
        $path = '/followers/ids.json?user_id='.$this->id;
165
        $response = $this->request($path);
166
        $response = json_decode($response);
167
        $response = count($response->ids);
168
        return $response;
169
    }
170
}
171