Completed
Push — main ( eacd92...54fb4a )
by
unknown
01:05
created

UserCreator::create()   A

Complexity

Conditions 4
Paths 10

Size

Total Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 24
rs 9.536
c 0
b 0
f 0
cc 4
nc 10
nop 3
1
<?php
2
3
namespace Addwiki\Mediawiki\Api\Service;
4
5
use Addwiki\Mediawiki\Api\Client\SimpleRequest;
6
use Addwiki\Mediawiki\Api\Client\UsageException;
7
8
/**
9
 * @access private
10
 */
11
class UserCreator extends Service {
12
13
	public function create( string $username, string $password, ?string $email = null ): bool {
14
		$params = [
15
			'createreturnurl' => $this->api->getApiUrl(),
16
			'createtoken' => $this->api->getToken( 'createaccount' ),
17
			'username' => $username,
18
			'password' => $password,
19
			'retype' => $password,
20
		];
21
22
		if ( $email !== null ) {
23
			$params['email'] = $email;
24
		}
25
26
		try {
27
			$result = $this->api->postRequest( new SimpleRequest( 'createaccount', $params ) );
28
			return $result['createaccount']['status'] === 'PASS';
29
		} catch ( UsageException $usageException ) {
0 ignored issues
show
Bug introduced by
The class Addwiki\Mediawiki\Api\Client\UsageException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
30
			// If the above request failed, try again in the old way.
31
			if ( $usageException->getApiCode() === 'noname' ) {
32
				return $this->createPreOneTwentySeven( $params );
33
			}
34
			throw $usageException;
35
		}
36
	}
37
38
	/**
39
	 * Create a user in the pre 1.27 manner.
40
	 * @link https://www.mediawiki.org/wiki/API:Account_creation/pre-1.27
41
	 */
42
	protected function createPreOneTwentySeven( array $params ): bool {
43
		$newParams = [
44
			'name' => $params['username'],
45
			'password' => $params['password'],
46
		];
47
		if ( array_key_exists( 'email', $params ) ) {
48
			$newParams['email'] = $params['email'];
49
		}
50
		// First get the token.
51
		$tokenRequest = new SimpleRequest( 'createaccount', $newParams );
52
		$result = $this->api->postRequest( $tokenRequest );
53
		if ( $result['createaccount']['result'] == 'NeedToken' ) {
54
			// Then send the token to create the account.
55
			$newParams['token'] = $result['createaccount']['token'];
56
			$request = new SimpleRequest( 'createaccount', $newParams );
57
			$result = $this->api->postRequest( $request );
58
		}
59
		return ( $result['createaccount']['result'] === 'Success' );
60
	}
61
62
}
63