Completed
Push — 1.0 ( efa4d7 )
by Yuichi
07:23
created

Config::getBaseUri()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 15
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

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