Completed
Push — master ( f5617d...0186d8 )
by Lukas
15:02 queued 23s
created
lib/private/Files/ObjectStore/Swift.php 2 patches
Indentation   +244 added lines, -244 removed lines patch added patch discarded remove patch
@@ -37,249 +37,249 @@
 block discarded – undo
37 37
 
38 38
 class Swift implements IObjectStore {
39 39
 
40
-	/**
41
-	 * @var \OpenCloud\OpenStack
42
-	 */
43
-	private $client;
44
-
45
-	/**
46
-	 * @var array
47
-	 */
48
-	private $params;
49
-
50
-	/**
51
-	 * @var \OpenCloud\ObjectStore\Service
52
-	 */
53
-	private $objectStoreService;
54
-
55
-	/**
56
-	 * @var \OpenCloud\ObjectStore\Resource\Container
57
-	 */
58
-	private $container;
59
-
60
-	private $memcache;
61
-
62
-	public function __construct($params) {
63
-		if (isset($params['bucket'])) {
64
-			$params['container'] = $params['bucket'];
65
-		}
66
-		if (!isset($params['container'])) {
67
-			$params['container'] = 'owncloud';
68
-		}
69
-		if (!isset($params['autocreate'])) {
70
-			// should only be true for tests
71
-			$params['autocreate'] = false;
72
-		}
73
-
74
-		if (isset($params['apiKey'])) {
75
-			$this->client = new Rackspace($params['url'], $params);
76
-			$cacheKey = $params['username'] . '@' . $params['url'] . '/' . $params['bucket'];
77
-		} else {
78
-			$this->client = new OpenStack($params['url'], $params);
79
-			$cacheKey = $params['username'] . '@' . $params['url'] . '/' . $params['bucket'];
80
-		}
81
-
82
-		$cacheFactory = \OC::$server->getMemCacheFactory();
83
-		$this->memcache = $cacheFactory->create('swift::' . $cacheKey);
84
-
85
-		$this->params = $params;
86
-	}
87
-
88
-	protected function init() {
89
-		if ($this->container) {
90
-			return;
91
-		}
92
-
93
-		$this->importToken();
94
-
95
-		/** @var Token $token */
96
-		$token = $this->client->getTokenObject();
97
-
98
-		if (!$token || $token->hasExpired()) {
99
-			try {
100
-				$this->client->authenticate();
101
-				$this->exportToken();
102
-			} catch (ClientErrorResponseException $e) {
103
-				$statusCode = $e->getResponse()->getStatusCode();
104
-				if ($statusCode == 412) {
105
-					throw new StorageAuthException('Precondition failed, verify the keystone url', $e);
106
-				} else if ($statusCode === 401) {
107
-					throw new StorageAuthException('Authentication failed, verify the username, password and possibly tenant', $e);
108
-				} else {
109
-					throw new StorageAuthException('Unknown error', $e);
110
-				}
111
-			}
112
-		}
113
-
114
-
115
-		/** @var Catalog $catalog */
116
-		$catalog = $this->client->getCatalog();
117
-
118
-		if (isset($this->params['serviceName'])) {
119
-			$serviceName = $this->params['serviceName'];
120
-		} else {
121
-			$serviceName = Service::DEFAULT_NAME;
122
-		}
123
-
124
-		if (isset($this->params['urlType'])) {
125
-			$urlType = $this->params['urlType'];
126
-			if ($urlType !== 'internalURL' && $urlType !== 'publicURL') {
127
-				throw new StorageNotAvailableException('Invalid url type');
128
-			}
129
-		} else {
130
-			$urlType = Service::DEFAULT_URL_TYPE;
131
-		}
132
-
133
-		$catalogItem = $this->getCatalogForService($catalog, $serviceName);
134
-		if (!$catalogItem) {
135
-			$available = implode(', ', $this->getAvailableServiceNames($catalog));
136
-			throw new StorageNotAvailableException(
137
-				"Service $serviceName not found in service catalog, available services: $available"
138
-			);
139
-		} else if (isset($this->params['region'])) {
140
-			$this->validateRegion($catalogItem, $this->params['region']);
141
-		}
142
-
143
-		$this->objectStoreService = $this->client->objectStoreService($serviceName, $this->params['region'], $urlType);
144
-
145
-		try {
146
-			$this->container = $this->objectStoreService->getContainer($this->params['container']);
147
-		} catch (ClientErrorResponseException $ex) {
148
-			// if the container does not exist and autocreate is true try to create the container on the fly
149
-			if (isset($this->params['autocreate']) && $this->params['autocreate'] === true) {
150
-				$this->container = $this->objectStoreService->createContainer($this->params['container']);
151
-			} else {
152
-				throw $ex;
153
-			}
154
-		}
155
-	}
156
-
157
-	private function exportToken() {
158
-		$export = $this->client->exportCredentials();
159
-		$export['catalog'] = array_map(function (CatalogItem $item) {
160
-			return [
161
-				'name' => $item->getName(),
162
-				'endpoints' => $item->getEndpoints(),
163
-				'type' => $item->getType()
164
-			];
165
-		}, $export['catalog']->getItems());
166
-		$this->memcache->set('token', json_encode($export));
167
-	}
168
-
169
-	private function importToken() {
170
-		$cachedTokenString = $this->memcache->get('token');
171
-		if ($cachedTokenString) {
172
-			$cachedToken = json_decode($cachedTokenString, true);
173
-			$cachedToken['catalog'] = array_map(function (array $item) {
174
-				$itemClass = new \stdClass();
175
-				$itemClass->name = $item['name'];
176
-				$itemClass->endpoints = array_map(function (array $endpoint) {
177
-					return (object) $endpoint;
178
-				}, $item['endpoints']);
179
-				$itemClass->type = $item['type'];
180
-
181
-				return $itemClass;
182
-			}, $cachedToken['catalog']);
183
-			try {
184
-				$this->client->importCredentials($cachedToken);
185
-			} catch (\Exception $e) {
186
-				$this->client->setTokenObject(new Token());
187
-			}
188
-		}
189
-	}
190
-
191
-	/**
192
-	 * @param Catalog $catalog
193
-	 * @param $name
194
-	 * @return null|CatalogItem
195
-	 */
196
-	private function getCatalogForService(Catalog $catalog, $name) {
197
-		foreach ($catalog->getItems() as $item) {
198
-			/** @var CatalogItem $item */
199
-			if ($item->hasType(Service::DEFAULT_TYPE) && $item->hasName($name)) {
200
-				return $item;
201
-			}
202
-		}
203
-
204
-		return null;
205
-	}
206
-
207
-	private function validateRegion(CatalogItem $item, $region) {
208
-		$endPoints = $item->getEndpoints();
209
-		foreach ($endPoints as $endPoint) {
210
-			if ($endPoint->region === $region) {
211
-				return;
212
-			}
213
-		}
214
-
215
-		$availableRegions = implode(', ', array_map(function ($endpoint) {
216
-			return $endpoint->region;
217
-		}, $endPoints));
218
-
219
-		throw new StorageNotAvailableException("Invalid region '$region', available regions: $availableRegions");
220
-	}
221
-
222
-	private function getAvailableServiceNames(Catalog $catalog) {
223
-		return array_map(function (CatalogItem $item) {
224
-			return $item->getName();
225
-		}, array_filter($catalog->getItems(), function (CatalogItem $item) {
226
-			return $item->hasType(Service::DEFAULT_TYPE);
227
-		}));
228
-	}
229
-
230
-	/**
231
-	 * @return string the container name where objects are stored
232
-	 */
233
-	public function getStorageId() {
234
-		return $this->params['container'];
235
-	}
236
-
237
-	/**
238
-	 * @param string $urn the unified resource name used to identify the object
239
-	 * @param resource $stream stream with the data to write
240
-	 * @throws Exception from openstack lib when something goes wrong
241
-	 */
242
-	public function writeObject($urn, $stream) {
243
-		$this->init();
244
-		$this->container->uploadObject($urn, $stream);
245
-	}
246
-
247
-	/**
248
-	 * @param string $urn the unified resource name used to identify the object
249
-	 * @return resource stream with the read data
250
-	 * @throws Exception from openstack lib when something goes wrong
251
-	 */
252
-	public function readObject($urn) {
253
-		$this->init();
254
-		$object = $this->container->getObject($urn);
255
-
256
-		// we need to keep a reference to objectContent or
257
-		// the stream will be closed before we can do anything with it
258
-		/** @var $objectContent \Guzzle\Http\EntityBody * */
259
-		$objectContent = $object->getContent();
260
-		$objectContent->rewind();
261
-
262
-		$stream = $objectContent->getStream();
263
-		// save the object content in the context of the stream to prevent it being gc'd until the stream is closed
264
-		stream_context_set_option($stream, 'swift', 'content', $objectContent);
265
-
266
-		return $stream;
267
-	}
268
-
269
-	/**
270
-	 * @param string $urn Unified Resource Name
271
-	 * @return void
272
-	 * @throws Exception from openstack lib when something goes wrong
273
-	 */
274
-	public function deleteObject($urn) {
275
-		$this->init();
276
-		// see https://github.com/rackspace/php-opencloud/issues/243#issuecomment-30032242
277
-		$this->container->dataObject()->setName($urn)->delete();
278
-	}
279
-
280
-	public function deleteContainer($recursive = false) {
281
-		$this->init();
282
-		$this->container->delete($recursive);
283
-	}
40
+    /**
41
+     * @var \OpenCloud\OpenStack
42
+     */
43
+    private $client;
44
+
45
+    /**
46
+     * @var array
47
+     */
48
+    private $params;
49
+
50
+    /**
51
+     * @var \OpenCloud\ObjectStore\Service
52
+     */
53
+    private $objectStoreService;
54
+
55
+    /**
56
+     * @var \OpenCloud\ObjectStore\Resource\Container
57
+     */
58
+    private $container;
59
+
60
+    private $memcache;
61
+
62
+    public function __construct($params) {
63
+        if (isset($params['bucket'])) {
64
+            $params['container'] = $params['bucket'];
65
+        }
66
+        if (!isset($params['container'])) {
67
+            $params['container'] = 'owncloud';
68
+        }
69
+        if (!isset($params['autocreate'])) {
70
+            // should only be true for tests
71
+            $params['autocreate'] = false;
72
+        }
73
+
74
+        if (isset($params['apiKey'])) {
75
+            $this->client = new Rackspace($params['url'], $params);
76
+            $cacheKey = $params['username'] . '@' . $params['url'] . '/' . $params['bucket'];
77
+        } else {
78
+            $this->client = new OpenStack($params['url'], $params);
79
+            $cacheKey = $params['username'] . '@' . $params['url'] . '/' . $params['bucket'];
80
+        }
81
+
82
+        $cacheFactory = \OC::$server->getMemCacheFactory();
83
+        $this->memcache = $cacheFactory->create('swift::' . $cacheKey);
84
+
85
+        $this->params = $params;
86
+    }
87
+
88
+    protected function init() {
89
+        if ($this->container) {
90
+            return;
91
+        }
92
+
93
+        $this->importToken();
94
+
95
+        /** @var Token $token */
96
+        $token = $this->client->getTokenObject();
97
+
98
+        if (!$token || $token->hasExpired()) {
99
+            try {
100
+                $this->client->authenticate();
101
+                $this->exportToken();
102
+            } catch (ClientErrorResponseException $e) {
103
+                $statusCode = $e->getResponse()->getStatusCode();
104
+                if ($statusCode == 412) {
105
+                    throw new StorageAuthException('Precondition failed, verify the keystone url', $e);
106
+                } else if ($statusCode === 401) {
107
+                    throw new StorageAuthException('Authentication failed, verify the username, password and possibly tenant', $e);
108
+                } else {
109
+                    throw new StorageAuthException('Unknown error', $e);
110
+                }
111
+            }
112
+        }
113
+
114
+
115
+        /** @var Catalog $catalog */
116
+        $catalog = $this->client->getCatalog();
117
+
118
+        if (isset($this->params['serviceName'])) {
119
+            $serviceName = $this->params['serviceName'];
120
+        } else {
121
+            $serviceName = Service::DEFAULT_NAME;
122
+        }
123
+
124
+        if (isset($this->params['urlType'])) {
125
+            $urlType = $this->params['urlType'];
126
+            if ($urlType !== 'internalURL' && $urlType !== 'publicURL') {
127
+                throw new StorageNotAvailableException('Invalid url type');
128
+            }
129
+        } else {
130
+            $urlType = Service::DEFAULT_URL_TYPE;
131
+        }
132
+
133
+        $catalogItem = $this->getCatalogForService($catalog, $serviceName);
134
+        if (!$catalogItem) {
135
+            $available = implode(', ', $this->getAvailableServiceNames($catalog));
136
+            throw new StorageNotAvailableException(
137
+                "Service $serviceName not found in service catalog, available services: $available"
138
+            );
139
+        } else if (isset($this->params['region'])) {
140
+            $this->validateRegion($catalogItem, $this->params['region']);
141
+        }
142
+
143
+        $this->objectStoreService = $this->client->objectStoreService($serviceName, $this->params['region'], $urlType);
144
+
145
+        try {
146
+            $this->container = $this->objectStoreService->getContainer($this->params['container']);
147
+        } catch (ClientErrorResponseException $ex) {
148
+            // if the container does not exist and autocreate is true try to create the container on the fly
149
+            if (isset($this->params['autocreate']) && $this->params['autocreate'] === true) {
150
+                $this->container = $this->objectStoreService->createContainer($this->params['container']);
151
+            } else {
152
+                throw $ex;
153
+            }
154
+        }
155
+    }
156
+
157
+    private function exportToken() {
158
+        $export = $this->client->exportCredentials();
159
+        $export['catalog'] = array_map(function (CatalogItem $item) {
160
+            return [
161
+                'name' => $item->getName(),
162
+                'endpoints' => $item->getEndpoints(),
163
+                'type' => $item->getType()
164
+            ];
165
+        }, $export['catalog']->getItems());
166
+        $this->memcache->set('token', json_encode($export));
167
+    }
168
+
169
+    private function importToken() {
170
+        $cachedTokenString = $this->memcache->get('token');
171
+        if ($cachedTokenString) {
172
+            $cachedToken = json_decode($cachedTokenString, true);
173
+            $cachedToken['catalog'] = array_map(function (array $item) {
174
+                $itemClass = new \stdClass();
175
+                $itemClass->name = $item['name'];
176
+                $itemClass->endpoints = array_map(function (array $endpoint) {
177
+                    return (object) $endpoint;
178
+                }, $item['endpoints']);
179
+                $itemClass->type = $item['type'];
180
+
181
+                return $itemClass;
182
+            }, $cachedToken['catalog']);
183
+            try {
184
+                $this->client->importCredentials($cachedToken);
185
+            } catch (\Exception $e) {
186
+                $this->client->setTokenObject(new Token());
187
+            }
188
+        }
189
+    }
190
+
191
+    /**
192
+     * @param Catalog $catalog
193
+     * @param $name
194
+     * @return null|CatalogItem
195
+     */
196
+    private function getCatalogForService(Catalog $catalog, $name) {
197
+        foreach ($catalog->getItems() as $item) {
198
+            /** @var CatalogItem $item */
199
+            if ($item->hasType(Service::DEFAULT_TYPE) && $item->hasName($name)) {
200
+                return $item;
201
+            }
202
+        }
203
+
204
+        return null;
205
+    }
206
+
207
+    private function validateRegion(CatalogItem $item, $region) {
208
+        $endPoints = $item->getEndpoints();
209
+        foreach ($endPoints as $endPoint) {
210
+            if ($endPoint->region === $region) {
211
+                return;
212
+            }
213
+        }
214
+
215
+        $availableRegions = implode(', ', array_map(function ($endpoint) {
216
+            return $endpoint->region;
217
+        }, $endPoints));
218
+
219
+        throw new StorageNotAvailableException("Invalid region '$region', available regions: $availableRegions");
220
+    }
221
+
222
+    private function getAvailableServiceNames(Catalog $catalog) {
223
+        return array_map(function (CatalogItem $item) {
224
+            return $item->getName();
225
+        }, array_filter($catalog->getItems(), function (CatalogItem $item) {
226
+            return $item->hasType(Service::DEFAULT_TYPE);
227
+        }));
228
+    }
229
+
230
+    /**
231
+     * @return string the container name where objects are stored
232
+     */
233
+    public function getStorageId() {
234
+        return $this->params['container'];
235
+    }
236
+
237
+    /**
238
+     * @param string $urn the unified resource name used to identify the object
239
+     * @param resource $stream stream with the data to write
240
+     * @throws Exception from openstack lib when something goes wrong
241
+     */
242
+    public function writeObject($urn, $stream) {
243
+        $this->init();
244
+        $this->container->uploadObject($urn, $stream);
245
+    }
246
+
247
+    /**
248
+     * @param string $urn the unified resource name used to identify the object
249
+     * @return resource stream with the read data
250
+     * @throws Exception from openstack lib when something goes wrong
251
+     */
252
+    public function readObject($urn) {
253
+        $this->init();
254
+        $object = $this->container->getObject($urn);
255
+
256
+        // we need to keep a reference to objectContent or
257
+        // the stream will be closed before we can do anything with it
258
+        /** @var $objectContent \Guzzle\Http\EntityBody * */
259
+        $objectContent = $object->getContent();
260
+        $objectContent->rewind();
261
+
262
+        $stream = $objectContent->getStream();
263
+        // save the object content in the context of the stream to prevent it being gc'd until the stream is closed
264
+        stream_context_set_option($stream, 'swift', 'content', $objectContent);
265
+
266
+        return $stream;
267
+    }
268
+
269
+    /**
270
+     * @param string $urn Unified Resource Name
271
+     * @return void
272
+     * @throws Exception from openstack lib when something goes wrong
273
+     */
274
+    public function deleteObject($urn) {
275
+        $this->init();
276
+        // see https://github.com/rackspace/php-opencloud/issues/243#issuecomment-30032242
277
+        $this->container->dataObject()->setName($urn)->delete();
278
+    }
279
+
280
+    public function deleteContainer($recursive = false) {
281
+        $this->init();
282
+        $this->container->delete($recursive);
283
+    }
284 284
 
285 285
 }
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -73,14 +73,14 @@  discard block
 block discarded – undo
