Failed Conditions
Pull Request — newinternal (#527)
by Simon
17:20 queued 07:22
created

BotMediaWikiClient   A

Complexity

Total Complexity 14

Size/Duplication

Total Lines 135
Duplicated Lines 8.89 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 0
Metric Value
dl 12
loc 135
rs 10
c 0
b 0
f 0
wmc 14
lcom 1
cbo 4

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 13 1
A doApiCall() 0 7 1
A ensureLoggedIn() 0 24 4
A callApi() 9 22 4
A logIn() 3 36 4

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
 * Wikipedia Account Creation Assistance tool                                 *
4
 *                                                                            *
5
 * All code in this file is released into the public domain by the ACC        *
6
 * Development Team. Please see team.json for a list of contributors.         *
7
 ******************************************************************************/
8
9
namespace Waca\Helpers;
10
11
use Waca\Exceptions\ApplicationLogicException;
12
use Waca\Exceptions\CurlException;
13
use Waca\Exceptions\MediaWikiApiException;
14
use Waca\Helpers\Interfaces\IMediaWikiClient;
15
use Waca\SiteConfiguration;
16
17
class BotMediaWikiClient implements IMediaWikiClient
18
{
19
    /**
20
     * @var HttpHelper
21
     */
22
    private $httpHelper;
23
    /** @var string */
24
    private $mediawikiWebServiceEndpoint;
25
    /** @var string */
26
    private $creationBotUsername;
27
    /** @var string */
28
    private $creationBotPassword;
29
    /** @var bool */
30
    private $knownLoggedIn = false;
31
32
    /**
33
     * BotMediaWikiClient constructor.
34
     *
35
     * @param SiteConfiguration $siteConfiguration
36
     */
37
    public function __construct(SiteConfiguration $siteConfiguration)
38
    {
39
        $this->mediawikiWebServiceEndpoint = $siteConfiguration->getMediawikiWebServiceEndpoint();
40
41
        $this->creationBotUsername = $siteConfiguration->getCreationBotUsername();
42
        $this->creationBotPassword = $siteConfiguration->getCreationBotPassword();
43
44
        $this->httpHelper = new HttpHelper(
45
            $siteConfiguration->getUserAgent(),
46
            $siteConfiguration->getCurlDisableVerifyPeer(),
47
            $siteConfiguration->getCurlCookieJar()
48
        );
49
    }
50
51
    function doApiCall($apiParams, $method = 'GET')
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
52
    {
53
        $this->ensureLoggedIn();
54
        $apiParams['assert'] = 'user';
55
56
        return $this->callApi($apiParams, $method);
57
    }
58
59
    private function ensureLoggedIn()
60
    {
61
        if ($this->knownLoggedIn) {
62
            return;
63
        }
64
65
        $userinfoResult = $this->callApi(array('action' => 'query', 'meta' => 'userinfo'), 'GET');
66
        if (isset($userinfoResult->query->userinfo->anon)) {
67
            // not logged in.
68
            $this->logIn();
69
70
            // retest
71
            $userinfoResult = $this->callApi(array('action' => 'query', 'meta' => 'userinfo'), 'GET');
72
            if (isset($userinfoResult->query->userinfo->anon)) {
73
                throw new MediaWikiApiException('Unable to log in.');
74
            }
75
            else {
76
                $this->knownLoggedIn = true;
77
            }
78
        }
79
        else {
80
            $this->knownLoggedIn = true;
81
        }
82
    }
83
84
    /**
85
     * @param $apiParams
86
     * @param $method
87
     *
88
     * @return mixed
89
     * @throws ApplicationLogicException
90
     * @throws CurlException
91
     */
92
    private function callApi($apiParams, $method)
93
    {
94
        $apiParams['format'] = 'json';
95
96 View Code Duplication
        if ($method == 'GET') {
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...
97
            $data = $this->httpHelper->get($this->mediawikiWebServiceEndpoint, $apiParams);
98
        }
99
        elseif ($method == 'POST') {
100
            $data = $this->httpHelper->post($this->mediawikiWebServiceEndpoint, $apiParams);
101
        }
102
        else {
103
            throw new ApplicationLogicException('Unsupported HTTP Method');
104
        }
105
106
        if ($data === false) {
107
            throw new CurlException('Curl error: ' . $this->httpHelper->getError());
108
        }
109
110
        $result = json_decode($data);
111
112
        return $result;
113
    }
114
115
    private function logIn()
116
    {
117
        // get token
118
        $tokenParams = array(
119
            'action' => 'query',
120
            'meta'   => 'tokens',
121
            'type'   => 'login',
122
        );
123
124
        $response = $this->callApi($tokenParams, 'POST');
125
126 View Code Duplication
        if (isset($response->error)) {
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...
127
            throw new MediaWikiApiException($response->error->code . ': ' . $response->error->info);
128
        }
129
130
        $token = $response->query->tokens->logintoken;
131
132
        if ($token === null) {
133
            throw new MediaWikiApiException('Edit token could not be acquired');
134
        }
135
136
        $params = array(
137
            'action' => 'login',
138
            'lgname' => $this->creationBotUsername,
139
            'lgpassword' => $this->creationBotPassword,
140
            'lgtoken' => $token,
141
        );
142
143
        $loginResponse = $this->callApi($params, 'POST');
144
145
        if($loginResponse->login->result == 'Success'){
146
            return;
147
        }
148
149
        throw new ApplicationLogicException(json_encode($loginResponse));
150
    }
151
}