Passed
Push — master ( 96e892...5b0e70 )
by Roeland
13:09
created

S3ConnectionTrait::getConnection()   F

Complexity

Conditions 14
Paths 1153

Size

Total Lines 58
Code Lines 39

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 14
eloc 39
nc 1153
nop 0
dl 0
loc 58
rs 2.1
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * @copyright Copyright (c) 2016 Robin Appelman <[email protected]>
4
 *
5
 * @author Morris Jobke <[email protected]>
6
 * @author Robin Appelman <[email protected]>
7
 *
8
 * @license GNU AGPL version 3 or any later version
9
 *
10
 * This program is free software: you can redistribute it and/or modify
11
 * it under the terms of the GNU Affero General Public License as
12
 * published by the Free Software Foundation, either version 3 of the
13
 * License, or (at your option) any later version.
14
 *
15
 * This program is distributed in the hope that it will be useful,
16
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18
 * GNU Affero General Public License for more details.
19
 *
20
 * You should have received a copy of the GNU Affero General Public License
21
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
22
 *
23
 */
24
25
namespace OC\Files\ObjectStore;
26
27
use Aws\ClientResolver;
28
use Aws\S3\Exception\S3Exception;
29
use Aws\S3\S3Client;
30
use OCP\ILogger;
31
32
trait S3ConnectionTrait {
33
	/** @var array */
34
	protected $params;
35
36
	/** @var S3Client */
37
	protected $connection;
38
39
	/** @var string */
40
	protected $id;
41
42
	/** @var string */
43
	protected $bucket;
44
45
	/** @var int */
46
	protected $timeout;
47
48
	protected $test;
49
50
	protected function parseParams($params) {
51
		if (empty($params['key']) || empty($params['secret']) || empty($params['bucket'])) {
52
			throw new \Exception("Access Key, Secret and Bucket have to be configured.");
53
		}
54
55
		$this->id = 'amazon::' . $params['bucket'];
56
57
		$this->test = isset($params['test']);
58
		$this->bucket = $params['bucket'];
59
		$this->timeout = !isset($params['timeout']) ? 15 : $params['timeout'];
60
		$params['region'] = empty($params['region']) ? 'eu-west-1' : $params['region'];
61
		$params['hostname'] = empty($params['hostname']) ? 's3.' . $params['region'] . '.amazonaws.com' : $params['hostname'];
62
		if (!isset($params['port']) || $params['port'] === '') {
63
			$params['port'] = (isset($params['use_ssl']) && $params['use_ssl'] === false) ? 80 : 443;
64
		}
65
		$this->params = $params;
66
	}
67
68
	public function getBucket() {
69
		return $this->bucket;
70
	}
71
72
	/**
73
	 * Returns the connection
74
	 *
75
	 * @return S3Client connected client
76
	 * @throws \Exception if connection could not be made
77
	 */
78
	public function getConnection() {
79
		if (!is_null($this->connection)) {
80
			return $this->connection;
81
		}
82
83
		$scheme = (isset($this->params['use_ssl']) && $this->params['use_ssl'] === false) ? 'http' : 'https';
84
		$base_url = $scheme . '://' . $this->params['hostname'] . ':' . $this->params['port'] . '/';
85
86
		$options = [
87
			'version' => isset($this->params['version']) ? $this->params['version'] : 'latest',
88
			'credentials' => [
89
				'key' => $this->params['key'],
90
				'secret' => $this->params['secret'],
91
			],
92
			'endpoint' => $base_url,
93
			'region' => $this->params['region'],
94
			'use_path_style_endpoint' => isset($this->params['use_path_style']) ? $this->params['use_path_style'] : false,
95
			'signature_provider' => \Aws\or_chain([self::class, 'legacySignatureProvider'], ClientResolver::_default_signature_provider())
96
		];
97
		if (isset($this->params['proxy'])) {
98
			$options['request.options'] = ['proxy' => $this->params['proxy']];
99
		}
100
		if (isset($this->params['legacy_auth']) && $this->params['legacy_auth']) {
101
			$options['signature_version'] = 'v2';
102
		}
103
		$this->connection = new S3Client($options);
104
105
		if (!$this->connection->isBucketDnsCompatible($this->bucket)) {
106
			$logger = \OC::$server->getLogger();
107
			$logger->debug('Bucket "' . $this->bucket . '" This bucket name is not dns compatible, it may contain invalid characters.',
108
					 ['app' => 'objectstore']);
109
		}
110
111
		if (!$this->connection->doesBucketExist($this->bucket)) {
112
			$logger = \OC::$server->getLogger();
113
			try {
114
				$logger->info('Bucket "' . $this->bucket . '" does not exist - creating it.', ['app' => 'objectstore']);
115
				if (!$this->connection->isBucketDnsCompatible($this->bucket)) {
116
					throw new \Exception("The bucket will not be created because the name is not dns compatible, please correct it: " . $this->bucket);
117
				}
118
				$this->connection->createBucket(array('Bucket' => $this->bucket));
119
				$this->testTimeout();
120
			} catch (S3Exception $e) {
121
				$logger->logException($e, [
122
					'message' => 'Invalid remote storage.',
123
					'level' => ILogger::DEBUG,
124
					'app' => 'objectstore',
125
				]);
126
				throw new \Exception('Creation of bucket "' . $this->bucket . '" failed. ' . $e->getMessage());
127
			}
128
		}
129
130
		// google cloud's s3 compatibility doesn't like the EncodingType parameter
131
		if (strpos($base_url, 'storage.googleapis.com')) {
132
			$this->connection->getHandlerList()->remove('s3.auto_encode');
133
		}
134
135
		return $this->connection;
136
	}
137
138
	/**
139
	 * when running the tests wait to let the buckets catch up
140
	 */
141
	private function testTimeout() {
142
		if ($this->test) {
143
			sleep($this->timeout);
144
		}
145
	}
146
147
	public static function legacySignatureProvider($version, $service, $region) {
0 ignored issues
show
Unused Code introduced by
The parameter $region is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

147
	public static function legacySignatureProvider($version, $service, /** @scrutinizer ignore-unused */ $region) {

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $service is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

147
	public static function legacySignatureProvider($version, /** @scrutinizer ignore-unused */ $service, $region) {

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
148
		switch ($version) {
149
			case 'v2':
150
			case 's3':
151
				return new S3Signature();
152
			default:
153
				return null;
154
		}
155
	}
156
}
157