Completed
Push — master ( 86adbf...92b61e )
by
unknown
02:54 queued 10s
created

Project::getBasicInfo()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 7
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 4
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 (!$this->basicInfo) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->basicInfo 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...
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 (!$this->metadata) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->metadata 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...
65
            $url = $this->getBasicInfo($this->nameUnnormalized)['url'];
0 ignored issues
show
Unused Code introduced by
The call to Project::getBasicInfo() has too many arguments starting with $this->nameUnnormalized.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
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 name of the page on this project that the user must create in order to opt in for
213
     * restricted statistics display.
214
     * @param User $user
215
     * @return string
216
     */
217
    public function userOptInPage(User $user)
218
    {
219
        $localPageName = 'User:' . $user->getUsername() . '/EditCounterOptIn.js';
220
        return $localPageName;
221
    }
222
223
    /**
224
     * Has a user opted in to having their restricted statistics displayed to anyone?
225
     * @param User $user
226
     * @return bool
227
     */
228
    public function userHasOptedIn(User $user)
229
    {
230
        // 1. First check to see if the whole project has opted in.
231
        if (!$this->userOptedIn) {
232
            $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...
233
            $this->userOptedIn = in_array($this->getDatabaseName(), $optedInProjects);
234
        }
235
        if ($this->userOptedIn) {
236
            return true;
237
        }
238
239
        // 2. Then see if the currently-logged-in user is requesting their own statistics.
240
        if ($user->isCurrentlyLoggedIn()) {
241
            return true;
242
        }
243
244
        // 3. Then see if the user has opted in on this project.
245
        $userNsId = 2;
246
        $localExists = $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 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...
247
            ->pageHasContent($this, $userNsId, $this->userOptInPage($user));
248
        if ($localExists) {
249
            return true;
250
        }
251
252
        // 4. Lastly, see if they've opted in globally on the default project or Meta.
253
        $globalPageName = $user->getUsername() . '/EditCounterGlobalOptIn.js';
254
        $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...
255
        if ($globalProject instanceof Project) {
256
            $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...
257
                ->pageHasContent($globalProject, $userNsId, $globalPageName);
258
            if ($globalExists) {
259
                return true;
260
            }
261
        }
262
263
        return false;
264
    }
265
266
    /**
267
     * Does this project support page assessments?
268
     * @return bool
269
     */
270
    public function hasPageAssessments()
271
    {
272
        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...
273
    }
274
275
    /**
276
     * Get the image URL of the badge for the given page assessment
277
     * @param  string $class  Valid classification for project, such as 'Start', 'GA', etc.
278
     * @return string         URL to image
279
     */
280
    public function getAssessmentBadgeURL($class)
281
    {
282
        $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...
283
284
        if (isset($config['class'][$class])) {
285
            return "https://upload.wikimedia.org/wikipedia/commons/" . $config['class'][$class]['badge'];
286
        } elseif (isset($config['class']['Unknown'])) {
287
            return "https://upload.wikimedia.org/wikipedia/commons/" . $config['class']['Unknown']['badge'];
288
        } else {
289
            return "";
290
        }
291
    }
292
}
293