Completed
Push — master ( 0c2959...f0bd19 )
by adam
06:19
created

ClientFactory::newClient()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 25
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 2
Bugs 0 Features 1
Metric Value
c 2
b 0
f 1
dl 0
loc 25
ccs 0
cts 6
cp 0
rs 8.5806
cc 4
eloc 16
nc 4
nop 0
crap 20
1
<?php
2
3
namespace Mediawiki\Api\Guzzle;
4
5
use GuzzleHttp\Client;
6
use GuzzleHttp\Handler\CurlHandler;
7
use GuzzleHttp\HandlerStack;
8
use Psr\Log\LoggerAwareInterface;
9
use Psr\Log\LoggerInterface;
10
use Psr\Log\NullLogger;
11
12
/**
13
 * @since 2.1.0
14
 *
15
 * @author Addshore
16
 */
17
class ClientFactory implements LoggerAwareInterface {
18
19
	private $client;
20
	private $logger;
21
	private $config;
22
23
	/**
24
	 * @since 2.1.0
25
	 *
26
	 * @param array $config with possible keys:
27
	 *          middleware => array of extra middleware to pass to guzzle
28
	 *          user-agent => string default user agent to use for requests
29
	 */
30
	public function __construct( array $config = array() ) {
31
		$this->logger = new NullLogger();
32
		$this->config = $config;
33
	}
34
35
	/**
36
	 * @since 2.1.0
37
	 *
38
	 * @return Client
39
	 */
40
	public function getClient() {
41
		if( $this->client === null ) {
42
			$this->client = $this->newClient();
43
		}
44
		return $this->client;
45
	}
46
47
	/**
48
	 * @return Client
49
	 */
50
	private function newClient() {
51
		$middlewareFactory = new MiddlewareFactory();
52
		$middlewareFactory->setLogger( $this->logger );
53
54
		$handlerStack = HandlerStack::create( new CurlHandler() );
55
		$handlerStack->push( $middlewareFactory->retry() );
56
57
		if( array_key_exists( 'user-agent', $this->config ) ) {
58
			$ua = $this->config['user-agent'];
59
		} else {
60
			$ua = 'Addwiki - mediawiki-api-base';
61
		}
62
63
		if( array_key_exists( 'middleware', $this->config ) ) {
64
			foreach( $this->config['middleware'] as $middleware ) {
65
				$handlerStack->push( $middleware );
66
			}
67
		}
68
69
		return new Client( array(
70
			'cookies' => true,
71
			'handler' => $handlerStack,
72
			'headers' => array( 'User-Agent' => $ua ),
73
		) );
74
	}
75
76
	/**
77
	 * Sets a logger instance on the object
78
	 *
79
	 * @since 2.1.0
80
	 *
81
	 * @param LoggerInterface $logger
82
	 *
83
	 * @return null
84
	 */
85
	public function setLogger( LoggerInterface $logger ) {
86
		$this->logger = $logger;
87
	}
88
89
}
90