Completed
Push — master ( 1833f9...78eb5a )
by MusikAnimal
05:59 queued 02:57
created

Page::getAssessments()   C

Complexity

Conditions 12
Paths 26

Size

Total Lines 74
Code Lines 48

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 1 Features 0
Metric Value
c 3
b 1
f 0
dl 0
loc 74
rs 5.3992
cc 12
eloc 48
nc 26
nop 0

How to fix   Long Method    Complexity   

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
 * This file contains only the Page class.
4
 */
5
6
namespace Xtools;
7
8
/**
9
 * A Page is a single wiki page in one project.
10
 */
11
class Page extends Model
12
{
13
14
    /** @var Project The project that this page belongs to. */
15
    protected $project;
16
17
    /** @var string The page name as provided at instantiation. */
18
    protected $unnormalizedPageName;
19
20
    /** @var string[] Metadata about this page. */
21
    protected $pageInfo;
22
23
    /** @var string[] Revision history of this page */
24
    protected $revisions;
25
26
    /**
27
     * Page constructor.
28
     * @param Project $project
29
     * @param string $pageName
30
     */
31
    public function __construct(Project $project, $pageName)
32
    {
33
        $this->project = $project;
34
        $this->unnormalizedPageName = $pageName;
35
    }
36
37
    /**
38
     * Get basic information about this page from the repository.
39
     * @return \string[]
40
     */
41
    protected function getPageInfo()
42
    {
43
        if (empty($this->pageInfo)) {
44
            $this->pageInfo = $this->getRepository()
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 getPageInfo() does only exist in the following sub-classes of Xtools\Repository: Xtools\PagesRepository. 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...
45
                    ->getPageInfo($this->project, $this->unnormalizedPageName);
46
        }
47
        return $this->pageInfo;
48
    }
49
50
    /**
51
     * Get the page's title.
52
     * @return string
53
     */
54
    public function getTitle()
55
    {
56
        $info = $this->getPageInfo();
57
        return isset($info['title']) ? $info['title'] : $this->unnormalizedPageName;
58
    }
59
60
    /**
61
     * Get the page's title without the namespace.
62
     * @return string
63
     */
64
    public function getTitleWithoutNamespace()
65
    {
66
        $info = $this->getPageInfo();
67
        $title = isset($info['title']) ? $info['title'] : $this->unnormalizedPageName;
68
        $nsName = $this->getNamespaceName();
69
        return str_replace($nsName . ':', '', $title);
70
    }
71
72
    /**
73
     * Get this page's database ID.
74
     * @return int
75
     */
76
    public function getId()
77
    {
78
        $info = $this->getPageInfo();
79
        return isset($info['pageid']) ? $info['pageid'] : null;
80
    }
81
82
    /**
83
     * Get this page's length in bytes.
84
     * @return int
85
     */
86
    public function getLength()
87
    {
88
        $info = $this->getPageInfo();
89
        return isset($info['length']) ? $info['length'] : null;
90
    }
91
92
    /**
93
     * Get HTML for the stylized display of the title.
94
     * The text will be the same as Page::getTitle().
95
     * @return string
96
     */
97
    public function getDisplayTitle()
98
    {
99
        $info = $this->getPageInfo();
100
        if (isset($info['displaytitle'])) {
101
            return $info['displaytitle'];
102
        }
103
        return $this->getTitle();
104
    }
105
106
    /**
107
     * Get the full URL of this page.
108
     * @return string
109
     */
110
    public function getUrl()
111
    {
112
        $info = $this->getPageInfo();
113
        return isset($info['fullurl']) ? $info['fullurl'] : null;
114
    }
115
116
    /**
117
     * Get the numerical ID of the namespace of this page.
118
     * @return int
119
     */
120
    public function getNamespace()
121
    {
122
        $info = $this->getPageInfo();
123
        return isset($info['ns']) ? $info['ns'] : null;
124
    }
125
126
    /**
127
     * Get the name of the namespace of this page.
128
     * @return string
129
     */
130
    public function getNamespaceName()
131
    {
132
        $info = $this->getPageInfo();
133
        return isset($info['ns'])
134
            ? $this->getProject()->getNamespaces()[$info['ns']]
135
            : null;
136
    }
137
138
    /**
139
     * Get the number of page watchers.
140
     * @return int
141
     */
142
    public function getWatchers()
143
    {
144
        $info = $this->getPageInfo();
145
        return isset($info['watchers']) ? $info['watchers'] : null;
146
    }
147
148
    /**
149
     * Whether or not this page exists.
150
     * @return bool
151
     */
152
    public function exists()
153
    {
154
        $info = $this->getPageInfo();
155
        return !isset($info['missing']) && !isset($info['invalid']);
156
    }
157
158
    /**
159
     * Get the Project to which this page belongs.
160
     * @return Project
161
     */
162
    public function getProject()
163
    {
164
        return $this->project;
165
    }
166
167
    /**
168
     * Get the language code for this page.
169
     * If not set, the language code for the project is returned.
170
     * @return string
171
     */
172
    public function getLang()
173
    {
174
        $info = $this->getPageInfo();
175
        if (isset($info['pagelanguage'])) {
176
            return $info['pagelanguage'];
177
        } else {
178
            return $this->getProject()->getLang();
179
        }
180
    }
181
182
    /**
183
     * Get the Wikidata ID of this page.
184
     * @return string
185
     */
186
    public function getWikidataId()
187
    {
188
        $info = $this->getPageInfo();
189
        if (isset($info['pageprops']['wikibase_item'])) {
190
            return $info['pageprops']['wikibase_item'];
191
        } else {
192
            return null;
193
        }
194
    }
195
196
    /**
197
     * Get the number of revisions the page has.
198
     * @param User $user Optionally limit to those of this user.
199
     * @return int
200
     */
201
    public function getNumRevisions(User $user = null)
202
    {
203
        // Return the count of revisions if already present
204
        if (!empty($this->revisions)) {
205
            return count($this->revisions);
206
        }
207
208
        // Otherwise do a COUNT in the event fetching
209
        // all revisions is not desired
210
        return (int) $this->getRepository()->getNumRevisions($this, $user);
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 getNumRevisions() does only exist in the following sub-classes of Xtools\Repository: Xtools\PagesRepository. 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...
211
    }
212
213
    /**
214
     * Get all edits made to this page.
215
     * @param User|null $user Specify to get only revisions by the given user.
216
     * @return array
217
     */
218
    public function getRevisions(User $user = null)
219
    {
220
        if ($this->revisions) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->revisions of type string[] is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
221
            return $this->revisions;
222
        }
223
224
        $this->revisions = $this->getRepository()->getRevisions($this, $user);
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 getRevisions() does only exist in the following sub-classes of Xtools\Repository: Xtools\EditCounterRepository, Xtools\PagesRepository. 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...
225
226
        return $this->revisions;
227
    }