73 73
 
74 74
 		if (isset($params['apiKey'])) {
75 75
 			$this->client = new Rackspace($params['url'], $params);
76
-			$cacheKey = $params['username'] . '@' . $params['url'] . '/' . $params['bucket'];
76
+			$cacheKey = $params['username'].'@'.$params['url'].'/'.$params['bucket'];
77 77
 		} else {
78 78
 			$this->client = new OpenStack($params['url'], $params);
79
-			$cacheKey = $params['username'] . '@' . $params['url'] . '/' . $params['bucket'];
79
+			$cacheKey = $params['username'].'@'.$params['url'].'/'.$params['bucket'];
80 80
 		}
81 81
 
82 82
 		$cacheFactory = \OC::$server->getMemCacheFactory();
83
-		$this->memcache = $cacheFactory->create('swift::' . $cacheKey);
83
+		$this->memcache = $cacheFactory->create('swift::'.$cacheKey);
84 84
 
85 85
 		$this->params = $params;
86 86
 	}
@@ -156,7 +156,7 @@  discard block
 block discarded – undo
156 156
 
157 157
 	private function exportToken() {
158 158
 		$export = $this->client->exportCredentials();
159
-		$export['catalog'] = array_map(function (CatalogItem $item) {
159
+		$export['catalog'] = array_map(function(CatalogItem $item) {
160 160
 			return [
161 161
 				'name' => $item->getName(),
162 162
 				'endpoints' => $item->getEndpoints(),
@@ -170,10 +170,10 @@  discard block
 block discarded – undo
170 170
 		$cachedTokenString = $this->memcache->get('token');
171 171
 		if ($cachedTokenString) {
172 172
 			$cachedToken = json_decode($cachedTokenString, true);
173
-			$cachedToken['catalog'] = array_map(function (array $item) {
173
+			$cachedToken['catalog'] = array_map(function(array $item) {
174 174
 				$itemClass = new \stdClass();
175 175
 				$itemClass->name = $item['name'];
176
-				$itemClass->endpoints = array_map(function (array $endpoint) {
176
+				$itemClass->endpoints = array_map(function(array $endpoint) {
177 177
 					return (object) $endpoint;
178 178
 				}, $item['endpoints']);
179 179
 				$itemClass->type = $item['type'];
@@ -212,7 +212,7 @@  discard block
 block discarded – undo
212 212
 			}
213 213
 		}
214 214
 
215
-		$availableRegions = implode(', ', array_map(function ($endpoint) {
215
+		$availableRegions = implode(', ', array_map(function($endpoint) {
216 216
 			return $endpoint->region;
217 217
 		}, $endPoints));
218 218
 
@@ -220,9 +220,9 @@  discard block
 block discarded – undo
220 220
 	}
221 221
 
222 222
 	private function getAvailableServiceNames(Catalog $catalog) {
223
-		return array_map(function (CatalogItem $item) {
223
+		return array_map(function(CatalogItem $item) {
224 224
 			return $item->getName();
225
-		}, array_filter($catalog->getItems(), function (CatalogItem $item) {
225
+		}, array_filter($catalog->getItems(), function(CatalogItem $item) {
226 226
 			return $item->hasType(Service::DEFAULT_TYPE);
227 227
 		}));
228 228
 	}
Please login to merge, or discard this patch.