WebDAVAdapter   C
last analyzed

Complexity

Total Complexity 55

Size/Duplication

Total Lines 402
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 8

Importance

Changes 0
Metric Value
wmc 55
lcom 1
cbo 8
dl 0
loc 402
rs 6
c 0
b 0
f 0

23 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A encodePath() 0 8 2
A getMetadata() 0 18 4
A has() 0 4 1
A read() 0 22 4
A write() 0 21 4
A writeStream() 0 4 1
A update() 0 4 1
A updateStream() 0 4 1
A rename() 0 19 4
A copy() 0 8 2
A delete() 0 13 3
B createDir() 0 28 6
A deleteDir() 0 4 1
A listContents() 0 20 4
A getSize() 0 4 1
A getTimestamp() 0 4 1
A getMimetype() 0 4 1
A getUseStreamedCopy() 0 4 1
A setUseStreamedCopy() 0 4 1
A nativeCopy() 0 24 5
A normalizeObject() 0 17 3
A isDirectory() 0 10 3

How to fix   Complexity   

Complex Class

Complex classes like WebDAVAdapter 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 WebDAVAdapter, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace League\Flysystem\WebDAV;
4
5
use League\Flysystem\Adapter\AbstractAdapter;
6
use League\Flysystem\Adapter\Polyfill\NotSupportingVisibilityTrait;
7
use League\Flysystem\Adapter\Polyfill\StreamedCopyTrait;
8
use League\Flysystem\Adapter\Polyfill\StreamedReadingTrait;
9
use League\Flysystem\Config;
10
use League\Flysystem\Util;
11
use LogicException;
12
use Sabre\DAV\Client;
13
use Sabre\DAV\Exception;
14
use Sabre\DAV\Exception\NotFound;
15
use Sabre\DAV\Xml\Property\ResourceType;
16
use Sabre\HTTP\HttpException;
17
18
class WebDAVAdapter extends AbstractAdapter
19
{
20
    use StreamedReadingTrait;
21
    use StreamedCopyTrait {
22
        StreamedCopyTrait::copy as streamedCopy;
23
    }
24
    use NotSupportingVisibilityTrait;
25
26
    protected static $metadataFields = [
27
        '{DAV:}displayname',
28
        '{DAV:}getcontentlength',
29
        '{DAV:}getcontenttype',
30
        '{DAV:}getlastmodified',
31
        '{DAV:}iscollection',
32
        '{DAV:}resourcetype',
33
    ];
34
35
    /**
36
     * @var array
37
     */
38
    protected static $resultMap = [
39
        '{DAV:}getcontentlength' => 'size',
40
        '{DAV:}getcontenttype' => 'mimetype',
41
        'content-length' => 'size',
42
        'content-type' => 'mimetype',
43
    ];
44
45
    /**
46
     * @var Client
47
     */
48
    protected $client;
49
50
    /**
51
     * @var bool
52
     */
53
    protected $useStreamedCopy = true;
54
55
    /**
56
     * Constructor.
57
     *
58
     * @param Client $client
59
     * @param string $prefix
60
     * @param bool $useStreamedCopy
61
     */
62
    public function __construct(Client $client, $prefix = null, $useStreamedCopy = true)
63
    {
64
        $this->client = $client;
65
        $this->setPathPrefix($prefix);
66
        $this->setUseStreamedCopy($useStreamedCopy);
67
    }
68
69
    /**
70
     * url encode a path
71
     *
72
     * @param string $path
73
     *
74
     * @return string
75
     */
76
    protected function encodePath($path)
77
	{
78
		$a = explode('/', $path);
79
		for ($i=0; $i<count($a); $i++) {
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
80
			$a[$i] = rawurlencode($a[$i]);
81
		}
82
		return implode('/', $a);
83
	}
84
85
    /**
86
     * {@inheritdoc}
87
     */
88
    public function getMetadata($path)
89
    {
90
        $location = $this->applyPathPrefix($this->encodePath($path));
91
92
        try {
93
            $result = $this->client->propFind($location, static::$metadataFields);
94
95
            if (empty($result)) {
96
                return false;
97
            }
98
99
            return $this->normalizeObject($result, $path);
100
        } catch (Exception $e) {
101
            return false;
102
        } catch (HttpException $e) {
103
            return false;
104
        }
105
    }
106
107
    /**
108
     * {@inheritdoc}
109
     */
110
    public function has($path)
111
    {
112
        return $this->getMetadata($path);
113
    }
114
115
    /**
116
     * {@inheritdoc}
117
     */
118
    public function read($path)
119
    {
120
        $location = $this->applyPathPrefix($this->encodePath($path));
121
122
        try {
123
            $response = $this->client->request('GET', $location);
124
125
            if ($response['statusCode'] !== 200) {
126
                return false;
127
            }
128
129
            return array_merge([
130
                'contents' => $response['body'],
131
                'timestamp' => strtotime(is_array($response['headers']['last-modified'])
132
                    ? current($response['headers']['last-modified'])
133
                    : $response['headers']['last-modified']),
134
                'path' => $path,
135
            ], Util::map($response['headers'], static::$resultMap));
136
        } catch (Exception $e) {
137
            return false;
138
        }
139
    }
140
141
    /**
142
     * {@inheritdoc}
143
     */
144
    public function write($path, $contents, Config $config)
145
    {
146
        if (!$this->createDir(Util::dirname($path), $config)) {
147
            return false;
148
        }
149
150
        $location = $this->applyPathPrefix($this->encodePath($path));
151
        $response = $this->client->request('PUT', $location, $contents);
152
153
        if ($response['statusCode'] >= 400) {
154
            return false;
155
        }
156
157
        $result = compact('path', 'contents');
158
159
        if ($config->get('visibility')) {
160
            throw new LogicException(__CLASS__.' does not support visibility settings.');
161
        }
162
163
        return $result;
164
    }
165
166
    /**
167
     * {@inheritdoc}
168
     */
169
    public function writeStream($path, $resource, Config $config)
170
    {
171
        return $this->write($path, $resource, $config);
0 ignored issues
show
Documentation introduced by
$resource is of type resource, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
172
    }
173
174
    /**
175
     * {@inheritdoc}
176
     */
177
    public function update($path, $contents, Config $config)
178
    {
179
        return $this->write($path, $contents, $config);
180
    }
181
182
    /**
183
     * {@inheritdoc}
184
     */
185
    public function updateStream($path, $resource, Config $config)
186
    {
187
        return $this->update($path, $resource, $config);
0 ignored issues
show
Documentation introduced by
$resource is of type resource, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
188
    }
189
190
    /**
191
     * {@inheritdoc}
192
     */
193
    public function rename($path, $newpath)
194
    {
195
        $location = $this->applyPathPrefix($this->encodePath($path));
196
        $newLocation = $this->applyPathPrefix($this->encodePath($newpath));
197
198
        try {
199
            $response = $this->client->request('MOVE', '/'.ltrim($location, '/'), null, [
200
                'Destination' => '/'.ltrim($newLocation, '/'),
201
            ]);
202
203
            if ($response['statusCode'] >= 200 && $response['statusCode'] < 300) {
204
                return true;
205
            }
206
        } catch (NotFound $e) {
207
            // Would have returned false here, but would be redundant
208
        }
209
210
        return false;
211
    }
212
213
    /**
214
     * {@inheritdoc}
215
     */
216
    public function copy($path, $newpath)
217
    {
218
        if ($this->useStreamedCopy === true) {
219
            return $this->streamedCopy($path, $newpath);
220
        } else {
221
            return $this->nativeCopy($path, $newpath);
222
        }
223
    }
224
225
    /**
226
     * {@inheritdoc}
227
     */
228
    public function delete($path)
229
    {
230
        $location = $this->applyPathPrefix($this->encodePath($path));
231
232
        try {
233
            $response =  $this->client->request('DELETE', $location)['statusCode'];
234
235
236
            return $response >= 200 && $response < 300;
237
        } catch (NotFound $e) {
238
            return false;
239
        }
240
    }
241
242
    /**
243
     * {@inheritdoc}
244
     */
245
    public function createDir($path, Config $config)
246
    {
247
        $encodedPath = $this->encodePath($path);
248
        $path = trim($path, '/');
249
250
        $result = compact('path') + ['type' => 'dir'];
251
252
        if (Util::normalizeDirname($path) === '' || $this->has($path)) {
253
            return $result;
254
        }
255
256
        $directories = explode('/', $path);
257
        if (count($directories) > 1) {
258
            $parentDirectories = array_splice($directories, 0, count($directories) - 1);
259
            if (!$this->createDir(implode('/', $parentDirectories), $config)) {
260
                return false;
261
            }
262
        }
263
264
        $location = $this->applyPathPrefix($encodedPath);
265
        $response = $this->client->request('MKCOL', $location . $this->pathSeparator);
266
267
        if ($response['statusCode'] !== 201) {
268
            return false;
269
        }
270
271
        return $result;
272
    }
273
274
    /**
275
     * {@inheritdoc}
276
     */
277
    public function deleteDir($dirname)
278
    {
279
        return $this->delete($dirname);
280
    }
281
282
    /**
283
     * {@inheritdoc}
284
     */
285
    public function listContents($directory = '', $recursive = false)
286
    {
287
        $location = $this->applyPathPrefix($this->encodePath($directory));
288
        $response = $this->client->propFind($location . '/', static::$metadataFields, 1);
289
290
        array_shift($response);
291
        $result = [];
292
293
        foreach ($response as $path => $object) {
294
            $path = $this->removePathPrefix(rawurldecode($path));
295
            $object = $this->normalizeObject($object, $path);
296
            $result[] = $object;
297
298
            if ($recursive && $object['type'] === 'dir') {
299
                $result = array_merge($result, $this->listContents($object['path'], true));
300
            }
301
        }
302
303
        return $result;
304
    }
305
306
    /**
307
     * {@inheritdoc}
308
     */
309
    public function getSize($path)
310
    {
311
        return $this->getMetadata($path);
312
    }
313
314
    /**
315
     * {@inheritdoc}
316
     */
317
    public function getTimestamp($path)
318
    {
319
        return $this->getMetadata($path);
320
    }
321
322
    /**
323
     * {@inheritdoc}
324
     */
325
    public function getMimetype($path)
326
    {
327
        return $this->getMetadata($path);
328
    }
329
330
    /**
331
     * @return boolean
332
     */
333
    public function getUseStreamedCopy()
334
    {
335
        return $this->useStreamedCopy;
336
    }
337
338
    /**
339
     * @param boolean $useStreamedCopy
340
     */
341
    public function setUseStreamedCopy($useStreamedCopy)
342
    {
343
        $this->useStreamedCopy = (bool)$useStreamedCopy;
344
    }
345
346
    /**
347
     * Copy a file through WebDav COPY method.
348
     *
349
     * @param string $path
350
     * @param string $newPath
351
     *
352
     * @return bool
353
     */
354
    protected function nativeCopy($path, $newPath)
355
    {
356
        if (!$this->createDir(Util::dirname($newPath), new Config())) {
357
            return false;
358
        }
359
360
        $location = $this->applyPathPrefix($this->encodePath($path));
361
        $newLocation = $this->applyPathPrefix($this->encodePath($newPath));
362
363
        try {
364
            $destination = $this->client->getAbsoluteUrl($newLocation);
365
            $response = $this->client->request('COPY', '/'.ltrim($location, '/'), null, [
366
                'Destination' => $destination,
367
            ]);
368
369
            if ($response['statusCode'] >= 200 && $response['statusCode'] < 300) {
370
                return true;
371
            }
372
        } catch (NotFound $e) {
373
            // Would have returned false here, but would be redundant
374
        }
375
376
        return false;
377
    }
378
379
    /**
380
     * Normalise a WebDAV repsonse object.
381
     *
382
     * @param array  $object
383
     * @param string $path
384
     *
385
     * @return array
386
     */
387
    protected function normalizeObject(array $object, $path)
388
    {
389
        if ($this->isDirectory($object)) {
390
            return ['type' => 'dir', 'path' => trim($path, '/')];
391
        }
392
393
        $result = Util::map($object, static::$resultMap);
394
395
        if (isset($object['{DAV:}getlastmodified'])) {
396
            $result['timestamp'] = strtotime($object['{DAV:}getlastmodified']);
397
        }
398
399
        $result['type'] = 'file';
400
        $result['path'] = trim($path, '/');
401
402
        return $result;
403
    }
404
405
    /**
406
     * @param array $object
407
     * @return bool
408
     */
409
    protected function isDirectory(array $object)
410
    {
411
        if (isset($object['{DAV:}resourcetype'])) {
412
            /** @var ResourceType $resourceType */
413
            $resourceType = $object['{DAV:}resourcetype'];
414
            return $resourceType->is('{DAV:}collection');
415
        }
416
417
        return isset($object['{DAV:}iscollection']) && $object['{DAV:}iscollection'] === '1';
418
    }
419
}
420