Completed
Pull Request — master (#39)
by Sam
02:37
created

ClientFactory::setLogger()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 3
ccs 3
cts 3
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 1
crap 1
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
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
25
	 *
26
	 * @param array $config All configuration settings supported by Guzzle, and these:
27
	 *          middleware => array of extra middleware to pass to guzzle
28
	 *          user-agent => string default user agent to use for requests
29
	 */
30 6
	public function __construct( array $config = [] ) {
31 6
		$this->logger = new NullLogger();
32 6
		$this->config = $config;
33 6
	}
34
35
	/**
36
	 * @since 2.1
37
	 *
38
	 * @return Client
39
	 */
40 6
	public function getClient() {
41 6
		if ( $this->client === null ) {
42 6
			$this->client = $this->newClient();
43
		}
44 6
		return $this->client;
45
	}
46
47
	/**
48
	 * @return Client
49
	 */
50 6
	private function newClient() {
51 6
		$this->config += [
52
			'cookies' => true,
53
			'headers' => [],
54
			'middleware' => [],
55
		];
56
57 6
		if ( !array_key_exists( 'User-Agent', $this->config['headers'] ) ) {
58 5
			if ( array_key_exists( 'user-agent', $this->config ) ) {
59 1
				$this->config['headers']['User-Agent'] = $this->config['user-agent'];
60
			} else {
61 4
				$this->config['headers']['User-Agent'] = 'Addwiki - mediawiki-api-base';
62
			}
63
		}
64 6
		unset( $this->config['user-agent'] );
65
66 6
		if ( !array_key_exists( 'handler', $this->config ) ) {
67 5
			$this->config['handler'] = HandlerStack::create( new CurlHandler() );
68
		}
69
70 6
		$middlewareFactory = new MiddlewareFactory();
71 6
		$middlewareFactory->setLogger( $this->logger );
72
73 6
		$this->config['middleware'][] = $middlewareFactory->retry();
74
75 6
		foreach ( $this->config['middleware'] as $name => $middleware ) {
76 6
			$this->config['handler']->push( $middleware );
77
		}
78 6
		unset( $this->config['middleware'] );
79
80 6
		return new Client( $this->config );
81
	}
82
83
	/**
84
	 * Sets a logger instance on the object
85
	 *
86
	 * @since 2.1
87
	 *
88
	 * @param LoggerInterface $logger The new Logger object.
89
	 *
90
	 * @return null
91
	 */
92 1
	public function setLogger( LoggerInterface $logger ) {
93 1
		$this->logger = $logger;
94 1
	}
95
96
}
97