1 | <?php |
||
17 | class ClientFactory implements LoggerAwareInterface { |
||
18 | |||
19 | private ?Client $client = null; |
||
|
|||
20 | private NullLogger $logger; |
||
21 | private array $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 | public function getClient(): ?Client { |
||
39 | if ( $this->client === null ) { |
||
40 | $this->client = $this->newClient(); |
||
41 | } |
||
42 | return $this->client; |
||
43 | } |
||
44 | |||
45 | private function newClient(): Client { |
||
46 | $this->config += [ |
||
47 | 'cookies' => true, |
||
48 | 'headers' => [], |
||
49 | 'middleware' => [], |
||
50 | ]; |
||
51 | |||
52 | if ( !array_key_exists( 'User-Agent', $this->config['headers'] ) ) { |
||
53 | if ( array_key_exists( 'user-agent', $this->config ) ) { |
||
54 | $this->config['headers']['User-Agent'] = $this->config['user-agent']; |
||
55 | } else { |
||
56 | $this->config['headers']['User-Agent'] = 'Addwiki - mediawiki-api-base'; |
||
57 | } |
||
58 | } |
||
59 | unset( $this->config['user-agent'] ); |
||
60 | |||
61 | if ( !array_key_exists( 'handler', $this->config ) ) { |
||
62 | $this->config['handler'] = HandlerStack::create( new CurlHandler() ); |
||
63 | } |
||
64 | |||
65 | $middlewareFactory = new MiddlewareFactory(); |
||
66 | $middlewareFactory->setLogger( $this->logger ); |
||
67 | |||
68 | $this->config['middleware'][] = $middlewareFactory->retry(); |
||
69 | |||
70 | foreach ( $this->config['middleware'] as $middleware ) { |
||
71 | $this->config['handler']->push( $middleware ); |
||
72 | } |
||
73 | unset( $this->config['middleware'] ); |
||
74 | |||
75 | return new Client( $this->config ); |
||
76 | } |
||
77 | |||
78 | /** |
||
79 | * Sets a logger instance on the object |
||
80 | * |
||
81 | * @since 2.1 |
||
82 | * |
||
83 | * @param LoggerInterface $logger The new Logger object. |
||
84 | * |
||
85 | * @return null |
||
86 | */ |
||
87 | public function setLogger( LoggerInterface $logger ) { |
||
88 | $this->logger = $logger; |
||
89 | } |
||
90 | |||
91 | } |
||
92 |