Completed
Push — master ( 11966d...5d848f )
by Sam
13s
created

UserCreator::create()   C

Complexity

Conditions 8
Paths 13

Size

Total Lines 34
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 72

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 34
ccs 0
cts 22
cp 0
rs 5.3846
cc 8
eloc 22
nc 13
nop 3
crap 72
1
<?php
2
3
namespace Mediawiki\Api\Service;
4
5
use InvalidArgumentException;
6
use Mediawiki\Api\SimpleRequest;
7
use Mediawiki\Api\UsageException;
8
9
/**
10
 * @access private
11
 *
12
 * @author Addshore
13
 */
14
class UserCreator extends Service {
15
16
	/**
17
	 * @param string $username
18
	 * @param string $password
19
	 * @param string|null $email
20
	 *
21
	 * @return bool
22
	 */
23
	public function create( $username, $password, $email = null ) {
24
		if ( !is_string( $username ) ) {
25
			throw new InvalidArgumentException( '$username should be a string' );
26
		}
27
		if ( !is_string( $password ) ) {
28
			throw new InvalidArgumentException( '$password should be a string' );
29
		}
30
		if ( !is_string( $email ) && !is_null( $email ) ) {
31
			throw new InvalidArgumentException( '$email should be a string or null' );
32
		}
33
34
		$params = [
35
			'createreturnurl' => $this->api->getApiUrl(),
36
			'createtoken' => $this->api->getToken( 'createaccount' ),
37
			'username' => $username,
38
			'password' => $password,
39
			'retype' => $password,
40
		];
41
42
		if ( !is_null( $email ) ) {
43
			$params['email'] = $email;
44
		}
45
46
		try {
47
			$result = $this->api->postRequest( new SimpleRequest( 'createaccount', $params ) );
48
			return $result['createaccount']['status'] === 'PASS';
49
		} catch ( UsageException $exception ) {
50
			// If the above request failed, try again in the old way.
51
			if ( $exception->getApiCode() === 'noname' ) {
52
				return $this->createPreOneTwentySeven( $params );
53
			}
54
			throw $exception;
55
		}
56
	}
57
58
	/**
59
	 * Create a user in the pre 1.27 manner.
60
	 * @link https://www.mediawiki.org/wiki/API:Account_creation/pre-1.27
61
	 * @return bool
62
	 */
63
	protected function createPreOneTwentySeven( $params ) {
64
		$newParams = [
65
			'name' => $params['username'],
66
			'password' => $params['password'],
67
		];
68
		if ( array_key_exists( 'email', $params ) ) {
69
			$newParams['email'] = $params['email'];
70
		}
71
		// First get the token.
72
		$tokenRequest = new SimpleRequest( 'createaccount', $newParams );
73
		$result = $this->api->postRequest( $tokenRequest );
74
		if ( $result['createaccount']['result'] == 'NeedToken' ) {
75
			// Then send the token to create the account.
76
			$newParams['token'] = $result['createaccount']['token'];
77
			$request = new SimpleRequest( 'createaccount', $newParams );
78
			$result = $this->api->postRequest( $request );
79
		}
80
		return ( $result['createaccount']['result'] === 'Success' );
81
	}
82
83
}
84