Completed
Push — guzzle-5 ( dcf186...84d635 )
by Chris
03:31
created

GuzzleAdapter   B

Complexity

Total Complexity 43

Size/Duplication

Total Lines 327
Duplicated Lines 1.83 %

Coupling/Cohesion

Components 1
Dependencies 5

Test Coverage

Coverage 100%

Importance

Changes 5
Bugs 0 Features 2
Metric Value
wmc 43
c 5
b 0
f 2
lcom 1
cbo 5
dl 6
loc 327
ccs 108
cts 108
cp 1
rs 8.3158

23 Methods

Rating   Name   Duplication   Size   Complexity  
C __construct() 6 24 7
A getBaseUrl() 0 4 1
A copy() 0 4 1
A createDir() 0 4 1
A delete() 0 4 1
A deleteDir() 0 4 1
B getMetadata() 0 26 4
A getMimetype() 0 4 1
A getSize() 0 4 1
A getTimestamp() 0 4 1
A getVisibility() 0 7 1
A has() 0 8 2
A listContents() 0 4 1
A read() 0 11 2
A readStream() 0 11 2
A rename() 0 4 1
A setVisibility() 0 8 2
A update() 0 4 1
A updateStream() 0 4 1
A write() 0 4 1
A writeStream() 0 4 1
A get() 0 14 3
B head() 0 26 6

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like GuzzleAdapter often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use GuzzleAdapter, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace Twistor\Flysystem;
4
5
use GuzzleHttp\Client;
6
use GuzzleHttp\ClientInterface;
7
use GuzzleHttp\Exception\BadResponseException;
8
use GuzzleHttp\Exception\ClientException;
9
use GuzzleHttp\Message\Response;
10
use League\Flysystem\AdapterInterface;
11
use League\Flysystem\Config;
12
use League\Flysystem\Util\MimeType;
13
14
/**
15
 * Uses Guzzle as a backend for HTTP URLs.
16
 */
