Completed
Push — 3.x ( e32815...7c4255 )
by Ryota
10:41 queued 09:27
created

Client::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 11
rs 9.9
c 0
b 0
f 0
cc 1
nc 1
nop 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Polidog\Chatwork\Client;
6
7
use GuzzleHttp\ClientInterface as HttpClientInterface;
8
use GuzzleHttp\Exception\GuzzleException;
9
use GuzzleHttp\Middleware;
10
use Polidog\Chatwork\Exception\ClientException;
11
use Psr\Http\Message\RequestInterface;
12
13
final class Client implements ClientInterface
14
{
15
    /**
16
     * @var string
17
     */
18
    private $apiVersion;
19
20
    /**
21
     * @var HttpClientInterface
22
     */
23
    private $httpClient;
24
25
    /**
26
     * @param string              $chatworkToken
27
     * @param HttpClientInterface $httpClient
28
     */
29
    public function __construct(
30
        HttpClientInterface $httpClient,
31
        string $chatworkToken,
32
        string $apiVersion
33
    ) {
34
        $httpClient->getConfig('handler')->push(Middleware::mapRequest(function (RequestInterface $request) use ($chatworkToken) {
35
            return $request->withHeader('X-ChatWorkToken', $chatworkToken);
36
        }));
37
        $this->apiVersion = $apiVersion;
38
        $this->httpClient = $httpClient;
39
    }
40
41
    /**
42
     * {@inheritdoc}
43
     */
44
    public function get(string $path, array $query = []): array
45
    {
46
        return $this->request('get', $path, [
47
            'query' => $query,
48
        ]);
49
    }
50
51
    /**
52
     * {@inheritdoc}
53
     */
54
    public function post(string $path, array $data = []): array
55
    {
56
        return $this->request('post', $path, [
57
            'form_params' => $data,
58
        ]);
59
    }
60
61
    /**
62
     * {@inheritdoc}
63
     */
64
    public function put(string $path, array $data = []): array
65
    {
66
        return $this->request('put', $path, [
67
            'form_params' => $data,
68
        ]);
69
    }
70
71
    /**
72
     * {@inheritdoc}
73
     */
74
    public function delete(string $path, array $query = []): array
75
    {
76
        return $this->request('delete', $path, [
77
            'query' => $query,
78
        ]);
79
    }
80
81
    private function request(string $method, string $path, array $options = []): array
82
    {
83
        $path = sprintf('/%s/%s', $this->apiVersion, $path);
84
        try {
85
            return json_decode($this->httpClient->request($method, $path, $options)->getBody()->getContents(), true);
86
        } catch (GuzzleException $e) {
87
            throw new ClientException(sprintf('request error. method = %s, path = %s', $method, $path), $e->getCode(), $e);
88
        }
89
    }
90
}
91