Completed
Push — master ( c51827...601203 )
by Sam
02:51
created

EditCounterRepository::getBlocksReceived()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 8

Duplication

Lines 10
Ratio 100 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 10
loc 10
rs 9.4285
cc 1
eloc 8
nc 1
nop 2
1
<?php
2
/**
3
 * This file contains only the EditCounterRepository class.
4
 */
5
6
namespace Xtools;
7
8
use AppBundle\Helper\AutomatedEditsHelper;
9
use DateInterval;
10
use DateTime;
11
use Mediawiki\Api\SimpleRequest;
12
13
/**
14
 * An EditCounterRepository is responsible for retrieving edit count information from the
15
 * databases and API. It doesn't do any post-processing of that information.
16
 */
17
class EditCounterRepository extends Repository
18
{
19
20
    /**
21
     * Get revision counts for the given user.
22
     * @param Project $project The project.
23
     * @param User $user The user.
24
     * @returns string[] With keys: 'deleted', 'live', 'total', 'first', 'last', '24h', '7d', '30d',
25
     * '365d', 'small', 'large', 'with_comments', and 'minor_edits'.
26
     */
27
    public function getRevisionCounts(Project $project, User $user)
28
    {
29
        // Set up cache.
30
        $cacheKey = 'revisioncounts.' . $project->getDatabaseName() . '.' . $user->getUsername();
31
        if ($this->cache->hasItem($cacheKey)) {
32
            return $this->cache->getItem($cacheKey)->get();
33
        }
34
35
        // Prepare the queries and execute them.
36
        $archiveTable = $this->getTableName($project->getDatabaseName(), 'archive');
37
        $revisionTable = $this->getTableName($project->getDatabaseName(), 'revision');
38
        $queries = [
39
            'deleted' => "SELECT COUNT(ar_id) FROM $archiveTable
40
                WHERE ar_user = :userId",
41
            'live' => "SELECT COUNT(rev_id) FROM $revisionTable
42
                WHERE rev_user = :userId",
43
            'day' => "SELECT COUNT(rev_id) FROM $revisionTable
44
                WHERE rev_user = :userId AND rev_timestamp >= DATE_SUB(NOW(), INTERVAL 1 DAY)",
45
            'week' => "SELECT COUNT(rev_id) FROM $revisionTable
46
                WHERE rev_user = :userId AND rev_timestamp >= DATE_SUB(NOW(), INTERVAL 1 WEEK)",
47
            'month' => "SELECT COUNT(rev_id) FROM $revisionTable
48
                WHERE rev_user = :userId AND rev_timestamp >= DATE_SUB(NOW(), INTERVAL 1 MONTH)",
49
            'year' => "SELECT COUNT(rev_id) FROM $revisionTable
50
                WHERE rev_user = :userId AND rev_timestamp >= DATE_SUB(NOW(), INTERVAL 1 YEAR)",
51
            'small' => "SELECT COUNT(rev_id) FROM $revisionTable
52
                WHERE rev_user = :userId AND rev_len < 20",
53
            'large' => "SELECT COUNT(rev_id) FROM $revisionTable
54
                WHERE rev_user = :userId AND rev_len > 1000",
55
            'with_comments' => "SELECT COUNT(rev_id) FROM $revisionTable
56
                WHERE rev_user = :userId AND rev_comment = ''",
57
            'minor' => "SELECT COUNT(rev_id) FROM $revisionTable
58
                WHERE rev_user = :userId AND rev_minor_edit = 1",
59
            'average_size' => "SELECT AVG(rev_len) FROM $revisionTable
60
                WHERE rev_user = :userId",
61
        ];
62
        $this->stopwatch->start($cacheKey);
63
        $revisionCounts = [];
64
        foreach ($queries as $varName => $query) {
65
            $resultQuery = $this->getProjectsConnection()->prepare($query);
66
            $userId = $user->getId($project);
67
            $resultQuery->bindParam("userId", $userId);
68
            $resultQuery->execute();
69
            $val = $resultQuery->fetchColumn();
70
            $revisionCounts[$varName] = $val ?: 0;
71
            $this->stopwatch->lap($cacheKey);
72
        }
73
74
        // 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...
75
        $this->stopwatch->stop($cacheKey);
76
        $cacheItem = $this->cache->getItem($cacheKey)
77
                ->set($revisionCounts)
78
                ->expiresAfter(new DateInterval('PT10M'));
79
        $this->cache->save($cacheItem);
80
81
        return $revisionCounts;
82
    }
83
84
    /**
85
     * Get the first and last revision dates (in MySQL YYYYMMDDHHMMSS format).
86
     * @param Project $project The project.
87
     * @param User $user The user.
88
     * @return string[] With keys 'first' and 'last'.
89
     */
90
    public function getRevisionDates(Project $project, User $user)
91
    {
92
        // Set up cache.
93
        $cacheKey = 'revisiondates.' . $project->getDatabaseName() . '.' . $user->getUsername();
94
        if ($this->cache->hasItem($cacheKey)) {
95
            return $this->cache->getItem($cacheKey)->get();
96
        }
97
98
        $this->stopwatch->start($cacheKey);
99
        $revisionTable = $this->getTableName($project->getDatabaseName(), 'revision');
100
        $query = "(SELECT 'first' AS `key`, rev_timestamp AS `date` FROM $revisionTable
101
            WHERE rev_user = :userId ORDER BY rev_timestamp ASC LIMIT 1)
102
            UNION
103
            (SELECT 'last' AS `key`, rev_timestamp AS `date` FROM $revisionTable
104
            WHERE rev_user = :userId ORDER BY rev_timestamp DESC LIMIT 1)";
105
        $resultQuery = $this->getProjectsConnection()->prepare($query);
106
        $userId = $user->getId($project);
107
        $resultQuery->bindParam("userId", $userId);
108
        $resultQuery->execute();
109
        $result = $resultQuery->fetchAll();
110
        $revisionDates = [];
111
        foreach ($result as $res) {
112
            $revisionDates[$res['key']] = $res['date'];
113
        }
114
115
        // 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...
116
        $cacheItem = $this->cache->getItem($cacheKey)
117
                ->set($revisionDates)
118
                ->expiresAfter(new DateInterval('PT10M'));
119
        $this->cache->save($cacheItem);
120
        $this->stopwatch->stop($cacheKey);
121
        return $revisionDates;
122
    }
