Completed
Push — response_middleware ( 918c24 )
by Yuichi
01:48
created

Config   B

Complexity

Total Complexity 36

Size/Duplication

Total Lines 236
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 0
Metric Value
wmc 36
lcom 1
cbo 3
dl 0
loc 236
rs 8.8
c 0
b 0
f 0

15 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 15 2
A configureAuth() 0 9 2
A configureBasicAuth() 0 6 2
A configureCert() 0 9 2
A getBasicAuthOptions() 0 10 2
A getCertOptions() 0 10 2
A toGuzzleConfig() 0 19 4
A get() 0 8 2
A getConfig() 0 4 1
B hasRequired() 0 12 5
A hasRequiredOnAuth() 0 8 3
A hasRequiredOnBasicAuth() 0 4 1
A hasRequiredOnCert() 0 4 1
A hasKeysByUse() 0 14 4
A getBaseUri() 0 15 3
1
<?php
2
3
namespace CybozuHttp;
4
5
use CybozuHttp\Exception\NotExistRequiredException;
6
use CybozuHttp\Middleware\FinishMiddleware;
7
use GuzzleHttp\HandlerStack;
8
9
/**
10
 * @author ochi51 <[email protected]>
11
 */
12
class Config
13
{
14
15
    /**
16
     * @var array $config
17
     */
18
    private $config;
19
20
    /**
21
     * @var array $default
22
     */
23
    private static $default = [
24
        'domain' => 'cybozu.com',
25
        'use_api_token' => false,
26
        'use_basic' => false,
27
        'use_client_cert' => false,
28
        'base_uri' => null,
29
        'concurrency' => 1,
30
        'response_middleware' => true,
31
        'debug' => false
32
    ];
33
34
    /**
35
     * @var array $required
36
     */
37
    private static $required = [
38
        'handler',
39
        'domain',
40
        'subdomain',
41
        'use_api_token',
42
        'use_basic',
43
        'use_client_cert',
44
        'base_uri',
45
        'debug'
46
    ];
47
48
    public function __construct(array $config)
49
    {
50
        $this->config = array_merge(self::$default, $config);
51
52
        $this->config['base_uri'] = $this->getBaseUri();
53
        $this->config['handler'] = $handler =  HandlerStack::create();
54
55
        $this->configureAuth();
56
        $this->configureBasicAuth();
57
        $this->configureCert();
58
59
        if ($this->config['response_middleware']) {
60
            $handler->before('http_errors', new FinishMiddleware(), 'cybozu_http.finish');
61
        }
62
    }
63
64
    private function configureAuth()
65
    {
66
        if ($this->get('use_api_token')) {
67
            $this->config['headers']['X-Cybozu-API-Token'] = $this->get('token');
68
        } else {
69
            $this->config['headers']['X-Cybozu-Authorization'] =
70
                base64_encode($this->get('login') . ':' . $this->get('password'));
71
        }
72
    }
73
74
    private function configureBasicAuth()
75
    {
76
        if ($this->get('use_basic')) {
77
            $this->config['auth'] = $this->getBasicAuthOptions();
78
        }
79
    }
80
81
    private function configureCert()
82
    {
83
        if ($this->get('use_client_cert')) {
84
            $this->config['verify'] = true;
85
            $this->config['cert'] = $this->getCertOptions();
86
        } else {
87
            $this->config['verify'] = false;
88
        }
89
    }
90
91
    /**
92
     * @return array
93
     * @throws NotExistRequiredException
94
     */
95
    private function getBasicAuthOptions()
96
    {
97
        if ($this->hasRequiredOnBasicAuth()) {
98
            return [
99
                $this->get('basic_login'),
100
                $this->get('basic_password')
101
            ];
102
        }
103
        throw new NotExistRequiredException('kintone.empty_basic_password');
104
    }
105
106
    /**
107
     * @return array
108
     * @throws NotExistRequiredException
109
     */
110
    private function getCertOptions()
111
    {
112
        if ($this->hasRequiredOnCert()) {
113
            return [
114
                $this->get('cert_file'),
115
                $this->get('cert_password')
116
            ];
117
        }
118
        throw new NotExistRequiredException('kintone.empty_cert');
119
    }
120
121
    /**
122
     * @return array
123
     */
124
    public function toGuzzleConfig()
125
    {
126
        $config = [
127
            'handler' => $this->get('handler'),
128
            'base_uri' => $this->get('base_uri'),
129
            'headers' => $this->get('headers'),
130
            'debug' => $this->get('debug') ? fopen($this->get('logfile'), 'ab') : false,
131
            'concurrency' => $this->get('concurrency')
132
        ];
133
        if ($this->get('auth')) {
134
            $config['auth'] = $this->get('auth');
135
        }
136
        $config['verify'] = $this->get('verify');
137
        if ($this->get('cert')) {
138
            $config['cert'] = $this->get('cert');
139
        }
140
141
        return $config;
142
    }
143
144
    /**
145
     * @param $key
146
     * @return string|bool
147
     */
148
    public function get($key)
149
    {
150
        if (isset($this->config[$key])) {
151
            return $this->config[$key];
152
        }
153
154
        return false;
155
    }
156
157
    /**
158
     * @return array
159
     */
160
    public function getConfig()
161
    {
162
        return $this->config;
163
    }
164
165
    /**
166
     * @return bool
167
     */
168
    public function hasRequired()
169
    {
170
        foreach (self::$required as $r) {
171
            if (!array_key_exists($r, $this->config)) {
172
                return false;
173
            }
174
        }
175
176
        return $this->hasRequiredOnAuth()
177
                && $this->hasRequiredOnBasicAuth()
178
                && $this->hasRequiredOnCert();
179
    }
180
181
    /**
182
     * @return bool
183
     */
184
    private function hasRequiredOnAuth()
185
    {
186
        if ($this->get('use_api_token')) {
187
            return !empty($this->get('token'));
188
        }
189
190
        return $this->get('login') && $this->get('password');
191
    }
192
193
    /**
194
     * @return bool
195
     */
196
    private function hasRequiredOnBasicAuth()
197
    {
198
        return $this->hasKeysByUse('use_basic', ['basic_login', 'basic_password']);
199
    }
200
201
    /**
202
     * @return bool
203
     */
204
    private function hasRequiredOnCert()
205
    {
206
        return $this->hasKeysByUse('use_client_cert', ['cert_file', 'cert_password']);
207
    }
208
209
    /**
210
     * @param string $use
211
     * @param string[] $keys
212
     * @return bool
213
     */
214
    private function hasKeysByUse($use, array $keys)
215
    {
216
        if (!$this->get($use)) {
217
            return true;
218
        }
219
220
        foreach ($keys as $key) {
221
            if (!$this->get($key)) {
222
                return false;
223
            }
224
        }
225
226
        return true;
227
    }
228
229
    /**
230
     * @return string
231
     */
232
    public function getBaseUri()
233
    {
234
        $subdomain = $this->get('subdomain');
235
        $uri = 'https://'. $subdomain;
236
237
        if (strpos($subdomain, '.') === false) {
238
            if ($this->get('use_client_cert')) {
239
                $uri .= '.s';
240
            }
241
242
            $uri .= '.'. $this->get('domain');
243
        }
244
245
        return $uri;
246
    }
247
}