Completed
Push — guzzle-6 ( ab3f50...dd69ff )
by Chris
03:59
created

GuzzleAdapter   B

Complexity

Total Complexity 43

Size/Duplication

Total Lines 329
Duplicated Lines 1.82 %

Coupling/Cohesion

Components 1
Dependencies 5

Test Coverage

Coverage 100%

Importance

Changes 4
Bugs 0 Features 2
Metric Value
wmc 43
c 4
b 0
f 2
lcom 1
cbo 5
dl 6
loc 329
ccs 110
cts 110
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 29 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 League\Flysystem\AdapterInterface;
10
use League\Flysystem\Config;
11
use League\Flysystem\Util\MimeType;
12
13
/**
14
 * Uses Guzzle as a backend for HTTP URLs.
15
 */
16
class GuzzleAdapter implements AdapterInterface
17
{
18
    /**
19
     * Whether this endpoint supports head requests.
20
     *
21
     * @var bool
22
     */
23
    protected $supportsHead = true;
24
25
    /**
26
     * The base URL.
27
     *
28
     * @var string
29
     */
30
    protected $base;
31
32
    /**
33
     * The Guzzle HTTP client.
34
     *
35
     * @var \GuzzleHttp\ClientInterface
36
     */
37
    protected $client;
38
39
    /**
40
     * The visibility of this adapter.
41
     *
42
     * @var string
43
     */
44
    protected $visibility = AdapterInterface::VISIBILITY_PUBLIC;
45
46
    /**
47
     * Constructs a GuzzleAdapter object.
48
     *
49
     * @param string                      $base   The base URL.
50
     * @param \GuzzleHttp\ClientInterface $client An optional Guzzle client.
51
     */
52 3
    public function __construct($base, ClientInterface $client = null)
53
    {
54 3
        $this->client = $client ?: new Client();
55
56 3
        $parsed = parse_url($base);
57 3
        $this->base = $parsed['scheme'] . '://';
58
59 3
        if (isset($parsed['user'])) {
60 3
            $this->visibility = AdapterInterface::VISIBILITY_PRIVATE;
61 3
            $this->base .= $parsed['user'];
62
63 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...
64 3
                $this->base .= ':' . $parsed['pass'];
65 3
            }
66
67 3
            $this->base .= '@';
68 3
        };
69
70 3
        $this->base .= $parsed['host'] . '/';
71
72 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...
73 3
            $this->base .= trim($parsed['path'], '/') . '/';
74 3
        }
75 3
    }
76
77
    /**
78
     * Returns the base URL.
79
     *
80
     * @return string The base URL.
81
     */
82 3
    public function getBaseUrl()
83
    {
84 3
        return $this->base;
85
    }
86
87
    /**
88
     * @inheritdoc
89
     */
90 3
    public function copy($path, $newpath)
91
    {
92 3
        return false;
93
    }
94
95
    /**
96
     * @inheritdoc
97
     */
98 3
    public function createDir($path, Config $config)
99
    {
100 3
        return false;
101
    }
102
103
    /**
104
     * @inheritdoc
105
     */
106 3
    public function delete($path)
107
    {
108 3
        return false;
109
    }
110
111
    /**
112
     * @inheritdoc
113
     */
114 3
    public function deleteDir($path)
115
    {
116 3
        return false;
117
    }
118
119
    /**
120
     * @inheritdoc
121
     */
122 3
    public function getMetadata($path)
123
    {
124 3
        if (! $response = $this->head($path)) {
125 3
            return false;
126
        }
127
128 3
        if ($mimetype = $response->getHeader('Content-Type')) {
129 3
            list($mimetype) = explode(';', reset($mimetype), 2);
130 3
            $mimetype = trim($mimetype);
131 3
        } else {
132
            // Remove any query strings or fragments.
133 3
            list($path) = explode('#', $path, 2);
134 3
            list($path) = explode('?', $path, 2);
135 3
            $extension = pathinfo($path, PATHINFO_EXTENSION);
136 3
            $mimetype = $extension ? MimeType::detectByFileExtension($extension) : 'text/plain';
137
        }
138
139 3
        $last_modified = $response->getHeader('Last-Modified');
140 3
        $length = $response->getHeader('Content-Length');
141
142
        return [
143 3
            'type' => 'file',
144 3
            'path' => $path,
145 3
            'timestamp' => (int) strtotime(reset($last_modified)),
146 3
            'size' => (int) reset($length),
147 3
            'visibility' => $this->visibility,
148 3
            'mimetype' => $mimetype,
149 3
        ];
150
    }