17
class GuzzleAdapter implements AdapterInterface
18
{
19
    /**
20
     * Whether this endpoint supports HEAD requests.
21
     *
22
     * @var bool
23
     */
24
    protected $supportsHead = true;
25
26
    /**
27
     * The base URL.
28
     *
29
     * @var string
30
     */
31
    protected $base;
32
33
    /**
34
     * The Guzzle HTTP client.
35
     *
36
     * @var \GuzzleHttp\ClientInterface
37
     */
38
    protected $client;
39
40
    /**
41
     * The visibility of this adapter.
42
     *
43
     * @var string
44
     */
45
    protected $visibility = AdapterInterface::VISIBILITY_PUBLIC;
46
47
    /**
48
     * Constructs an Http object.
49
     *
50
     * @param string                      $base   The base URL.
51
     * @param \GuzzleHttp\ClientInterface $client An optional Guzzle client.
52
     */
53 3
    public function __construct($base, ClientInterface $client = null)
54
    {
55 3
        $this->client = $client ?: new Client();
56
57 3
        $parsed = parse_url($base);
58 3
        $this->base = $parsed['scheme'] . '://';
59
60 3
        if (isset($parsed['user'])) {
61 3
            $this->visibility = AdapterInterface::VISIBILITY_PRIVATE;
62 3
            $this->base .= $parsed['user'];
63
64 3 View Code Duplication
            if (isset($parsed['pass']) && $parsed['pass'] !== '') {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
65 3
                $this->base .= ':' . $parsed['pass'];
66 3
            }
67
68 3
            $this->base .= '@';
69 3
        };
70
71 3
        $this->base .= $parsed['host'] . '/';
72
73 3 View Code Duplication
        if (isset($parsed['path']) && $parsed['path'] !== '/') {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
74 3
            $this->base .= trim($parsed['path'], '/') . '/';
75 3
        }
76 3
    }
77
78
    /**
79
     * Returns the base URL.
80
     *
81
     * @return string The base URL.
82
     */
83 3
    public function getBaseUrl()
84
    {
85 3
        return $this->base;
86
    }
87
88
    /**
89
     * @inheritdoc
90
     */
91 3
    public function copy($path, $newpath)
92
    {
93 3
        return false;
94
    }
95
96
    /**
97
     * @inheritdoc
98
     */
99 3
    public function createDir($path, Config $config)
100
    {
101 3
        return false;
102
    }
103
104
    /**
105
     * @inheritdoc
106
     */
107 3
    public function delete($path)
108
    {
109 3
        return false;
110
    }
111
112
    /**
113
     * @inheritdoc
114
     */
115 3
    public function deleteDir($path)
116
    {
117 3
        return false;
118
    }
119
120
    /**
121
     * @inheritdoc
122
     */
123 3
    public function getMetadata($path)
124
    {
125 3
        if (! $response = $this->head($path)) {
126 3
            return false;
127
        }
128
129 3
        if ($mimetype = $response->getHeader('Content-Type')) {
130 3
            list($mimetype) = explode(';', $mimetype, 2);
131 3
            $mimetype = trim($mimetype);
132 3
        } else {
133
            // Remove any query strings or fragments.
134 3
            list($path) = explode('#', $path, 2);
135 3
            list($path) = explode('?', $path, 2);
136 3
            $extension = pathinfo($path, PATHINFO_EXTENSION);
137 3
            $mimetype = $extension ? MimeType::detectByFileExtension($extension) : 'text/plain';
138
        }
139
140
        return [
141 3
            'type' => 'file',
142 3
            'path' => $path,
143 3
            'timestamp' => (int) strtotime($response->getHeader('Last-Modified')),
144 3
            'size' => (int) $response->getHeader('Content-Length'),
145 3
            'visibility' => $this->visibility,
146 3
            'mimetype' => $mimetype,
147 3
        ];
148
    }
149
150
    /**
151
     * @inheritdoc
152
     */
153 3
    public function getMimetype($path)
154
    {
155 3
        return $this->getMetadata($path);
156
    }
157
158
    /**
159
     * @inheritdoc
160
     */
161 3
    public function getSize($path)
162
    {
163 3
        return $this->getMetadata($path);
164
    }
165
166
    /**
167
     * @inheritdoc
168
     */
169 3
    public function getTimestamp($path)
170
    {
171 3
        return $this->getMetadata($path);
172
    }
173
174
    /**
175
     * @inheritdoc
176
     */
177 3
    public function getVisibility($path)
178
    {
179
        return [
180 3
            'path' => $path,
181 3
            'visibility' => $this->visibility,
182 3
        ];
183
    }
184
185
    /**
186
     * @inheritdoc
187
     */
188 3
    public function has($path)
189
    {
190 3
        if (! $response = $this->head($path)) {
191 3
            return false;
192
        }
193
194 3
        return (int) $response->getStatusCode() === 200;
195
    }
196
197
    /**
198
     * @inheritdoc
199
     */
200 3
    public function listContents($directory = '', $recursive = false)
201
    {
202 3
        return [];
203
    }
204
205
    /**
206
     * @inheritdoc
207
     */
208 3
    public function read($path)
209
    {
210 3
        if (! $response = $this->get($path)) {
211 3
            return false;
212
        }
213
214
        return [
215 3
            'path' => $path,
216 3
            'contents' => (string) $response->getBody(),
217 3
        ];
218
    }
219
220
    /**
221
     * @inheritdoc
222
     */
223 3
    public function readStream($path)
224
    {
225 3
        if (! $response = $this->get($path)) {
226 3
            return false;
227
        }
228
229
        return [
230 3
            'path' => $path,
231 3
            'stream' => $response->getBody()->detach(),
232 3
        ];
233
    }
234
235
    /**
236
     * @inheritdoc
237
     */
238 3
    public function rename($path, $newpath)
239
    {
240 3
        return false;
241
    }
242
243
    /**
244
     * @inheritdoc
245
     */
246 3
    public function setVisibility($path, $visibility)
247
    {
248 3
        if ($visibility === $this->visibility) {
249 3
            return $this->getVisibility($path);
250
        }
251
252 3
        return false;
253
    }
254
255
    /**
256
     * @inheritdoc
257
     */
258 3
    public function update($path, $contents, Config $conf)
259
    {
260 3
        return false;
261
    }
262
263
    /**
264
     * @inheritdoc
265
     */
266 3
    public function updateStream($path, $resource, Config $config)
267
    {
268 3
        return false;
269
    }
270
271
    /**
272
     * @inheritdoc
273
     */
274 3
    public function write($path, $contents, Config $config)
275
    {
276 3
        return false;
277
    }
278
279
    /**
280
     * @inheritdoc
281
     */
282 3
    public function writeStream($path, $resource, Config $config)
283
    {
284 3
        return false;
285
    }
286
287
    /**
288
     * Performs a GET request.
289
     *
290
     * @param string $path The path to GET.
291
     *
292
     * @return \GuzzleHttp\Message\Response|false The response or false if failed.
293
     */
294 6
    protected function get($path)
295
    {
296
        try {
297 6
            $response = $this->client->get($this->base . $path);
298 6
        } catch (BadResponseException $e) {
299 6
            return false;
300
        }
301
302 6
        if ((int) $response->getStatusCode() !== 200) {
303 3
            return false;
304
        }
305
306 6
        return $response;
307
    }
308
309
310
    /**
311
     * Performs a HEAD request.
312
     *
313
     * @param string $path The path to HEAD.
314
     *
315
     * @return \GuzzleHttp\Message\Response|false The response or false if failed.
316
     */
317 6
    protected function head($path)
318
    {
319 6
        if (! $this->supportsHead) {
320 3
            return $this->get($path);
321
        }
322
323
        try {
324 6
            $response = $this->client->head($this->base . $path);
325 6
        } catch (ClientException $e) {
326 6
            if ((int) $e->getResponse()->getStatusCode() === 405) {
327 3
                $this->supportsHead = false;
328
329 3
                return $this->get($path);
330
            }
331
332 6
            return false;
333 3
        } catch (BadResponseException $e) {
334 3
            return false;
335
        }
336
337 6
        if ((int) $response->getStatusCode() !== 200) {
338 3
            return false;
339
        }
340
341 6
        return $response;
342
    }
343
}
344