Passed
Pull Request — master (#1187)
by René
04:10
created

PreferencesService   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 56
Duplicated Lines 0 %

Importance

Changes 2
Bugs 1 Features 0
Metric Value
wmc 5
eloc 18
c 2
b 1
f 0
dl 0
loc 56
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A write() 0 8 2
A get() 0 2 1
A __construct() 0 12 2
1
<?php
2
/**
3
 * @copyright Copyright (c) 2017 Vinzenz Rosenkranz <[email protected]>
4
 *
5
 * @author René Gieling <[email protected]>
6
 *
7
 * @license GNU AGPL version 3 or any later version
8
 *
9
 *  This program is free software: you can redistribute it and/or modify
10
 *  it under the terms of the GNU Affero General Public License as
11
 *  published by the Free Software Foundation, either version 3 of the
12
 *  License, or (at your option) any later version.
13
 *
14
 *  This program is distributed in the hope that it will be useful,
15
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
16
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17
 *  GNU Affero General Public License for more details.
18
 *
19
 *  You should have received a copy of the GNU Affero General Public License
20
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
21
 *
22
 */
23
24
namespace OCA\Polls\Service;
25
26
use OCA\Polls\Exceptions\NotAuthorizedException;
27
28
use OCA\Polls\Db\Preferences;
29
use OCA\Polls\Db\PreferencesMapper;
30
31
class PreferencesService {
32
33
	/** @var PreferencesMapper */
34
	private $preferencesMapper;
35
36
	/** @var Preferences */
37
	private $preferences;
38
39
	/** @var String */
40
	private $userId;
41
42
	/**
43
	 * SystemService constructor.
44
	 * @param PreferencesMapper $preferencesMapper
45
	 */
46
	public function __construct(
47
		$UserId,
48
		PreferencesMapper $preferencesMapper
49
	) {
50
		$this->userId = $UserId;
51
		$this->preferencesMapper = $preferencesMapper;
52
		try {
53
			$this->preferences = $this->preferencesMapper->find($this->userId);
54
		} catch (\Exception $e) {
55
			$this->preferences = new Preferences();
56
			$this->preferences->setUserId($this->userId);
57
			$this->preferences = $this->preferencesMapper->insert($this->preferences);
58
		}
59
	}
60
	/**
61
	 * get
62
	 * Read all preferences
63
	 * @NoAdminRequired
64
	 * @NoCSRFRequired
65
	 * @return Preferences
66
	 */
67
	public function get() {
68
		return $this->preferences;
69
	}
70
71
	/**
72
	 * write
73
	 * Write references
74
	 * @NoAdminRequired
75
	 * @param array $settings
76
	 * @return Preferences
77
	 * @throws NotAuthorizedException
78
	 */
79
	public function write($settings) {
80
		if (!$this->userId) {
81
			throw new NotAuthorizedException;
82
		}
83
84
		$this->preferences->setPreferences(json_encode($settings));
85
		$this->preferences->setTimestamp(time());
86
		return $this->preferencesMapper->update($this->preferences);
87
	}
88
}
89