Completed
Pull Request — master (#223)
by korelstar
06:08
created

SettingsService::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 7
rs 10
cc 1
nc 1
nop 2
1
<?php
2
3
namespace OCA\Notes\Service;
4
use OCP\AppFramework\Controller;
5
6
use OCP\IConfig;
7
use OCP\IRequest;
8
use OCP\IUserManager;
9
use OCP\IUserSession;
10
use OCP\Files\IRootFolder;
11
use OCP\AppFramework\Http\JSONResponse;
12
13
class SettingsService
14
{
15
	private $config;
16
	private $uid;
17
	private $root;
18
19
	/* Default values */
20
	private $defaults = [
21
		"notesPath" => "Notes",
22
		"fileSuffix" => ".txt",
23
	];
24
25
	public function __construct(
26
		IConfig $config,
27
		IUserSession $userSession
28
	) {
29
		$this->config = $config;
30
		$this->uid = $userSession->getUser()->getUID();
31
	}
32
33
	/**
34
	 * @throws \OCP\PreConditionNotMetException
35
	 */
36
	public function set($settings) {
37
		// remove illegal or obsolete settings
38
		foreach($settings as $name => $value) {
39
			if(!array_key_exists($name, $this->defaults)) {
40
				unset($settings[$name]);
41
			}
42
		}
43
		$this->config->setUserValue($this->uid, 'notes', 'settings', json_encode($settings));
44
	}
45
46
	public function getAll() {
47
		$settings = json_decode($this->config->getUserValue($this->uid, 'notes', 'settings'));
48
		if(is_object($settings)) {
49
			// use default for empty settings
50
			foreach($this->defaults as $name => $defaultValue) {
51
				if(!property_exists($settings, $name) || empty($settings->{$name})) {
52
					$settings->{$name} = $defaultValue;
53
				}
54
			}
55
		} else {
56
			$settings = (object)$this->defaults;
57
		}
58
		return $settings;
59
	}
60
61
	/**
62
	 * @throws \OCP\PreConditionNotMetException
63
	 */
64
	public function get($name) {
65
		$settings = $this->getAll();
66
		if(property_exists($settings, $name)) {
67
			return $settings->{$name};
68
		} else {
69
			throw new \OCP\PreConditionNotMetException('Setting '.$name.' not found.');
70
		}
71
	}
72
}
73