Completed
Push — master ( fd0e42...04f419 )
by Lukas
31s
created

DIContainer::__construct()   B

Complexity

Conditions 3
Paths 2

Size

Total Lines 205
Code Lines 118

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 118
nc 2
nop 3
dl 0
loc 205
rs 8.2857
c 0
b 0
f 0

How to fix   Long Method   

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, ownCloud, Inc.
4
 *
5
 * @author Bernhard Posselt <[email protected]>
6
 * @author Christoph Wurst <[email protected]>
7
 * @author Joas Schilling <[email protected]>
8
 * @author Jörn Friedrich Dreyer <[email protected]>
9
 * @author Lukas Reschke <[email protected]>
10
 * @author Morris Jobke <[email protected]>
11
 * @author Robin McCorkell <[email protected]>
12
 * @author Roeland Jago Douma <[email protected]>
13
 * @author Thomas Müller <[email protected]>
14
 * @author Thomas Tanghus <[email protected]>
15
 *
16
 * @license AGPL-3.0
17
 *
18
 * This code is free software: you can redistribute it and/or modify
19
 * it under the terms of the GNU Affero General Public License, version 3,
20
 * as published by the Free Software Foundation.
21
 *
22
 * This program is distributed in the hope that it will be useful,
23
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
24
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25
 * GNU Affero General Public License for more details.
26
 *
27
 * You should have received a copy of the GNU Affero General Public License, version 3,
28
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
29
 *
30
 */
