Completed
Branch master (86dc85)
by
unknown
23:45
created

ForeignDBFile::getDescriptionShortUrl()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 19
Code Lines 12

Duplication

Lines 6
Ratio 31.58 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 6
loc 19
rs 9.4285
cc 3
eloc 12
nc 3
nop 0
1
<?php
2
/**
3
 * Foreign file with an accessible MediaWiki database.
4
 *
5
 * This program is free software; you can redistribute it and/or modify
6
 * it under the terms of the GNU General Public License as published by
7
 * the Free Software Foundation; either version 2 of the License, or
8
 * (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License along
16
 * with this program; if not, write to the Free Software Foundation, Inc.,
17
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18
 * http://www.gnu.org/copyleft/gpl.html
19
 *
20
 * @file
21
 * @ingroup FileAbstraction
22
 */
23
24
/**
25
 * Foreign file with an accessible MediaWiki database
26
 *
27
 * @ingroup FileAbstraction
28
 */
29
class ForeignDBFile extends LocalFile {
30
	/**
31
	 * @param Title $title
32
	 * @param FileRepo $repo
33
	 * @param null $unused
34
	 * @return ForeignDBFile
35
	 */
36
	static function newFromTitle( $title, $repo, $unused = null ) {
37
		return new self( $title, $repo );
38
	}
39
40
	/**
41
	 * Create a ForeignDBFile from a title
42
	 * Do not call this except from inside a repo class.
43
	 *
44
	 * @param stdClass $row
45
	 * @param FileRepo $repo
46
	 * @return ForeignDBFile
47
	 */
48 View Code Duplication
	static function newFromRow( $row, $repo ) {
49
		$title = Title::makeTitle( NS_FILE, $row->img_name );
50
		$file = new self( $title, $repo );
51
		$file->loadFromRow( $row );
52
53
		return $file;
54
	}
55
56
	/**
57
	 * @param string $srcPath
58
	 * @param int $flags
59
	 * @param array $options
60
	 * @return FileRepoStatus
61
	 * @throws MWException
62
	 */
63
	function publish( $srcPath, $flags = 0, array $options = [] ) {
64
		$this->readOnlyError();
65
	}
66
67
	/**
68
	 * @param string $oldver
69
	 * @param string $desc
70
	 * @param string $license
71
	 * @param string $copyStatus
72
	 * @param string $source
73
	 * @param bool $watch
74
	 * @param bool|string $timestamp
75
	 * @param User $user User object or null to use $wgUser
76
	 * @return bool
77
	 * @throws MWException
78
	 */
79
	function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
80
		$watch = false, $timestamp = false, User $user = null ) {
81
		$this->readOnlyError();
82
	}
83
84
	/**
85
	 * @param array $versions
86
	 * @param bool $unsuppress
87
	 * @return FileRepoStatus
88
	 * @throws MWException
89
	 */
90
	function restore( $versions = [], $unsuppress = false ) {
91
		$this->readOnlyError();
92
	}
93
94
	/**
95
	 * @param string $reason
96
	 * @param bool $suppress
97
	 * @param User|null $user
98
	 * @return FileRepoStatus
99
	 * @throws MWException
100
	 */
101
	function delete( $reason, $suppress = false, $user = null ) {
102
		$this->readOnlyError();
103
	}
104
105
	/**
106
	 * @param Title $target
107
	 * @return FileRepoStatus
108
	 * @throws MWException
109
	 */
110
	function move( $target ) {
111
		$this->readOnlyError();
112
	}
113
114
	/**
115
	 * @return string
116
	 */
117
	function getDescriptionUrl() {
118
		// Restore remote behavior
119
		return File::getDescriptionUrl();
120
	}
121
122
	/**
123
	 * @param bool|Language $lang Optional language to fetch description in.
124
	 * @return string
125
	 */
126
	function getDescriptionText( $lang = false ) {
127
		global $wgLang;
128
129
		if ( !$this->repo->fetchDescription ) {
130
			return false;
131
		}
132
133
		$lang = $lang ?: $wgLang;
134
		$renderUrl = $this->repo->getDescriptionRenderUrl( $this->getName(), $lang->getCode() );
135
		if ( !$renderUrl ) {
136
			return false;
137
		}
138
139
		$touched = $this->repo->getSlaveDB()->selectField(
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class FileRepo as the method getSlaveDB() does only exist in the following sub-classes of FileRepo: ForeignDBRepo, ForeignDBViaLBRepo, LocalRepo. 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...
140
			'page',
141
			'page_touched',
142
			[
143
				'page_namespace' => NS_FILE,
144
				'page_title' => $this->title->getDBkey()
145
			]
146
		);
147
		if ( $touched === false ) {
148
			return false; // no description page
149
		}
150
151
		$cache = ObjectCache::getMainWANInstance();
152
153
		return $cache->getWithSetCallback(
154
			$this->repo->getLocalCacheKey(
155
				'RemoteFileDescription',
156
				'url',
157
				$lang->getCode(),
158
				$this->getName(),
159
				$touched
160
			),
161
			$this->repo->descriptionCacheExpiry ?: $cache::TTL_UNCACHEABLE,
162 View Code Duplication
			function ( $oldValue, &$ttl, array &$setOpts ) use ( $renderUrl ) {
163
				wfDebug( "Fetching shared description from $renderUrl\n" );
164
				$res = Http::get( $renderUrl, [], __METHOD__ );
165
				if ( !$res ) {
166
					$ttl = WANObjectCache::TTL_UNCACHEABLE;
167
				}
168
169
				return $res;
170
			}
171
		);
172
	}
173
174
	/**
175
	 * Get short description URL for a file based on the page ID.
176
	 *
177
	 * @return string
178
	 * @throws DBUnexpectedError
179
	 * @since 1.27
180
	 */
181
	public function getDescriptionShortUrl() {
182
		$dbr = $this->repo->getSlaveDB();
0 ignored issues
show
Bug introduced by
The method getSlaveDB does only exist in LocalRepo, but not in FileRepo and ForeignAPIRepo.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
183
		$pageId = $dbr->selectField(
184
			'page',
185
			'page_id',
186
			[
187
				'page_namespace' => NS_FILE,
188
				'page_title' => $this->title->getDBkey()
189
			]
190
		);
191
192 View Code Duplication
		if ( $pageId !== false ) {
193
			$url = $this->repo->makeUrl( [ 'curid' => $pageId ] );
194
			if ( $url !== false ) {
195
				return $url;
196
			}
197
		}
198
		return null;
199
	}
200
201
}
202