228
229
    /**
230
     * Get the statement for a single revision,
231
     * so that you can iterate row by row.
232
     * @param User|null $user Specify to get only revisions by the given user.
233
     * @return Doctrine\DBAL\Driver\PDOStatement
234
     */
235
    public function getRevisionsStmt(User $user = null)
236
    {
237
        return $this->getRepository()->getRevisionsStmt($this, $user);
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 getRevisionsStmt() does only exist in the following sub-classes of Xtools\Repository: Xtools\PagesRepository. 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...
238
    }
239
240
    /**
241
     * Get various basic info used in the API, including the
242
     *   number of revisions, unique authors, initial author
243
     *   and edit count of the initial author.
244
     * This is combined into one query for better performance.
245
     * Caching is intentionally disabled, because using the gadget,
246
     *   this will get hit for a different page constantly, where
247
     *   the likelihood of cache benefiting us is slim.
248
     * @return string[]
249
     */
250
    public function getBasicEditingInfo()
251
    {
252
        return $this->getRepository()->getBasicEditingInfo($this);
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 getBasicEditingInfo() does only exist in the following sub-classes of Xtools\Repository: Xtools\PagesRepository. 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...
253
    }
254
255
    /**
256
     * Get assessments of this page
257
     * @return string[]|false `false` if unsupported, or array in the format of:
258
     *         [
259
     *             'assessment' => 'C', // overall assessment
260
     *             'wikiprojects' => [
261
     *                 'Biography' => [
262
     *                     'assessment' => 'C',
263
     *                     'badge' => 'url',
264
     *                 ],
265
     *                 ...
266
     *             ],
267
     *             'wikiproject_prefix' => 'Wikipedia:WikiProject_',
268
     *         ]
269
     */
