ClearBucket   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 59
Duplicated Lines 0 %

Test Coverage

Coverage 79.17%

Importance

Changes 0
Metric Value
wmc 8
eloc 23
dl 0
loc 59
ccs 19
cts 24
cp 0.7917
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
B handle() 0 39 7
A validateParams() 0 3 1
1
<?php
2
/**
3
 *  This file is part of the Simple S3 package.
4
 *
5
 * (c) Mauro Cassani<https://github.com/mauretto78>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 *
10
 */
11
12
namespace Matecat\SimpleS3\Commands\Handlers;
13
14
use Exception;
15
use Matecat\SimpleS3\Commands\CommandHandler;
16
17
class ClearBucket extends CommandHandler
18
{
19
    /**
20
     * Clear a bucket.
21
     *
22
     * @param array{bucket: string} $params
23
     *
24
     * @return bool
25
     * @throws Exception
26
     */
27 6
    public function handle(array $params = ['bucket' => 'no-bucket-provided']): bool
28
    {
29 6
        $bucketName = $params[ 'bucket' ];
30 6
        $errors     = [];
31
32 6
        if (false === $this->client->hasBucket(['bucket' => $bucketName])) {
33
            $this->commandHandlerLogger?->log($this, sprintf('Bucket \'%s\' does not exists', $bucketName), 'warning');
34
35
            return false;
36
        }
37
38 6
        $items = $this->client->getItemsInABucket(['bucket' => $bucketName]);
39
40 6
        if (count($items) === 0) {
41 3
            return true;
42
        }
43
44 4
        foreach ($items as $key) {
45 4
            $version = null;
46 4
            if (str_contains($key, '<VERSION_ID:')) {
47 1
                $v       = explode('<VERSION_ID:', $key);
48 1
                $version = str_replace('>', '', $v[ 1 ]);
49 1
                $key     = $v[ 0 ];
50
            }
51
52 4
            if (false === $delete = $this->client->deleteItem(['bucket' => $bucketName, 'key' => $key, 'version' => $version])) {
53
                $errors[] = $delete;
54
            }
55
        }
56
57 4
        if (count($errors) === 0) {
58 4
            $this->commandHandlerLogger?->log($this, sprintf('Bucket \'%s\' was successfully cleared', $bucketName));
59
60 4
            return true;
61
        }
62
63
        $this->commandHandlerLogger?->log($this, sprintf('Something went wrong while clearing bucket \'%s\'', $bucketName), 'warning');
64
65
        return false;
66
    }
67
68
    /**
69
     * @param array<string, string> $params
70
     *
71
     * @return bool
72
     */
73 6
    public function validateParams(array $params = []): bool
74
    {
75 6
        return isset($params[ 'bucket' ]);
76
    }
77
}
78