Completed
Push — 0.1 ( 1296ef...144915 )
by Yuichi
19:51 queued 09:46
created

Config::getBaseUrl()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 3

Importance

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