Completed
Push — master ( 458768...717411 )
by Sam
03:06
created

EditCounterRepository::getLogCounts()   B

Complexity

Conditions 5
Paths 7

Size

Total Lines 71
Code Lines 50

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 71
rs 8.5309
c 0
b 0
f 0
cc 5
eloc 50
nc 7
nop 2

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Xtools;
4
5
use Mediawiki\Api\SimpleRequest;
6
7
class EditCounterRepository extends Repository
8
{
9
10
    /**
11
     * Get revision counts for the given user.
12
     * @param User $user The user.
13
     * @returns string[] With keys: 'deleted', 'live', 'total', 'first', 'last', '24h', '7d', '30d',
14
     * '365d', 'small', 'large', 'with_comments', and 'minor_edits'.
15
     */
16
    public function getRevisionCounts(Project $project, User $user)
17
    {
18
        // Set up cache.
19
        $cacheKey = 'revisioncounts.' . $project->getDatabaseName() . '.' . $user->getUsername();
20
        if ($this->cache->hasItem($cacheKey)) {
21
            return $this->cache->getItem($cacheKey)->get();
22
        }
23
24
        // Prepare the queries and execute them.
25
        $archiveTable = $this->getTableName($project->getDatabaseName(), 'archive');
26
        $revisionTable = $this->getTableName($project->getDatabaseName(), 'revision');
27
        $queries = [
28
            'deleted' => "SELECT COUNT(ar_id) FROM $archiveTable
29
                WHERE ar_user = :userId",
30
            'live' => "SELECT COUNT(rev_id) FROM $revisionTable
31
                WHERE rev_user = :userId",
32
            'day' => "SELECT COUNT(rev_id) FROM $revisionTable
33
                WHERE rev_user = :userId AND rev_timestamp >= DATE_SUB(NOW(), INTERVAL 1 DAY)",
34
            'week' => "SELECT COUNT(rev_id) FROM $revisionTable
35
                WHERE rev_user = :userId AND rev_timestamp >= DATE_SUB(NOW(), INTERVAL 1 WEEK)",
36
            'month' => "SELECT COUNT(rev_id) FROM $revisionTable
37
                WHERE rev_user = :userId AND rev_timestamp >= DATE_SUB(NOW(), INTERVAL 1 MONTH)",
38
            'year' => "SELECT COUNT(rev_id) FROM $revisionTable
39
                WHERE rev_user = :userId AND rev_timestamp >= DATE_SUB(NOW(), INTERVAL 1 YEAR)",
40
            'small' => "SELECT COUNT(rev_id) FROM $revisionTable
41
                WHERE rev_user = :userId AND rev_len < 20",
42
            'large' => "SELECT COUNT(rev_id) FROM $revisionTable
43
                WHERE rev_user = :userId AND rev_len > 1000",
44
            'with_comments' => "SELECT COUNT(rev_id) FROM $revisionTable
45
                WHERE rev_user = :userId AND rev_comment = ''",
46
            'minor' => "SELECT COUNT(rev_id) FROM $revisionTable
47
                WHERE rev_user = :userId AND rev_minor_edit = 1",
48
            'average_size' => "SELECT AVG(rev_len) FROM $revisionTable
49
                WHERE rev_user = :userId",
50
        ];
51
        $this->stopwatch->start($cacheKey);
52
        $revisionCounts = [];
53
        foreach ($queries as $varName => $query) {
54
            $resultQuery = $this->getProjectsConnection()->prepare($query);
55
            $userId = $user->getId($project);
56
            $resultQuery->bindParam("userId", $userId);
57
            $resultQuery->execute();
58
            $val = $resultQuery->fetchColumn();
59
            $revisionCounts[$varName] = $val ?: 0;
60
            $this->stopwatch->lap($cacheKey);
61
        }
62
63
        // Cache for 10 minutes, and return.
1 ignored issue
show
Unused Code Comprehensibility introduced by
36% 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...
64
        $this->stopwatch->stop($cacheKey);
65
        $cacheItem = $this->cache->getItem($cacheKey)
66
                ->set($revisionCounts)
67
                ->expiresAfter(new \DateInterval('PT10M'));
68
        $this->cache->save($cacheItem);
69
70
        return $revisionCounts;
71
    }
72
73
    /**
74
     * Get the first and last revision dates (in MySQL YYYYMMDDHHMMSS format).
75
     * @return string[] With keys 'first' and 'last'.
76
     */
77
    public function getRevisionDates(Project $project, User $user)
78
    {
79
        // Set up cache.
80
        $cacheKey = 'revisiondates.' . $project->getDatabaseName() . '.' . $user->getUsername();
81
        if ($this->cache->hasItem($cacheKey)) {
82
            return $this->cache->getItem($cacheKey)->get();
83
        }
84
85
        $this->stopwatch->start($cacheKey);
86
        $revisionTable = $this->getTableName($project->getDatabaseName(), 'revision');
87
        $query = "(SELECT 'first' AS `key`, rev_timestamp AS `date` FROM $revisionTable
88
            WHERE rev_user = :userId ORDER BY rev_timestamp ASC LIMIT 1)
89
            UNION
90
            (SELECT 'last' AS `key`, rev_timestamp AS `date` FROM $revisionTable
91
            WHERE rev_user = :userId ORDER BY rev_timestamp DESC LIMIT 1)";
92
        $resultQuery = $this->getProjectsConnection()->prepare($query);
93
        $userId = $user->getId($project);
94
        $resultQuery->bindParam("userId", $userId);
95
        $resultQuery->execute();
96
        $result = $resultQuery->fetchAll();
97
        $revisionDates = [];
98
        foreach ($result as $res) {
99
            $revisionDates[$res['key']] = $res['date'];
100
        }
101
102
        // Cache for 10 minutes, and return.
1 ignored issue
show
Unused Code Comprehensibility introduced by
36% 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...
103
        $cacheItem = $this->cache->getItem($cacheKey)
104
                ->set($revisionDates)
105
                ->expiresAfter(new \DateInterval('PT10M'));
106
        $this->cache->save($cacheItem);
107
        $this->stopwatch->stop($cacheKey);
108
        return $revisionDates;
109
    }