151
152
    /**
153
     * @inheritdoc
154
     */
155 3
    public function getMimetype($path)
156
    {
157 3
        return $this->getMetadata($path);
158
    }
159
160
    /**
161
     * @inheritdoc
162
     */
163 3
    public function getSize($path)
164
    {
165 3
        return $this->getMetadata($path);
166
    }
167
168
    /**
169
     * @inheritdoc
170
     */
171 3
    public function getTimestamp($path)
172
    {
173 3
        return $this->getMetadata($path);
174
    }
175
176
    /**
177
     * @inheritdoc
178
     */
179 3
    public function getVisibility($path)
180
    {
181
        return [
182 3
            'path' => $path,
183 3
            'visibility' => $this->visibility,
184 3
        ];
185
    }
186
187
    /**
188
     * @inheritdoc
189
     */
190 3
    public function has($path)
191
    {
192 3
        if (! $response = $this->head($path)) {
193 3
            return false;
194
        }
195
196 3
        return $response->getStatusCode() === 200;
197
    }
198
199
    /**
200
     * @inheritdoc
201
     */
202 3
    public function listContents($directory = '', $recursive = false)
203
    {
204 3
        return [];
205
    }
206
207
    /**
208
     * @inheritdoc
209
     */
210 3
    public function read($path)
211
    {
212 3
        if (! $response = $this->get($path)) {
213 3
            return false;
214
        }
215
216
        return [
217 3
            'path' => $path,
218 3
            'contents' => (string) $response->getBody(),
219 3
        ];
220
    }
221
222
    /**
223
     * @inheritdoc
224
     */
225 3
    public function readStream($path)
226
    {
227 3
        if (! $response = $this->get($path)) {
228 3
            return false;
229
        }
230
231
        return [
232 3
            'path' => $path,
233 3
            'stream' => $response->getBody()->detach(),
234 3
        ];
235
    }
236
237
    /**
238
     * @inheritdoc
239
     */
240 3
    public function rename($path, $newpath)
241
    {
242 3
        return false;
243
    }
244
245
    /**
246
     * @inheritdoc
247
     */
248 3
    public function setVisibility($path, $visibility)
249
    {
250 3
        if ($visibility === $this->visibility) {
251 3
            return $this->getVisibility($path);
252
        }
253
254 3
        return false;
255
    }
256
257
    /**
258
     * @inheritdoc
259
     */
260 3
    public function update($path, $contents, Config $conf)
261
    {
262 3
        return false;
263
    }
264
265
    /**
266
     * @inheritdoc
267
     */
268 3
    public function updateStream($path, $resource, Config $config)
269
    {
270 3
        return false;
271
    }
272
273
    /**
274
     * @inheritdoc
275
     */
276 3
    public function write($path, $contents, Config $config)
277
    {
278 3
        return false;
279
    }
280
281
    /**
282
     * @inheritdoc
283
     */
284 3
    public function writeStream($path, $resource, Config $config)
285
    {
286 3
        return false;
287
    }
288
289
    /**
290
     * Performs a GET request.
291
     *
292
     * @param string $path The path to GET.
293
     *
294
     * @return \GuzzleHttp\Psr7\Response|false The response or false if failed.
295
     */
296 6
    protected function get($path)
297
    {
298
        try {
299 6
            $response = $this->client->get($this->base . $path);
300 6
        } catch (BadResponseException $e) {
301 6
            return false;
302
        }
303
304 6
        if ($response->getStatusCode() !== 200) {
305 3
            return false;
306
        }
307
308 6
        return $response;
309
    }
310
311
    /**
312
     * Performs a HEAD request.
313
     *
314
     * @param string $path The path to HEAD.
315
     *
316
     * @return \GuzzleHttp\Psr7\Response|false The response or false if failed.
317
     */
318 6
    protected function head($path)
319
    {
320 6
        if (! $this->supportsHead) {
321 3
            return $this->get($path);
322
        }
323
324
        try {
325 6
            $response = $this->client->head($this->base . $path);
326 6
        } catch (ClientException $e) {
327 6
            if ($e->getResponse()->getStatusCode() === 405) {
328 3
                $this->supportsHead = false;
329
330 3
                return $this->get($path);
331
            }
332
333 6
            return false;
334 3
        } catch (BadResponseException $e) {
335 3
            return false;
336
        }
337
338 6
        if ($response->getStatusCode() !== 200) {
339 3
            return false;
340
        }
341
342 6
        return $response;
343
    }
344
}
345