31
32
33
namespace OC\AppFramework\DependencyInjection;
34
35
use OC;
36
use OC\AppFramework\Core\API;
37
use OC\AppFramework\Http;
38
use OC\AppFramework\Http\Dispatcher;
39
use OC\AppFramework\Http\Output;
40
use OC\AppFramework\Middleware\MiddlewareDispatcher;
41
use OC\AppFramework\Middleware\Security\CORSMiddleware;
42
use OC\AppFramework\Middleware\OCSMiddleware;
43
use OC\AppFramework\Middleware\Security\SecurityMiddleware;
44
use OC\AppFramework\Middleware\SessionMiddleware;
45
use OC\AppFramework\Utility\SimpleContainer;
46
use OC\Core\Middleware\TwoFactorMiddleware;
47
use OC\RichObjectStrings\Validator;
48
use OC\ServerContainer;
49
use OCP\AppFramework\Http\IOutput;
50
use OCP\AppFramework\IApi;
51
use OCP\AppFramework\IAppContainer;
52
use OCP\Files\Folder;
53
use OCP\Files\IAppData;
54
use OCP\IL10N;
55
use OCP\IRequest;
56
use OCP\IServerContainer;
57
use OCP\IUserSession;
58
use OCP\RichObjectStrings\IValidator;
59
use OCP\Util;
60
61
class DIContainer extends SimpleContainer implements IAppContainer {
62
63
	/**
64
	 * @var array
65
	 */
66
	private $middleWares = array();
67
68
	/** @var ServerContainer */
69
	private $server;
70
71
	/**
72
	 * Put your class dependencies in here
73
	 * @param string $appName the name of the app
74
	 * @param array $urlParams
75
	 * @param ServerContainer $server
76
	 */
77
	public function __construct($appName, $urlParams = array(), ServerContainer $server = null){
78
		parent::__construct();
79
		$this['AppName'] = $appName;
80
		$this['urlParams'] = $urlParams;
81
82
		/** @var \OC\ServerContainer $server */
83
		if ($server === null) {
84
			$server = \OC::$server;
85
		}
86
		$this->server = $server;
87
		$this->server->registerAppContainer($appName, $this);
88
89
		// aliases
90
		$this->registerAlias('appName', 'AppName');
91
		$this->registerAlias('webRoot', 'WebRoot');
92
		$this->registerAlias('userId', 'UserId');
93
94
		/**
95
		 * Core services
96
		 */
97
		$this->registerService(IOutput::class, function($c){
0 ignored issues
show
Unused Code introduced by
The parameter $c is not used and could be removed.

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

Loading history...
98
			return new Output($this->getServer()->getWebRoot());
99
		});
100
101
		$this->registerService(Folder::class, function() {
102
			return $this->getServer()->getUserFolder();
103
		});
104
105
		$this->registerService(IAppData::class, function (SimpleContainer $c) {
106
			return $this->getServer()->getAppDataDir($c->query('AppName'));
107
		});
108
109
		$this->registerService(IL10N::class, function($c) {
110
			return $this->getServer()->getL10N($c->query('AppName'));
111
		});
112
113
		$this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
114
		$this->registerAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
115
116
		$this->registerService(IRequest::class, function() {
117
			return $this->getServer()->query(IRequest::class);
118
		});
119
		$this->registerAlias('Request', IRequest::class);
120
121
		$this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
122
		$this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
123
124
		$this->registerAlias(\OC\User\Session::class, \OCP\IUserSession::class);
125
126
		$this->registerService(IServerContainer::class, function ($c) {
0 ignored issues
show
Unused Code introduced by
The parameter $c is not used and could be removed.

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

Loading history...
127
			return $this->getServer();
128
		});
129
		$this->registerAlias('ServerContainer', IServerContainer::class);
130
131
		$this->registerService(\OCP\WorkflowEngine\IManager::class, function ($c) {
132
			return $c->query('OCA\WorkflowEngine\Manager');
133
		});
134
135
		$this->registerService(\OCP\AppFramework\IAppContainer::class, function ($c) {
136
			return $c;
137
		});
138
139
		// commonly used attributes
140
		$this->registerService('UserId', function ($c) {
141
			return $c->query('OCP\\IUserSession')->getSession()->get('user_id');
142
		});
143
144
		$this->registerService('WebRoot', function ($c) {
145
			return $c->query('ServerContainer')->getWebRoot();
146
		});
147
148
		$this->registerService('fromMailAddress', function() {
149
			return Util::getDefaultEmailAddress('no-reply');
150
		});
151
152
		$this->registerService('OC_Defaults', function ($c) {
153
			return $c->getServer()->getThemingDefaults();
154
		});
155
156
		$this->registerService('OCP\Encryption\IManager', function ($c) {
0 ignored issues
show
Unused Code introduced by
The parameter $c is not used and could be removed.

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

Loading history...
157
			return $this->getServer()->getEncryptionManager();
158
		});
159
160
		$this->registerService(IValidator::class, function($c) {
161
			return $c->query(Validator::class);
162
		});
163
164
		$this->registerService(\OC\Security\IdentityProof\Manager::class, function ($c) {
0 ignored issues
show
Unused Code introduced by
The parameter $c is not used and could be removed.

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

Loading history...
165
			return new \OC\Security\IdentityProof\Manager(
166
				$this->getServer()->getAppDataDir('identityproof'),
167
				$this->getServer()->getCrypto()
168
			);
169
		});
170
171
172
		/**
173
		 * App Framework APIs
174
		 */
175
		$this->registerService('API', function($c){
176
			$c->query('OCP\\ILogger')->debug(
177
				'Accessing the API class is deprecated! Use the appropriate ' .
178
				'services instead!'
179
			);
180
			return new API($c['AppName']);
0 ignored issues
show
Deprecated Code introduced by
The class OC\AppFramework\Core\API has been deprecated.

This class, trait or interface has been deprecated.

Loading history...
181
		});
182
183
		$this->registerService('Protocol', function($c){
184
			/** @var \OC\Server $server */
185
			$server = $c->query('ServerContainer');
186
			$protocol = $server->getRequest()->getHttpProtocol();
187
			return new Http($_SERVER, $protocol);
188
		});
189
190
		$this->registerService('Dispatcher', function($c) {
191
			return new Dispatcher(
192
				$c['Protocol'],
193
				$c['MiddlewareDispatcher'],
194
				$c['ControllerMethodReflector'],
195
				$c['Request']
196
			);
197
		});
198
199
		/**
200
		 * App Framework default arguments
201
		 */
202
		$this->registerParameter('corsMethods', 'PUT, POST, GET, DELETE, PATCH');
203
		$this->registerParameter('corsAllowedHeaders', 'Authorization, Content-Type, Accept');
204
		$this->registerParameter('corsMaxAge', 1728000);
205
206
		/**
207
		 * Middleware
208
		 */
209
		$app = $this;
210
		$this->registerService('SecurityMiddleware', function($c) use ($app){
211
			/** @var \OC\Server $server */
212
			$server = $app->getServer();
213
214
			return new SecurityMiddleware(
215
				$c['Request'],
216
				$c['ControllerMethodReflector'],
217
				$server->getNavigationManager(),
218
				$server->getURLGenerator(),
219
				$server->getLogger(),
220
				$server->getSession(),
221
				$c['AppName'],
222
				$app->isLoggedIn(),
0 ignored issues
show
Deprecated Code introduced by
The method OC\AppFramework\Dependen...Container::isLoggedIn() has been deprecated with message: use IUserSession->isLoggedIn()

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
223
				$app->isAdminUser(),
0 ignored issues
show
Deprecated Code introduced by
The method OC\AppFramework\Dependen...ontainer::isAdminUser() has been deprecated with message: use IGroupManager->isAdmin($userId)

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
224
				$server->getContentSecurityPolicyManager(),
0 ignored issues
show
Compatibility introduced by
$server->getContentSecurityPolicyManager() of type object<OCP\Security\ICon...tSecurityPolicyManager> is not a sub-type of object<OC\Security\CSP\C...tSecurityPolicyManager>. It seems like you assume a concrete implementation of the interface OCP\Security\IContentSecurityPolicyManager to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
225
				$server->getCsrfTokenManager(),
226
				$server->getContentSecurityPolicyNonceManager(),
227
				$server->getBruteForceThrottler()
228
			);
229
230
		});
231
232
		$this->registerService('CORSMiddleware', function($c) {
233
			return new CORSMiddleware(
234
				$c['Request'],
235
				$c['ControllerMethodReflector'],
236
				$c->query(IUserSession::class),
237
				$c->getServer()->getBruteForceThrottler()
238
			);
239
		});
240
241
		$this->registerService('SessionMiddleware', function($c) use ($app) {
242
			return new SessionMiddleware(
243
				$c['Request'],
244
				$c['ControllerMethodReflector'],
245
				$app->getServer()->getSession()
246
			);
247
		});
248
249
		$this->registerService('TwoFactorMiddleware', function (SimpleContainer $c) use ($app) {
250
			$twoFactorManager = $c->getServer()->getTwoFactorAuthManager();
251
			$userSession = $app->getServer()->getUserSession();
252
			$session = $app->getServer()->getSession();
253
			$urlGenerator = $app->getServer()->getURLGenerator();
254
			$reflector = $c['ControllerMethodReflector'];
255
			$request = $app->getServer()->getRequest();
256
			return new TwoFactorMiddleware($twoFactorManager, $userSession, $session, $urlGenerator, $reflector, $request);
0 ignored issues
show
Compatibility introduced by
$userSession of type object<OCP\IUserSession> is not a sub-type of object<OC\User\Session>. It seems like you assume a concrete implementation of the interface OCP\IUserSession to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
257
		});
258
259
		$this->registerService('OCSMiddleware', function (SimpleContainer $c) {
260
			return new OCSMiddleware(
261
				$c['Request']
262
			);
263
		});
264
265
		$middleWares = &$this->middleWares;
266
		$this->registerService('MiddlewareDispatcher', function($c) use (&$middleWares) {
267
			$dispatcher = new MiddlewareDispatcher();
268
			$dispatcher->registerMiddleware($c['CORSMiddleware']);
269
			$dispatcher->registerMiddleware($c['OCSMiddleware']);
270
			$dispatcher->registerMiddleware($c['SecurityMiddleware']);
271
			$dispatcher->registerMiddleWare($c['TwoFactorMiddleware']);
272
273
			foreach($middleWares as $middleWare) {
274
				$dispatcher->registerMiddleware($c[$middleWare]);
275
			}
276
277
			$dispatcher->registerMiddleware($c['SessionMiddleware']);
278
			return $dispatcher;
279
		});
280
281
	}
282
283
284
	/**
285
	 * @deprecated implements only deprecated methods
286
	 * @return IApi
287
	 */
288
	function getCoreApi()
289
	{
290
		return $this->query('API');
291
	}
292
293
	/**
294
	 * @return \OCP\IServerContainer
295
	 */
296
	function getServer()
297
	{
298
		return $this->server;
299
	}
300
301
	/**
302
	 * @param string $middleWare
303
	 * @return boolean|null
304
	 */
305
	function registerMiddleWare($middleWare) {
306
		array_push($this->middleWares, $middleWare);
307
	}
308
309
	/**
310
	 * used to return the appname of the set application
311
	 * @return string the name of your application
312
	 */
313
	function getAppName() {
314
		return $this->query('AppName');
315
	}
316
317
	/**
318
	 * @deprecated use IUserSession->isLoggedIn()
319
	 * @return boolean
320
	 */
321
	function isLoggedIn() {
322
		return \OC::$server->getUserSession()->isLoggedIn();
323
	}
324
325
	/**
326
	 * @deprecated use IGroupManager->isAdmin($userId)
327
	 * @return boolean
328
	 */
329
	function isAdminUser() {
330
		$uid = $this->getUserId();
331
		return \OC_User::isAdminUser($uid);
332
	}
333
334
	private function getUserId() {
335
		return $this->getServer()->getSession()->get('user_id');
336
	}
337
338
	/**
339
	 * @deprecated use the ILogger instead
340
	 * @param string $message
341
	 * @param string $level
342
	 * @return mixed
343
	 */
344
	function log($message, $level) {
345
		switch($level){
346
			case 'debug':
347
				$level = \OCP\Util::DEBUG;
348
				break;
349
			case 'info':
350
				$level = \OCP\Util::INFO;
351
				break;
352
			case 'warn':
353
				$level = \OCP\Util::WARN;
354
				break;
355
			case 'fatal':
356
				$level = \OCP\Util::FATAL;
357
				break;
358
			default:
359
				$level = \OCP\Util::ERROR;
360
				break;
361
		}
362
		\OCP\Util::writeLog($this->getAppName(), $message, $level);
363
	}
364
365
	/**
366
	 * Register a capability
367
	 *
368
	 * @param string $serviceName e.g. 'OCA\Files\Capabilities'
369
	 */
370
	public function registerCapability($serviceName) {
371
		$this->query('OC\CapabilitiesManager')->registerCapability(function() use ($serviceName) {
372
			return $this->query($serviceName);
373
		});
374
	}
375
376
	public function query($name) {
377
		$name = $this->sanitizeName($name);
378
379
		if ($this->offsetExists($name)) {
380
			return parent::query($name);
381
		} else {
382
			if (strpos($name, 'OCA\\') === 0 && substr_count($name, '\\') >= 2) {
383
				$segments = explode('\\', $name);
384
				if (strtolower($segments[1]) === strtolower($this['AppName'])) {
385
					return parent::query($name);
386
				}
387
			} else if ($this['AppName'] === 'settings' && strpos($name, 'OC\\Settings\\') === 0) {
388
				return parent::query($name);
389
			} else if ($this['AppName'] === 'core' && strpos($name, 'OC\\Core\\') === 0) {
390
				return parent::query($name);
391
			}
392
		}
393
394
		return $this->getServer()->query($name);
395
	}
396
}
397