110
111
    /**
112
     * Get page counts for the given user, both for live and deleted pages/revisions.
113
     * @param Project $project The project.
114
     * @param User $user The user.
115
     * @return int[] With keys: edited-live, edited-deleted, created-live, created-deleted.
116
     */
117
    public function getPageCounts(Project $project, User $user)
118
    {
119
        // Set up cache.
120
        $cacheKey = 'pagecounts.'.$project->getDatabaseName().'.'.$user->getUsername();
121
        if ($this->cache->hasItem($cacheKey)) {
122
            return $this->cache->getItem($cacheKey)->get();
123
        }
124
        $this->stopwatch->start($cacheKey, 'XTools');
125
126
        // Build and execute query.
127
        $revisionTable = $this->getTableName($project->getDatabaseName(), 'revision');
128
        $archiveTable = $this->getTableName($project->getDatabaseName(), 'archive');
129
        $resultQuery = $this->getProjectsConnection()->prepare("
130
            (SELECT 'edited-live' AS source, COUNT(DISTINCT rev_page) AS value
131
                FROM $revisionTable
132
                WHERE rev_user_text=:username)
133
            UNION
134
            (SELECT 'edited-deleted' AS source, COUNT(DISTINCT ar_page_id) AS value
135
                FROM $archiveTable
136
                WHERE ar_user_text=:username)
137
            UNION
138
            (SELECT 'created-live' AS source, COUNT(DISTINCT rev_page) AS value
139
                FROM $revisionTable
140
                WHERE rev_user_text=:username AND rev_parent_id=0)
141
            UNION
142
            (SELECT 'created-deleted' AS source, COUNT(DISTINCT ar_page_id) AS value
143
                FROM $archiveTable
144
                WHERE ar_user_text=:username AND ar_parent_id=0)
145
            ");
146
        $username = $user->getUsername();
147
        $resultQuery->bindParam("username", $username);
148
        $resultQuery->execute();
149
        $results = $resultQuery->fetchAll();
150
151
        $pageCounts = array_combine(
152
            array_map(function ($e) {
153
                return $e['source'];
154
            }, $results),
155
            array_map(function ($e) {
156
                return $e['value'];
157
            }, $results)
158
        );
159
160
        // Cache for 10 minutes, and return.
1 ignored issue
show
Unused Code Comprehensibility introduced by
36% 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...
161
        $cacheItem = $this->cache->getItem($cacheKey)
162
            ->set($pageCounts)
163
            ->expiresAfter(new \DateInterval('PT10M'));
164
        $this->cache->save($cacheItem);
165
        $this->stopwatch->stop($cacheKey);
166
        return $pageCounts;
167
    }
168
169
    /**
170
     * Get log totals for a user.
171
     * @param Project $project The project.
172
     * @param User $user The user.
173
     * @return integer[] Keys are "<log>-<action>" strings, values are counts.
174
     */
175
    public function getLogCounts(Project $project, User $user)
176
    {
177
        // Set up cache.
178
        $cacheKey = 'logcounts.'.$project->getDatabaseName().'.'.$user->getUsername();
179
        if ($this->cache->hasItem($cacheKey)) {
180
            return $this->cache->getItem($cacheKey)->get();
181
        }
182
        $this->stopwatch->start($cacheKey, 'XTools');
183
184
        // Query.
185
        $sql = "SELECT CONCAT(log_type, '-', log_action) AS source, COUNT(log_id) AS value
186
            FROM " . $this->getTableName($project->getDatabaseName(), 'logging') . "
187
            WHERE log_user = :userId
188
            GROUP BY log_type, log_action";
189
        $resultQuery = $this->getProjectsConnection()->prepare($sql);
190
        $userId = $user->getId($project);
191
        $resultQuery->bindParam('userId', $userId);
192
        $resultQuery->execute();
193
        $results = $resultQuery->fetchAll();
194
        $logCounts = array_combine(
195
            array_map(function ($e) {
196
                return $e['source'];
197
            }, $results),
198
            array_map(function ($e) {
199
                return $e['value'];
200
            }, $results)
201
        );
202
203
        // Make sure there is some value for each of the wanted counts.
204
        $requiredCounts = [
205
            'thanks-thank',
206
            'review-approve',
207
            'patrol-patrol',
208
            'block-block',
209
            'block-unblock',
210
            'protect-protect',
211
            'protect-unprotect',
212
            'move-move',
213
            'delete-delete',
214
            'delete-revision',
215
            'delete-restore',
216
            'import-import',
217
            'upload-upload',
218
            'upload-overwrite',
219
        ];
220
        foreach ($requiredCounts as $req) {
221
            if (!isset($logCounts[$req])) {
222
                $logCounts[$req] = 0;
223
            }
224
        }
225
226
        // Add Commons upload count, if applicable.
227
        $logCounts['files_uploaded_commons'] = 0;
228
        if ($this->isLabs()) {
229
            $sql = "SELECT COUNT(log_id) FROM commonswiki_p.logging_userindex
230
                WHERE log_type = 'upload' AND log_action = 'upload' AND log_user = :userId";
231
            $resultQuery = $this->getProjectsConnection()->prepare($sql);
232
            $resultQuery->bindParam('userId', $userId);
233
            $resultQuery->execute();
234
            $logCounts['files_uploaded_commons'] = $resultQuery->fetchColumn();
235
        }
236
237
        // Cache for 10 minutes, and return.
1 ignored issue
show
Unused Code Comprehensibility introduced by
36% 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...
238
        $cacheItem = $this->cache->getItem($cacheKey)
239
            ->set($logCounts)
240
            ->expiresAfter(new \DateInterval('PT10M'));
241
        $this->cache->save($cacheItem);
242
        $this->stopwatch->stop($cacheKey);
243
244
        return $logCounts;
0 ignored issues
show
Best Practice introduced by
The expression return $logCounts; seems to be an array, but some of its elements' types (boolean) are incompatible with the return type documented by Xtools\EditCounterRepository::getLogCounts of type integer[].

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
245
    }
246
247
    /**
248
     * Get a user's total edit count on one or more project.
249
     * Requires the CentralAuth extension to be installed on the project.
250
     *
251
     * @param string $username The username.
252
     * @param Project $project The project.
253
     * @return mixed[]|boolean Array of total edit counts, or false if none could be found.
254
     */
255
    public function getRevisionCountsAllProjects($username, Project $project)
256
    {
257
        $api = $this->getMediawikiApi($project);
258
        $params = [
259
            'meta' => 'globaluserinfo',
260
            'guiprop' => 'editcount|merged',
261
            'guiuser' => $username,
262
        ];
263
        $query = new SimpleRequest('query', $params);
264
        $result = $api->getRequest($query);
265
        if (!isset($result['query']['globaluserinfo']['merged'])) {
266
            return false;
267
        }
268
        $out = [];
269
        foreach ($result['query']['globaluserinfo']['merged'] as $merged) {
270
            // The array structure here should match what's done in
271
            // EditCounterHelper::getTopProjectsEditCounts()
1 ignored issue
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...
272
            $out[$merged['wiki']] = [
273
                'total' => $merged['editcount'],
274
            ];
275
        }
276
277
        return $out;
278
    }
279
280
    /**
281
     * Get total edit counts for the top 10 projects for this user.
282
     * @param string $username The username.
283
     * @return string[] Elements are arrays with 'dbName', 'url', 'name', and 'total'.
284
     */
285
    public function getTopProjectsEditCounts($projectUrl, $username, $numProjects = 10)
286
    {
287
        $this->debug("Getting top project edit counts for $username");
0 ignored issues
show
Bug introduced by
The method debug() does not seem to exist on object<Xtools\EditCounterRepository>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
288
        $cacheKey = 'topprojectseditcounts.' . $username;
289
        if ($this->cacheHas($cacheKey)) {
0 ignored issues
show
Bug introduced by
The method cacheHas() does not seem to exist on object<Xtools\EditCounterRepository>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
290
            return $this->cacheGet($cacheKey);
0 ignored issues
show
Bug introduced by
The method cacheGet() does not seem to exist on object<Xtools\EditCounterRepository>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
291
        }
292
293
        // First try to get the edit count from the API (if CentralAuth is installed).
294
        /** @var ApiHelper */
295
        $api = $this->container->get('app.api_helper');
296
        $topEditCounts = $api->getEditCount($username, $projectUrl);
297
        if (false === $topEditCounts) {
298
            // If no CentralAuth, fall back to querying each database in turn.
299
            foreach ($this->labsHelper->getProjectsInfo() as $project) {
300
                $this->container->get('logger')->debug('Getting edit count for ' . $project['url']);
301
                $revisionTableName = $this->labsHelper->getTable('revision', $project['dbName']);
0 ignored issues
show
Bug introduced by
The property labsHelper does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
302
                $sql = "SELECT COUNT(rev_id) FROM $revisionTableName WHERE rev_user_text=:username";
303
                $stmt = $this->replicas->prepare($sql);
0 ignored issues
show
Bug introduced by
The property replicas does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
304
                $stmt->bindParam("username", $username);
305
                $stmt->execute();
306
                $total = (int)$stmt->fetchColumn();
307
                $topEditCounts[$project['dbName']] = array_merge($project, ['total' => $total]);
308
            }
309
        }
310
        uasort($topEditCounts, function ($a, $b) {
311
            return $b['total'] - $a['total'];
312
        });
313
        $out = array_slice($topEditCounts, 0, $numProjects);
314
315
        // Cache for ten minutes.
316
        $this->cacheSave($cacheKey, $out, 'PT10M');
0 ignored issues
show
Bug introduced by
The method cacheSave() does not seem to exist on object<Xtools\EditCounterRepository>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
317
318
        return $out;
319
    }
320
321
    /**
322
     * Get the given user's total edit counts per namespace.
323
     * @param string $username The username of the user.
324
     * @return integer[] Array keys are namespace IDs, values are the edit counts.
325
     */
326
    public function getNamespaceTotals($username)
327
    {
328
        $userId = $this->getUserId($username);
0 ignored issues
show
Bug introduced by
The method getUserId() does not seem to exist on object<Xtools\EditCounterRepository>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
329
        $sql = "SELECT page_namespace, count(rev_id) AS total
330
            FROM " . $this->labsHelper->getTable('revision') . " r
331
                JOIN " . $this->labsHelper->getTable('page') . " p on r.rev_page = p.page_id
332
            WHERE r.rev_user = :id GROUP BY page_namespace";
333
        $resultQuery = $this->replicas->prepare($sql);
334
        $resultQuery->bindParam(":id", $userId);
335
        $resultQuery->execute();
336
        $results = $resultQuery->fetchAll();
337
        $namespaceTotals = array_combine(array_map(function ($e) {
338
            return $e['page_namespace'];
339
        }, $results), array_map(function ($e) {
340
            return $e['total'];
341
        }, $results));
342
343
        return $namespaceTotals;
344
    }
345
346
    /**
347
     * Get this user's most recent 10 edits across all projects.
348
     * @param string $username The username.
349
     * @param integer $topN The number of items to return.
350
     * @param integer $days The number of days to search from each wiki.
351
     * @return string[]
352
     */
353
    public function getRecentGlobalContribs($username, $projects = [], $topN = 10, $days = 30)
354
    {
355
        $allRevisions = [];
356
        foreach ($this->labsHelper->getProjectsInfo($projects) as $project) {
357
            $cacheKey = "globalcontribs.{$project['dbName']}.$username";
358
            if ($this->cacheHas($cacheKey)) {
0 ignored issues
show
Bug introduced by
The method cacheHas() does not seem to exist on object<Xtools\EditCounterRepository>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
359
                $revisions = $this->cacheGet($cacheKey);
0 ignored issues
show
Bug introduced by
The method cacheGet() does not seem to exist on object<Xtools\EditCounterRepository>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
360
            } else {
361
                $sql =
362
                    "SELECT rev_id, rev_timestamp, UNIX_TIMESTAMP(rev_timestamp) AS unix_timestamp, " .
363
                    " rev_minor_edit, rev_deleted, rev_len, rev_parent_id, rev_comment, " .
364
                    " page_title, page_namespace " . " FROM " .
365
                    $this->labsHelper->getTable('revision', $project['dbName']) . "    JOIN " .
366
                    $this->labsHelper->getTable('page', $project['dbName']) .
367
                    "    ON (rev_page = page_id)" .
368
                    " WHERE rev_timestamp > NOW() - INTERVAL $days DAY AND rev_user_text LIKE :username" .
369
                    " ORDER BY rev_timestamp DESC" . " LIMIT 10";
370
                $resultQuery = $this->replicas->prepare($sql);
371
                $resultQuery->bindParam(":username", $username);
372
                $resultQuery->execute();
373
                $revisions = $resultQuery->fetchAll();
374
                $this->cacheSave($cacheKey, $revisions, 'PT15M');
0 ignored issues
show
Bug introduced by
The method cacheSave() does not seem to exist on object<Xtools\EditCounterRepository>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
375
            }
376
            if (count($revisions) === 0) {
377
                continue;
378
            }
379
            $revsWithProject = array_map(function (&$item) use ($project) {
380
                $item['project_name'] = $project['wikiName'];
381
                $item['project_url'] = $project['url'];
382
                $item['project_db_name'] = $project['dbName'];
383
                $item['rev_time_formatted'] = date('Y-m-d H:i', $item['unix_timestamp']);
384
385
                return $item;
386
            }, $revisions);
387
            $allRevisions = array_merge($allRevisions, $revsWithProject);
388
        }
389
        usort($allRevisions, function ($a, $b) {
390
            return $b['rev_timestamp'] - $a['rev_timestamp'];
391
        });
392
393
        return array_slice($allRevisions, 0, $topN);
394
    }
395
396
    /**
397
     * Get data for a bar chart of monthly edit totals per namespace.
398
     * @param string $username The username.
399
     * @return string[]
400
     */
401
    public function getMonthCounts($username)
402
    {
403
        $cacheKey = "monthcounts.$username";
404
        if ($this->cacheHas($cacheKey)) {
0 ignored issues
show
Bug introduced by
The method cacheHas() does not seem to exist on object<Xtools\EditCounterRepository>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
405
            return $this->cacheGet($cacheKey);
0 ignored issues
show
Bug introduced by
The method cacheGet() does not seem to exist on object<Xtools\EditCounterRepository>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
406
        }
407
408
        $sql =
409
            "SELECT " . "     YEAR(rev_timestamp) AS `year`," .
410
            "     MONTH(rev_timestamp) AS `month`," . "     page_namespace," .
411
            "     COUNT(rev_id) AS `count` " . " FROM " . $this->labsHelper->getTable('revision') .
412
            "    JOIN " . $this->labsHelper->getTable('page') . " ON (rev_page = page_id)" .
413
            " WHERE rev_user_text = :username" .
414
            " GROUP BY YEAR(rev_timestamp), MONTH(rev_timestamp), page_namespace " .
415
            " ORDER BY rev_timestamp DESC";
416
        $resultQuery = $this->replicas->prepare($sql);
417
        $resultQuery->bindParam(":username", $username);
418
        $resultQuery->execute();
419
        $totals = $resultQuery->fetchAll();
420
        $out = [
421
            'years' => [],
422
            'namespaces' => [],
423
            'totals' => [],
424
        ];
425
        $out['max_year'] = 0;
426
        $out['min_year'] = date('Y');
427
        foreach ($totals as $total) {
428
            // Collect all applicable years and namespaces.
429
            $out['max_year'] = max($out['max_year'], $total['year']);
430
            $out['min_year'] = min($out['min_year'], $total['year']);
431
            // Collate the counts by namespace, and then year and month.
432
            $ns = $total['page_namespace'];
433
            if (!isset($out['totals'][$ns])) {
434
                $out['totals'][$ns] = [];
435
            }
436
            $out['totals'][$ns][$total['year'] . $total['month']] = $total['count'];
437
        }
438
        // Fill in the blanks (where no edits were made in a given month for a namespace).
439
        for ($y = $out['min_year']; $y <= $out['max_year']; $y++) {
440
            for ($m = 1; $m <= 12; $m++) {
441
                foreach ($out['totals'] as $nsId => &$total) {
442
                    if (!isset($total[$y . $m])) {
443
                        $total[$y . $m] = 0;
444
                    }
445
                }
446
            }
447
        }
448
        $this->cacheSave($cacheKey, $out, 'PT10M');
0 ignored issues
show
Bug introduced by
The method cacheSave() does not seem to exist on object<Xtools\EditCounterRepository>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
449
450
        return $out;
0 ignored issues
show
Best Practice introduced by
The expression return $out; seems to be an array, but some of its elements' types (array) are incompatible with the return type documented by Xtools\EditCounterRepository::getMonthCounts of type string[].

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
451
    }
452
453
    /**
454
     * Get yearly edit totals for this user, grouped by namespace.
455
     * @param string $username
456
     * @return string[] ['<namespace>' => ['<year>' => 'total', ... ], ... ]
457
     */
458
    public function getYearCounts($username)
459
    {
460
        $cacheKey = "yearcounts.$username";
461
        if ($this->cacheHas($cacheKey)) {
0 ignored issues
show
Bug introduced by
The method cacheHas() does not seem to exist on object<Xtools\EditCounterRepository>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
462
            return $this->cacheGet($cacheKey);
0 ignored issues
show
Bug introduced by
The method cacheGet() does not seem to exist on object<Xtools\EditCounterRepository>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
463
        }
464
465
        $sql =
466
            "SELECT " . "     SUBSTR(CAST(rev_timestamp AS CHAR(4)), 1, 4) AS `year`," .
467
            "     page_namespace," . "     COUNT(rev_id) AS `count` " . " FROM " .
468
            $this->labsHelper->getTable('revision') . "    JOIN " .
469
            $this->labsHelper->getTable('page') . " ON (rev_page = page_id)" .
470
            " WHERE rev_user_text = :username" .
471
            " GROUP BY SUBSTR(CAST(rev_timestamp AS CHAR(4)), 1, 4), page_namespace " .
472
            " ORDER BY rev_timestamp DESC ";
473
        $resultQuery = $this->replicas->prepare($sql);
474
        $resultQuery->bindParam(":username", $username);
475
        $resultQuery->execute();
476
        $totals = $resultQuery->fetchAll();
477
        $out = [
478
            'years' => [],
479
            'namespaces' => [],
480
            'totals' => [],
481
        ];
482
        foreach ($totals as $total) {
483
            $out['years'][$total['year']] = $total['year'];
484
            $out['namespaces'][$total['page_namespace']] = $total['page_namespace'];
485
            if (!isset($out['totals'][$total['page_namespace']])) {
486
                $out['totals'][$total['page_namespace']] = [];
487
            }
488
            $out['totals'][$total['page_namespace']][$total['year']] = $total['count'];
489
        }
490
        $this->cacheSave($cacheKey, $out, 'PT10M');
0 ignored issues
show
Bug introduced by
The method cacheSave() does not seem to exist on object<Xtools\EditCounterRepository>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
491
492
        return $out;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $out; (array<string,array>) is incompatible with the return type documented by Xtools\EditCounterRepository::getYearCounts of type string[].

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
493
    }
494
495
    /**
496
     * Get data for the timecard chart, with totals grouped by day and to the nearest two-hours.
497
     * @param string $username The user's username.
498
     * @return string[]
499
     */
500
    public function getTimeCard($username)
501
    {
502
        $cacheKey = "timecard.$username";
503
        if ($this->cacheHas($cacheKey)) {
0 ignored issues
show
Bug introduced by
The method cacheHas() does not seem to exist on object<Xtools\EditCounterRepository>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
504
            return $this->cacheGet($cacheKey);
0 ignored issues
show
Bug introduced by
The method cacheGet() does not seem to exist on object<Xtools\EditCounterRepository>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
505
        }
506
507
        $hourInterval = 2;
508
        $xCalc = "ROUND(HOUR(rev_timestamp)/$hourInterval)*$hourInterval";
509
        $sql =
510
            "SELECT " . "     DAYOFWEEK(rev_timestamp) AS `y`, " . "     $xCalc AS `x`, " .
511
            "     COUNT(rev_id) AS `r` " . " FROM " . $this->labsHelper->getTable('revision') .
512
            " WHERE rev_user_text = :username" . " GROUP BY DAYOFWEEK(rev_timestamp), $xCalc " .
513
            " ";
514
        $resultQuery = $this->replicas->prepare($sql);
515
        $resultQuery->bindParam(":username", $username);
516
        $resultQuery->execute();
517
        $totals = $resultQuery->fetchAll();
518
        // Scale the radii: get the max, then scale each radius.
519
        // This looks inefficient, but there's a max of 72 elements in this array.
520
        $max = 0;
521
        foreach ($totals as $total) {
522
            $max = max($max, $total['r']);
523
        }
524
        foreach ($totals as &$total) {
525
            $total['r'] = round($total['r'] / $max * 100);
526
        }
527
        $this->cacheSave($cacheKey, $totals, 'PT10M');
0 ignored issues
show
Bug introduced by
The method cacheSave() does not seem to exist on object<Xtools\EditCounterRepository>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
528
529
        return $totals;
530
    }
531
532
    /**
533
     * Get a summary of automated edits made by the given user in their last 1000 edits.
534
     * Will cache the result for 10 minutes.
535
     * @param User $user The user.
536
     * @return integer[] Array of edit counts, keyed by all tool names from
537
     * app/config/semi_automated.yml
538
     * @TODO this is broke
539
     */
540
    public function countAutomatedRevisions(Project $project, User $user)
541
    {
542
        $userId = $user->getId($project);
543
        $cacheKey = "automatedEdits.".$project->getDatabaseName().'.'.$userId;
544
        if ($this->cache->hasItem($cacheKey)) {
545
            $this->log->debug("Using cache for $cacheKey");
546
            return $this->cache->getItem($cacheKey)->get();
547
        }
548
549
        // Get the most recent 1000 edit summaries.
550
        $revisionTable = $this->getTableName($project->getDatabaseName(), 'revision');
551
        $sql = "SELECT rev_comment FROM $revisionTable
552
            WHERE rev_user=:userId ORDER BY rev_timestamp DESC LIMIT 1000";
553
        $resultQuery = $this->getProjectsConnection()->prepare($sql);
554
        $resultQuery->bindParam("userId", $userId);
555
        $resultQuery->execute();
556
        $results = $resultQuery->fetchAll();
557
        $out = [];
558
        foreach ($results as $result) {
559
            $toolName = $this->getTool($result['rev_comment']);
0 ignored issues
show
Bug introduced by
The method getTool() does not exist on Xtools\EditCounterRepository. Did you maybe mean getToolsConnection()?

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...
560
            if ($toolName) {
561
                if (!isset($out[$toolName])) {
562
                    $out[$toolName] = 0;
563
                }
564
                $out[$toolName]++;
565
            }
566
        }
567
        arsort($out);
568
569
        // Cache for 10 minutes.
570
        $this->log->debug("Saving $cacheKey to cache", [$out]);
571
        $this->cacheSave($cacheKey, $out, 'PT10M');
0 ignored issues
show
Bug introduced by
The method cacheSave() does not seem to exist on object<Xtools\EditCounterRepository>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
572
573
        return $out;
574
    }
575
}
576