Completed
Push — master ( 56c982...731a12 )
by Matthew
03:00
created

AutomatedEditsHelper   A

Complexity

Total Complexity 17

Size/Duplication

Total Lines 169
Duplicated Lines 18.93 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 0
Metric Value
wmc 17
c 0
b 0
f 0
lcom 1
cbo 4
dl 32
loc 169
rs 10

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A isAutomated() 10 10 3
A isRevert() 12 12 3
A getTool() 10 10 3
A getTools() 0 8 2
B getNonautomatedEdits() 0 69 5

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 AppBundle\Helper;
4
5
use DateTime;
6
use Doctrine\DBAL\Connection;
7
use Psr\Cache\CacheItemPoolInterface;
8
use Symfony\Component\Config\Definition\Exception\Exception;
9
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
10
use Symfony\Component\DependencyInjection\ContainerInterface;
11
use Symfony\Component\VarDumper\VarDumper;
12
use Xtools\ProjectRepository;
13
14
class AutomatedEditsHelper extends HelperBase
15
{
16
17
    /** @var string[] The list of tools that are considered reverting. */
18
    public $revertTools = [
19
        'Generic rollback',
20
        'Undo',
21
        'Pending changes revert',
22
        'Huggle',
23
        'STiki',
24
        'Igloo',
25
        'WikiPatroller',
26
        'Twinkle revert',
27
        'Bot revert'
28
    ];
29
30
    /** @var string[] The list of tool names and their regexes. */
31
    protected $tools;
32
33
    public function __construct(ContainerInterface $container)
34
    {
35
        $this->container = $container;
0 ignored issues
show
Documentation Bug introduced by
$container is of type object<Symfony\Component...ion\ContainerInterface>, but the property $container was declared to be of type object<Symfony\Component...ncyInjection\Container>. Are you sure that you always receive this specific sub-class here, or does it make sense to add an instanceof check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a given class or a super-class is assigned to a property that is type hinted more strictly.

Either this assignment is in error or an instanceof check should be added for that assignment.

class Alien {}

class Dalek extends Alien {}

class Plot
{
    /** @var  Dalek */
    public $villain;
}

$alien = new Alien();
$plot = new Plot();
if ($alien instanceof Dalek) {
    $plot->villain = $alien;
}
Loading history...
36
    }
37
38
    /**
39
     * Was the edit (semi-)automated, based on the edit summary?
40
     * @param  string  $summary Edit summary
41
     * @return boolean          Yes or no
42
     */
43 View Code Duplication
    public function isAutomated($summary)
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...
44
    {
45
        foreach ($this->getTools() as $tool => $regex) {
46
            if (preg_match("/$regex/", $summary)) {
47
                return true;
48
            }
49
        }
50
51
        return false;
52
    }
53
54
    /**
55
     * Was the edit a revert, based on the edit summary?
56
     * @param  string $summary Edit summary
57
     * @return boolean         Yes or no
58
     */
59 View Code Duplication
    public function isRevert($summary)
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...
60
    {
61
        foreach ($this->revertTools as $tool) {
62
            $regex = $this->getTools()[$tool];
63
64
            if (preg_match("/$regex/", $summary)) {
65
                return true;
66
            }
67
        }
68
69
        return false;
70
    }
71
72
    /**
73
     * Get the name of the tool that matched the given edit summary
74
     * @param  string $summary Edit summary
75
     * @return string|boolean  Name of tool, or false if nothing was found
76
     */
77 View Code Duplication
    public function getTool($summary)
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...
78
    {
79
        foreach ($this->getTools() as $tool => $regex) {
80
            if (preg_match("/$regex/", $summary)) {
81
                return $tool;
82
            }
83
        }
84
85
        return false;
86
    }
87
88
    /**
89
     * Get the list of automated tools
90
     * @return array Associative array of 'tool name' => 'regex'
91
     */
92
    public function getTools()
93
    {
94
        if (is_array($this->tools)) {
95
            return $this->tools;
96
        }
97
        $this->tools = $this->container->getParameter("automated_tools");
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->container->getParameter('automated_tools') of type * is incompatible with the declared type array<integer,string> of property $tools.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
98
        return $this->tools;
99
    }
100
101
    /**
102
     * Get a list of nonautomated edits by a user
103
     * @param  string         $project   Project domain such as en.wikipedia.org
104
     * @param  string         $username
105
     * @param  string|integer $namespace Numerical value or 'all' for all namespaces
106
     * @param  integer        $offset    Used for pagination, offset results by N edits
107
     * @return string[]       Data as returned by database query, includes:
108
     *                        'page_title' (string, including namespace),
109
     *                        'namespace' (integer), 'rev_id' (int),
110
     *                        'timestamp' (DateTime), 'minor_edit' (bool)
111
     *                        'sumamry' (string)
112
     */
113
    public function getNonautomatedEdits($project, $username, $namespace, $offset = 0)
114
    {
115
        $project = ProjectRepository::getProject($project, $this->container);
116
        $namespaces = $project->getNamespaces();
117
118
        $conn = $this->container->get('doctrine')->getManager('replicas')->getConnection();
119
120
        $lh = $this->container->get('app.labs_helper');
121
        $revTable = $lh->getTable('revision', $project->getDatabaseName());
122
        $pageTable = $lh->getTable('page', $project->getDatabaseName());
123
124
        $AEBTypes = $this->container->getParameter('automated_tools');
125
        $allAETools = $conn->quote(implode('|', $AEBTypes), \PDO::PARAM_STR);
126
127
        $namespaceClause = $namespace === 'all' ? '' : "AND rev_namespace = $namespace";
0 ignored issues
show
Unused Code introduced by
$namespaceClause is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
128
129
        // First get the non-automated contribs
130
        $query = "SELECT page_title, page_namespace, rev_id, rev_len, rev_parent_id,
131
                         rev_timestamp, rev_minor_edit, rev_comment
132
                  FROM $pageTable JOIN $revTable ON page_id = rev_page
133
                  WHERE rev_user_text = :username
134
                  AND rev_timestamp > 0
135
                  AND rev_comment NOT RLIKE $allAETools
136
                  ORDER BY rev_id DESC
137
                  LIMIT 50
138
                  OFFSET $offset";
139
        $editData = $conn->executeQuery($query, ['username' => $username])->fetchAll();
140
141
        // Get diff sizes, based on length of each parent revision
142
        $parentRevIds = array_map(function ($edit) {
143
            return $edit['rev_parent_id'];
144
        }, $editData);
145
        $query = "SELECT rev_len, rev_id
146
                  FROM revision
147
                  WHERE rev_id IN (" . implode(',', $parentRevIds) . ")";
148
        $diffSizeData = $conn->executeQuery($query)->fetchAll();
149
150
        // reformat with rev_id as the key, rev_len as the value
151
        $diffSizes = [];
152
        foreach ($diffSizeData as $diff) {
153
            $diffSizes[$diff['rev_id']] = $diff['rev_len'];
154
        }
155
156
        // Build our array of nonautomated edits
157
        $editData = array_map(function ($edit) use ($namespaces, $diffSizes) {
158
            $pageTitle = $edit['page_title'];
159
160
            if ($edit['page_namespace'] !== '0') {
161
                $pageTitle = $namespaces[$edit['page_namespace']] . ":$pageTitle";
162
            }
163
164
            $diffSize = $edit['rev_len'];
165
            if ($edit['rev_parent_id'] > 0) {
166
                $diffSize = $edit['rev_len'] - $diffSizes[$edit['rev_parent_id']];
167
            }
168
169
            return [
170
                'page_title' => $pageTitle,
171
                'namespace' => (int) $edit['page_namespace'],
172
                'rev_id' => (int) $edit['rev_id'],
173
                'timestamp' => DateTime::createFromFormat('YmdHis', $edit['rev_timestamp']),
174
                'minor_edit' => (bool) $edit['rev_minor_edit'],
175
                'summary' => $edit['rev_comment'],
176
                'size' => $diffSize
177
            ];
178
        }, $editData);
179
180
        return $editData;
181
    }
182
}
183