Completed
Pull Request — master (#46)
by Sam
06:47 queued 49s
created

UserCreator::create()   C

Complexity

Conditions 8
Paths 11

Size

Total Lines 35
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 13.8319

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 35
ccs 11
cts 20
cp 0.55
rs 5.3846
cc 8
eloc 21
nc 11
nop 3
crap 13.8319
1
<?php
2
3
namespace Mediawiki\Api\Service;
4
5
use InvalidArgumentException;
6
use Mediawiki\Api\MediawikiApi;
7
use Mediawiki\Api\SimpleRequest;
8
9
/**
10
 * @access private
11
 *
12
 * @author Addshore
13
 */
14
class UserCreator {
15
16
	/**
17
	 * @var MediawikiApi
18
	 */
19
	private $api;
20
21
	/**
22
	 * @param MediawikiApi $api
23
	 */
24 1
	public function __construct( MediawikiApi $api ) {
25 1
		$this->api = $api;
26 1
	}
27
28
	/**
29
	 * @param string $username
30
	 * @param string $password
31
	 * @param string|null $email
32
	 *
33
	 * @return bool
34
	 */
35 1
	public function create( $username, $password, $email = null ) {
36 1
		if ( !is_string( $username ) ) {
37
			throw new InvalidArgumentException( '$username should be a string' );
38
		}
39 1
		if ( !is_string( $password ) ) {
40
			throw new InvalidArgumentException( '$password should be a string' );
41
		}
42 1
		if ( !is_string( $email ) && !is_null( $email ) ) {
43
			throw new InvalidArgumentException( '$email should be a string or null' );
44
		}
45
46
		$params = [
47 1
			'name' => $username,
48 1
			'password' => $password,
49
		];
50
51 1
		if ( !is_null( $email ) ) {
52
			$params['email'] = $email;
53
		}
54
55 1
		$result = $this->api->postRequest( new SimpleRequest( 'createaccount', $params ) );
56 1
		if ( $result['createaccount']['result'] == 'NeedToken' ) {
57
			$result = $this->api->postRequest(
58
				new SimpleRequest(
59
					'createaccount',
60
					array_merge( [ 'token' => $result['createaccount']['token'] ], $params )
61
				)
62
			);
63
		}
64 1
		if ( $result['createaccount']['result'] === 'Success' ) {
65
			return true;
66
		}
67
68 1
		return false;
69
	}
70
71
}
72