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

GuzzleAdapter::head()   B

Complexity

Conditions 6
Paths 6

Size

Total Lines 26
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 6

Importance

Changes 2
Bugs 0 Features 1
Metric Value
c 2
b 0
f 1
dl 0
loc 26
ccs 14
cts 14
cp 1
rs 8.439
cc 6
eloc 15
nc 6
nop 1
crap 6
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