Completed
Push — main ( d84a15...26c7b4 )
by
unknown
04:34
created

ClientFactory   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 80
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Importance

Changes 0
Metric Value
wmc 9
c 0
b 0
f 0
lcom 1
cbo 5
dl 0
loc 80
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A getClient() 0 6 2
A newClient() 0 32 5
A setLogger() 0 3 1
1
<?php
2
3
namespace Addwiki\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
	public function __construct( array $config = [] ) {
31
		$this->logger = new NullLogger();
32
		$this->config = $config;
33
	}
34
35
	/**
36
	 * @since 2.1
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
		$this->config += [
52
			'cookies' => true,
53
			'headers' => [],
54
			'middleware' => [],
55
		];
56
57
		if ( !array_key_exists( 'User-Agent', $this->config['headers'] ) ) {
58
			if ( array_key_exists( 'user-agent', $this->config ) ) {
59
				$this->config['headers']['User-Agent'] = $this->config['user-agent'];
60
			} else {
61
				$this->config['headers']['User-Agent'] = 'Addwiki - mediawiki-api-base';
62
			}
63
		}
64
		unset( $this->config['user-agent'] );
65
66
		if ( !array_key_exists( 'handler', $this->config ) ) {
67
			$this->config['handler'] = HandlerStack::create( new CurlHandler() );
68
		}
69
70
		$middlewareFactory = new MiddlewareFactory();
71
		$middlewareFactory->setLogger( $this->logger );
72
73
		$this->config['middleware'][] = $middlewareFactory->retry();
74
75
		foreach ( $this->config['middleware'] as $middleware ) {
76
			$this->config['handler']->push( $middleware );
77
		}
78
		unset( $this->config['middleware'] );
79
80
		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
	public function setLogger( LoggerInterface $logger ) {
93
		$this->logger = $logger;
94
	}
95
96
}
97