blob: 704a1660c2aefef36ea9823c6e58239a433c08fc (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
|
<?php
namespace Mediawiki\Api\Guzzle;
use GuzzleHttp\Client;
use GuzzleHttp\Handler\CurlHandler;
use GuzzleHttp\HandlerStack;
use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
/**
* @since 2.1
*
* @author Addshore
*/
class ClientFactory implements LoggerAwareInterface {
private $client;
private $logger;
private $config;
/**
* @since 2.1
*
* @param array $config All configuration settings supported by Guzzle, and these:
* middleware => array of extra middleware to pass to guzzle
* user-agent => string default user agent to use for requests
*/
public function __construct( array $config = [] ) {
$this->logger = new NullLogger();
$this->config = $config;
}
/**
* @since 2.1
*
* @return Client
*/
public function getClient() {
if ( $this->client === null ) {
$this->client = $this->newClient();
}
return $this->client;
}
/**
* @return Client
*/
private function newClient() {
$this->config += [
'cookies' => true,
'headers' => [],
'middleware' => [],
];
if ( !array_key_exists( 'User-Agent', $this->config['headers'] ) ) {
if ( array_key_exists( 'user-agent', $this->config ) ) {
$this->config['headers']['User-Agent'] = $this->config['user-agent'];
} else {
$this->config['headers']['User-Agent'] = 'Addwiki - mediawiki-api-base';
}
}
unset( $this->config['user-agent'] );
if ( !array_key_exists( 'handler', $this->config ) ) {
$this->config['handler'] = HandlerStack::create( new CurlHandler() );
}
$middlewareFactory = new MiddlewareFactory();
$middlewareFactory->setLogger( $this->logger );
$this->config['middleware'][] = $middlewareFactory->retry();
foreach ( $this->config['middleware'] as $name => $middleware ) {
$this->config['handler']->push( $middleware );
}
unset( $this->config['middleware'] );
return new Client( $this->config );
}
/**
* Sets a logger instance on the object
*
* @since 2.1
*
* @param LoggerInterface $logger The new Logger object.
*
* @return null
*/
public function setLogger( LoggerInterface $logger ) {
$this->logger = $logger;
}
}
|