Completed
Push — master ( f2592a...8849ab )
by
unknown
06:43
created

Facebook   A

Complexity

Total Complexity 23

Size/Duplication

Total Lines 224
Duplicated Lines 3.57 %

Coupling/Cohesion

Components 1
Dependencies 9

Importance

Changes 21
Bugs 3 Features 3
Metric Value
wmc 23
c 21
b 3
f 3
lcom 1
cbo 9
dl 8
loc 224
rs 10

8 Methods

Rating   Name   Duplication   Size   Complexity  
C request() 0 44 8
A post() 0 47 3
B getProfile() 0 26 2
A getPermissions() 0 7 1
A getStats() 0 4 1
B getPages() 8 30 3
B getGroups() 0 30 3
A getFriendsCount() 0 15 2

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\AuthorizationException;
6
use Borfast\Socializr\Exceptions\ExpiredTokenException;
7
use Borfast\Socializr\Exceptions\GenericPostingException;
8
use Borfast\Socializr\Group;
9
use Borfast\Socializr\Page;
10
use Borfast\Socializr\Post;
11
use Borfast\Socializr\Profile;
12
use Borfast\Socializr\Response;
13
14
class Facebook extends AbstractConnector
15
{
16
    public static $provider = 'Facebook';
17
18
    /** @var Profile */
19
    protected $profile = null;
20
21
    public function request($path, $method = 'GET', $params = [], $headers = [])
22
    {
23
        $result = parent::request($path, $method, $params, $headers);
24
25
        $json_result = json_decode($result, true);
26
27
28
        if (isset($json_result['error'])) {
29
            if (isset($json_result['error']['error_subcode'])) {
30
                $error_subcode = $json_result['error']['error_subcode'];
31
            } else {
32
                $error_subcode = 'n/a';
33
            }
34
35
            $error_type = $json_result['error']['type'];
36
            $error_code = $json_result['error']['code'];
37
            $error_message = $json_result['error']['message'];
38
39
            $msg = 'Error type: %s. Error code: %s. Error subcode: %s. Message: %s';
40
            $msg = sprintf(
41
                $msg,
42
                $error_type,
43
                $error_code,
44
                $error_subcode,
45
                $error_message
46
            );
47
48
49
            if ($error_type == 'OAuthException' &&
50
                // Handling random issues by steering them towards GenericPostingException
51
                $error_code != 1 &&
52
                strpos($error_message, 'Provided link was incorrect or disallowed') === false
53
            ) {
54
                throw new ExpiredTokenException($msg);
55
            } else if ($error_type == 'GraphMethodException' && $error_code == '100') {
56
                throw new AuthorizationException();
57
            } else {
58
                throw new GenericPostingException($msg);
59
            }
60
61
        }
62
63
        return $result;
64
    }
65
66
67
    public function post(Post $post)
68
    {
69
        $msg  = $post->title;
70
        $msg .= "\n\n";
71
        $msg .= $post->body;
72
        $msg = trim($msg);
73
74
        if (empty($post->media)) {
75
            $path = '/'.$this->getUid().'/feed';
76
77
            $params = [
78
                // 'caption' => $post->title,
0 ignored issues
show
Unused Code Comprehensibility introduced by
56% 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...
79
                'description' => '',
80
                'link' => $post->url,
81
                'message' => $msg
82
            ];
83
        } else {
84
            $path = '/'.$this->getUid().'/photos';
85
86
            $msg .= "\n";
87
            $msg .= $post->url;
88
89
            $params = [
90
                'url' => $post->media[0],
91
                'caption' => $msg
92
            ];
93
        }
94
95
        $method = 'POST';
96
97
        $result = $this->request($path, $method, $params);
98
99
        $json_result = json_decode($result, true);
100
101
        // If there's no ID, the post didn't go through
102
        if (!isset($json_result['id'])) {
103
            $msg = "Unknown error posting to Facebook profile.";
104
            throw new GenericPostingException($msg, 1);
105
        }
106
107
        $response = new Response;
108
        $response->setRawResponse($result); // This is already JSON.
109
        $response->setProvider('Facebook');
110
        $response->setPostId($json_result['id']);
111
112
        return $response;
113
    }
114
115
    public function getProfile()
116
    {
117
        if (is_null($this->profile)) {
118
            $path = '/me';
119
            $result = $this->request($path);
120
            $json_result = json_decode($result, true);
121
122
            $mapping = [
123
                'id' => 'id',
124
                'email' => 'email',
125
                'name' => 'name',
126
                'first_name' => 'first_name',
127
                'middle_name' => 'middle_name',
128
                'last_name' => 'last_name',
129
                'username' => 'username',
130
                // 'username' => 'email', // Facebook Graph API 2.0 doesn't have username
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% 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...
131
                'link' => 'link'
132
            ];
133
134
            $this->profile = Profile::create($mapping, $json_result);
135
            $this->profile->provider = static::$provider;
136
            $this->profile->raw_response = $result;
137
        }
138
139
        return $this->profile;
140
    }
141
142
    public function getPermissions()
143
    {
144
        $profile = $this->getProfile();
145
146
        $path = '/'.$profile->id.'/permissions';
147
        return $this->request($path);
148
    }
149
150
    public function getStats()
151
    {
152
        return $this->getFriendsCount();
153
    }
154
155
    public function getPages()
156
    {
157
        $profile = $this->getProfile();
158
159
        $path = '/'.$profile->id.'/accounts?fields=name,picture,access_token,id,can_post,likes,link,username';
160
        $result = $this->request($path);
161
        $json_result = json_decode($result, true);
162
163
        $pages = [];
164
165
        $mapping = [
166
            'id' => 'id',
167
            'name' => 'name',
168
            'link' => 'link',
169
            'can_post' => 'can_post',
170
            'access_token' => 'access_token'
171
        ];
172
173
        // Make the page IDs available as the array keys
174 View Code Duplication
        if (!empty($json_result['data'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
175
            foreach ($json_result['data'] as $page) {
176
                $pages[$page['id']] = Page::create($mapping, $page);
177
                $pages[$page['id']]->picture = $page['picture']['data']['url'];
178
                $pages[$page['id']]->provider = static::$provider;
179
                $pages[$page['id']]->raw_response = $result;
180
            }
181
        }
182
183
        return $pages;
184
    }
185
186
    public function getGroups()
187
    {
188
        $profile = $this->getProfile();
189
190
        $path = '/'.$profile->id.'/groups?fields=id,name,icon';
191
        $result = $this->request($path);
192
        $json_result = json_decode($result, true);
193
194
        $groups = [];
195
196
        $mapping = [
197
            'id' => 'id',
198
            'name' => 'name',
199
            'picture' => 'icon'
200
        ];
201
202
        // Make the group IDs available as the array keys
203
        if (!empty($json_result['data'])) {
204
            foreach ($json_result['data'] as $group) {
205
                $groups[$group['id']] = Group::create($mapping, $group);
206
                $groups[$group['id']]->picture = $group['icon'];
207
                $groups[$group['id']]->link = 'https://www.facebook.com/groups/' . $group['id'];
208
                $groups[$group['id']]->can_post = true;
209
                $groups[$group['id']]->provider = static::$provider;
210
                $groups[$group['id']]->raw_response = $result;
211
            }
212
        }
213
214
        return $groups;
215
    }
216
217
    /****************************************************
218
     *
219
     * From here on these are Facebook-specific methods.
220
     *
221
     ***************************************************/
222
    public function getFriendsCount()
223
    {
224
        $path = '/'.$this->getUid().'/friends';
225
        $result = $this->request($path);
226
227
        $response = json_decode($result);
228
229
        if (property_exists($response, 'summary')) {
230
            $response = $response->summary->total_count;
231
        } else {
232
            $response = '-';
233
        }
234
235
        return $response;
236
    }
237
}
238