270
    public function getAssessments()
271
    {
272
        if (!$this->project->hasPageAssessments() || $this->getNamespace() !== 0) {
273
            return false;
274
        }
275
276
        $projectDomain = $this->project->getDomain();
277
        $config = $this->project->getRepository()->getAssessmentsConfig($projectDomain);
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 getAssessmentsConfig() 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...
278
        $data = $this->getRepository()->getAssessments($this->project, [$this->getId()]);
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 getAssessments() does only exist in the following sub-classes of Xtools\Repository: Xtools\PagesRepository. 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...
279
280
        // Set the default decorations for the overall quality assessment
281
        // This will be replaced with the first valid class defined for any WikiProject
282
        $overallQuality = $config['class']['Unknown'];
283
        $overallQuality['value'] = '???';
284
285
        $decoratedAssessments = [];
286
287
        foreach ($data as $assessment) {
288
            $classValue = $assessment['class'];
289
290
            // Use ??? as the presented value when the class is unknown or is not defined in the config
291
            if ($classValue === 'Unknown' || $classValue === '' || !isset($config['class'][$classValue])) {
292
                $classAttrs = $config['class']['Unknown'];
293
                $assessment['class']['value'] = '???';
294
                $assessment['class']['category'] = $classAttrs['category'];
295
                $assessment['class']['color'] = $classAttrs['color'];
296
                $assessment['class']['badge'] = "https://upload.wikimedia.org/wikipedia/commons/"
297
                    . $classAttrs['badge'];
298
            } else {
299
                $classAttrs = $config['class'][$classValue];
300
                $assessment['class'] = [
301
                    'value' => $classValue,
302
                    'color' => $classAttrs['color'],
303
                    'category' => $classAttrs['category'],
304
                ];
305
306
                // add full URL to badge icon
307
                if ($classAttrs['badge'] !== '') {
308
                    $assessment['class']['badge'] = $this->project->getAssessmentBadgeURL($classValue);
309
                }
310
            }
311
312
            if ($overallQuality['value'] === '???') {
313
                $overallQuality = $assessment['class'];
314
                $overallQuality['category'] = $classAttrs['category'];
315
            }
316
317
            $importanceValue = $assessment['importance'];
318
            $importanceUnknown = $importanceValue === 'Unknown' || $importanceValue === '';
319
320
            if ($importanceUnknown || !isset($config['importance'][$importanceValue])) {
321
                $importanceAttrs = $config['importance']['Unknown'];
322
                $assessment['importance'] = $importanceAttrs;
323
                $assessment['importance']['value'] = '???';
324
                $assessment['importance']['category'] = $importanceAttrs['category'];
325
            } else {
326
                $importanceAttrs = $config['importance'][$importanceValue];
327
                $assessment['importance'] = [
328
                    'value' => $importanceValue,
329
                    'color' => $importanceAttrs['color'],
330
                    'weight' => $importanceAttrs['weight'], // numerical weight for sorting purposes
331
                    'category' => $importanceAttrs['category'],
332
                ];
333
            }
334
335
            $decoratedAssessments[$assessment['wikiproject']] = $assessment;
336
        }
337
338
        return [
339
            'assessment' => $overallQuality,
340
            'wikiprojects' => $decoratedAssessments,
341
            'wikiproject_prefix' => $config['wikiproject_prefix']
342
        ];
343
    }
344
345
    /**
346
     * Get CheckWiki errors for this page
347
     * @return string[] See getErrors() for format
348
     */
349
    public function getCheckWikiErrors()
350
    {
351
        return $this->getRepository()->getCheckWikiErrors($this);
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 getCheckWikiErrors() does only exist in the following sub-classes of Xtools\Repository: Xtools\PagesRepository. 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...
352
    }
353
354
    /**
355
     * Get Wikidata errors for this page
356
     * @return string[] See getErrors() for format
357
     */
358
    public function getWikidataErrors()
