Completed
Push — master ( cd44b6...7febf5 )
by MusikAnimal
03:41 queued 01:27
created

Project::getMetadata()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 5
nc 2
nop 0
1
<?php
2
/**
3
 * This file contains only the Project class.
4
 */
5
6
namespace Xtools;
7
8
use Mediawiki\Api\MediawikiApi;
9
use Symfony\Component\VarDumper\VarDumper;
10
11
/**
12
 * A Project is a single wiki that XTools is querying.
13
 */
14
class Project extends Model
15
{
16
17
    /** @var string The project name as supplied by the user. */
18
    protected $nameUnnormalized;
19
20
    /** @var string[] Basic metadata about the project */
21
    protected $metadata;
22
23
    /** @var string[] Project's 'dbName', 'url' and 'lang'. */
24
    protected $basicInfo;
25
26
    /**
27
     * Whether the user being queried for in this session
28
     *   has opted in to restricted statistics
29
     * @var bool
30
     */
31
    protected $userOptedIn;
32
33
    /**
34
     * Create a new Project.
35
     * @param string $nameOrUrl The project's database name or URL.
36
     */
37
    public function __construct($nameOrUrl)
38
    {
39
        $this->nameUnnormalized = $nameOrUrl;
40
    }
41
42
    /**
43
     * Get 'dbName', 'url' and 'lang' of the project, the relevant basic info
44
     *   we can get from the meta database. This is all you need to make
45
     *   database queries. More comprehensive metadata can be fetched with
46
     *   getMetadata() at the expense of an API call, which may be cached.
47
     * @return string[]
48
     */
49
    protected function getBasicInfo()
50
    {
51
        if (empty($this->basicInfo)) {
52
            $this->basicInfo = $this->getRepository()->getOne($this->nameUnnormalized);
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 getOne() 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...
53
        }
54
        return $this->basicInfo;
55
    }
56
57
    /**
58
     * Get full metadata about the project. See ProjectRepository::getMetadata
59
     *   for more information.
60
     * @return string[]
61
     */
62
    protected function getMetadata()
63
    {
64
        if (empty($this->metadata)) {
65
            $url = $this->getBasicInfo()['url'];
66
            $this->metadata = $this->getRepository()->getMetadata($url);
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 getMetadata() 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...
67
        }
68
        return $this->metadata;
69
    }
70
71
    /**
72
     * Does this project exist?
73
     * @return bool
74
     */
75
    public function exists()
76
    {
77
        return !empty($this->getDomain());
78
    }
79
80
    /**
81
     * The unique domain name of this project, without protocol or path components.
82
     * This should be used as the canonical project identifier.
83
     *
84
     * @return string
85
     */
86
    public function getDomain()
87
    {
88
        $url = isset($this->getBasicInfo()['url']) ? $this->getBasicInfo()['url'] : '';
89
        return parse_url($url, PHP_URL_HOST);
90
    }
91
92
    /**
93
     * The name of the database for this project.
94
     *
95
     * @return string
96
     */
97
    public function getDatabaseName()
98
    {
99
        return isset($this->getBasicInfo()['dbName']) ? $this->getBasicInfo()['dbName'] : '';
100
    }
101
102
    /**
103
     * The language for this project.
104
     *
105
     * @return string
106
     */
107
    public function getLang()
108
    {
109
        return isset($this->getBasicInfo()['lang']) ? $this->getBasicInfo()['lang'] : '';
110
    }
111
112
    /**
113
     * The project URL is the fully-qualified domain name, with protocol and trailing slash.
114
     *
115
     * @param bool $withTrailingSlash Whether to append a slash.
116
     * @return string
117
     */
118
    public function getUrl($withTrailingSlash = true)
119
    {
120
        return rtrim($this->getBasicInfo()['url'], '/') . ($withTrailingSlash ? '/' : '');
121
    }
122
123
    /**
124
     * Get a MediawikiApi object for this Project.
125
     *
126
     * @return MediawikiApi
127
     */
128
    public function getApi()
129
    {
130
        return $this->getRepository()->getMediawikiApi($this);
131
    }
132
133
    /**
134
     * The base URL path of this project (that page titles are appended to).
135
     * For some wikis the title (apparently) may not be at the end.
136
     * Replace $1 with the article name.
137
     *
138
     * @link https://www.mediawiki.org/wiki/Manual:$wgArticlePath
139
     *
140
     * @return string
141
     */
142 View Code Duplication
    public function getArticlePath()
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...
143
    {
144
        $metadata = $this->getMetadata();
145
        return isset($metadata['general']['articlePath'])
146
            ? $metadata['general']['articlePath']
147
            : '/wiki/$1';
148
    }
149
150
    /**
151
     * The URL path of the directory that contains index.php, with no trailing slash.
152
     * Defaults to '/w' which is the same as the normal WMF set-up.
153
     *
154
     * @link https://www.mediawiki.org/wiki/Manual:$wgScriptPath
155
     *
156
     * @return string
157
     */
158 View Code Duplication
    public function getScriptPath()
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...
159
    {
160
        $metadata = $this->getMetadata();
161
        return isset($metadata['general']['scriptPath'])
162
            ? $metadata['general']['scriptPath']
163
            : '/w';
164
    }
165
166
    /**
167
     * The URL path to index.php
168
     * Defaults to '/w/index.php' which is the same as the normal WMF set-up.
169
     *
170
     * @return string
171
     */
172
    public function getScript()
173
    {
174
        $metadata = $this->getMetadata();
175
        return isset($metadata['general']['script'])
176
            ? $metadata['general']['script']
177
            : $this->getScriptPath() . '/index.php';
178
    }
179
180
    /**
181
     * The full URL to api.php
182
     *
183
     * @return string
184
     */
185
    public function getApiUrl()
186
    {
187
        return rtrim($this->getUrl(), '/') . $this->getRepository()->getApiPath();
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 getApiPath() 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...
188
    }
189
190
    /**
191
     * Get this project's title, the human-language full title of the wiki (e.g. "English
192
     * Wikipedia" or
193
     */
194
    public function getTitle()
195
    {
196
        $metadata = $this->getMetadata();
197
        return $metadata['general']['wikiName'].' ('.$this->getDomain().')';
198
    }
199
200
    /**
201
     * Get an array of this project's namespaces and their IDs.
202
     *
203
     * @return string[] Keys are IDs, values are names.
204
     */
205
    public function getNamespaces()
206
    {
207
        $metadata = $this->getMetadata();
208
        return $metadata['namespaces'];
209
    }
210
211
    /**
212
     * Get the title of the Main Page.
213
     * @return string
214
     */
215 View Code Duplication
    public function getMainPage()
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...
216
    {
217
        $metadata = $this->getMetadata();
218
        return isset($metadata['general']['mainpage'])
219
            ? $metadata['general']['mainpage']
220
            : '';
221
    }
222
223
    /**
224
     * Get a list of users who are in one of the given user groups.
225
     * @param string[] User groups to search for.
226
     * @return string[] User groups keyed by user name.
227
     */
228
    public function getUsersInGroups($groups)
229
    {
230
        $users = [];
231
        $usersAndGroups = $this->getRepository()->getUsersInGroups($this, $groups);
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 getUsersInGroups() 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...
232
        foreach ($usersAndGroups as $userAndGroup) {
233
            $username = $userAndGroup['user_name'];
234
            if (isset($users[$username])) {
235
                array_push($users[$username], $userAndGroup['ug_group']);
236
            } else {
237
                $users[$username] = [$userAndGroup['ug_group']];
238
            }
239
        }
240
        return $users;
241
    }
242
243
    /**
244
     * Get the name of the page on this project that the user must create in order to opt in for
245
     * restricted statistics display.
246
     * @param User $user
247
     * @return string
248
     */
249
    public function userOptInPage(User $user)
250
    {
251
        $localPageName = 'User:' . $user->getUsername() . '/EditCounterOptIn.js';
252
        return $localPageName;
253
    }
254
255
    /**
256
     * Has a user opted in to having their restricted statistics displayed to anyone?
257
     * @param User $user
258
     * @return bool
259
     */
260
    public function userHasOptedIn(User $user)
261
    {
262
        // 1. First check to see if the whole project has opted in.
263
        if (!$this->userOptedIn) {
264
            $optedInProjects = $this->getRepository()->optedIn();
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 optedIn() 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...
265
            $this->userOptedIn = in_array($this->getDatabaseName(), $optedInProjects);
266
        }
267
        if ($this->userOptedIn) {
268
            return true;
269
        }
270
271
        // 2. Then see if the currently-logged-in user is requesting their own statistics.
272
        if ($user->isCurrentlyLoggedIn()) {
273
            return true;
274
        }
275
276
        // 3. Then see if the user has opted in on this project.
277
        $userNsId = 2;
278
        // Remove namespace since we're querying the database and supplying a namespace ID.
279
        $optInPage = preg_replace('/^User:/', '', $this->userOptInPage($user));
280
        $localExists = $this->getRepository()->pageHasContent($this, $userNsId, $optInPage);
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 pageHasContent() 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...
281
        if ($localExists) {
282
            return true;
283
        }
284
285
        // 4. Lastly, see if they've opted in globally on the default project or Meta.
286
        $globalPageName = $user->getUsername() . '/EditCounterGlobalOptIn.js';
287
        $globalProject = $this->getRepository()->getGlobalProject();
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 getGlobalProject() 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...
288
        if ($globalProject instanceof Project) {
289
            $globalExists = $globalProject->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 pageHasContent() 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...
290
                ->pageHasContent($globalProject, $userNsId, $globalPageName);
291
            if ($globalExists) {
292
                return true;
293
            }
294
        }
295
296
        return false;
297
    }
298
299
    /**
300
     * Does this project support page assessments?
301
     * @return bool
302
     */
303
    public function hasPageAssessments()
304
    {
305
        return (bool) $this->getRepository()->getAssessmentsConfig($this->getDomain());
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...
306
    }
307
308
    /**
309
     * Get the image URL of the badge for the given page assessment
310
     * @param  string $class  Valid classification for project, such as 'Start', 'GA', etc.
311
     * @return string         URL to image
312
     */
313
    public function getAssessmentBadgeURL($class)
314
    {
315
        $config = $this->getRepository()->getAssessmentsConfig($this->getDomain());
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...
316
317
        if (isset($config['class'][$class])) {
318
            return "https://upload.wikimedia.org/wikipedia/commons/" . $config['class'][$class]['badge'];
319
        } elseif (isset($config['class']['Unknown'])) {
320
            return "https://upload.wikimedia.org/wikipedia/commons/" . $config['class']['Unknown']['badge'];
321
        } else {
322
            return "";
323
        }
324
    }
325
326
    /**
327
     * Normalize and quote a table name for use in SQL.
328
     * @param string $tableName
329
     * @param string|null $tableExtension Optional table extension, which will only get used if we're on Labs.
330
     * @return string Fully-qualified and quoted table name.
331
     */
332
    public function getTableName($tableName, $tableExtension = null)
333
    {
334
        return $this->getRepository()->getTableName($this->getDatabaseName(), $tableName, $tableExtension);
335
    }
336
}
337