Passed
Pull Request — 3.x (#12)
by Ryota
04:40 queued 03:14
created

ClientFactory::createHttpClient()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 7
nc 2
nop 2
dl 0
loc 12
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Polidog\Chatwork\Client;
6
7
use GuzzleHttp\HandlerStack;
8
use GuzzleHttp\Middleware;
9
use Psr\Http\Message\RequestInterface;
10
11
final class ClientFactory
12
{
13
    /**
14
     * HttpOptions.
15
     *
16
     * @var array
17
     */
18
    private static $httpOptions = [
19
        'base_uri' => 'https://api.chatwork.com/',
20
        'defaults' => [
21
            'timeout' => 60,
22
            'debug' => false,
23
        ],
24
        'headers' => [
25
            'User-Agent' => 'php-chatwork-api v2',
26
            'Accept' => 'application/json',
27
        ],
28
    ];
29
30
    /**
31
     * @deprecated
32
     *
33
     * @param string $token
34
     * @param string $version
35
     * @param array $httpOptions
36
     * @return ClientInterface
37
     */
38
    public static function create(string $token, string $version, array $httpOptions = []): ClientInterface
39
    {
40
        $httpOptions = array_merge(self::$httpOptions, $httpOptions);
41
42
        return new Client($token, $version, new \GuzzleHttp\Client($httpOptions));
43
    }
44
45
    public static function createHttpClient(string $chatworkToken, array $middlewares = []): \GuzzleHttp\Client
46
    {
47
        $stack = new HandlerStack();
48
        $stack->push(Middleware::mapRequest(static fn (RequestInterface $request) => $request->withHeader('X-ChatWorkToken', $chatworkToken)));
49
        foreach ($middlewares as $middleware) {
50
            $stack->push($middleware);
51
        }
52
53
        $options = array_merge(self::$httpOptions, [
54
          'handler' => $stack,
55
        ]);
56
        return new \GuzzleHttp\Client($options);
57
    }
58
}
59