359
    {
360
        $errors = [];
361
362
        if (empty($this->getWikidataId())) {
363
            return [];
364
        }
365
366
        $wikidataInfo = $this->getRepository()->getWikidataInfo($this);
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 getWikidataInfo() does only exist in the following sub-classes of Xtools\Repository: Xtools\PagesRepository. 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...
367
368
        $terms = array_map(function ($entry) {
369
            return $entry['term'];
370
        }, $wikidataInfo);
371
372
        $lang = $this->getLang();
373
374 View Code Duplication
        if (!in_array('label', $terms)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
375
            $errors[] = [
376
                'prio' => 2,
377
                'name' => 'Wikidata',
378
                'notice' => "Label for language <em>$lang</em> is missing", // FIXME: i18n
379
                'explanation' => "See: <a target='_blank' " .
380
                    "href='//www.wikidata.org/wiki/Help:Label'>Help:Label</a>",
381
            ];
382
        }
383
384 View Code Duplication
        if (!in_array('description', $terms)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
385
            $errors[] = [
386
                'prio' => 3,
387
                'name' => 'Wikidata',
388
                'notice' => "Description for language <em>$lang</em> is missing", // FIXME: i18n
389
                'explanation' => "See: <a target='_blank' " .
390
                    "href='//www.wikidata.org/wiki/Help:Description'>Help:Description</a>",
391
            ];
392
        }
393
394
        return $errors;
395
    }
396
397
    /**
398
     * Get Wikidata and CheckWiki errors, if present
399
     * @return string[] List of errors in the format:
400
     *    [[
401
     *         'prio' => int,
402
     *         'name' => string,
403
     *         'notice' => string (HTML),
404
     *         'explanation' => string (HTML)
405
     *     ], ... ]
406
     */
407
    public function getErrors()
408
    {
409
        // Includes label and description
410
        $wikidataErrors = $this->getWikidataErrors();
411
412
        $checkWikiErrors = $this->getCheckWikiErrors();
413
414
        return array_merge($wikidataErrors, $checkWikiErrors);
415
    }
416
417
    /**
418
     * Get all wikidata items for the page, not just languages of sister projects
419
     * @return int Number of records.
420
     */
421
    public function getWikidataItems()
422
    {
423
        return $this->getRepository()->getWikidataItems($this);
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 getWikidataItems() does only exist in the following sub-classes of Xtools\Repository: Xtools\PagesRepository. 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...
424
    }
425
426
    /**
427
     * Count wikidata items for the page, not just languages of sister projects
428
     * @return int Number of records.
429
     */
430
    public function countWikidataItems()
431
    {
432
        return $this->getRepository()->countWikidataItems($this);
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 countWikidataItems() does only exist in the following sub-classes of Xtools\Repository: Xtools\PagesRepository. 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...
433
    }
434
435
    /**
436
     * Get number of in and outgoing links and redirects to this page.
437
     * @return string[] Counts with the keys 'links_ext_count', 'links_out_count',
438
     *                  'links_in_count' and 'redirects_count'
439
     */
440
    public function countLinksAndRedirects()
441
    {
442
        return $this->getRepository()->countLinksAndRedirects($this);
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 countLinksAndRedirects() does only exist in the following sub-classes of Xtools\Repository: Xtools\PagesRepository. 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...
443
    }
444
445
    /**
446
     * Get the sum of pageviews for the given page and timeframe.
447
     * @param string|DateTime $start In the format YYYYMMDD
448
     * @param string|DateTime $end In the format YYYYMMDD
449
     * @return string[]
450
     */
451
    public function getPageviews($start, $end)
452
    {
453
        try {
454
            $pageviews = $this->getRepository()->getPageviews($this, $start, $end);
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 getPageviews() does only exist in the following sub-classes of Xtools\Repository: Xtools\PagesRepository. 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...
455
        } catch (\GuzzleHttp\Exception\ClientException $e) {
456
            // 404 means zero pageviews
457
            return 0;
458
        }
459
460
        return array_sum(array_map(function ($item) {
461
            return (int) $item['views'];
462
        }, $pageviews['items']));
463
    }
464
465
    /**
466
     * Get the sum of pageviews over the last N days
467
     * @param int [$days] Default 30
468
     * @return int Number of pageviews
469
     */
470
    public function getLastPageviews($days = 30)
471
    {
472
        $start = date('Ymd', strtotime("-$days days"));
473
        $end = date('Ymd');
474
        return $this->getPageviews($start, $end);
475
    }
476
}
477