Completed
Pull Request — master (#223)
by korelstar
01:42
created

SettingsService::getAll()   A

Complexity

Conditions 5
Paths 2

Size

Total Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 14
rs 9.4888
c 0
b 0
f 0
cc 5
nc 2
nop 0
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, empty and default settings
38
		foreach($settings as $name => $value) {
39
			if(!array_key_exists($name, $this->defaults)
40
				|| empty($value)
41
				|| $value === $this->defaults[$name]
42
			) {
43
				unset($settings[$name]);
44
			}
45
		}
46
		$this->config->setUserValue($this->uid, 'notes', 'settings', json_encode($settings));
47
	}
48
49
	public function getAll() {
50
		$settings = json_decode($this->config->getUserValue($this->uid, 'notes', 'settings'));
51
		if(is_object($settings)) {
52
			// use default for empty settings
53
			foreach($this->defaults as $name => $defaultValue) {
54
				if(!property_exists($settings, $name) || empty($settings->{$name})) {
55
					$settings->{$name} = $defaultValue;
56
				}
57
			}
58
		} else {
59
			$settings = (object)$this->defaults;
60
		}
61
		return $settings;
62
	}
63
64
	/**
65
	 * @throws \OCP\PreConditionNotMetException
66
	 */
67
	public function get($name) {
68
		$settings = $this->getAll();
69
		if(property_exists($settings, $name)) {
70
			return $settings->{$name};
71
		} else {
72
			throw new \OCP\PreConditionNotMetException('Setting '.$name.' not found.');
73
		}
74
	}
75
}
76