ConfigMapper::set()   B
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 36
Code Lines 12

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 36
rs 8.8571
cc 2
eloc 12
nc 2
nop 3
1
<?php
2
3
namespace OCA\Chat\Db;
4
5
use \OCP\AppFramework\Db\Mapper;
6
use \OCP\IDb;
7
8
class ConfigMapper extends Mapper {
9
10
	/**
11
	 * @var string ownCloud user id
12
	 */
13
	private $user;
14
15
	/**
16
	 * @var \OCP\Security\ICrypto
17
	 */
18
	private $crypto;
19
20
	public function __construct(IDb $api, $user, $crypto){
21
		parent::__construct($api, 'chat_config');
22
		$this->user = $user;
23
		$this->crypto = $crypto;
24
	}
25
26
	/**
27
	 * @param $backend id of the backend
28
	 * @return array config Values
29
	 */
30
	public function getByBackend($backend){
31
32
		$sql = <<<SQL
33
				SELECT
34
					*
35
				FROM
36
					`*PREFIX*chat_config`
37
				WHERE
38
					`user` = ?
39
				AND
40
					`backend` = ?
41
SQL;
42
		$values = array();
43
		$result = $this->findEntities($sql, array($this->user, $backend));
44
		foreach ($result as $r) {
45
			$values[$r->getKey()]  = $this->crypto->decrypt($r->getValue());
46
		}
47
		return $values;
48
	}
49
50
	/**
51
	 * @param $backend id of the backend
52
	 * @param $key key of the config value
53
	 * @param $value the config value
54
	 */
55
	public function set($backend, $key, $value){
56
		$value = $this->crypto->encrypt($value);
57
		if($this->hasKey($backend, $key, $value)){
58
			$sql = <<<SQL
59
				UPDATE
60
					`*PREFIX*chat_config`
61
				SET
62
					`value` = ?
63
				WHERE
64
					`user` = ?
65
				AND
66
					`backend` = ?
67
				AND
68
					`key` = ?
69
SQL;
70
			$this->execute($sql, array($value, $this->user, $backend, $key));
71
		} else {
72
			$sql = <<<SQL
73
				INSERT
74
				INTO
75
					`*PREFIX*chat_config`
76
				(
77
					`user`,
78
					`key`,
79
					`value`,
80
					`backend`
81
				) VALUES (
82
					?,
83
					?,
84
					?,
85
					?
86
				)
87
SQL;
88
			$this->execute($sql, array($this->user, $key, $value, $backend));
89
		}
90
	}
91
92
	public function hasKey($backend, $key, $value){
93
		try {
94
			$sql = <<<SQL
95
			SELECT
96
				*
97
			FROM
98
				`*PREFIX*chat_config`
99
			WHERE
100
				`backend` = ?
101
			AND
102
				`key` = ?
103
			AND
104
				`user` = ?
105
SQL;
106
			$this->findEntity($sql, array($backend, $key, $this->user));
107
			return true;
108
		} catch (DoesNotExistException $e){
109
			return false;
110
		}
111
	}
112
	
113
}