Completed
Push — guzzle-6 ( 5b50be...9aebd7 )
by Chris
02:43
created

GuzzleAdapter::getResponseMetadata()   B

Complexity

Conditions 5
Paths 9

Size

Total Lines 23
Code Lines 13

Duplication

Lines 7
Ratio 30.43 %

Code Coverage

Tests 8
CRAP Score 5

Importance

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