Completed
Branch newinternal (104de7)
by Simon
10:16
created

BlacklistHelper   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 90
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 2
Bugs 1 Features 0
Metric Value
wmc 7
c 2
b 1
f 0
lcom 1
cbo 1
dl 0
loc 90
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
B isBlacklisted() 0 31 5
A performWikiLookup() 0 18 1
1
<?php
2
3
namespace Waca\Helpers;
4
5
use Waca\Exceptions\CurlException;
6
use Waca\Helpers\Interfaces\IBlacklistHelper;
7
8
class BlacklistHelper implements IBlacklistHelper
9
{
10
	/** @var HttpHelper */
11
	private $httpHelper;
12
	/**
13
	 * Cache of previously requested usernames
14
	 * @var array
15
	 */
16
	private $cache = array();
17
	/** @var string */
18
	private $mediawikiWebServiceEndpoint;
19
20
	/**
21
	 * BlacklistHelper constructor.
22
	 *
23
	 * @param HttpHelper $httpHelper
24
	 * @param string     $mediawikiWebServiceEndpoint
25
	 */
26
	public function __construct(HttpHelper $httpHelper, $mediawikiWebServiceEndpoint)
27
	{
28
		$this->httpHelper = $httpHelper;
29
		$this->mediawikiWebServiceEndpoint = $mediawikiWebServiceEndpoint;
30
	}
31
32
	/**
33
	 * Returns a value indicating whether the provided username is blacklisted by the on-wiki title blacklist
34
	 *
35
	 * @param string $username
36
	 *
37
	 * @return false|string False if the username is not blacklisted, else the blacklist entry.
38
	 */
39
	public function isBlacklisted($username)
40
	{
41
		if (isset($this->cache[$username])) {
42
			$result = $this->cache[$username];
43
			if ($result === false) {
44
				return false;
45
			}
46
47
			return $result['line'];
48
		}
49
50
		try {
51
			$result = $this->performWikiLookup($username);
52
		}
53
		catch (CurlException $ex) {
54
			// @todo log this, but fail gracefully.
55
			return false;
56
		}
57
58
		if ($result['result'] === 'ok') {
59
			// not blacklisted
60
			$this->cache[$username] = false;
61
62
			return false;
63
		}
64
		else {
65
			$this->cache[$username] = $result;
66
67
			return $result['line'];
68
		}
69
	}
70
71
	/**
72
	 * Performs a fetch to MediaWiki for the relevant title blacklist entry
73
	 *
74
	 * @param string $username The username to look up
75
	 *
76
	 * @return array
77
	 * @throws CurlException
78
	 */
79
	private function performWikiLookup($username)
80
	{
81
		$endpoint = $this->mediawikiWebServiceEndpoint;
82
83
		$parameters = array(
84
			'action'       => 'titleblacklist',
85
			'format'       => 'php',
86
			'tbtitle'      => $username,
87
			'tbaction'     => 'new-account',
88
			'tbnooverride' => true,
89
		);
90
91
		$apiResult = $this->httpHelper->get($endpoint, $parameters);
92
93
		$data = unserialize($apiResult);
94
95
		return $data['titleblacklist'];
96
	}
97
}