123
124
    /**
125
     * Get page counts for the given user, both for live and deleted pages/revisions.
126
     * @param Project $project The project.
127
     * @param User $user The user.
128
     * @return int[] With keys: edited-live, edited-deleted, created-live, created-deleted.
129
     */
130
    public function getPageCounts(Project $project, User $user)
131
    {
132
        // Set up cache.
133
        $cacheKey = 'pagecounts.'.$project->getDatabaseName().'.'.$user->getUsername();
134
        if ($this->cache->hasItem($cacheKey)) {
135
            return $this->cache->getItem($cacheKey)->get();
136
        }
137
        $this->stopwatch->start($cacheKey, 'XTools');
138
139
        // Build and execute query.
140
        $revisionTable = $this->getTableName($project->getDatabaseName(), 'revision');
141
        $archiveTable = $this->getTableName($project->getDatabaseName(), 'archive');
142
        $resultQuery = $this->getProjectsConnection()->prepare("
143
            (SELECT 'edited-live' AS source, COUNT(DISTINCT rev_page) AS value
144
                FROM $revisionTable
145
                WHERE rev_user_text=:username)
146
            UNION
147
            (SELECT 'edited-deleted' AS source, COUNT(DISTINCT ar_page_id) AS value
148
                FROM $archiveTable
149
                WHERE ar_user_text=:username)
150
            UNION
151
            (SELECT 'created-live' AS source, COUNT(DISTINCT rev_page) AS value
152
                FROM $revisionTable
153
                WHERE rev_user_text=:username AND rev_parent_id=0)
154
            UNION
155
            (SELECT 'created-deleted' AS source, COUNT(DISTINCT ar_page_id) AS value
156
                FROM $archiveTable
157
                WHERE ar_user_text=:username AND ar_parent_id=0)
158
            ");
159
        $username = $user->getUsername();
160
        $resultQuery->bindParam("username", $username);
161
        $resultQuery->execute();
162
        $results = $resultQuery->fetchAll();
163
164
        $pageCounts = array_combine(
165
            array_map(function ($e) {
166
                return $e['source'];
167
            }, $results),
168
            array_map(function ($e) {
169
                return $e['value'];
170
            }, $results)
171
        );
172
173
        // 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...
174
        $cacheItem = $this->cache->getItem($cacheKey)
175
            ->set($pageCounts)
176
            ->expiresAfter(new DateInterval('PT10M'));
177
        $this->cache->save($cacheItem);
178
        $this->stopwatch->stop($cacheKey);
179
        return $pageCounts;
180
    }
181
182
    /**
183
     * Get log totals for a user.
184
     * @param Project $project The project.
185
     * @param User $user The user.
186
     * @return integer[] Keys are "<log>-<action>" strings, values are counts.
187
     */
188
    public function getLogCounts(Project $project, User $user)
189
    {
190
        // Set up cache.
191
        $cacheKey = 'logcounts.'.$project->getDatabaseName().'.'.$user->getUsername();
192
        if ($this->cache->hasItem($cacheKey)) {
193
            return $this->cache->getItem($cacheKey)->get();
194
        }
195
        $this->stopwatch->start($cacheKey, 'XTools');
196
197
        // Query.
198
        $sql = "SELECT CONCAT(log_type, '-', log_action) AS source, COUNT(log_id) AS value
199
            FROM " . $this->getTableName($project->getDatabaseName(), 'logging') . "
200
            WHERE log_user = :userId
201
            GROUP BY log_type, log_action";
202
        $resultQuery = $this->getProjectsConnection()->prepare($sql);
203
        $userId = $user->getId($project);
204
        $resultQuery->bindParam('userId', $userId);
205
        $resultQuery->execute();
206
        $results = $resultQuery->fetchAll();
207
        $logCounts = array_combine(
208
            array_map(function ($e) {
209
                return $e['source'];
210
            }, $results),
211
            array_map(function ($e) {
212
                return $e['value'];
213
            }, $results)
214
        );
215
216
        // Make sure there is some value for each of the wanted counts.
217
        $requiredCounts = [
218
            'thanks-thank',
219
            'review-approve',
220
            'patrol-patrol',
221
            'block-block',
222
            'block-reblock',
223
            'block-unblock',
224
            'protect-protect',
225
            'protect-unprotect',
226
            'move-move',
227
            'delete-delete',
228
            'delete-revision',
229
            'delete-restore',
230
            'import-import',
231
            'upload-upload',
232
            'upload-overwrite',
233
        ];
234
        foreach ($requiredCounts as $req) {
235
            if (!isset($logCounts[$req])) {
236
                $logCounts[$req] = 0;
237
            }
238
        }
239
240
        // Add Commons upload count, if applicable.
241
        $logCounts['files_uploaded_commons'] = 0;
242
        if ($this->isLabs()) {
243
            $sql = "SELECT COUNT(log_id) FROM commonswiki_p.logging_userindex
244
                WHERE log_type = 'upload' AND log_action = 'upload' AND log_user = :userId";
245
            $resultQuery = $this->getProjectsConnection()->prepare($sql);
246
            $resultQuery->bindParam('userId', $userId);
247
            $resultQuery->execute();
248
            $logCounts['files_uploaded_commons'] = $resultQuery->fetchColumn();
249
        }
250
251
        // 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...
252
        $cacheItem = $this->cache->getItem($cacheKey)
253
            ->set($logCounts)
254
            ->expiresAfter(new DateInterval('PT10M'));
255
        $this->cache->save($cacheItem);
256
        $this->stopwatch->stop($cacheKey);
257
258
        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...
259
    }
260
261
    /**
262
     * @param Project $project
263
     * @param User $user
264
     * @return array
265
     */
266 View Code Duplication
    public function getBlocksSet(Project $project, User $user)
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...
267
    {
268
        $ipblocksTable = $this->getTableName($project->getDatabaseName(), 'ipblocks');
269
        $sql = "SELECT * FROM $ipblocksTable WHERE ipb_by = :userId";
270
        $resultQuery = $this->getProjectsConnection()->prepare($sql);
271
        $userId = $user->getId($project);
272
        $resultQuery->bindParam('userId', $userId);
273
        $resultQuery->execute();
274
        return $resultQuery->fetchAll();
275
    }
276
277
    /**
278
     * @param Project $project
279
     * @param User $user
280
     * @return array
281
     */
282 View Code Duplication
    public function getBlocksReceived(Project $project, User $user)
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...
283
    {
284
        $ipblocksTable = $this->getTableName($project->getDatabaseName(), 'ipblocks');
285
        $sql = "SELECT * FROM $ipblocksTable WHERE ipb_user = :userId";
286
        $resultQuery = $this->getProjectsConnection()->prepare($sql);
287
        $userId = $user->getId($project);
288
        $resultQuery->bindParam('userId', $userId);
289
        $resultQuery->execute();
290
        return $resultQuery->fetchAll();
291
    }
292
293
    /**
294
     * Get a user's total edit count on all projects.
295
     * @see EditCounterRepository::globalEditCountsFromCentralAuth()
296
     * @see EditCounterRepository::globalEditCountsFromDatabases()
297
     * @param User $user The user.
298
     * @param Project $project The project to start from.
299
     * @return mixed[] Elements are arrays with 'project' (Project), and 'total' (int).
300
     */
301
    public function globalEditCounts(User $user, Project $project)
302
    {
303
        // Get the edit counts from CentralAuth or database.
304
        $editCounts = $this->globalEditCountsFromCentralAuth($user, $project);
305
        if ($editCounts === false) {
306
            $editCounts = $this->globalEditCountsFromDatabases($user, $project);
307
        }
308
309
        // Pre-populate all projects' metadata, to prevent each project call from fetching it.
310
        $project->getRepository()->getAll();
1 ignored issue
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Xtools\Repository as the method getAll() does only exist in the following sub-classes of Xtools\Repository: Xtools\ProjectRepository. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
311
312
        // Compile the output.
313
        $out = [];
314
        foreach ($editCounts as $editCount) {
315
            $out[] = [
316
                'project' => ProjectRepository::getProject($editCount['dbname'], $this->container),
317
                'total' => $editCount['total'],
318
            ];
319
        }
320
        return $out;
321
    }
322
323
    /**
324
     * Get a user's total edit count on one or more project.
325
     * Requires the CentralAuth extension to be installed on the project.
326
     *
327
     * @param User $user The user.
328
     * @param Project $project The project to start from.
329
     * @return mixed[] Elements are arrays with 'dbname' (string), and 'total' (int).
330
     */
331
    protected function globalEditCountsFromCentralAuth(User $user, Project $project)
332
    {
333
        $this->log->debug(__METHOD__." Getting global edit counts for ".$user->getUsername());
334
        // Set up cache and stopwatch.
335
        $cacheKey = 'globalRevisionCounts.'.$user->getUsername();
336
        if ($this->cache->hasItem($cacheKey)) {
337
            return $this->cache->getItem($cacheKey)->get();
338
        }
339
        $this->stopwatch->start($cacheKey, 'XTools');
340
341
        // Load all projects, so it doesn't have to request metadata about each one as it goes.
342
        $project->getRepository()->getAll();
1 ignored issue
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Xtools\Repository as the method getAll() does only exist in the following sub-classes of Xtools\Repository: Xtools\ProjectRepository. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
343
344
        $api = $this->getMediawikiApi($project);
345
        $params = [
346
            'meta' => 'globaluserinfo',
347
            'guiprop' => 'editcount|merged',
348
            'guiuser' => $user->getUsername(),
349
        ];
350
        $query = new SimpleRequest('query', $params);
351
        $result = $api->getRequest($query);
352
        if (!isset($result['query']['globaluserinfo']['merged'])) {
353
            return [];
354
        }
355
        $out = [];
356
        foreach ($result['query']['globaluserinfo']['merged'] as $result) {
357
            $out[] = [
358
                'dbname' => $result['wiki'],
359
                'total' => $result['editcount'],
360
            ];
361
        }
362
363
        // 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...
364
        $cacheItem = $this->cache->getItem($cacheKey)
365
            ->set($out)
366
            ->expiresAfter(new DateInterval('PT10M'));
367
        $this->cache->save($cacheItem);
368
        $this->stopwatch->stop($cacheKey);
369
370
        return $out;
371
    }
372
373
    /**
374
     * Get total edit counts from all projects for this user.
375
     * @see EditCounterRepository::globalEditCountsFromCentralAuth()
376
     * @param User $user The user.
377
     * @param Project $project The project to start from.
378
     * @return mixed[] Elements are arrays with 'dbname' (string), and 'total' (int).
379
     */
380
    protected function globalEditCountsFromDatabases(User $user, Project $project)
381
    {
382
        $stopwatchName = 'globalRevisionCounts.'.$user->getUsername();
383
        $allProjects = $project->getRepository()->getAll();
1 ignored issue
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Xtools\Repository as the method getAll() does only exist in the following sub-classes of Xtools\Repository: Xtools\ProjectRepository. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
384
        $topEditCounts = [];
385
        foreach ($allProjects as $projectMeta) {
386
            $revisionTableName = $this->getTableName($projectMeta['dbName'], 'revision');
387
            $sql = "SELECT COUNT(rev_id) FROM $revisionTableName WHERE rev_user_text=:username";
388
            $stmt = $this->getProjectsConnection()->prepare($sql);
389
            $stmt->bindParam("username", $user->getUsername());
0 ignored issues
show
Bug introduced by
$user->getUsername() cannot be passed to bindparam() as the parameter $variable expects a reference.
Loading history...
390
            $stmt->execute();
391
            $total = (int)$stmt->fetchColumn();
392
            $topEditCounts[] = [
393
                'dbname' => $projectMeta['dbName'],
394
                'total' => $total,
395
            ];
396
            $this->stopwatch->lap($stopwatchName);
397
        }
398
        return $topEditCounts;
399
    }
400
401
    /**
402
     * Get the given user's total edit counts per namespace on the given project.
403
     * @param Project $project The project.
404
     * @param User $user The user.
405
     * @return integer[] Array keys are namespace IDs, values are the edit counts.
406
     */
407
    public function getNamespaceTotals(Project $project, User $user)
408
    {
409
        // Cache?
410
        $userId = $user->getId($project);
411
        $cacheKey = "ec.namespacetotals.{$project->getDatabaseName()}.$userId";
412
        $this->stopwatch->start($cacheKey, 'XTools');
413
        if ($this->cache->hasItem($cacheKey)) {
414
            return $this->cache->getItem($cacheKey)->get();
415
        }
416
417
        // Query.
418
        $revisionTable = $this->getTableName($project->getDatabaseName(), 'revision');
419
        $pageTable = $this->getTableName($project->getDatabaseName(), 'page');
420
        $sql = "SELECT page_namespace, COUNT(rev_id) AS total
421
            FROM $pageTable p JOIN $revisionTable r ON (r.rev_page = p.page_id)
422
            WHERE r.rev_user = :id
423
            GROUP BY page_namespace";
424
        $resultQuery = $this->getProjectsConnection()->prepare($sql);
425
        $resultQuery->bindParam(":id", $userId);
426
        $resultQuery->execute();
427
        $results = $resultQuery->fetchAll();
428
        $namespaceTotals = array_combine(array_map(function ($e) {
429
            return $e['page_namespace'];
430
        }, $results), array_map(function ($e) {
431
            return $e['total'];
432
        }, $results));
433
434
        // Cache and return.
435
        $cacheItem = $this->cache->getItem($cacheKey);
436
        $cacheItem->set($namespaceTotals);
437
        $cacheItem->expiresAfter(new DateInterval('PT15M'));
438
        $this->cache->save($cacheItem);
439
        $this->stopwatch->stop($cacheKey);
440
        return $namespaceTotals;
441
    }
442
443
    /**
444
     * Get revisions by this user.
445
     * @param Project $project The project.
446
     * @param User $user The user.
447
     * @param DateTime $oldest The oldest revision time of interest (only return greater than this).
448
     * @param int $lim The number of results to return.
449
     * @return array|mixed
450
     */
451
    public function getRevisions(Project $project, User $user, DateTime $oldest = null, $lim = null)
452
    {
453
        $username = $user->getUsername();
454
        $cacheKey = "globalcontribs.{$project->getDatabaseName()}.$username";
455
        $this->stopwatch->start($cacheKey, 'XTools');
456
        if ($this->cache->hasItem($cacheKey)) {
457
            return $this->cache->getItem($cacheKey)->get();
458
        }
459
        $revisionTable = $this->getTableName($project->getDatabaseName(), 'revision');
460
        $pageTable = $this->getTableName($project->getDatabaseName(), 'page');
461
        $whereTimestamp = ($oldest instanceof DateTime)
462
            ? ' AND revs.rev_timestamp > '.$oldest->format('YmdHis')
463
            : '';
464
        // Column aliases here should match those used in PagesRepository::getRevisions()
465
        $sql = "SELECT
466
                revs.rev_id AS id,
467
                revs.rev_timestamp AS timestamp,
468
                UNIX_TIMESTAMP(revs.rev_timestamp) AS unix_timestamp,
469
                revs.rev_minor_edit AS minor,
470
                revs.rev_deleted AS deleted,
471
                revs.rev_len AS length,
472
                (CAST(revs.rev_len AS SIGNED) - IFNULL(parentrevs.rev_len, 0)) AS length_change,
473
                revs.rev_parent_id AS parent_id,
474
                revs.rev_comment AS comment,
475
                revs.rev_user_text AS username,
476
                page.page_title,
477
                page.page_namespace
478
            FROM $revisionTable AS revs
479
                JOIN $pageTable AS page ON (rev_page = page_id)
480
                LEFT JOIN $revisionTable AS parentrevs ON (revs.rev_parent_id = parentrevs.rev_id)
481
            WHERE revs.rev_user_text LIKE :username $whereTimestamp
482
            ORDER BY revs.rev_timestamp DESC";
483
        if (is_numeric($lim)) {
484
            $sql .= " LIMIT $lim";
485
        }
486
        $resultQuery = $this->getProjectsConnection()->prepare($sql);
487
        $resultQuery->bindParam(":username", $username);
488
        $resultQuery->execute();
489
        $revisions = $resultQuery->fetchAll();
490
491
        // Cache this.
492
        $cacheItem = $this->cache->getItem($cacheKey);
493
        $cacheItem->set($revisions);
494
        $cacheItem->expiresAfter(new DateInterval('PT15M'));
495
        $this->cache->save($cacheItem);
496
497
        $this->stopwatch->stop($cacheKey);
498
        return $revisions;
499
    }
500
501
    /**
502
     * Get data for a bar chart of monthly edit totals per namespace.
503
     * @param Project $project The project.
504
     * @param User $user The user.
505
     * @return string[]
506
     */
507 View Code Duplication
    public function getMonthCounts(Project $project, User $user)
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...
508
    {
509
        $username = $user->getUsername();
510
        $cacheKey = "monthcounts.$username";
511
        $this->stopwatch->start($cacheKey, 'XTools');
512
        if ($this->cache->hasItem($cacheKey)) {
513
            return $this->cache->getItem($cacheKey)->get();
514
        }
515
516
        $revisionTable = $this->getTableName($project->getDatabaseName(), 'revision');
517
        $pageTable = $this->getTableName($project->getDatabaseName(), 'page');
518
        $sql =
519
            "SELECT "
520
            . "     YEAR(rev_timestamp) AS `year`,"
521
            . "     MONTH(rev_timestamp) AS `month`,"
522
            . "     page_namespace,"
523
            . "     COUNT(rev_id) AS `count` "
524
            .  " FROM $revisionTable JOIN $pageTable ON (rev_page = page_id)"
525
            . " WHERE rev_user_text = :username"
526
            . " GROUP BY YEAR(rev_timestamp), MONTH(rev_timestamp), page_namespace "
527
            . " ORDER BY rev_timestamp DESC";
528
        $resultQuery = $this->getProjectsConnection()->prepare($sql);
529
        $resultQuery->bindParam(":username", $username);
530
        $resultQuery->execute();
531
        $totals = $resultQuery->fetchAll();
532
        
533
        $cacheItem = $this->cache->getItem($cacheKey);
534
        $cacheItem->expiresAfter(new DateInterval('PT10M'));
535
        $cacheItem->set($totals);
536
        $this->cache->save($cacheItem);
537
538
        $this->stopwatch->stop($cacheKey);
539
        return $totals;
540
    }
541
542
    /**
543
     * Get yearly edit totals for this user, grouped by namespace.
544
     * @param Project $project The project.
545
     * @param User $user The user.
546
     * @return string[] ['<namespace>' => ['<year>' => 'total', ... ], ... ]
547
     */
548 View Code Duplication
    public function getYearCounts(Project $project, User $user)
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...
549
    {
550
        $username = $user->getUsername();
551
        $cacheKey = "yearcounts.$username";
552
        $this->stopwatch->start($cacheKey, 'XTools');
553
        if ($this->cache->hasItem($cacheKey)) {
554
            return $this->cache->getItem($cacheKey)->get();
555
        }
556
557
        $revisionTable = $this->getTableName($project->getDatabaseName(), 'revision');
558
        $pageTable = $this->getTableName($project->getDatabaseName(), 'page');
559
        $sql = "SELECT "
560
            . "     YEAR(rev_timestamp) AS `year`,"
561
            . "     page_namespace,"
562
            . "     COUNT(rev_id) AS `count` "
563
            . " FROM $revisionTable JOIN $pageTable ON (rev_page = page_id)"
564
            . " WHERE rev_user_text = :username"
565
            . " GROUP BY YEAR(rev_timestamp), page_namespace "
566
            . " ORDER BY rev_timestamp DESC ";
567
        $resultQuery = $this->getProjectsConnection()->prepare($sql);
568
        $resultQuery->bindParam(":username", $username);
569
        $resultQuery->execute();
570
        $totals = $resultQuery->fetchAll();
571
572
        $cacheItem = $this->cache->getItem($cacheKey);
573
        $cacheItem->set($totals);
574
        $cacheItem->expiresAfter(new DateInterval('P10M'));
575
        $this->cache->save($cacheItem);
576
577
        $this->stopwatch->stop($cacheKey);
578
        return $totals;
579
    }
580
581
    /**
582
     * Get data for the timecard chart, with totals grouped by day and to the nearest two-hours.
583
     * @param Project $project
584
     * @param User $user
585
     * @return string[]
586
     */
587
    public function getTimeCard(Project $project, User $user)
588
    {
589
        $username = $user->getUsername();
590
        $cacheKey = "timecard.".$username;
591
        $this->stopwatch->start($cacheKey, 'XTools');
592
        if ($this->cache->hasItem($cacheKey)) {
593
            return $this->cache->getItem($cacheKey)->get();
594
        }
595
596
        $hourInterval = 2;
597
        $xCalc = "ROUND(HOUR(rev_timestamp)/$hourInterval) * $hourInterval";
598
        $revisionTable = $this->getTableName($project->getDatabaseName(), 'revision');
599
        $sql = "SELECT "
600
            . "     DAYOFWEEK(rev_timestamp) AS `y`, "
601
            . "     $xCalc AS `x`, "
602
            . "     COUNT(rev_id) AS `r` "
603
            . " FROM $revisionTable"
604
            . " WHERE rev_user_text = :username"
605
            . " GROUP BY DAYOFWEEK(rev_timestamp), $xCalc ";
606
        $resultQuery = $this->getProjectsConnection()->prepare($sql);
607
        $resultQuery->bindParam(":username", $username);
608
        $resultQuery->execute();
609
        $totals = $resultQuery->fetchAll();
610
        // Scale the radii: get the max, then scale each radius.
611
        // This looks inefficient, but there's a max of 72 elements in this array.
612
        $max = 0;
613
        foreach ($totals as $total) {
614
            $max = max($max, $total['r']);
615
        }
616
        foreach ($totals as &$total) {
617
            $total['r'] = round($total['r'] / $max * 100);
618
        }
619
        $cacheItem = $this->cache->getItem($cacheKey);
620
        $cacheItem->expiresAfter(new DateInterval('PT10M'));
621
        $cacheItem->set($totals);
622
        $this->cache->save($cacheItem);
623
624
        $this->stopwatch->stop($cacheKey);
625
        return $totals;
626
    }
627
628
    /**
629
     * Get a summary of automated edits made by the given user in their last 1000 edits.
630
     * Will cache the result for 10 minutes.
631
     * @param Project $project The project.
632
     * @param User $user The user.
633
     * @return integer[] Array of edit counts, keyed by all tool names from
634
     * app/config/semi_automated.yml
635
     * @TODO This currently uses AutomatedEditsHelper but that could probably be refactored.
636
     */
637
    public function countAutomatedRevisions(Project $project, User $user)
638
    {
639
        $userId = $user->getId($project);
640
        $cacheKey = "automatedEdits.".$project->getDatabaseName().'.'.$userId;
641
        $this->stopwatch->start($cacheKey, 'XTools');
642
        if ($this->cache->hasItem($cacheKey)) {
643
            $this->log->debug("Using cache for $cacheKey");
644
            return $this->cache->getItem($cacheKey)->get();
645
        }
646
647
        /** @var AutomatedEditsHelper $automatedEditsHelper */
648
        $automatedEditsHelper = $this->container->get("app.automated_edits_helper");
649
650
        // Get the most recent 1000 edit summaries.
651
        $revisionTable = $this->getTableName($project->getDatabaseName(), 'revision');
652
        $sql = "SELECT rev_comment FROM $revisionTable
653
            WHERE rev_user=:userId ORDER BY rev_timestamp DESC LIMIT 1000";
654
        $resultQuery = $this->getProjectsConnection()->prepare($sql);
655
        $resultQuery->bindParam("userId", $userId);
656
        $resultQuery->execute();
657
        $results = $resultQuery->fetchAll();
658
        $editCounts = [];
659
        foreach ($results as $result) {
660
            $toolName = $automatedEditsHelper->getTool($result['rev_comment']);
661
            if ($toolName) {
662
                if (!isset($editCounts[$toolName])) {
663
                    $editCounts[$toolName] = 0;
664
                }
665
                $editCounts[$toolName]++;
666
            }
667
        }
668
        arsort($editCounts);
669
670
        // Cache for 10 minutes.
671
        $this->log->debug("Saving $cacheKey to cache", [$editCounts]);
672
        $cacheItem = $this->cache->getItem($cacheKey);
673
        $cacheItem->set($editCounts);
674
        $cacheItem->expiresAfter(new DateInterval('PT10M'));
675
        $this->cache->save($cacheItem);
676
677
        $this->stopwatch->stop($cacheKey);
678
        return $editCounts;
679
    }
680
}
681